From 0963cc9ce4ed218ed1e3807da8b96683b9afa91c Mon Sep 17 00:00:00 2001 From: didier Date: Thu, 18 Mar 2021 01:16:08 +0000 Subject: [PATCH] Add Sentiment Analysis from FinBrain --- .../behavioural_analysis/ba_controller.py | 8 + .../behavioural_analysis/finbrain_view.py | 159 ++++++++++++++++++ tests/test_ba_finbrain_api.py | 10 ++ 3 files changed, 177 insertions(+) create mode 100644 gamestonk_terminal/behavioural_analysis/finbrain_view.py create mode 100644 tests/test_ba_finbrain_api.py diff --git a/gamestonk_terminal/behavioural_analysis/ba_controller.py b/gamestonk_terminal/behavioural_analysis/ba_controller.py index 20bb0d1c1a4..6cfd52414a1 100644 --- a/gamestonk_terminal/behavioural_analysis/ba_controller.py +++ b/gamestonk_terminal/behavioural_analysis/ba_controller.py @@ -12,6 +12,7 @@ from gamestonk_terminal.behavioural_analysis import ( google_view, reddit_view, stocktwits_view, + finbrain_view, ) from prompt_toolkit.completion import NestedCompleter @@ -39,6 +40,7 @@ class BehaviouralAnalysisController: "regions", "queries", "rise", + "finbrain", ] def __init__(self, ticker: str, start: datetime): @@ -89,6 +91,8 @@ class BehaviouralAnalysisController: print(" queries top related queries with this stock") print(" rise top rising related queries with stock") print("") + print(" finbrain sentiment from 15+ major news headlines") + print("") def switch(self, an_input: str): """Process and dispatch input @@ -210,6 +214,10 @@ class BehaviouralAnalysisController: twitter_view.sentiment(other_args, self.ticker) + def call_finbrain(self, other_args: List[str]): + """Process finbrain command""" + finbrain_view.sentiment_analysis(other_args, self.ticker) + def menu(ticker: str, start: datetime): """Behavioural Analysis Menu""" diff --git a/gamestonk_terminal/behavioural_analysis/finbrain_view.py b/gamestonk_terminal/behavioural_analysis/finbrain_view.py new file mode 100644 index 00000000000..592b31afa00 --- /dev/null +++ b/gamestonk_terminal/behavioural_analysis/finbrain_view.py @@ -0,0 +1,159 @@ +"""Finbrain View Module""" +__docformat__ = "numpy" + +import argparse +import warnings +import requests +import pandas as pd +from matplotlib import pyplot as plt +from pandas.plotting import register_matplotlib_converters +from datetime import datetime +import numpy as np +from typing import List +from gamestonk_terminal.helper_funcs import ( + parse_known_args_and_warn, + plot_autoscale, + patch_pandas_text_adjustment, +) +from gamestonk_terminal.config_plot import PLOT_DPI +from gamestonk_terminal import feature_flags as gtff +from colorama import Fore, Style + + +register_matplotlib_converters() + + +def sentiment_coloring(val: float, last_val: float) -> str: + if float(val) > last_val: + color = Fore.GREEN + else: + color = Fore.RED + return f"{color}{val}{Style.RESET_ALL}" + + +def get_sentiment(ticker: str) -> pd.DataFrame: + """Gets Sentiment analysis provided by FinBrain's API + + Parameters + ---------- + ticker : str + Ticker to get the sentiment analysis from + + Returns + ------- + DataFrame() + Empty if there was an issue with data retrieval + """ + result = requests.get(f"https://api.finbrain.tech/v0/sentiments/{ticker}") + sentiment = pd.DataFrame() + if result.status_code == 200: + if "sentimentAnalysis" in result.json(): + sentiment = pd.DataFrame.from_dict( + result.json()["sentimentAnalysis"], orient="index" + ) + sentiment.index = pd.to_datetime(sentiment.index).to_pydatetime() + sentiment.index.name = "date" + sentiment.columns = ["Sentiment Analysis"] + else: + print("Unexpected data format from FinBrain API") + else: + print("Request error in retrieving sentiment from FinBrain API") + + return sentiment + + +def plot_sentiment(sentiment: pd.DataFrame, ticker: str): + """Plot Sentiment analysis provided by FinBrain's API + + Parameters + ---------- + sentiment : pd.DataFrame + Dataframe with sentiment data to plot + ticker : str + Ticker to get the sentiment analysis from + """ + plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI) + for index, row in sentiment.iterrows(): + if float(row["Sentiment Analysis"]) >= 0: + plt.scatter(index, float(row["Sentiment Analysis"]), s=100, c="green") + else: + plt.scatter(index, float(row["Sentiment Analysis"]), s=100, c="red") + plt.axhline(y=0, color="k", linestyle="--", lw=2) + plt.xlabel("Time") + plt.ylabel("Sentiment") + plt.grid(b=True, which="major", color="#666666", linestyle="-") + plt.minorticks_on() + plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) + start_date = sentiment.index[0].strftime("%Y/%m/%d") + plt.title(f"FinBrain's Sentiment Analysis For {ticker} since {start_date}") + plt.ylim([-1.1, 1.1]) + senValues = np.array(pd.to_numeric(sentiment["Sentiment Analysis"].values)) + senNone = np.array(0 * len(sentiment)) + plt.fill_between( + sentiment.index, + pd.to_numeric(sentiment["Sentiment Analysis"].values), + 0, + where=(senValues < senNone), + alpha=0.30, + color="red", + interpolate=True, + ) + plt.fill_between( + sentiment.index, + pd.to_numeric(sentiment["Sentiment Analysis"].values), + 0, + where=(senValues >= senNone), + alpha=0.30, + color="green", + interpolate=True, + ) + if gtff.USE_ION: + plt.ion() + plt.show() + + +def sentiment_analysis(other_args: List[str], ticker: str): + """Sentiment analysis from FinBrain + + Parameters + ---------- + other_args : List[str] + Command line arguments to be processed with argparse + ticker : str + Ticker to get the sentiment analysis from + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="finbrain", + description="""FinBrain collects the news headlines from 15+ major financial news + sources on a daily basis and analyzes them to generate sentiment scores + for more than 4500 US stocks. + + [Source: FinBrain Technologies develops deep learning algorithms for + financial analysis and prediction, which currently serves traders from + more than 150 countries all around the world.]""", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + df_sentiment = get_sentiment(ticker) + + if not df_sentiment.empty: + plot_sentiment(df_sentiment, ticker) + + if gtff.USE_COLOR: + print( + df_sentiment["Sentiment Analysis"] + .apply(sentiment_coloring, last_val=0) + .to_string() + ) + else: + print(df_sentiment.to_string()) + print("") + + except Exception as e: + print(e, "\n") + print("") diff --git a/tests/test_ba_finbrain_api.py b/tests/test_ba_finbrain_api.py new file mode 100644 index 00000000000..03893ac0166 --- /dev/null +++ b/tests/test_ba_finbrain_api.py @@ -0,0 +1,10 @@ +""" behavioural_analysis/finbrain_view.py tests """ +import unittest + +# from gamestonk_terminal.behavioural_analysis.finbrain_view import sentiment_analysis + + +class TestBaFinbrainApi(unittest.TestCase): + def test_sentiment_analysis(self): + # sentiment_analysis([], "TSLA") + print("")