Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fund refactor #2291

Merged
merged 3 commits into from
Aug 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions openbb_terminal/mutual_funds/avanza_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,20 @@


@log_start_end(log=logger)
def get_data(fund_name: str):
def get_data(name: str):
"""Gets the data from Avanza

Parameters
----------
fund_name: str
name: str
Full name of the fund
"""
ava_fund = pd.read_csv(
os.path.join("openbb_terminal", "mutual_funds", "avanza_fund_ID.csv"),
index_col=0,
)
ava_fund.index = ava_fund.index.str.upper()
fund_id = ava_fund.loc[fund_name, "ID"]
fund_id = ava_fund.loc[name, "ID"]
url = f"https://www.avanza.se/_api/fund-guide/guide/{fund_id}"
response = requests.get(url)
fund_data = response.json()
Expand Down
22 changes: 11 additions & 11 deletions openbb_terminal/mutual_funds/avanza_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,18 @@


@log_start_end(log=logger)
def display_allocation(fund_name: str, focus: str):
def display_allocation(name: str, focus: str):
"""Displays the allocation of the selected swedish fund

Parameters
----------
fund_name: str
name: str
Full name of the fund
focus: str
The focus of the displayed allocation/exposure of the fund
"""
# Code mostly taken from: https://github.com/northern-64bit/Portfolio-Report-Generator/tree/main
fund_data = avanza_model.get_data(fund_name.upper())
# Taken from: https://github.com/northern-64bit/Portfolio-Report-Generator/tree/main
fund_data = avanza_model.get_data(name.upper())
if focus in ["holding", "all"]:
table_row = []
console.print("")
Expand All @@ -51,7 +51,7 @@ def display_allocation(fund_name: str, focus: str):
table_row.append(table_row_temp)
header = ["Holding", "Allocation in %", "Country"]
holding_data = pd.DataFrame(table_row, columns=header)
print_rich_table(holding_data, title=f"{fund_name}'s Holdings", headers=header)
print_rich_table(holding_data, title=f"{name}'s Holdings", headers=header)
if focus in ["sector", "all"]:
table_row = []
console.print("")
Expand All @@ -63,7 +63,7 @@ def display_allocation(fund_name: str, focus: str):
header = ["Sector", "Allocation in %"]
sector_data = pd.DataFrame(table_row, columns=header)
print_rich_table(
sector_data, title=f"{fund_name}'s Sector Weighting", headers=header
sector_data, title=f"{name}'s Sector Weighting", headers=header
)
if focus in ["country", "all"]:
table_row = []
Expand All @@ -76,26 +76,26 @@ def display_allocation(fund_name: str, focus: str):
header = ["Country", "Allocation in %"]
country_data = pd.DataFrame(table_row, columns=header)
print_rich_table(
country_data, title=f"{fund_name}'s Country Weighting", headers=header
country_data, title=f"{name}'s Country Weighting", headers=header
)


@log_start_end(log=logger)
def display_info(fund_name: str):
def display_info(name: str):
"""Displays info of swedish funds

Parameters
----------
fund_name: str
name: str
Full name of the fund
"""
fund_data = avanza_model.get_data(fund_name.upper())
fund_data = avanza_model.get_data(name.upper())
text = f"\nSwedish Description:\n\n{fund_data['description']}\n\nThe fund is managed by:\n"
for manager in fund_data["fundManagers"]:
text = text + f"\t- {manager['name']} since {manager['startDate']}\n"
text = (
text
+ f"from {fund_data['adminCompany']['name']}.\nThe currency of the fund is {fund_data['currency']}"
+ f"from {fund_data['adminCompany']['name']}.\nFund currency is {fund_data['currency']}"
f" and it the fund started {fund_data['startDate']}."
)
if fund_data["indexFund"]:
Expand Down
33 changes: 19 additions & 14 deletions openbb_terminal/mutual_funds/investpy_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ def get_overview(country: str = "united states", limit: int = 20) -> pd.DataFram
Country to get overview for
limit: int
Number of results to get

Returns
-------
pd.DataFrame
Dataframe containing overview
"""
return investpy.funds.get_funds_overview(
country=country, as_json=False, n_results=limit
Expand Down Expand Up @@ -108,12 +113,12 @@ def get_fund_name_from_symbol(symbol: str) -> Tuple[str, str]:


@log_start_end(log=logger)
def get_fund_info(fund: str, country: str = "united states") -> pd.DataFrame:
def get_fund_info(name: str, country: str = "united states") -> pd.DataFrame:
"""

Parameters
----------
fynd: str
name: str
Name of fund (not symbol) to get information
country: str
Country of fund
Expand All @@ -123,26 +128,26 @@ def get_fund_info(fund: str, country: str = "united states") -> pd.DataFrame:
pd.DataFrame
Dataframe of fund information
"""
return investpy.funds.get_fund_information(fund, country).T
return investpy.funds.get_fund_information(name, country).T


@log_start_end(log=logger)
def get_fund_historical(
fund: str,
name: str,
country: str = "united states",
name: bool = False,
by_name: bool = False,
start_date: datetime = (datetime.now() - timedelta(days=366)),
end_date: datetime = datetime.now(),
) -> Tuple[pd.DataFrame, str, str, str]:
"""Get historical fund data

Parameters
----------
fund: str
name: str
Fund to get data for. If using fund name, include `name=True`
country: str
Country of fund
name : bool
by_name : bool
Flag to search by name instead of symbol
start_date: datetime
Start date of data in format YYYY-MM-DD
Expand All @@ -160,20 +165,20 @@ def get_fund_historical(
str:
Country that matches search results
"""
if name:
fund_name = fund
if by_name:
fund_name = name
try:
fund_symbol, matching_country = get_fund_symbol_from_name(fund)
fund_symbol, matching_country = get_fund_symbol_from_name(name)
except RuntimeError as e:
logger.exception(str(e))
return pd.DataFrame(), fund, "", country
return pd.DataFrame(), name, "", country
else:
fund_symbol = fund
fund_symbol = name
try:
fund_name, matching_country = get_fund_name_from_symbol(fund)
fund_name, matching_country = get_fund_name_from_symbol(name)
except RuntimeError as e:
logger.exception(str(e))
return pd.DataFrame(), "", fund, country
return pd.DataFrame(), "", name, country

# Note that dates for investpy need to be in the format dd/mm/yyyy
from_date = start_date.strftime("%d/%m/%Y")
Expand Down
20 changes: 10 additions & 10 deletions openbb_terminal/mutual_funds/investpy_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def display_search(
country: str = "united states",
limit: int = 10,
sortby: str = "",
ascending: bool = False,
ascend: bool = False,
):
"""Display results of searching for Mutual Funds

Expand All @@ -46,7 +46,7 @@ def display_search(
Number to show
sortby: str
Column to sort by
ascending: bool
ascend: bool
Flag to sort in ascending order
"""
searches = investpy_model.search_funds(by, value)
Expand All @@ -61,7 +61,7 @@ def display_search(
searches = searches.drop(columns=["country", "underlying"])

if sortby:
searches = searches.sort_values(by=sortby, ascending=ascending)
searches = searches.sort_values(by=sortby, ascending=ascend)

print_rich_table(
searches.head(limit),
Expand Down Expand Up @@ -99,25 +99,25 @@ def display_overview(country: str = "united states", limit: int = 10, export: st


@log_start_end(log=logger)
def display_fund_info(fund_name: str, country: str = "united states"):
def display_fund_info(name: str, country: str = "united states"):
"""Display fund information. Finds name from symbol first if name is false

Parameters
----------
fund: str
name: str
Fund name to get info for
country : str
Country of fund
"""
info = (
investpy_model.get_fund_info(fund_name, country)
investpy_model.get_fund_info(name, country)
.reset_index(drop=False)
.applymap(lambda x: np.nan if not x else x)
.dropna()
)
print_rich_table(
info,
title=f"[bold]{fund_name.title()} Information[/bold]",
title=f"[bold]{name.title()} Information[/bold]",
show_index=False,
headers=["Info", "Value"],
)
Expand All @@ -126,7 +126,7 @@ def display_fund_info(fund_name: str, country: str = "united states"):
@log_start_end(log=logger)
def display_historical(
data: pd.DataFrame,
fund: str = "",
name: str = "",
export: str = "",
external_axes: Optional[List[plt.Axes]] = None,
):
Expand All @@ -136,7 +136,7 @@ def display_historical(
----------
data: pd.DataFrame
Dataframe containing historical data
fund: str
name: str
Fund symbol or name
export: str
Format to export data
Expand All @@ -152,7 +152,7 @@ def display_historical(
ax.set_xlim([data.index[0], data.index[-1]])
ax.set_xlabel("Date")
ax.set_ylabel("Close Price")
ax.set_title(f"{fund.title()} Price History")
ax.set_title(f"{name.title()} Price History")
theme.style_primary_axis(ax)
if external_axes is None:
theme.visualize_output()
Expand Down
2 changes: 1 addition & 1 deletion openbb_terminal/mutual_funds/mutual_fund_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ def call_search(self, other_args: List[str]):
country=self.country,
limit=ns_parser.limit,
sortby=ns_parser.sortby,
ascending=ns_parser.ascending,
ascend=ns_parser.ascending,
)
return self.queue

Expand Down
6 changes: 3 additions & 3 deletions openbb_terminal/mutual_funds/yfinance_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@


@log_start_end(log=logger)
def get_information(fund: str) -> Dict:
def get_information(name: str) -> Dict:
"""Get fund information for fund symbol

Parameters
----------
fund : str
name : str
Symbol of fund

Returns
-------
dict
Dictionary containing fund information
"""
return yf.Ticker(fund).info
return yf.Ticker(name).info
22 changes: 11 additions & 11 deletions openbb_terminal/mutual_funds/yfinance_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,23 @@


@log_start_end(log=logger)
def display_sector(fund: str, min_pct_to_display: float = 5, export: str = ""):
def display_sector(name: str, min_pct_to_display: float = 5, export: str = ""):
"""Display sector weightings for fund

Parameters
----------
fund: str
name: str
Fund symbol
min_pct_to_display: float
Minimum percentage to display sector
export: str
Type of format to export data
"""
sector_weights = yfinance_model.get_information(fund)
sector_weights = yfinance_model.get_information(name)
if "sectorWeightings" not in sector_weights.keys():
console.print(
f"Sector Weights are not found for {fund}. Either the symbol is incorrect or there is an issue "
"in pulling from yahoo.\n"
f"Sector Weights are not found for {name}. Either the symbol is incorrect or there "
"is an issue in pulling from yahoo.\n"
)
return
sector_weights = sector_weights["sectorWeightings"]
Expand All @@ -60,7 +60,7 @@ def display_sector(fund: str, min_pct_to_display: float = 5, export: str = ""):
show_index=True,
index_name="Sector",
headers=["Weight (%)"],
title=f"[bold]{fund.upper()} Sector Weightings[/bold] ",
title=f"[bold]{name.upper()} Sector Weightings[/bold] ",
)

main_holdings = df_weight[df_weight.Weight > min_pct_to_display].to_dict()[
Expand All @@ -80,7 +80,7 @@ def display_sector(fund: str, min_pct_to_display: float = 5, export: str = ""):
labeldistance=1.05,
startangle=90,
)
ax.set_title(f"Sector holdings of {fund.upper()}")
ax.set_title(f"Sector holdings of {name.upper()}")
fig.tight_layout()
if obbff.USE_ION:
plt.ion()
Expand All @@ -89,12 +89,12 @@ def display_sector(fund: str, min_pct_to_display: float = 5, export: str = ""):


@log_start_end(log=logger)
def display_equity(fund: str):
def display_equity(name: str):
"""Display equity holdings for fund

Parameters
----------
fund: str
name: str
Fund symbol
"""
title_map = {
Expand All @@ -112,7 +112,7 @@ def display_equity(fund: str):
"priceToCashflowCat": "Price To Cashflow Cat",
}

equity_hold = yfinance_model.get_information(fund)["equityHoldings"]
equity_hold = yfinance_model.get_information(name)["equityHoldings"]
df_weight = pd.DataFrame.from_dict(equity_hold, orient="index")
df_weight = df_weight.apply(lambda x: round(100 * x, 3))
df_weight.index = df_weight.index.map(title_map)
Expand All @@ -121,5 +121,5 @@ def display_equity(fund: str):
show_index=True,
index_name="Equity",
headers=["Holding"],
title=f"[bold]{fund.upper()} Equity Holdings[/bold] ",
title=f"[bold]{name.upper()} Equity Holdings[/bold] ",
)