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

hotfix/fix-stocks-search-sdk3: Fixes the stocks search so that it doesn't print_rich_table() for SDK. #5329

Merged
merged 6 commits into from
Aug 17, 2023
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
20 changes: 17 additions & 3 deletions openbb_terminal/stocks/stocks_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def call_search(self, other_args: List[str]):
parser,
other_args,
EXPORT_ONLY_RAW_DATA_ALLOWED,
limit=10,
limit=0,
):
# Mapping
sector = stocks_helper.map_parse_choices(self.sector)[ns_parser.sector]
Expand All @@ -263,7 +263,7 @@ def call_search(self, other_args: List[str]):
list(stocks_helper.market_coverage_suffix.keys())
)[ns_parser.exchange_country]

stocks_helper.search(
df = stocks_helper.search(
query=" ".join(ns_parser.query),
country=ns_parser.country,
sector=sector,
Expand All @@ -272,8 +272,22 @@ def call_search(self, other_args: List[str]):
exchange=exchange,
exchange_country=exchange_country,
all_exchanges=ns_parser.all_exchanges,
limit=ns_parser.limit,
)
if ns_parser.export:
export_data(
ns_parser.export,
os.path.dirname(os.path.abspath(__file__)),
"search",
df,
" ".join(ns_parser.sheet_name) if ns_parser.sheet_name else None,
)
if not ns_parser.export:
stocks_helper.print_rich_table(
df,
show_index=False,
headers=df.columns,
title="Stock Search Results",
)

@log_start_end(log=logger)
def call_tob(self, other_args: List[str]):
Expand Down
81 changes: 44 additions & 37 deletions openbb_terminal/stocks/stocks_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,6 @@ def search(
exchange: str = "",
exchange_country: str = "",
all_exchanges: bool = False,
limit: int = 0,
) -> pd.DataFrame:
"""Search selected query for tickers.

Expand All @@ -142,8 +141,6 @@ def search(
Search by exchange country to find stock matching the criteria
all_exchanges: bool
Whether to search all exchanges, without this option only the United States market is searched
limit : int
The limit of results shown, where 0 means all the results

Returns
-------
Expand Down Expand Up @@ -228,43 +225,11 @@ def search(

df = df[["name", "country", "sector", "industry_group", "industry", "exchange"]]
# To automate renaming columns
headers = [col.replace("_", " ") for col in df.columns.tolist()]

title = "Companies found"
if query:
title += f" on term {query}"
if exchange_country and exchange:
title += f" on the exchange {exchange} in {exchange_country.replace('_', ' ').title()}"
if exchange and not exchange_country:
title += f" on the exchange {exchange}"
if exchange_country and not exchange:
title += f" on an exchange in {exchange_country.replace('_', ' ').title()}"
if country:
title += f" in {country.replace('_', ' ').title()}"
if sector:
title += f" within {sector}"
if industry_group:
title += f" and {industry_group}"
if industry:
title += f" and {industry}"
if not sector and industry_group:
title += f" within {industry_group}"
if not sector and industry:
title += f" within {industry}"

df.columns = [col.replace("_", " ") for col in df.columns.tolist()]
df = df.fillna(value=np.nan)
df = df.iloc[df.isnull().sum(axis=1).mul(1).argsort()]

print_rich_table(
df,
show_index=True,
headers=headers,
index_name="Symbol",
title=title,
limit=limit,
)

return df
return df.reset_index()


def load( # pylint: disable=too-many-return-statements
Expand Down Expand Up @@ -1108,3 +1073,45 @@ def heikin_ashi(data: pd.DataFrame) -> pd.DataFrame:
]

return pd.concat([data, ha], axis=1)


def calculate_adjusted_prices(df: pd.DataFrame, column: str, dividends: bool = False):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This helper was committed unintentionally and is part of fixing something unrelated. It can stay or go, but can be used to help fix some issues with the AlphaVantage adjusted prices data.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Id rather it not be in, but it hurts nothing

"""Calculates the split-adjusted prices, or split and dividend adjusted prices.

Parameters
------------
df: pd.DataFrame
DataFrame with unadjusted OHLCV values + Split Factor + Dividend
column: str
The column name to adjust.
dividends: bool
Whether to adjust for both splits and dividends. Default is split-adjusted only.

Returns
--------
pd.DataFrame
DataFrame with adjusted prices.
"""

df = df.copy()
adj_column = "Adj " + column

# Reverse the DataFrame order, sorting by date in descending order
df.sort_index(ascending=False, inplace=True)

price_col = df[column].values
split_col = df["Volume Factor"] if column == "Volume" else df["Split Factor"].values
dividend_col = df["Dividend"].values if dividends else np.zeros(len(price_col))
adj_price_col = np.zeros(len(df.index))
adj_price_col[0] = price_col[0]

for i in range(1, len(price_col)):
adj_price_col[i] = adj_price_col[i - 1] + adj_price_col[i - 1] * (
((price_col[i] * split_col[i - 1]) - price_col[i - 1] - dividend_col[i - 1])
/ price_col[i - 1]
)
df[adj_column] = adj_price_col

# Change the DataFrame order back to dates ascending
df.sort_index(ascending=True, inplace=True)
return df
1 change: 0 additions & 1 deletion tests/openbb_terminal/stocks/test_stocks_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,6 @@ def test_call_func_expect_queue(expected_queue, func, queue):
[],
dict(
query="microsoft",
limit=1,
country="",
sector="",
industry_group="",
Expand Down
6 changes: 4 additions & 2 deletions tests/openbb_terminal/stocks/test_stocks_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def test_search(mocker, use_tab):
target="openbb_terminal.core.session.current_user.__current_user",
new=mock_current_user,
)
stocks_helper.search(
df = stocks_helper.search(
query="microsoft",
country="United_States",
sector="",
Expand All @@ -66,7 +66,9 @@ def test_search(mocker, use_tab):
exchange="",
exchange_country="",
all_exchanges=False,
limit=5,
)
stocks_helper.print_rich_table(
df, show_index=False, title="Company Search Results", headers=df.columns
)


Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
name country sector industry_group industry exchange
symbol
MSFT Microsoft Corporation United States Information Technology Software & Services Software NMS
symbol name country sector industry group industry exchange
0 MSFT Microsoft Corporation United States Information Technology Software & Services Software NMS
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
name country sector industry_group industry exchange
symbol
MSFT Microsoft Corporation United States Information Technology Software & Services Software NMS
symbol name country sector industry group industry exchange
0 MSFT Microsoft Corporation United States Information Technology Software & Services Software NMS