Fixes stocks integration tests (#2862)

* fixed integrated test test_stocks_ba.openbb

* fixed integrated test test_stocks_dd.openbb

* improved and centralised the check

* fix lint

* reverted the generalisation and used it localy instead

* fixed typo and removed comments

* replaced 2 if for or condition

Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com>
This commit is contained in:
hjoaquim
2022-10-17 12:36:07 +02:00
committed by GitHub
parent 7c3572daed
commit 467fe6bd0f
3 changed files with 84 additions and 74 deletions

View File

@@ -126,7 +126,7 @@ def get_sentiment(
symbol: str,
n_tweets: int = 15,
n_days_past: int = 2,
):
) -> pd.DataFrame:
"""Get sentiments from symbol
Parameters
@@ -172,7 +172,9 @@ def get_sentiment(
end_date=dt_recent.strftime(dt_format),
)
if temp.empty:
if (isinstance(temp, pd.DataFrame) and temp.empty) or (
not isinstance(temp, pd.DataFrame) and not temp
):
return pd.DataFrame()
df_tweets = pd.concat([df_tweets, temp])

View File

@@ -40,7 +40,9 @@ def display_inference(symbol: str, limit: int = 100, export: str = ""):
"""
df_tweets = twitter_model.load_analyze_tweets(symbol, limit)
if df_tweets.empty:
if (isinstance(df_tweets, pd.DataFrame) and df_tweets.empty) or (
not isinstance(df_tweets, pd.DataFrame) and not df_tweets
):
return
# Parse tweets
@@ -102,84 +104,85 @@ def display_sentiment(
df_tweets = twitter_model.get_sentiment(symbol, n_tweets, n_days_past)
if not df_tweets.empty:
if df_tweets.empty:
return
ax1, ax2, ax3 = None, None, None
ax1, ax2, ax3 = None, None, None
if compare:
# This plot has 3 axes
if external_axes is None:
_, axes = plt.subplots(
3, 1, sharex=False, figsize=plot_autoscale(), dpi=cfg_plot.PLOT_DPI
)
ax1, ax2, ax3 = axes
elif is_valid_axes_count(external_axes, 3):
(ax1, ax2, ax3) = external_axes
else:
return
if compare:
# This plot has 3 axes
if external_axes is None:
_, axes = plt.subplots(
3, 1, sharex=False, figsize=plot_autoscale(), dpi=cfg_plot.PLOT_DPI
)
ax1, ax2, ax3 = axes
elif is_valid_axes_count(external_axes, 3):
(ax1, ax2, ax3) = external_axes
else:
# This plot has 2 axes
if external_axes is None:
_, axes = plt.subplots(
2, 1, sharex=True, figsize=plot_autoscale(), dpi=cfg_plot.PLOT_DPI
)
ax1, ax2 = axes
elif is_valid_axes_count(external_axes, 2):
(ax1, ax2) = external_axes
else:
return
return
else:
# This plot has 2 axes
if external_axes is None:
_, axes = plt.subplots(
2, 1, sharex=True, figsize=plot_autoscale(), dpi=cfg_plot.PLOT_DPI
)
ax1, ax2 = axes
elif is_valid_axes_count(external_axes, 2):
(ax1, ax2) = external_axes
else:
return
ax1.plot(
pd.to_datetime(df_tweets["created_at"]),
df_tweets["cumulative_compound"].values,
)
ax1.set_ylabel("\nCumulative\nVADER Sentiment")
for _, day_df in df_tweets.groupby(by="Day"):
day_df["time"] = pd.to_datetime(day_df["created_at"])
day_df = day_df.sort_values(by="time")
ax1.plot(
pd.to_datetime(df_tweets["created_at"]),
df_tweets["cumulative_compound"].values,
day_df["time"],
day_df["sentiment"].cumsum(),
label=pd.to_datetime(day_df["date"]).iloc[0].strftime("%Y-%m-%d"),
)
ax1.set_ylabel("\nCumulative\nVADER Sentiment")
for _, day_df in df_tweets.groupby(by="Day"):
day_df["time"] = pd.to_datetime(day_df["created_at"])
day_df = day_df.sort_values(by="time")
ax1.plot(
day_df["time"],
day_df["sentiment"].cumsum(),
label=pd.to_datetime(day_df["date"]).iloc[0].strftime("%Y-%m-%d"),
)
ax2.bar(
df_tweets["date"],
df_tweets["positive"],
color=theme.up_color,
width=theme.volume_bar_width / 100,
)
ax2.bar(
df_tweets["date"],
-1 * df_tweets["negative"],
color=theme.down_color,
df_tweets["positive"],
color=theme.up_color,
width=theme.volume_bar_width / 100,
)
ax1.set_title(
f"Twitter's {symbol} total compound sentiment over time is {round(np.sum(df_tweets['sentiment']), 2)}"
)
ax2.bar(
df_tweets["date"],
-1 * df_tweets["negative"],
color=theme.down_color,
width=theme.volume_bar_width / 100,
)
ax1.set_title(
f"Twitter's {symbol} total compound sentiment over time is {round(np.sum(df_tweets['sentiment']), 2)}"
)
theme.style_primary_axis(ax1)
theme.style_primary_axis(ax1)
ax2.set_ylabel("VADER Polarity Scores")
theme.style_primary_axis(ax2)
ax2.set_ylabel("VADER Polarity Scores")
theme.style_primary_axis(ax2)
if compare:
# get stock end price for each corresponding day if compare == True
closing_price_df = get_closing_price(symbol, n_days_past)
if ax3:
ax3.plot(
closing_price_df["Date"],
closing_price_df["Close"],
label=pd.to_datetime(closing_price_df["Date"])
.iloc[0]
.strftime("%Y-%m-%d"),
)
if compare:
# get stock end price for each corresponding day if compare == True
closing_price_df = get_closing_price(symbol, n_days_past)
if ax3:
ax3.plot(
closing_price_df["Date"],
closing_price_df["Close"],
label=pd.to_datetime(closing_price_df["Date"])
.iloc[0]
.strftime("%Y-%m-%d"),
)
ax3.set_ylabel("Stock Price")
theme.style_primary_axis(ax3)
ax3.set_ylabel("Stock Price")
theme.style_primary_axis(ax3)
if external_axes is None:
theme.visualize_output()
if external_axes is None:
theme.visualize_output()
export_data(
export, os.path.dirname(os.path.abspath(__file__)), "sentiment", df_tweets

View File

@@ -3,6 +3,7 @@ __docformat__ = "numpy"
import logging
import os
import pandas as pd
from openbb_terminal.decorators import log_start_end
from openbb_terminal.helper_funcs import export_data, print_rich_table
@@ -34,17 +35,21 @@ def rating(symbol: str, limit: int = 10, export: str = ""):
"""
df = fmp_model.get_rating(symbol)
if (isinstance(df, pd.DataFrame) and df.empty) or (
not isinstance(df, pd.DataFrame) and not df
):
return
# TODO: This could be displayed in a nice rating plot over time
if not df.empty:
df = df.astype(str).applymap(lambda x: add_color(x))
df = df.astype(str).applymap(lambda x: add_color(x))
print_rich_table(
df.head(limit),
headers=df.columns,
show_index=True,
title="Rating",
)
print_rich_table(
df.head(limit),
headers=df.columns,
show_index=True,
title="Rating",
)
export_data(
export,