From 876d1aab3e3f4cae0f568b0933970a55052cd295 Mon Sep 17 00:00:00 2001 From: jmaslek Date: Fri, 1 Oct 2021 12:01:00 -0400 Subject: [PATCH] Refactor BA Menu (#768) * Finnhub and finbrain fns * Twitter menu (forex/ba adjusted) * Google menu * Reddit menu pt1 * Reddit commands * Stocktwits commands * Sentimentinvestor commands * Update crypto-dd * Review pt 1 * Hugo server * Review comments - get rid of all prints/errors in model... --- .../behavioural_analysis/finbrain_model.py | 31 + .../behavioural_analysis/finbrain_view.py | 148 +-- .../behavioural_analysis/finnhub_model.py | 28 + .../behavioural_analysis/finnhub_view.py | 103 +- .../behavioural_analysis/google_model.py | 78 ++ .../behavioural_analysis/google_view.py | 279 ++--- .../behavioural_analysis/reddit_helpers.py | 33 + .../behavioural_analysis/reddit_model.py | 500 ++++++++ .../behavioural_analysis/reddit_view.py | 1028 ++++------------- .../sentimentinvestor_model.py | 306 +++++ .../sentimentinvestor_view.py | 753 +++--------- .../behavioural_analysis/stocktwits_model.py | 117 ++ .../behavioural_analysis/stocktwits_view.py | 253 +--- .../behavioural_analysis/twitter_model.py | 93 ++ .../behavioural_analysis/twitter_view.py | 447 +++---- .../due_diligence/finbrain_crypto_view.py | 2 +- .../behavioural_analysis/ba_controller.py | 978 +++++++++++++++- gamestonk_terminal/helper_funcs.py | 116 +- .../behavioural_analysis/ba_controller.py | 952 +++++++++++++-- .../stocks/stocks_controller.py | 17 +- .../behavioural_analysis/bullbear/_index.md | 4 +- .../behavioural_analysis/emerging/_index.md | 26 +- .../behavioural_analysis/getdd/_index.md | 5 +- .../{finbrain => headlines}/_index.md | 2 +- .../behavioural_analysis/historical/_index.md | 4 +- .../behavioural_analysis/metrics/_index.md | 5 +- .../behavioural_analysis/social/_index.md | 5 +- website/data/menu/main.yml | 4 +- 28 files changed, 3774 insertions(+), 2543 deletions(-) create mode 100644 gamestonk_terminal/common/behavioural_analysis/finbrain_model.py create mode 100644 gamestonk_terminal/common/behavioural_analysis/finnhub_model.py create mode 100644 gamestonk_terminal/common/behavioural_analysis/google_model.py create mode 100644 gamestonk_terminal/common/behavioural_analysis/reddit_helpers.py create mode 100644 gamestonk_terminal/common/behavioural_analysis/reddit_model.py create mode 100644 gamestonk_terminal/common/behavioural_analysis/sentimentinvestor_model.py create mode 100644 gamestonk_terminal/common/behavioural_analysis/stocktwits_model.py create mode 100644 gamestonk_terminal/common/behavioural_analysis/twitter_model.py rename website/content/stocks/behavioural_analysis/{finbrain => headlines}/_index.md (97%) diff --git a/gamestonk_terminal/common/behavioural_analysis/finbrain_model.py b/gamestonk_terminal/common/behavioural_analysis/finbrain_model.py new file mode 100644 index 00000000000..7b08659c93d --- /dev/null +++ b/gamestonk_terminal/common/behavioural_analysis/finbrain_model.py @@ -0,0 +1,31 @@ +"""FinBrain Model""" +__docformat__ = "numpy" + +import pandas as pd +import requests + + +def get_sentiment(ticker: str) -> pd.DataFrame: + """Gets Sentiment analysis provided by FinBrain's API [Source: finbrain] + + 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"] + return sentiment diff --git a/gamestonk_terminal/common/behavioural_analysis/finbrain_view.py b/gamestonk_terminal/common/behavioural_analysis/finbrain_view.py index 14004542dd3..1cfb189fa64 100644 --- a/gamestonk_terminal/common/behavioural_analysis/finbrain_view.py +++ b/gamestonk_terminal/common/behavioural_analysis/finbrain_view.py @@ -1,20 +1,16 @@ """FinBrain View Module""" __docformat__ = "numpy" -import argparse -from typing import List -import requests +import os from matplotlib import pyplot as plt import matplotlib.dates as mdates import pandas as pd from pandas.plotting import register_matplotlib_converters import numpy as np from colorama import Fore, Style - -from gamestonk_terminal.helper_funcs import ( - parse_known_args_and_warn, - plot_autoscale, -) +from tabulate import tabulate +from gamestonk_terminal.helper_funcs import plot_autoscale, export_data +from gamestonk_terminal.common.behavioural_analysis import finbrain_model from gamestonk_terminal.config_plot import PLOT_DPI from gamestonk_terminal import feature_flags as gtff @@ -23,44 +19,10 @@ register_matplotlib_converters() def sentiment_coloring(val: float, last_val: float) -> str: - if float(val) > last_val: - color = Fore.GREEN - else: - color = Fore.RED + color = Fore.GREEN if float(val) > last_val else 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 @@ -71,27 +33,29 @@ def plot_sentiment(sentiment: pd.DataFrame, ticker: str): ticker : str Ticker to get the sentiment analysis from """ - plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI) + fig, ax = plt.subplots(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") + ax.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) + ax.scatter(index, float(row["Sentiment Analysis"]), s=100, c="red") + ax.axhline(y=0, color="k", linestyle="--", lw=2) + ax.set_xlabel("Time") + ax.set_ylabel("Sentiment") + ax.grid(b=True, which="major", color="#666666", linestyle="-") + ax.minorticks_on() + ax.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) start_date = sentiment.index[-1].strftime("%Y/%m/%d") - plt.title(f"FinBrain's Sentiment Analysis for {ticker.upper()} since {start_date}") + ax.set_title( + f"FinBrain's Sentiment Analysis for {ticker.upper()} since {start_date}" + ) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y/%m/%d")) plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1)) plt.gcf().autofmt_xdate() - plt.ylim([-1.1, 1.1]) + ax.set_ylim([-1.1, 1.1]) senValues = np.array(pd.to_numeric(sentiment["Sentiment Analysis"].values)) senNone = np.array(0 * len(sentiment)) - plt.fill_between( + ax.fill_between( sentiment.index, pd.to_numeric(sentiment["Sentiment Analysis"].values), 0, @@ -100,7 +64,7 @@ def plot_sentiment(sentiment: pd.DataFrame, ticker: str): color="red", interpolate=True, ) - plt.fill_between( + ax.fill_between( sentiment.index, pd.to_numeric(sentiment["Sentiment Analysis"].values), 0, @@ -111,53 +75,57 @@ def plot_sentiment(sentiment: pd.DataFrame, ticker: str): ) if gtff.USE_ION: plt.ion() + fig.tight_layout() plt.show() -def sentiment_analysis(other_args: List[str], ticker: str): +def display_sentiment_analysis(ticker: str, export: 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 + export : str + Format to export data """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - 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.FinBrain Technologies develops deep learning - algorithms for financial analysis and prediction, which currently serves - traders from more than 150 countries all around the world. - [Source: https://finbrain.tech]""", - ) + df_sentiment = finbrain_model.get_sentiment(ticker) + if df_sentiment.empty: + print("No sentiment data found.\n") + return - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return + plot_sentiment(df_sentiment, ticker) - df_sentiment = get_sentiment(ticker) + df_sentiment.sort_index(ascending=True, inplace=True) - if not df_sentiment.empty: - plot_sentiment(df_sentiment, ticker) - - df_sentiment.sort_index(ascending=True, inplace=True) - - if gtff.USE_COLOR: - print( - df_sentiment["Sentiment Analysis"] - .apply(sentiment_coloring, last_val=0) - .to_string() + if gtff.USE_COLOR: + color_df = df_sentiment["Sentiment Analysis"].apply( + sentiment_coloring, last_val=0 + ) + if gtff.USE_TABULATE_DF: + color_df = pd.DataFrame( + data=color_df.values, + index=pd.to_datetime(df_sentiment.index).strftime("%Y-%m-%d"), ) + print(tabulate(color_df, headers=["Sentiment"], tablefmt="fancy_grid")) + else: + print(color_df.to_string()) + else: + if gtff.USE_TABULATE_DF: + print( + tabulate( + pd.DataFrame( + data=df_sentiment.values, + index=pd.to_datetime(df_sentiment.index).strftime("%Y-%m-%d"), + ), + headers=["Sentiment"], + tablefmt="fancy_grid", + ) + ) + else: print(df_sentiment.to_string()) - print("") - - except Exception as e: - print(e, "\n") - print("") + print("") + export_data( + export, os.path.dirname(os.path.abspath(__file__)), "headlines", df_sentiment + ) diff --git a/gamestonk_terminal/common/behavioural_analysis/finnhub_model.py b/gamestonk_terminal/common/behavioural_analysis/finnhub_model.py new file mode 100644 index 00000000000..95ff851ae52 --- /dev/null +++ b/gamestonk_terminal/common/behavioural_analysis/finnhub_model.py @@ -0,0 +1,28 @@ +"""Finnhub Model""" +__docformat__ = "numpy" + +from typing import Dict +import requests +from gamestonk_terminal import config_terminal as cfg + + +def get_sentiment_stats(ticker: str) -> Dict: + """Get sentiment stats [Source: finnhub] + + Parameters + ---------- + ticker : str + Ticker to get sentiment stats + + Returns + ------- + Dict + Get sentiment stats + """ + response = requests.get( + f"https://finnhub.io/api/v1/news-sentiment?symbol={ticker}&token={cfg.API_FINNHUB_KEY}" + ) + if response.status_code == 200: + return response.json() + + return {} diff --git a/gamestonk_terminal/common/behavioural_analysis/finnhub_view.py b/gamestonk_terminal/common/behavioural_analysis/finnhub_view.py index ab0c42ea933..63e652387f4 100644 --- a/gamestonk_terminal/common/behavioural_analysis/finnhub_view.py +++ b/gamestonk_terminal/common/behavioural_analysis/finnhub_view.py @@ -1,83 +1,50 @@ -import argparse -from typing import List, Dict -import requests -from gamestonk_terminal import config_terminal as cfg -from gamestonk_terminal.helper_funcs import ( - parse_known_args_and_warn, -) +"""Finnhub View""" +__docformat__ = "numpy" + +import os + +import pandas as pd + +from gamestonk_terminal.helper_funcs import export_data +from gamestonk_terminal.common.behavioural_analysis import finnhub_model -def get_sentiment_stats(ticker: str) -> Dict: - """Get sentiment stats - - Parameters - ---------- - ticker : str - Ticker to get sentiment stats - - Returns - ------- - Dict - Get sentiment stats - """ - response = requests.get( - f"https://finnhub.io/api/v1/news-sentiment?symbol={ticker}&token={cfg.API_FINNHUB_KEY}" - ) - if response.status_code == 200: - return response.json() - - return {} - - -def sentiment_stats(other_args: List[str], ticker: str): +def display_sentiment_stats(ticker: str, export: str = ""): """ Sentiment stats which displays buzz, news score, articles last week, articles weekly average, bullish vs bearish percentages, sector average bullish percentage, and sector average news score Parameters ---------- - other_args : List[str] - Command line arguments to be processed with argparse ticker : str Ticker to get sentiment stats + export : str + Format to export data """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="stats", - description=""" - Sentiment stats which displays buzz, news score, articles last week, articles weekly average, - bullish vs bearish percentages, sector average bullish percentage, and sector average news score. - [Source: https://finnhub.io] - """, - ) + d_stats = finnhub_model.get_sentiment_stats(ticker) - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return + if d_stats: + print( + f""" +Buzz: {round(100*d_stats['buzz']['buzz'],2)} % +News Score: {round(100*d_stats['companyNewsScore'],2)} % - d_stats = get_sentiment_stats(ticker) +Articles Last Week: {d_stats['buzz']['articlesInLastWeek']} +Articles Weekly Average: {d_stats['buzz']['weeklyAverage']} - if d_stats: - print(f"Buzz: {round(100*d_stats['buzz']['buzz'],2)} %") - print(f"News Score: {round(100*d_stats['companyNewsScore'],2)} %") - print("") - print(f"Articles Last Week: {d_stats['buzz']['articlesInLastWeek']}") - print(f"Articles Weekly Average: {d_stats['buzz']['weeklyAverage']}") - print("") - print(f"Bullish: {round(100*d_stats['sentiment']['bullishPercent'],2)} %") - print(f"Bearish: {round(100*d_stats['sentiment']['bearishPercent'],2)} %") - print("") - print( - f"Sector Average Bullish: {round(100*d_stats['sectorAverageBullishPercent'],2)} %" - ) - print( - f"Sector Average News Score: {round(100*d_stats['sectorAverageNewsScore'],2)} %" - ) - else: - print("No sentiment stats found.") - print("") +Bullish: {round(100*d_stats['sentiment']['bullishPercent'],2)} % +Bearish: {round(100*d_stats['sentiment']['bearishPercent'],2)} % - except Exception as e: - print(e, "\n") +Sector Average Bullish: {round(100*d_stats['sectorAverageBullishPercent'],2)} +Sector Average News Score: {round(100*d_stats['sectorAverageNewsScore'],2)} %""" + ) + export_data( + export, + os.path.dirname(os.path.abspath(__file__)), + "stats", + pd.DataFrame(d_stats), + ) + + else: + print("No sentiment stats found.") + print("") diff --git a/gamestonk_terminal/common/behavioural_analysis/google_model.py b/gamestonk_terminal/common/behavioural_analysis/google_model.py new file mode 100644 index 00000000000..407892fc865 --- /dev/null +++ b/gamestonk_terminal/common/behavioural_analysis/google_model.py @@ -0,0 +1,78 @@ +"""Google Model""" +__docformat__ = "numpy" + +import pandas as pd +from pytrends.request import TrendReq + + +def get_mentions(ticker: str) -> pd.DataFrame: + """Get interest over time from google api [Source: google] + + Parameters + ---------- + ticker : str + Stock ticker + + Returns + ------- + pd.DataFrame + Dataframe of interest over time + """ + pytrend = TrendReq() + pytrend.build_payload(kw_list=[ticker]) + return pytrend.interest_over_time() + + +def get_regions(ticker: str) -> pd.DataFrame: + """Get interest by region from google api [Source: google] + + Parameters + ---------- + ticker : str + Ticker to look at + + Returns + ------- + pd.DataFrame + Dataframe of interest by region + """ + pytrend = TrendReq() + pytrend.build_payload(kw_list=[ticker]) + return pytrend.interest_by_region() + + +def get_queries(ticker: str) -> pd.DataFrame: + """Get related queries from google api [Source: google] + + Parameters + ---------- + ticker : str + Stock ticker to compare + + Returns + ------- + pd.DataFrame + Dataframe of related queries + """ + pytrend = TrendReq() + pytrend.build_payload(kw_list=[ticker]) + return pytrend.related_queries() + + +def get_rise(ticker: str) -> pd.DataFrame: + """Get top rising related queries with this stock's query [Source: google] + + Parameters + ---------- + ticker : str + Stock ticker + + Returns + ------- + pd.DataFrame + Dataframe containing rising related queries + """ + pytrend = TrendReq() + pytrend.build_payload(kw_list=[ticker]) + df_related_queries = pytrend.related_queries() + return df_related_queries[ticker]["rising"] diff --git a/gamestonk_terminal/common/behavioural_analysis/google_view.py b/gamestonk_terminal/common/behavioural_analysis/google_view.py index 74f198a221e..f6df2b24405 100644 --- a/gamestonk_terminal/common/behavioural_analysis/google_view.py +++ b/gamestonk_terminal/common/behavioural_analysis/google_view.py @@ -1,217 +1,160 @@ -import argparse -from typing import List +"""Google View""" +__docformat__ = "numpy" + +import os from datetime import datetime -from pytrends.request import TrendReq + +from tabulate import tabulate import matplotlib.pyplot as plt -from gamestonk_terminal.helper_funcs import ( - check_positive, - valid_date, - parse_known_args_and_warn, -) + +from gamestonk_terminal.helper_funcs import plot_autoscale, export_data +from gamestonk_terminal.common.behavioural_analysis import google_model +from gamestonk_terminal import config_plot as cfp, feature_flags as gtff -def mentions(other_args: List[str], ticker: str, start: datetime): +def display_mentions(ticker: str, start: datetime, export: str = ""): """Plot weekly bars of stock's interest over time. other users watchlist. [Source: Google] Parameters ---------- - other_args : List[str] - Command line arguments to be processed with argparse ticker : str Ticker - start : str + start : datetime Start date + export: str + Format to export data """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="mentions", - description=""" - Plot weekly bars of stock's interest over time. other users watchlist. [Source: Google] - """, - ) - parser.add_argument( - "-s", - "--start", - type=valid_date, - dest="start", - default=start, - help="starting date (format YYYY-MM-DD) from when we are interested in stock's mentions.", + df_interest = google_model.get_mentions(ticker) + + fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfp.PLOT_DPI) + ax.set_title(f"Interest over time on {ticker}") + if start: + df_interest = df_interest[start:] # type: ignore + ax.bar(df_interest.index, df_interest[ticker], width=2) + ax.bar( + df_interest.index[-1], + df_interest[ticker].values[-1], + color="tab:orange", + width=2, + ) + else: + ax.bar(df_interest.index, df_interest[ticker], width=1) + ax.bar( + df_interest.index[-1], + df_interest[ticker].values[-1], + color="tab:orange", + width=1, + ) + + ax.grid(b=True, which="major", color="#666666", linestyle="-") + ax.set_ylabel("Interest [%]") + ax.set_xlabel("Time") + + if gtff.USE_ION: + plt.ion() + fig.tight_layout() + plt.show() + print("") + export_data( + export, os.path.dirname(os.path.abspath(__file__)), "mentions", df_interest ) - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - pytrend = TrendReq() - pytrend.build_payload(kw_list=[ticker]) - df_interest = pytrend.interest_over_time() - - plt.title(f"Interest over time on {ticker}") - if ns_parser.start: - df_interest = df_interest[ns_parser.start :] - plt.bar(df_interest.index, df_interest[ticker], width=2) - plt.bar( - df_interest.index[-1], - df_interest[ticker].values[-1], - color="tab:orange", - width=2, - ) - else: - plt.bar(df_interest.index, df_interest[ticker], width=1) - plt.bar( - df_interest.index[-1], - df_interest[ticker].values[-1], - color="tab:orange", - width=1, - ) - - plt.grid(b=True, which="major", color="#666666", linestyle="-") - plt.ylabel("Interest [%]") - plt.xlabel("Time") - plt.show() - print("") - - except Exception as e: - print(e, "\n") - - -def regions(other_args: List[str], ticker: str): +def display_regions(ticker: str, num: int = 5, export: str = ""): """Plot bars of regions based on stock's interest. [Source: Google] Parameters ---------- - other_args : List[str] - Command line arguments to be processed with argparse ticker : str Ticker + num: int + Number of regions to show + export: str + Format to export data """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="regions", - description="""Plot bars of regions based on stock's interest. [Source: Google]""", - ) - parser.add_argument( - "-n", - "--num", - action="store", - dest="n_num", - type=check_positive, - default=10, - help="number of regions to plot that show highest interest.", - ) - - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - pytrend = TrendReq() - pytrend.build_payload(kw_list=[ticker]) - df_interest_region = pytrend.interest_by_region() + df_interest_region = google_model.get_regions(ticker) + if not df_interest_region.empty: df_interest_region = df_interest_region.sort_values( [ticker], ascending=False - ).head(ns_parser.n_num) - - plt.figure(figsize=(25, 5)) - plt.title(f"Top's regions interest on {ticker}") - plt.bar(df_interest_region.index, df_interest_region[ticker], width=0.8) - plt.grid(b=True, which="major", color="#666666", linestyle="-") - plt.ylabel("Interest [%]") - plt.xlabel("Region") + ).head(num) + df = df_interest_region.copy() + fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfp.PLOT_DPI) + ax.set_title(f"Top's regions interest on {ticker}") + ax.bar(df_interest_region.index, df_interest_region[ticker], width=0.8) + ax.grid(b=True, which="major", color="#666666", linestyle="-") + ax.set_ylabel("Interest [%]") + ax.set_xlabel("Region") + if gtff.USE_ION: + plt.ion() + fig.tight_layout() plt.show() - print("") - - except Exception as e: - print(e, "\n") + else: + print("No region data found.") + print("") + export_data(export, os.path.dirname(os.path.abspath(__file__)), "regions", df) -def queries(other_args: List[str], ticker: str): +def display_queries(ticker: str, num: int = 5, export: str = ""): """Print top related queries with this stock's query. [Source: Google] Parameters ---------- - other_args : List[str] - Command line arguments to be processed with argparse ticker : str Ticker + num: int + Number of regions to show + export: str + Format to export data """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="queries", - description="""Print top related queries with this stock's query. [Source: Google]""", - ) - parser.add_argument( - "-n", - "--num", - action="store", - dest="n_num", - type=check_positive, - default=10, - help="number of top related queries to print.", - ) - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - pytrend = TrendReq() - pytrend.build_payload(kw_list=[ticker]) - df_related_queries = pytrend.related_queries() - df_related_queries = df_related_queries[ticker]["top"].head(ns_parser.n_num) - df_related_queries["value"] = df_related_queries["value"].apply( - lambda x: str(x) + "%" + df_related_queries = google_model.get_queries(ticker) + df = df_related_queries.copy() + df_related_queries = df_related_queries[ticker]["top"].head(num) + df_related_queries["value"] = df_related_queries["value"].apply( + lambda x: str(x) + "%" + ) + print(f"Top {ticker}'s related queries") + if gtff.USE_TABULATE_DF: + print( + tabulate( + df_related_queries, + headers=df_related_queries.columns, + tablefmt="fancy_grid", + ) ) - print(f"Top {ticker}'s related queries") + else: print(df_related_queries.to_string(index=False)) - print("") - - except Exception as e: - print(e, "\n") + print("") + export_data(export, os.path.dirname(os.path.abspath(__file__)), "queries", df) -def rise(other_args: List[str], ticker: str): +def display_rise(ticker: str, num: int, export: str = ""): """Print top rising related queries with this stock's query. [Source: Google] Parameters ---------- - other_args : List[str] - Command line arguments to be processed with argparse ticker : str Ticker + num: int + Number of regions to show + export: str + Format to export data """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="rise", - description="""Print top rising related queries with this stock's query. [Source: Google]""", - ) - parser.add_argument( - "-n", - "--num", - action="store", - dest="n_num", - type=check_positive, - default=10, - help="number of top rising related queries to print.", - ) + df_related_queries = google_model.get_rise(ticker) + df = df_related_queries.copy() + df_related_queries = df_related_queries.head(num) - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return + print(f"Top rising {ticker}'s related queries") - pytrend = TrendReq() - pytrend.build_payload(kw_list=[ticker]) - df_related_queries = pytrend.related_queries() - df_related_queries = df_related_queries[ticker]["rising"].head(ns_parser.n_num) - print(f"Top rising {ticker}'s related queries") + if gtff.USE_TABULATE_DF: + print( + tabulate( + df_related_queries, + headers=df_related_queries.columns, + tablefmt="fancy_grid", + ) + ) + else: print(df_related_queries.to_string(index=False)) - print("") - - except Exception as e: - print(e, "\n") + print("") + export_data(export, os.path.dirname(os.path.abspath(__file__)), "rise", df) diff --git a/gamestonk_terminal/common/behavioural_analysis/reddit_helpers.py b/gamestonk_terminal/common/behavioural_analysis/reddit_helpers.py new file mode 100644 index 00000000000..f2c03221cc0 --- /dev/null +++ b/gamestonk_terminal/common/behavioural_analysis/reddit_helpers.py @@ -0,0 +1,33 @@ +"""Reddit Helpers""" +__docformat__ = "numpy" + +from typing import List +import re + +import praw + + +def find_tickers(submission: praw.models.reddit.submission.Submission) -> List[str]: + """Extracts potential tickers from reddit submission + + Parameters + ---------- + submission : praw.models.reddit.submission.Submission + Reddit post to scan + + Returns + ------- + List[str] + List of potential tickers + """ + ls_text = [submission.selftext, submission.title] + submission.comments.replace_more(limit=0) + for comment in submission.comments.list(): + ls_text.append(comment.body) + + l_tickers_found = [] + for s_text in ls_text: + for s_ticker in set(re.findall(r"([A-Z]{3,5} )", s_text)): + l_tickers_found.append(s_ticker.strip()) + + return l_tickers_found diff --git a/gamestonk_terminal/common/behavioural_analysis/reddit_model.py b/gamestonk_terminal/common/behavioural_analysis/reddit_model.py new file mode 100644 index 00000000000..f01a95c820b --- /dev/null +++ b/gamestonk_terminal/common/behavioural_analysis/reddit_model.py @@ -0,0 +1,500 @@ +"""Reddit Model""" +__docformat__ = "numpy" + +from typing import List, Dict, Tuple +from datetime import datetime, timedelta +import pandas as pd +from prawcore.exceptions import ResponseException +from requests import HTTPError +from psaw import PushshiftAPI +import praw +import finviz +from gamestonk_terminal import config_terminal as cfg + +from gamestonk_terminal.common.behavioural_analysis.reddit_helpers import find_tickers + +l_sub_reddits = [ + "Superstonk", + "pennystocks", + "RobinHoodPennyStocks", + "Daytrading", + "StockMarket", + "stocks", + "investing", + "wallstreetbets", +] + +# pylint:disable=inconsistent-return-statements + + +def get_watchlists( + n_to_get: int, +) -> Tuple[List[praw.models.reddit.submission.Submission], Dict, int]: + """Get reddit users watchlists [Source: reddit] + + Parameters + ---------- + n_to_get : int + Number of posts to look through + + Returns + ------- + List[praw.models.reddit.submission.Submission]: + List of reddit submissions + Dict: + Dictionary of tickers and counts + int + Count of how many posts were analyzed + """ + d_watchlist_tickers: Dict = {} + l_watchlist_author = [] + subs = [] + + praw_api = praw.Reddit( + client_id=cfg.API_REDDIT_CLIENT_ID, + client_secret=cfg.API_REDDIT_CLIENT_SECRET, + username=cfg.API_REDDIT_USERNAME, + user_agent=cfg.API_REDDIT_USER_AGENT, + password=cfg.API_REDDIT_PASSWORD, + ) + psaw_api = PushshiftAPI() + submissions = psaw_api.search_submissions( + subreddit=l_sub_reddits, + q="WATCHLIST|Watchlist|watchlist", + filter=["id"], + ) + n_flair_posts_found = 0 + for sub in submissions: + submission = praw_api.submission(id=sub.id) + if ( + not submission.removed_by_category + and submission.selftext + and submission.link_flair_text not in ["Yolo", "Meme"] + and submission.author.name not in l_watchlist_author + ): + l_tickers_found = find_tickers(submission) + + if l_tickers_found: + # Add another author's name to the parsed watchlists + l_watchlist_author.append(submission.author.name) + + # Lookup stock tickers within a watchlist + for key in l_tickers_found: + if key in d_watchlist_tickers: + # Increment stock ticker found + d_watchlist_tickers[key] += 1 + else: + # Initialize stock ticker found + d_watchlist_tickers[key] = 1 + + # Increment count of valid posts found + n_flair_posts_found += 1 + subs.append(submission) + if n_flair_posts_found > n_to_get - 1: + break + return subs, d_watchlist_tickers, n_flair_posts_found + + +def get_popular_tickers( + n_top: int, posts_to_look_at: int, subreddits: str = "" +) -> pd.DataFrame: + """Get popular tickers from list of subreddits [Source: reddit] + + Parameters + ---------- + n_top : int + Number of top tickers to get + posts_to_look_at : int + How many posts to analyze in each subreddit + subreddits : str, optional + String of comma separated subreddits. + + Returns + ------- + pd.DataFrame + DataFrame of top tickers from supplied subreddits + """ + if subreddits: + sub_reddit_list = subreddits.split(",") if "," in subreddits else [subreddits] + else: + sub_reddit_list = l_sub_reddits + d_watchlist_tickers: Dict = {} + l_watchlist_author = [] + + praw_api = praw.Reddit( + client_id=cfg.API_REDDIT_CLIENT_ID, + client_secret=cfg.API_REDDIT_CLIENT_SECRET, + username=cfg.API_REDDIT_USERNAME, + user_agent=cfg.API_REDDIT_USER_AGENT, + password=cfg.API_REDDIT_PASSWORD, + ) + + psaw_api = PushshiftAPI() + for s_sub_reddit in sub_reddit_list: + print( + f"Search for latest tickers for {posts_to_look_at} '{s_sub_reddit}' posts" + ) + submissions = psaw_api.search_submissions( + subreddit=s_sub_reddit, + limit=posts_to_look_at, + filter=["id"], + ) + + n_tickers = 0 + for submission in submissions: + try: + # Get more information about post using PRAW api + submission = praw_api.submission(id=submission.id) + + # Ensure that the post hasn't been removed by moderator in the meanwhile, + # that there is a description and it's not just an image, that the flair is + # meaningful, and that we aren't re-considering same author's content + if ( + not submission.removed_by_category + and (submission.selftext or submission.title) + and submission.author.name not in l_watchlist_author + ): + l_tickers_found = find_tickers(submission) + + if l_tickers_found: + n_tickers += len(l_tickers_found) + + # Add another author's name to the parsed watchlists + l_watchlist_author.append(submission.author.name) + + # Lookup stock tickers within a watchlist + for key in l_tickers_found: + if key in d_watchlist_tickers: + # Increment stock ticker found + d_watchlist_tickers[key] += 1 + else: + # Initialize stock ticker found + d_watchlist_tickers[key] = 1 + + except ResponseException: + print( + "Received a response from Reddit with an authorization error. check your token.\n" + ) + return pd.DataFrame() + + print(f" {n_tickers} potential tickers found.") + lt_watchlist_sorted = sorted( + d_watchlist_tickers.items(), key=lambda item: item[1], reverse=True + ) + + if lt_watchlist_sorted: + n_top_stocks = 0 + # pylint: disable=redefined-outer-name + popular_tickers = [] + for t_ticker in lt_watchlist_sorted: + if n_top_stocks > n_top: + break + try: + # If try doesn't trigger exception, it means that this stock exists on finviz + # thus we can print it. + stock_info = finviz.get_stock(t_ticker[0]) + popular_tickers.append( + ( + t_ticker[1], + t_ticker[0], + stock_info["Company"], + stock_info["Sector"], + stock_info["Price"], + stock_info["Change"], + stock_info["Perf Month"], + f"https://finviz.com/quote.ashx?t={t_ticker[0]}", + ) + ) + n_top_stocks += 1 + except HTTPError as e: + if e.response.status_code != 404: + print(f"Unexpected exception from Finviz: {e}") + except Exception as e: + print(e, "\n") + return + + popular_tickers_df = pd.DataFrame( + popular_tickers, + columns=[ + "Mentions", + "Ticker", + "Company", + "Sector", + "Price", + "Change", + "Perf Month", + "URL", + ], + ) + return popular_tickers_df + + +def get_spac_community( + limit: int, popular: bool +) -> Tuple[List[praw.models.reddit.submission.Submission], Dict]: + """Get top tickers from r/SPACs [Source: reddit] + + Parameters + ---------- + limit : int + Number of posts to look at + popular : bool + Search by hot instead of new + + Returns + ------- + List[praw.models.reddit.submission.Submission]: + List of reddit submission + Dict: + Dictionary of tickers and number of mentions + """ + praw_api = praw.Reddit( + client_id=cfg.API_REDDIT_CLIENT_ID, + client_secret=cfg.API_REDDIT_CLIENT_SECRET, + username=cfg.API_REDDIT_USERNAME, + user_agent=cfg.API_REDDIT_USER_AGENT, + password=cfg.API_REDDIT_PASSWORD, + ) + + d_watchlist_tickers: Dict = {} + l_watchlist_author = [] + + if popular: + submissions = praw_api.subreddit("SPACs").hot(limit=limit) + else: + submissions = praw_api.subreddit("SPACs").new(limit=limit) + + subs = [] + for sub in submissions: + if not sub: + break + + # Get more information about post using PRAW api + submission = praw_api.submission(id=sub.id) + + # Ensure that the post hasn't been removed by moderator in the meanwhile, + # that there is a description and it's not just an image, that the flair is + # meaningful, and that we aren't re-considering same author's watchlist + if ( + not submission.removed_by_category + and submission.selftext + and submission.link_flair_text not in ["Yolo", "Meme"] + and submission.author.name not in l_watchlist_author + ): + l_tickers_found = find_tickers(submission) + + if l_tickers_found: + # Add another author's name to the parsed watchlists + l_watchlist_author.append(submission.author.name) + subs.append(submission) + # Lookup stock tickers within a watchlist + for key in l_tickers_found: + if key in d_watchlist_tickers: + # Increment stock ticker found + d_watchlist_tickers[key] += 1 + else: + # Initialize stock ticker found + d_watchlist_tickers[key] = 1 + return subs, d_watchlist_tickers + + +def get_spac( + limit: int = 5, +) -> Tuple[List[praw.models.reddit.submission.Submission], Dict, int]: + """Get posts containing SPAC from top subreddits [Source: reddit] + + Parameters + ---------- + limit : int, optional + Number of posts to get for each subreddit, by default 5 + + Returns + ------- + List[praw.models.reddit.submission.Submission] : + List of reddit submissions + Dict : + Dictionary of tickers and counts + int : + Number of posts found. + """ + praw_api = praw.Reddit( + client_id=cfg.API_REDDIT_CLIENT_ID, + client_secret=cfg.API_REDDIT_CLIENT_SECRET, + username=cfg.API_REDDIT_USERNAME, + user_agent=cfg.API_REDDIT_USER_AGENT, + password=cfg.API_REDDIT_PASSWORD, + ) + + d_watchlist_tickers: Dict = {} + l_watchlist_author = [] + subs = [] + psaw_api = PushshiftAPI() + submissions = psaw_api.search_submissions( + subreddit=l_sub_reddits, + q="SPAC|Spac|spac|Spacs|spacs", + filter=["id"], + ) + n_flair_posts_found = 0 + for submission in submissions: + + # Get more information about post using PRAW api + submission = praw_api.submission(id=submission.id) + + # Ensure that the post hasn't been removed by moderator in the meanwhile, + # that there is a description and it's not just an image, that the flair is + # meaningful, and that we aren't re-considering same author's watchlist + if ( + not submission.removed_by_category + and submission.selftext + and submission.link_flair_text not in ["Yolo", "Meme"] + and submission.author.name not in l_watchlist_author + ): + l_tickers_found = find_tickers(submission) + subs.append(submission) + if l_tickers_found: + # Add another author's name to the parsed watchlists + l_watchlist_author.append(submission.author.name) + + # Lookup stock tickers within a watchlist + for key in l_tickers_found: + if key in d_watchlist_tickers: + # Increment stock ticker found + d_watchlist_tickers[key] += 1 + else: + # Initialize stock ticker found + d_watchlist_tickers[key] = 1 + + # Increment count of valid posts found + n_flair_posts_found += 1 + + # Check if number of wanted posts found has been reached + if n_flair_posts_found > limit - 1: + break + + return subs, d_watchlist_tickers, n_flair_posts_found + + +def get_wsb_community( + limit: int = 10, new: bool = False +) -> List[praw.models.reddit.submission.Submission]: + """Get wsb posts [Source: reddit] + + Parameters + ---------- + limit : int, optional + Number of posts to get, by default 10 + new : bool, optional + Flag to sort by new instead of hot, by default False + + Returns + ------- + List[praw.models.reddit.submission.Submission] + List of reddit submissions + """ + praw_api = praw.Reddit( + client_id=cfg.API_REDDIT_CLIENT_ID, + client_secret=cfg.API_REDDIT_CLIENT_SECRET, + username=cfg.API_REDDIT_USERNAME, + user_agent=cfg.API_REDDIT_USER_AGENT, + password=cfg.API_REDDIT_PASSWORD, + ) + + if new: + submissions = praw_api.subreddit("wallstreetbets").new(limit=limit) + else: + submissions = praw_api.subreddit("wallstreetbets").hot(limit=limit) + + subs = [] + for submission in submissions: + submission = praw_api.submission(id=submission.id) + # Ensure that the post hasn't been removed by moderator in the meanwhile, + # that there is a description and it's not just an image, that the flair is + # meaningful, and that we aren't re-considering same author's watchlist + if not submission.removed_by_category: + subs.append(submission) + return subs + + +def get_due_dilligence( + ticker: str, limit: int = 5, n_days: int = 3, show_all_flairs: bool = False +) -> List[praw.models.reddit.submission.Submission]: + """Gets due dilligence posts from list of subreddits [Source: reddit] + + Parameters + ---------- + ticker: str + Stock ticker + limit: int + Number of posts to get + n_days: int + Number of days back to get posts + show_all_flairs: bool + Search through all flairs (apart from Yolo and Meme) + + Returns + ------- + List[praw.models.reddit.submission.Submission] + List of submissions + """ + praw_api = praw.Reddit( + client_id=cfg.API_REDDIT_CLIENT_ID, + client_secret=cfg.API_REDDIT_CLIENT_SECRET, + username=cfg.API_REDDIT_USERNAME, + user_agent=cfg.API_REDDIT_USER_AGENT, + password=cfg.API_REDDIT_PASSWORD, + ) + + psaw_api = PushshiftAPI() + + n_ts_after = int((datetime.today() - timedelta(days=n_days)).timestamp()) + l_flair_text = [ + "DD", + "technical analysis", + "Catalyst", + "News", + "Advice", + "Chart", + "Charts and Setups", + "Fundamental Analysis", + "forex", + "Trade Idea", + ] + l_sub_reddits_dd = [ + "pennystocks", + "RobinHoodPennyStocks", + "Daytrading", + "StockMarket", + "stocks", + "investing", + "wallstreetbets", + "forex", + "Forexstrategy", + ] + + submissions = psaw_api.search_submissions( + after=int(n_ts_after), subreddit=l_sub_reddits_dd, q=ticker, filter=["id"] + ) + n_flair_posts_found = 0 + subs = [] + for submission in submissions: + # Get more information about post using PRAW api + submission = praw_api.submission(id=submission.id) + + # Ensure that the post hasn't been removed in the meanwhile + if not submission.removed_by_category: + + # Either just filter out Yolo, and Meme flairs, or focus on DD, based on b_DD flag + if ( + submission.link_flair_text in l_flair_text, + submission.link_flair_text not in ["Yolo", "Meme"], + )[show_all_flairs]: + + subs.append(submission) + # Increment count of valid posts found + n_flair_posts_found += 1 + + # Check if number of wanted posts found has been reached + if n_flair_posts_found > limit - 1: + break + + return subs diff --git a/gamestonk_terminal/common/behavioural_analysis/reddit_view.py b/gamestonk_terminal/common/behavioural_analysis/reddit_view.py index 15ae0eeb846..a99696c51e4 100644 --- a/gamestonk_terminal/common/behavioural_analysis/reddit_view.py +++ b/gamestonk_terminal/common/behavioural_analysis/reddit_view.py @@ -1,877 +1,267 @@ -import argparse +"""Reddit View""" +__docformat__ = "numpy" + +import os import warnings -from typing import List, Dict -from datetime import datetime, timedelta -import pandas as pd -from prawcore.exceptions import ResponseException -from requests import HTTPError -from psaw import PushshiftAPI -import praw +from datetime import datetime +from typing import Dict + import finviz -from gamestonk_terminal.helper_funcs import check_positive, parse_known_args_and_warn -from gamestonk_terminal import config_terminal as cfg -from gamestonk_terminal.helper_funcs import ( - print_and_record_reddit_post, - find_tickers, -) +import praw +from prettytable import PrettyTable +from tabulate import tabulate + +from gamestonk_terminal import feature_flags as gtff +from gamestonk_terminal.common.behavioural_analysis import reddit_model +from gamestonk_terminal.helper_funcs import export_data -def watchlist(other_args: List[str]): +def print_and_record_reddit_post( + submissions_dict: Dict, submission: praw.models.reddit.submission.Submission +): + """Prints reddit submission + + Parameters + ---------- + submissions_dict : Dict + Dictionary for storing reddit post information + submission : praw.models.reddit.submission.Submission + Submission to show + """ + # Refactor data + s_datetime = datetime.utcfromtimestamp(submission.created_utc).strftime( + "%d/%m/%Y %H:%M:%S" + ) + s_link = f"https://old.reddit.com{submission.permalink}" + s_all_awards = "".join( + f"{award['count']} {award['name']}\n" for award in submission.all_awardings + ) + + s_all_awards = s_all_awards[:-2] + # Create dictionary with data to construct dataframe allows to save data + submissions_dict[submission.id] = { + "created_utc": s_datetime, + "subreddit": submission.subreddit, + "link_flair_text": submission.link_flair_text, + "title": submission.title, + "score": submission.score, + "link": s_link, + "num_comments": submission.num_comments, + "upvote_ratio": submission.upvote_ratio, + "awards": s_all_awards, + } + # Print post data collected so far + print(f"{s_datetime} - {submission.title}") + print(f"{s_link}") + t_post = PrettyTable( + ["Subreddit", "Flair", "Score", "# Comments", "Upvote %", "Awards"] + ) + t_post.add_row( + [ + submission.subreddit, + submission.link_flair_text, + submission.score, + submission.num_comments, + f"{round(100 * submission.upvote_ratio)}%", + s_all_awards, + ] + ) + print(t_post) + print("\n") + + +def display_watchlist(num: int): """Print other users watchlist. [Source: Reddit] Parameters ---------- - other_args: List[str] - Arguments for argparse + num: int + Maximum number of submissions to look at """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="watchlist", - description="""Print other users watchlist. [Source: Reddit]""", - ) - parser.add_argument( - "-l", - "--limit", - action="store", - dest="n_limit", - type=check_positive, - default=5, - help="limit of posts with watchlists retrieved.", - ) - - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - l_sub_reddits = [ - "Superstonk", - "pennystocks", - "RobinHoodPennyStocks", - "Daytrading", - "StockMarket", - "stocks", - "investing", - "wallstreetbets", - ] - - d_submission: Dict = {} - d_watchlist_tickers: Dict = {} - l_watchlist_links = [] - l_watchlist_author = [] - - praw_api = praw.Reddit( - client_id=cfg.API_REDDIT_CLIENT_ID, - client_secret=cfg.API_REDDIT_CLIENT_SECRET, - username=cfg.API_REDDIT_USERNAME, - user_agent=cfg.API_REDDIT_USER_AGENT, - password=cfg.API_REDDIT_PASSWORD, + subs, d_watchlist_tickers, n_flair_posts_found = reddit_model.get_watchlists(num) + for sub in subs: + print_and_record_reddit_post({}, sub) + if n_flair_posts_found > 0: + lt_watchlist_sorted = sorted( + d_watchlist_tickers.items(), key=lambda item: item[1], reverse=True ) - - # dt_last_time_market_close = get_last_time_market_was_open( - # datetime.now() - timedelta(hours=24) - # ) - # n_ts_after = int(dt_last_time_market_close.timestamp()) - psaw_api = PushshiftAPI() - submissions = psaw_api.search_submissions( - # after=n_ts_after, - subreddit=l_sub_reddits, - q="WATCHLIST|Watchlist|watchlist", - filter=["id"], - ) - - n_flair_posts_found = 0 - while True: + s_watchlist_tickers = "" + n_tickers = 0 + for t_ticker in lt_watchlist_sorted: try: - submission = next(submissions, None) - - # Check if search_submissions didn't get anymore posts - if not submission: - break - - # Get more information about post using PRAW api - submission = praw_api.submission(id=submission.id) - - # Ensure that the post hasn't been removed by moderator in the meanwhile, - # that there is a description and it's not just an image, that the flair is - # meaningful, and that we aren't re-considering same author's watchlist - if ( - not submission.removed_by_category - and submission.selftext - and submission.link_flair_text not in ["Yolo", "Meme"] - and submission.author.name not in l_watchlist_author - ): - l_tickers_found = find_tickers(submission) - - if l_tickers_found: - # Add another author's name to the parsed watchlists - l_watchlist_author.append(submission.author.name) - - # Lookup stock tickers within a watchlist - for key in l_tickers_found: - if key in d_watchlist_tickers: - # Increment stock ticker found - d_watchlist_tickers[key] += 1 - else: - # Initialize stock ticker found - d_watchlist_tickers[key] = 1 - - l_watchlist_links.append( - f"https://old.reddit.com{submission.permalink}" - ) - - print_and_record_reddit_post(d_submission, submission) - - # Increment count of valid posts found - n_flair_posts_found += 1 - - # Check if number of wanted posts found has been reached - if n_flair_posts_found > ns_parser.n_limit - 1: - break - except ResponseException: - print( - "Received a response from Reddit with an authorization error. check your token.\n" - ) - return - - if n_flair_posts_found: - lt_watchlist_sorted = sorted( - d_watchlist_tickers.items(), key=lambda item: item[1], reverse=True + # If try doesn't trigger exception, it means that this stock exists on finviz + # thus we can print it. + finviz.get_stock(t_ticker[0]) + if int(t_ticker[1]) > 1: + s_watchlist_tickers += f"{t_ticker[1]} {t_ticker[0]}, " + n_tickers += 1 + except Exception: + # print(e, "\n") + pass + if n_tickers: + print( + "The following stock tickers have been mentioned more than once across the previous watchlists:" ) - s_watchlist_tickers = "" - n_tickers = 0 - for t_ticker in lt_watchlist_sorted: - try: - # If try doesn't trigger exception, it means that this stock exists on finviz - # thus we can print it. - finviz.get_stock(t_ticker[0]) - if int(t_ticker[1]) > 1: - s_watchlist_tickers += f"{t_ticker[1]} {t_ticker[0]}, " - n_tickers += 1 - except Exception: - # print(e, "\n") - pass - if n_tickers: - print( - "The following stock tickers have been mentioned more than once across the previous watchlists:" - ) - print(s_watchlist_tickers[:-2] + "\n") - print("") + print(s_watchlist_tickers[:-2] + "\n") - except Exception as e: - print(e, "\n") - print("") + print("") -def popular_tickers(other_args: List[str]): +def display_popular_tickers( + n_top: int = 10, posts_to_look_at: int = 50, subreddits: str = "", export: str = "" +): """Print latest popular tickers. [Source: Reddit] Parameters ---------- - other_args: List[str] - Arguments for argparse + n_top : int + Number of top tickers to get + posts_to_look_at : int + How many posts to analyze in each subreddit + subreddits : str, optional + String of comma separated subreddits. + export : str + Format to export dataframe """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="popular", - description="""Print latest popular tickers. [Source: Reddit]""", + popular_tickers_df = reddit_model.get_popular_tickers( + n_top, posts_to_look_at, subreddits ) - parser.add_argument( - "-n", - "--number", - action="store", - dest="n_top", - type=check_positive, - default=10, - help="display top N tickers", - ) - parser.add_argument( - "-l", - "--limit", - action="store", - dest="n_limit", - type=check_positive, - default=50, - help="limit of posts retrieved per sub reddit.", - ) - parser.add_argument( - "-s", - "--sub", - action="store", - dest="s_subreddit", - type=str, - help=""" - subreddits to look for tickers, e.g. pennystocks,stocks. - Default: pennystocks, RobinHoodPennyStocks, Daytrading, StockMarket, stocks, investing, - wallstreetbets - """, - ) - - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - # n_ts_after = int( - # (datetime.today() - timedelta(days=ns_parser.n_days)).timestamp() - # ) - - if ns_parser.s_subreddit: - if "," in ns_parser.s_subreddit: - l_sub_reddits = ns_parser.s_subreddit.split(",") - else: - l_sub_reddits = [ns_parser.s_subreddit] - else: - l_sub_reddits = [ - "Superstonk", - "pennystocks", - "RobinHoodPennyStocks", - "Daytrading", - "StockMarket", - "stocks", - "investing", - "wallstreetbets", - ] - - # d_submission = {} - d_watchlist_tickers: Dict = {} - # l_watchlist_links = [] - l_watchlist_author = [] - - praw_api = praw.Reddit( - client_id=cfg.API_REDDIT_CLIENT_ID, - client_secret=cfg.API_REDDIT_CLIENT_SECRET, - username=cfg.API_REDDIT_USERNAME, - user_agent=cfg.API_REDDIT_USER_AGENT, - password=cfg.API_REDDIT_PASSWORD, - ) - - psaw_api = PushshiftAPI() - - for s_sub_reddit in l_sub_reddits: + if not popular_tickers_df.empty: + print(f"\nThe following TOP {n_top} tickers have been mentioned:") + if gtff.USE_TABULATE_DF: print( - f"Search for latest tickers under {ns_parser.n_limit} '{s_sub_reddit}' posts" - ) - submissions = psaw_api.search_submissions( - # after=int(n_ts_after), - subreddit=s_sub_reddit, - limit=ns_parser.n_limit, - filter=["id"], + tabulate( + popular_tickers_df, + headers=popular_tickers_df.columns, + tablefmt="fancy_grid", + showindex=False, + ) ) + else: + print(popular_tickers_df.to_string()) + else: + print("No tickers found") - n_tickers = 0 - while True: - try: - submission = next(submissions, None) - if submission: - # Get more information about post using PRAW api - submission = praw_api.submission(id=submission.id) + print("") + export_data( + export, + os.path.dirname(os.path.abspath(__file__)), + "popular", + popular_tickers_df, + ) - # Ensure that the post hasn't been removed by moderator in the meanwhile, - # that there is a description and it's not just an image, that the flair is - # meaningful, and that we aren't re-considering same author's content - if ( - not submission.removed_by_category - and (submission.selftext or submission.title) - and submission.author.name not in l_watchlist_author - ): - l_tickers_found = find_tickers(submission) - if l_tickers_found: - n_tickers += len(l_tickers_found) +def display_spac_community(limit: int = 10, popular: bool = False): + """Look at tickers mentioned in r/SPACs [Source: Reddit] - # Add another author's name to the parsed watchlists - l_watchlist_author.append(submission.author.name) - - # Lookup stock tickers within a watchlist - for key in l_tickers_found: - if key in d_watchlist_tickers: - # Increment stock ticker found - d_watchlist_tickers[key] += 1 - else: - # Initialize stock ticker found - d_watchlist_tickers[key] = 1 - - # Check if search_submissions didn't get anymore posts - else: - break - except ResponseException: - print( - "Received a response from Reddit with an authorization error. check your token.\n" - ) - return - - print(f" {n_tickers} potential tickers found.") + Parameters + ---------- + limit: int + Number of posts to look through + popular: bool + Search by popular instead of new + """ + subs, d_watchlist_tickers = reddit_model.get_spac_community(limit, popular) + for sub in subs: + print_and_record_reddit_post({}, sub) + if d_watchlist_tickers: lt_watchlist_sorted = sorted( d_watchlist_tickers.items(), key=lambda item: item[1], reverse=True ) + s_watchlist_tickers = "" + n_tickers = 0 + for t_ticker in lt_watchlist_sorted: + try: + # If try doesn't trigger exception, it means that this stock exists on finviz + # thus we can print it. + finviz.get_stock(t_ticker[0]) + if int(t_ticker[1]) > 1: + s_watchlist_tickers += f"{t_ticker[1]} {t_ticker[0]}, " + n_tickers += 1 + except Exception: + # print(e, "\n") + pass - if lt_watchlist_sorted: - n_top_stocks = 0 - # pylint: disable=redefined-outer-name - popular_tickers = [] - for t_ticker in lt_watchlist_sorted: - if n_top_stocks > ns_parser.n_top: - break - try: - # If try doesn't trigger exception, it means that this stock exists on finviz - # thus we can print it. - stock_info = finviz.get_stock(t_ticker[0]) - popular_tickers.append( - ( - t_ticker[1], - t_ticker[0], - stock_info["Company"], - stock_info["Sector"], - stock_info["Price"], - stock_info["Change"], - stock_info["Perf Month"], - f"https://finviz.com/quote.ashx?t={t_ticker[0]}", - ) - ) - n_top_stocks += 1 - except HTTPError as e: - if e.response.status_code != 404: - print(f"Unexpected exception from Finviz: {e}") - except Exception as e: - print(e, "\n") - return - - popular_tickers_df = pd.DataFrame( - popular_tickers, - columns=[ - "Mentions", - "Ticker", - "Company", - "Sector", - "Price", - "Change", - "Perf Month", - "URL", - ], + if n_tickers: + print( + "The following stock tickers have been mentioned more than once across the previous SPACs:" ) - - print(f"\nThe following TOP {ns_parser.n_top} tickers have been mentioned:") - - print(popular_tickers_df, "\n") - else: - print("No tickers found") - - print("") - - except ResponseException: - print( - "Received a response from Reddit with an authorization error. check your token.\n" - ) - return - - except Exception as e: - print(e, "\n") + print(s_watchlist_tickers[:-2]) + print("") -def spac_community(other_args: List[str]): - """Print other users SPACs announcement under subreddit 'SPACs' [Source: Reddit] +def display_spac(limit: int = 5): + """Look at posts containing 'spac' in top communities Parameters ---------- - other_args: List[str] - Arguments for argparse + limit: int + Number of posts to get from each subreddit """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="spac_c", - description="""Print other users SPACs announcement under subreddit 'SPACs'. [Source: Reddit]""", - ) - parser.add_argument( - "-l", - "--limit", - action="store", - dest="n_limit", - type=check_positive, - default=10, - help="limit of posts with SPACs retrieved", - ) - parser.add_argument( - "-p", - "--popular", - action="store_true", - default=False, - dest="b_popular", - help="popular flag, if true the posts retrieved are based on score rather than time", - ) + warnings.filterwarnings("ignore") # To avoid printing the warning + subs, d_watchlist_tickers, n_flair_posts_found = reddit_model.get_spac(limit) + for sub in subs: + print_and_record_reddit_post({}, sub) - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - praw_api = praw.Reddit( - client_id=cfg.API_REDDIT_CLIENT_ID, - client_secret=cfg.API_REDDIT_CLIENT_SECRET, - username=cfg.API_REDDIT_USERNAME, - user_agent=cfg.API_REDDIT_USER_AGENT, - password=cfg.API_REDDIT_PASSWORD, + if n_flair_posts_found > 0: + lt_watchlist_sorted = sorted( + d_watchlist_tickers.items(), key=lambda item: item[1], reverse=True ) - - d_submission: Dict = {} - d_watchlist_tickers: Dict = {} - l_watchlist_links = [] - l_watchlist_author = [] - - # psaw_api = PushshiftAPI() - - if ns_parser.b_popular: - submissions = praw_api.subreddit("SPACs").hot(limit=ns_parser.n_limit) - else: - submissions = praw_api.subreddit("SPACs").new(limit=ns_parser.n_limit) - - while True: + s_watchlist_tickers = "" + n_tickers = 0 + for t_ticker in lt_watchlist_sorted: try: - submission = next(submissions, None) - if submission: - # Get more information about post using PRAW api - submission = praw_api.submission(id=submission.id) - - # Ensure that the post hasn't been removed by moderator in the meanwhile, - # that there is a description and it's not just an image, that the flair is - # meaningful, and that we aren't re-considering same author's watchlist - if ( - not submission.removed_by_category - and submission.selftext - and submission.link_flair_text not in ["Yolo", "Meme"] - and submission.author.name not in l_watchlist_author - ): - l_tickers_found = find_tickers(submission) - - if l_tickers_found: - # Add another author's name to the parsed watchlists - l_watchlist_author.append(submission.author.name) - - # Lookup stock tickers within a watchlist - for key in l_tickers_found: - if key in d_watchlist_tickers: - # Increment stock ticker found - d_watchlist_tickers[key] += 1 - else: - # Initialize stock ticker found - d_watchlist_tickers[key] = 1 - - l_watchlist_links.append( - f"https://old.reddit.com{submission.permalink}" - ) - - print_and_record_reddit_post(d_submission, submission) - - # Check if search_submissions didn't get anymore posts - else: - break - except ResponseException: - print( - "Received a response from Reddit with an authorization error. check your token.\n" - ) - return - - if d_watchlist_tickers: - lt_watchlist_sorted = sorted( - d_watchlist_tickers.items(), key=lambda item: item[1], reverse=True + # If try doesn't trigger exception, it means that this stock exists on finviz + # thus we can print it. + finviz.get_stock(t_ticker[0]) + if int(t_ticker[1]) > 1: + s_watchlist_tickers += f"{t_ticker[1]} {t_ticker[0]}, " + n_tickers += 1 + except Exception: + pass + if n_tickers: + print( + "The following stock tickers have been mentioned more than once across the previous SPACs:" ) - s_watchlist_tickers = "" - n_tickers = 0 - for t_ticker in lt_watchlist_sorted: - try: - # If try doesn't trigger exception, it means that this stock exists on finviz - # thus we can print it. - finviz.get_stock(t_ticker[0]) - if int(t_ticker[1]) > 1: - s_watchlist_tickers += f"{t_ticker[1]} {t_ticker[0]}, " - n_tickers += 1 - except Exception: - # print(e, "\n") - pass - - if n_tickers: - print( - "The following stock tickers have been mentioned more than once across the previous SPACs:" - ) - print(s_watchlist_tickers[:-2]) - print("") - - except Exception as e: - print(e, "\n") + print(s_watchlist_tickers[:-2]) + print("") -def spac(other_args: List[str]): - """Show other users SPACs announcement [Source: Reddit] +def display_wsb_community(limit: int = 10, new: bool = False): + """Show WSB posts Parameters ---------- - other_args: List[str] - Arguments for argparse + limit : int, optional + Number of posts to look at, by default 10 + new : bool, optional + Flag to sort by new instead of hot, by default False """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="spac", - description="""Show other users SPACs announcement. [Source: Reddit]""", - ) - parser.add_argument( - "-l", - "--limit", - action="store", - dest="n_limit", - type=check_positive, - default=5, - help="limit of posts with SPACs retrieved.", - ) + subs = reddit_model.get_wsb_community(limit, new) - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - praw_api = praw.Reddit( - client_id=cfg.API_REDDIT_CLIENT_ID, - client_secret=cfg.API_REDDIT_CLIENT_SECRET, - username=cfg.API_REDDIT_USERNAME, - user_agent=cfg.API_REDDIT_USER_AGENT, - password=cfg.API_REDDIT_PASSWORD, - ) - - d_submission: Dict = {} - d_watchlist_tickers: Dict = {} - l_watchlist_links = [] - l_watchlist_author = [] - - # n_ts_after = int( - # (datetime.today() - timedelta(days=ns_parser.n_days)).timestamp() - # ) - l_sub_reddits = [ - "Superstonk", - "pennystocks", - "RobinHoodPennyStocks", - "Daytrading", - "StockMarket", - "stocks", - "investing", - "wallstreetbets", - ] - - warnings.filterwarnings("ignore") # To avoid printing the warning - psaw_api = PushshiftAPI() - submissions = psaw_api.search_submissions( - # after=n_ts_after, - subreddit=l_sub_reddits, - q="SPAC|Spac|spac|Spacs|spacs", - filter=["id"], - ) - n_flair_posts_found = 0 - while True: - try: - submission = next(submissions, None) - if submission: - # Get more information about post using PRAW api - submission = praw_api.submission(id=submission.id) - - # Ensure that the post hasn't been removed by moderator in the meanwhile, - # that there is a description and it's not just an image, that the flair is - # meaningful, and that we aren't re-considering same author's watchlist - if ( - not submission.removed_by_category - and submission.selftext - and submission.link_flair_text not in ["Yolo", "Meme"] - and submission.author.name not in l_watchlist_author - ): - l_tickers_found = find_tickers(submission) - - if l_tickers_found: - # Add another author's name to the parsed watchlists - l_watchlist_author.append(submission.author.name) - - # Lookup stock tickers within a watchlist - for key in l_tickers_found: - if key in d_watchlist_tickers: - # Increment stock ticker found - d_watchlist_tickers[key] += 1 - else: - # Initialize stock ticker found - d_watchlist_tickers[key] = 1 - - l_watchlist_links.append( - f"https://old.reddit.com{submission.permalink}" - ) - - print_and_record_reddit_post(d_submission, submission) - - # Increment count of valid posts found - n_flair_posts_found += 1 - - # Check if number of wanted posts found has been reached - if n_flair_posts_found > ns_parser.n_limit - 1: - break - - # Check if search_submissions didn't get anymore posts - else: - break - except ResponseException: - print( - "Received a response from Reddit with an authorization error. check your token.\n" - ) - return - - if n_flair_posts_found: - lt_watchlist_sorted = sorted( - d_watchlist_tickers.items(), key=lambda item: item[1], reverse=True - ) - s_watchlist_tickers = "" - n_tickers = 0 - for t_ticker in lt_watchlist_sorted: - try: - # If try doesn't trigger exception, it means that this stock exists on finviz - # thus we can print it. - finviz.get_stock(t_ticker[0]) - if int(t_ticker[1]) > 1: - s_watchlist_tickers += f"{t_ticker[1]} {t_ticker[0]}, " - n_tickers += 1 - except Exception: - # print(e, "\n") - pass - if n_tickers: - print( - "The following stock tickers have been mentioned more than once across the previous SPACs:" - ) - print(s_watchlist_tickers[:-2]) - print("") - - except Exception as e: - print(e, "\n") + for sub in subs: + print_and_record_reddit_post({}, sub) -def wsb_community(other_args: List[str]): - """Print what WSB gang are up to in subreddit wallstreetbets. [Source: Reddit] - - Parameters - ---------- - other_args: List[str] - Arguments for argparse - """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="wsb", - description="""Print what WSB gang are up to in subreddit wallstreetbets. [Source: Reddit]""", - ) - parser.add_argument( - "-l", - "--limit", - action="store", - dest="n_limit", - type=check_positive, - default=10, - help="limit of posts to print.", - ) - parser.add_argument( - "-n", - "--new", - action="store_true", - default=False, - dest="b_new", - help="new flag, if true the posts retrieved are based on being more recent rather than their score.", - ) - - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - praw_api = praw.Reddit( - client_id=cfg.API_REDDIT_CLIENT_ID, - client_secret=cfg.API_REDDIT_CLIENT_SECRET, - username=cfg.API_REDDIT_USERNAME, - user_agent=cfg.API_REDDIT_USER_AGENT, - password=cfg.API_REDDIT_PASSWORD, - ) - - d_submission: Dict = {} - l_watchlist_links = [] - - # psaw_api = PushshiftAPI() - - if ns_parser.b_new: - submissions = praw_api.subreddit("wallstreetbets").new( - limit=ns_parser.n_limit - ) - else: - submissions = praw_api.subreddit("wallstreetbets").hot( - limit=ns_parser.n_limit - ) - while True: - try: - submission = next(submissions, None) - if submission: - # Get more information about post using PRAW api - submission = praw_api.submission(id=submission.id) - - # Ensure that the post hasn't been removed by moderator in the meanwhile, - # that there is a description and it's not just an image, that the flair is - # meaningful, and that we aren't re-considering same author's watchlist - if not submission.removed_by_category: - - l_watchlist_links.append( - f"https://old.reddit.com{submission.permalink}" - ) - - print_and_record_reddit_post(d_submission, submission) - - # Check if search_submissions didn't get anymore posts - else: - break - except ResponseException: - print( - "Received a response from Reddit with an authorization error. check your token.\n" - ) - return - except Exception as e: - print(e, "\n") - - -def get_due_diligence(other_args: List[str], ticker: str): +def display_due_diligence( + ticker: str, limit: int = 10, n_days: int = 3, show_all_flairs: bool = False +): """Display Reddit due diligence data for a given ticker Parameters ---------- - other_args : List[str] - argparse other args - ["-l", "5"] - ticker : str + ticker: str Stock ticker + limit: int + Number of posts to get + n_days: int + Number of days back to get posts + show_all_flairs: bool + Search through all flairs (apart from Yolo and Meme) """ - parser = argparse.ArgumentParser( - add_help=False, - prog="getdd", - description=""" - Print top stock's due diligence from other users. [Source: Reddit] - """, - ) - parser.add_argument( - "-l", - "--limit", - action="store", - dest="n_limit", - type=check_positive, - default=5, - help="limit of posts to retrieve.", - ) - parser.add_argument( - "-d", - "--days", - action="store", - dest="n_days", - type=check_positive, - default=3, - help="number of prior days to look for.", - ) - parser.add_argument( - "-a", - "--all", - action="store_true", - dest="b_all", - default=False, - help=""" - search through all flairs (apart from Yolo and Meme), otherwise we focus on - specific flairs: DD, technical analysis, Catalyst, News, Advice, Chart - """, - ) - - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - praw_api = praw.Reddit( - client_id=cfg.API_REDDIT_CLIENT_ID, - client_secret=cfg.API_REDDIT_CLIENT_SECRET, - username=cfg.API_REDDIT_USERNAME, - user_agent=cfg.API_REDDIT_USER_AGENT, - password=cfg.API_REDDIT_PASSWORD, - ) - - psaw_api = PushshiftAPI() - - n_ts_after = int( - (datetime.today() - timedelta(days=ns_parser.n_days)).timestamp() - ) - l_flair_text = [ - "DD", - "technical analysis", - "Catalyst", - "News", - "Advice", - "Chart", - "Charts and Setups", - "Fundamental Analysis", - "forex", - "Trade Idea", - ] - l_sub_reddits = [ - "pennystocks", - "RobinHoodPennyStocks", - "Daytrading", - "StockMarket", - "stocks", - "investing", - "wallstreetbets", - "forex", - "Forexstrategy", - ] - - submissions = psaw_api.search_submissions( - after=int(n_ts_after), subreddit=l_sub_reddits, q=ticker, filter=["id"] - ) - d_submission = {} # type: ignore - n_flair_posts_found = 0 - while True: - submission = next(submissions, None) - if submission: - # Get more information about post using PRAW api - submission = praw_api.submission(id=submission.id) - - # Ensure that the post hasn't been removed in the meanwhile - if not submission.removed_by_category: - - # Either just filter out Yolo, and Meme flairs, or focus on DD, based on b_DD flag - if ( - submission.link_flair_text in l_flair_text, - submission.link_flair_text not in ["Yolo", "Meme"], - )[ns_parser.b_all]: - - print_and_record_reddit_post(d_submission, submission) - - # If needed, submission.comments could give us the top comments - - # Increment count of valid posts found - n_flair_posts_found += 1 - - # Check if number of wanted posts found has been reached - if n_flair_posts_found > ns_parser.n_limit - 1: - break - - # Check if search_submissions didn't get anymore posts - else: - break - - print( - f"{('No more posts with specified requirements found.', '')[n_flair_posts_found > ns_parser.n_limit-1]}", - "\n", - ) - # Create df with found data. Useful for saving all info in excel file. - # df_submissions = pd.DataFrame.from_dict( - # d_submission, orient='index', columns=list(d_submission[next(iter(d_submission.keys()))].keys()) - # ) - # df_submissions.sort_values(by=['created_utc'], inplace=True, ascending=True) - - except Exception as e: - print(e) - print("") + subs = reddit_model.get_due_dilligence(ticker, limit, n_days, show_all_flairs) + for sub in subs: + print_and_record_reddit_post({}, sub) + if not subs: + print(f"No DD posts found for {ticker}\n") diff --git a/gamestonk_terminal/common/behavioural_analysis/sentimentinvestor_model.py b/gamestonk_terminal/common/behavioural_analysis/sentimentinvestor_model.py new file mode 100644 index 00000000000..082093aa238 --- /dev/null +++ b/gamestonk_terminal/common/behavioural_analysis/sentimentinvestor_model.py @@ -0,0 +1,306 @@ +"""SentimentInvestor Model""" +__docformat__ = "numpy" + +import dataclasses +import datetime +import logging +import multiprocessing +import os +import statistics +import time +from typing import Any, List, Optional, Tuple, Union + +import pandas as pd +from colorama import Fore, Style +from sentipy.sentipy import Sentipy + +from gamestonk_terminal import config_terminal as cfg + +sentipy: Sentipy = Sentipy( + token=cfg.API_SENTIMENTINVESTOR_TOKEN, key=cfg.API_SENTIMENTINVESTOR_KEY +) + +# TODO: Make code more consistent with rest of repository. + + +@dataclasses.dataclass +class _Boundary: + """Represents a strong or weak bounding inequality for categorising a value""" + + min: Union[float, int] + "Minimum value that this metric could take" + max: Union[float, int] + "Maximum value that this metric could take" + strong: bool = False + "Whether this a strongly bounded inequality" + + def categorise(self, num: Union[float, int]) -> Tuple[str, str]: + """ + Categorise a given number using this bounding inequality + + Parameters + ---------- + num: the number to bucket + + Returns + ------- + A color string and a string with low / medium / high as appropriate + + """ + + if num is None or self.min is None or self.max is None: + return Style.DIM + Fore.WHITE, "N/A" + + boundaries = [self.min + (self.max - self.min) / 5 * i for i in range(1, 5)] + + if (num <= self.min or num >= self.max) and self.strong: + return Fore.WHITE, "Extreme (anomaly?)" + if num < boundaries[0]: + return Style.BRIGHT + Fore.RED, "Much Lower" + if num < boundaries[1]: + return Fore.RED, "Lower" + if num < boundaries[2]: + return Fore.YELLOW, "Same" + if num < boundaries[3]: + return Fore.GREEN, "Higher" + return Style.BRIGHT + Fore.GREEN, "Much Higher" + + +def _get_past_week_average(ticker: str, metric: str) -> float: + """Gets last 1 week average""" + historical_data = [ + dp + for dp in sentipy.historical( + ticker, metric, int(time.time() - 60 * 60 * 24 * 7), int(time.time()) + ).values() + if dp is not None + ] + return statistics.mean(historical_data) if historical_data else None + + +@dataclasses.dataclass +class _MetricInfo: + name: str + """Metric attribute name""" + title: str + """Human-friendly attribute name""" + description: str + """Metric attribute description""" + format: str + """Format string for presenting the value""" + + +class _Metric(_MetricInfo): + boundary: _Boundary + """A contextual range to for this metric""" + ticker: str + """Ticker symbol for which this metric relates""" + value: Union[float, int] + """Value""" + + def __init__( + self, + metric_info: _MetricInfo, + ticker: str, + value: Union[float, int], + boundary: Optional[_Boundary] = None, + ): + super().__init__(**dataclasses.asdict(metric_info)) + + weekly_mean = _get_past_week_average(ticker, self.name) + self.boundary = ( + _Boundary(0, None if weekly_mean is None else 2 * weekly_mean) + if boundary is None + else boundary + ) + self.ticker = ticker + self.value = value + + def visualise(self) -> Tuple[str, str, str, str]: + color, category = self.boundary.categorise(self.value) + return ( + color + self.title, + category, + "N/A" if self.value is None else f"{self.value:{self.format}}", + self.description + Style.RESET_ALL, + ) + + +core_metrics = [ + _MetricInfo( + "sentiment", + "Sentiment Score", + "the percentage of people that are talking positively about a stock", + ".0%", + ), + _MetricInfo( + "AHI", + "Average Hype Index", + "how much people are talking about a stock on social media", + ".3f", + ), + _MetricInfo( + "RHI", + "Relative Hype Index", + "whether people are talking about a stock more or less than usual", + ".3f", + ), + _MetricInfo( + "SGP", + "Standard General Perception", + "whether people are more or less positive about a stock than usual", + ".3f", + ), +] + +social_metrics = [ + _MetricInfo( + "reddit_comment_mentions", + "Reddit Comment Mentions", + "the number of mentions this stock has received in Reddit comments", + "n", + ), + _MetricInfo( + "reddit_comment_sentiment", + "Reddit Comment Sentiment", + "percentage of Reddit comments mentioning this stock in a positive light", + ".0%", + ), + _MetricInfo( + "reddit_post_mentions", + "Reddit Post Mentions", + "the number of mentions this stock has received in Reddit posts", + "n", + ), + _MetricInfo( + "reddit_post_sentiment", + "Reddit Post Sentiment", + "percentage of Reddit posts mentioning this stock in a positive light", + ".0%", + ), + _MetricInfo( + "tweet_mentions", + "Twitter Mentions", + "the number of mentions this stock has received on Twitter", + "n", + ), + _MetricInfo( + "tweet_sentiment", + "Twitter Sentiment", + "percentage of tweets mentioning this stock in a positive light", + ".0%", + ), + _MetricInfo( + "stocktwits_post_mentions", + "Stocktwits Mentions", + "the number of mentions this stock has received in Stocktwits posts", + "n", + ), + _MetricInfo( + "stocktwits_post_sentiment", + "Stocktwits Sentiment", + "percentage of Stocktwits posts mentioning this stock in a positive light", + ".0%", + ), + _MetricInfo( + "yahoo_finance_comment_mentions", + "Yahoo! Finance Comment Mentions", + "the number of mentions this stock has received in Yahoo! Finance comments", + "n", + ), + _MetricInfo( + "yahoo_finance_comment_sentiment", + "Yahoo! Finance Comment Sentiment", + "percentage of Yahoo! Finance comments mentioning this stock in a positive light", + ".0%", + ), +] + + +def _contextualise_metrics( + data: object, ticker: str, metric_infos: List[_MetricInfo] +) -> Optional[List[_Metric]]: + arguments = [] + for metric_info in metric_infos: + if not hasattr(data, metric_info.name): + logging.error( + "data for %s stock is incomplete. If you believe this is an error, " + "please contact hello@sentimentinvestor.com", + ticker, + ) + return None + arguments.append((metric_info, ticker, data.__getattribute__(metric_info.name))) + + with multiprocessing.Pool(os.cpu_count()) as pool: + return pool.starmap(_Metric, arguments) + + +def get_metrics(ticker: str) -> Optional[List[_Metric]]: + """Get core metrics for ticker""" + data = sentipy.parsed(ticker) + return _contextualise_metrics(data, ticker, core_metrics) + + +def get_socials(ticker: str) -> Optional[List[_Metric]]: + """Get social metrics for ticker""" + data = sentipy.raw(ticker) + return _contextualise_metrics(data, ticker, social_metrics) + + +def get_historical(ticker: str, metric: str) -> pd.DataFrame: + """Get historical sentiment data [Source: sentimentinvestor] + + Parameters + ---------- + ticker : str + Stock + metric : str + Metric to get + + Returns + ------- + pd.DataFrame + Dataframe of historical sentiment + """ + data = sentipy.historical( + ticker, + metric, + int(time.time() - 60 * 60 * 24 * 7), + int(time.time()), + ) + df = pd.DataFrame.from_dict( + { + "date": map(datetime.datetime.utcfromtimestamp, data.keys()), + metric: data.values(), + } + ) + + df.sort_index(ascending=True, inplace=True) + return df + + +def get_top(metric: str, limit: int) -> List[List[Any]]: + """Get top stocks based on metric from sentimentinvestor [Source: sentimentinvestor] + + Parameters + ---------- + metric : str + Metric to get top tickers for + limit : int + Number of tickes to get + + Returns + ------- + List[List[Any]] + List of tickers and scores + """ + data = sentipy.sort(metric, limit) + + table: List[List[Any]] = [] + for index, stock in enumerate(data): + if not hasattr(stock, "symbol") or not hasattr(stock, metric): + logging.warning("data for stock %s is incomplete, ignoring", index + 1) + table.append([]) + else: + table.append([index + 1, stock.symbol, stock.__getattribute__(metric)]) + return table diff --git a/gamestonk_terminal/common/behavioural_analysis/sentimentinvestor_view.py b/gamestonk_terminal/common/behavioural_analysis/sentimentinvestor_view.py index 846e964eba8..eedae2bb952 100644 --- a/gamestonk_terminal/common/behavioural_analysis/sentimentinvestor_view.py +++ b/gamestonk_terminal/common/behavioural_analysis/sentimentinvestor_view.py @@ -1,28 +1,24 @@ -import argparse -import dataclasses -import datetime -import logging -import multiprocessing -import os -import statistics -import textwrap -import time -from typing import Union, Optional, List, Tuple, Any +"""SentimentInvestor View""" +__docformat__ = "numpy" + +from typing import List import matplotlib.dates as mdates import pandas as pd import seaborn as sns -from colorama import Fore, Style +import tabulate +from colorama import Style from matplotlib import pyplot as plt from sentipy.sentipy import Sentipy -import tabulate from gamestonk_terminal import config_terminal as cfg -from gamestonk_terminal.config_plot import PLOT_DPI -from gamestonk_terminal.helper_funcs import ( - parse_known_args_and_warn, - plot_autoscale, +from gamestonk_terminal.common.behavioural_analysis import sentimentinvestor_model +from gamestonk_terminal.common.behavioural_analysis.sentimentinvestor_model import ( + _Boundary, + _Metric, ) +from gamestonk_terminal.config_plot import PLOT_DPI +from gamestonk_terminal.helper_funcs import plot_autoscale sentipy: Sentipy = Sentipy( token=cfg.API_SENTIMENTINVESTOR_TOKEN, key=cfg.API_SENTIMENTINVESTOR_KEY @@ -31,300 +27,26 @@ sentipy: Sentipy = Sentipy( pd.plotting.register_matplotlib_converters() - -# suppress warning messages for a clean interface -logging.getLogger().setLevel(logging.CRITICAL) - -__command_descriptions = { - "popularsi": f""" - The {Style.BRIGHT}popular{Style.RESET_ALL} command prints the stocks with highest Average Hype Index right now. - - {Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL} - --- - AHI is a measure of how much people are talking about a stock on social media. - It is calculated by dividing the total number of mentions for the chosen stock - on a social network by the mean number of mentions any stock receives on that - social medium. - - === - - {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to - generate hourly metrics on over 2,000 stocks. Sentiment provides volume and - sentiment metrics powered by proprietary NLP models. - """, - "emerging": f""" - The {Style.BRIGHT}emerging{Style.RESET_ALL} command prints the stocks with highest Relative Hype Index right now. - - {Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL} - --- - RHI is a measure of whether people are talking about a stock more or less than - usual, calculated by dividing the mean AHI for the past day by the mean AHI for - for the past week for that stock. - - === - - {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to - generate hourly metrics on over 2,000 stocks. Sentiment provides volume and - sentiment metrics powered by proprietary NLP models. - """, -} +# TODO: Make code more consisnet with rest of repository -def sort_sentiment(metric: str, other_args: List[str], command_name: str) -> None: - parser = argparse.ArgumentParser( - add_help=False, - prog=command_name, - formatter_class=argparse.RawDescriptionHelpFormatter, - description=textwrap.dedent(__command_descriptions[command_name]), - ) +def display_top(metric: str, limit: int): + """Displays top stocks from sentimentinvestor based on metric [Source: sentimentinvestor] - parser.add_argument( - "-l", - "--limit", - action="store", - dest="limit", - type=int, - default=10, - help="the maximum number of stocks to retrieve", - ) - - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - data = sentipy.sort(metric, ns_parser.limit) - - table: List[List[Any]] = [] - for index, stock in enumerate(data): - if not hasattr(stock, "symbol") or not hasattr(stock, metric): - logging.warning("data for stock %s is incomplete, ignoring", index + 1) - table.append([]) - else: - table.append([index + 1, stock.symbol, stock.__getattribute__(metric)]) - - print( - tabulate.tabulate(table, headers=["Rank", "Ticker", metric], floatfmt=".3f") - ) - print("") - - except Exception as e: - logging.error(e) - print(e, "\n") - - -@dataclasses.dataclass -class _Boundary: - """Represents a strong or weak bounding inequality for categorising a value""" - - min: Union[float, int] - "Minimum value that this metric could take" - max: Union[float, int] - "Maximum value that this metric could take" - strong: bool = False - "Whether this a strongly bounded inequality" - - def categorise(self, num: Union[float, int]) -> Tuple[str, str]: - """ - Categorise a given number using this bounding inequality - - Parameters - ---------- - num: the number to bucket - - Returns - ------- - A color string and a string with low / medium / high as appropriate - - """ - - if num is None or self.min is None or self.max is None: - return Style.DIM + Fore.WHITE, "N/A" - - boundaries = [self.min + (self.max - self.min) / 5 * i for i in range(1, 5)] - - if (num <= self.min or num >= self.max) and self.strong: - return Fore.WHITE, "Extreme (anomaly?)" - if num < boundaries[0]: - return Style.BRIGHT + Fore.RED, "Much Lower" - if num < boundaries[1]: - return Fore.RED, "Lower" - if num < boundaries[2]: - return Fore.YELLOW, "Same" - if num < boundaries[3]: - return Fore.GREEN, "Higher" - return Style.BRIGHT + Fore.GREEN, "Much Higher" - - -def _get_past_week_average(ticker: str, metric: str) -> float: - historical_data = [ - dp - for dp in sentipy.historical( - ticker, metric, int(time.time() - 60 * 60 * 24 * 7), int(time.time()) - ).values() - if dp is not None - ] - return statistics.mean(historical_data) if historical_data else None - - -@dataclasses.dataclass -class _MetricInfo: - name: str - """Metric attribute name""" - title: str - """Human-friendly attribute name""" - description: str - """Metric attribute description""" - format: str - """Format string for presenting the value""" - - -class _Metric(_MetricInfo): - boundary: _Boundary - """A contextual range to for this metric""" - ticker: str - """Ticker symbol for which this metric relates""" - value: Union[float, int] - """Value""" - - def __init__( - self, - metric_info: _MetricInfo, - ticker: str, - value: Union[float, int], - boundary: Optional[_Boundary] = None, - ): - super().__init__(**dataclasses.asdict(metric_info)) - - weekly_mean = _get_past_week_average(ticker, self.name) - self.boundary = ( - _Boundary(0, None if weekly_mean is None else 2 * weekly_mean) - if boundary is None - else boundary - ) - self.ticker = ticker - self.value = value - - def visualise(self) -> Tuple[str, str, str, str]: - color, category = self.boundary.categorise(self.value) - return ( - color + self.title, - category, - "N/A" if self.value is None else f"{self.value:{self.format}}", - self.description + Style.RESET_ALL, - ) - - -core_metrics = [ - _MetricInfo( - "sentiment", - "Sentiment Score", - "the percentage of people that are talking positively about a stock", - ".0%", - ), - _MetricInfo( - "AHI", - "Average Hype Index", - "how much people are talking about a stock on social media", - ".3f", - ), - _MetricInfo( - "RHI", - "Relative Hype Index", - "whether people are talking about a stock more or less than usual", - ".3f", - ), - _MetricInfo( - "SGP", - "Standard General Perception", - "whether people are more or less positive about a stock than usual", - ".3f", - ), -] - -social_metrics = [ - _MetricInfo( - "reddit_comment_mentions", - "Reddit Comment Mentions", - "the number of mentions this stock has received in Reddit comments", - "n", - ), - _MetricInfo( - "reddit_comment_sentiment", - "Reddit Comment Sentiment", - "percentage of Reddit comments mentioning this stock in a positive light", - ".0%", - ), - _MetricInfo( - "reddit_post_mentions", - "Reddit Post Mentions", - "the number of mentions this stock has received in Reddit posts", - "n", - ), - _MetricInfo( - "reddit_post_sentiment", - "Reddit Post Sentiment", - "percentage of Reddit posts mentioning this stock in a positive light", - ".0%", - ), - _MetricInfo( - "tweet_mentions", - "Twitter Mentions", - "the number of mentions this stock has received on Twitter", - "n", - ), - _MetricInfo( - "tweet_sentiment", - "Twitter Sentiment", - "percentage of tweets mentioning this stock in a positive light", - ".0%", - ), - _MetricInfo( - "stocktwits_post_mentions", - "Stocktwits Mentions", - "the number of mentions this stock has received in Stocktwits posts", - "n", - ), - _MetricInfo( - "stocktwits_post_sentiment", - "Stocktwits Sentiment", - "percentage of Stocktwits posts mentioning this stock in a positive light", - ".0%", - ), - _MetricInfo( - "yahoo_finance_comment_mentions", - "Yahoo! Finance Comment Mentions", - "the number of mentions this stock has received in Yahoo! Finance comments", - "n", - ), - _MetricInfo( - "yahoo_finance_comment_sentiment", - "Yahoo! Finance Comment Sentiment", - "percentage of Yahoo! Finance comments mentioning this stock in a positive light", - ".0%", - ), -] - - -def _contextualise_metrics( - data: object, ticker: str, metric_infos: List[_MetricInfo] -) -> Optional[List[_Metric]]: - arguments = [] - for metric_info in metric_infos: - if not hasattr(data, metric_info.name): - logging.error( - "data for %s stock is incomplete. If you believe this is an error, " - "please contact hello@sentimentinvestor.com", - ticker, - ) - return None - arguments.append((metric_info, ticker, data.__getattribute__(metric_info.name))) - - with multiprocessing.Pool(os.cpu_count()) as pool: - return pool.starmap(_Metric, arguments) + Parameters + ---------- + metric : str + Metric to get top for + limit : int + Number of tickers to get + """ + table = sentimentinvestor_model.get_top(metric, limit) + print(tabulate.tabulate(table, headers=["Rank", "Ticker", metric], floatfmt=".3f")) + print("") def _tabulate_metrics(ticker: str, metrics_list: List[_Metric]): + """Tabulates sentiment investor data""" table_data = [] table_headers = [ f"{Style.BRIGHT}{ticker}{Style.RESET_ALL} Metrics", @@ -340,6 +62,7 @@ def _tabulate_metrics(ticker: str, metrics_list: List[_Metric]): def _customise_plot() -> None: + """Customizes sentimentinvestor plot""" sns.set( font="Arial", style="darkgrid", @@ -371,318 +94,124 @@ def _customise_plot() -> None: plt.legend(frameon=False) -def _parse_args_for_ticker(other_args: List[str], ticker: str, command: str, desc: str): - parser = argparse.ArgumentParser( - add_help=False, - prog=command, - formatter_class=argparse.RawDescriptionHelpFormatter, - description=desc, +def display_metrics(ticker: str) -> None: + """Display sentiment investor metrics for stock ticker""" + if not sentipy.supported(ticker): + print("This stock is not supported by the SentimentInvestor API.") + return + + metric_values = sentimentinvestor_model.get_metrics(ticker) + + if not metric_values: + print("No data available or an error occurred.") + return + + print(_tabulate_metrics(ticker, metric_values)) + print() + + +def display_social(ticker: str) -> None: + """Display sentiment investor social metrics for ticker""" + if not sentipy.supported(ticker): + print("This stock is not supported by the SentimentInvestor API.") + return + + metric_values = sentimentinvestor_model.get_socials(ticker) + + if not metric_values: + print("No data available or an error occurred.") + return + + print(_tabulate_metrics(ticker, metric_values)) + print("") + + +def display_historical( + ticker: str, sort_param: str, sort_dir: str, metric: str +) -> None: + """Show historical sentiment from sentimentinvestor [Source: sentimentinvestor] + + Parameters + ---------- + ticker : str + Stock ticker + sort_param : str + Parameter to sort table by + sort_dir : str + Direction for sorting + metric : str + Metric to get data for. Either 'sentiment', 'AHI', 'RHI', 'SGP' + """ + if not sentipy.supported(ticker): + print("This stock is not supported by the SentimentInvestor API.") + return + + df = sentimentinvestor_model.get_historical(ticker, metric) + + if df.empty: + print("The dataset is empty, something must have gone wrong") + return + + _customise_plot() + + # use seaborn to lineplot + ax = sns.lineplot( + data=df, + x="date", + y=metric, + legend=False, + label=[metric], ) - parser.add_argument( - "ticker", - action="store", - type=str, - nargs="?", - default=ticker, - help="ticker to use instead of the loaded one", + # always show zero on the y-axis + plt.ylim(bottom=0) + + # set the x-axis date formatting + ax.xaxis.set_major_formatter(mdates.DateFormatter("%x")) + + # scale the plot appropriately + plt.gcf().set_size_inches(plot_autoscale()) + plt.gcf().set_dpi(PLOT_DPI) + plt.gcf().autofmt_xdate() + + # fill below the line + plt.fill_between(df.date, df[metric], alpha=0.3) + + # add title e.g. AAPL sentiment since 22/07/21 + plt.title(f"{ticker} {metric} since {min(df.date).strftime('%x')}") + + plt.show() + + ### + + boundary = _Boundary(0, max(df[metric].max(), 2 * df[metric].mean())) + + # average for each day + aggregated = df.resample("D", on="date").mean() + + # reverse the ordering if requested + aggregated.sort_values( + metric if sort_param == "value" else sort_param, + axis=0, + ascending=sort_dir == "asc", + inplace=True, ) - return parse_known_args_and_warn(parser, other_args) + # format the date according to user's locale + aggregated.index = aggregated.index.strftime("%x") + # apply coloring to every value + aggregated[metric] = [ + boundary.categorise(value)[0] + str(value) + Style.RESET_ALL + for value in aggregated[metric] + ] -def metrics(ticker: str, other_args: List[str]) -> None: - command_description = f""" - {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to - generate hourly metrics on over 2,000 stocks. Sentiment provides volume and - sentiment metrics powered by proprietary NLP models. - - The {Style.BRIGHT}metrics{Style.RESET_ALL} command prints the following realtime metrics: - - {Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL} - --- - AHI is a measure of how much people are talking about a stock on social media. - It is calculated by dividing the total number of mentions for the chosen stock - on a social network by the mean number of mentions any stock receives on that - social medium. - - {Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL} - --- - RHI is a measure of whether people are talking about a stock more or less than - usual, calculated by dividing the mean AHI for the past day by the mean AHI for - for the past week for that stock. - - {Style.BRIGHT}Sentiment Score{Style.RESET_ALL} - --- - Sentiment score is the percentage of people talking positively about the stock. - For each social network the number of positive posts/comments is divided by the - total number of both positive and negative posts/comments. - - {Style.BRIGHT}SGP (Standard General Perception){Style.RESET_ALL} - --- - SGP is a measure of whether people are more or less positive about a stock than - usual. It is calculated by averaging the past day of sentiment values and then - dividing it by the average of the past week of sentiment values. - """ - - ns_parser = _parse_args_for_ticker( - other_args=other_args, - ticker=ticker, - command="metrics", - desc=textwrap.dedent(command_description), + print( + tabulate.tabulate( + aggregated, + headers=["Day", f"average {metric}"], + tablefmt="psql", + floatfmt=".3f", + ), + "\n", ) - - try: - - if not ns_parser: - logging.error("There was an error in parsing the command-line arguments.") - return - - if not sentipy.supported(ns_parser.ticker): - print("This stock is not supported by the SentimentInvestor API.") - return - - data = sentipy.parsed(ns_parser.ticker) - - metric_values = _contextualise_metrics(data, ns_parser.ticker, core_metrics) - - if not metric_values: - logging.error("No data available or an error occurred.") - return - - print(_tabulate_metrics(ns_parser.ticker, metric_values)) - print() - - except Exception as e: - logging.error(e) - print(e, "\n") - - -def socials(ticker: str, other_args: List[str]) -> None: - command_description = f""" - {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to - generate hourly metrics on over 2,000 stocks. Sentiment provides volume and - sentiment metrics powered by proprietary NLP models. - - The {Style.BRIGHT}social{Style.RESET_ALL} command prints the raw data for a given stock, including the number - of mentions it has received on social media in the last hour and the sentiment - score of those comments. - """ - - try: - - ns_parser = _parse_args_for_ticker( - other_args=other_args, - ticker=ticker, - command="social", - desc=textwrap.dedent(command_description), - ) - - if not ns_parser: - logging.error("There was an error in parsing the command-line arguments.") - return - - if not sentipy.supported(ns_parser.ticker): - print("This stock is not supported by the SentimentInvestor API.") - return - - data = sentipy.raw(ns_parser.ticker) - - metric_values = _contextualise_metrics(data, ns_parser.ticker, social_metrics) - - if not metric_values: - logging.error("No data available or an error occurred.") - return - - print(_tabulate_metrics(ns_parser.ticker, metric_values)) - print() - - except Exception as e: - logging.error(e) - print(e, "\n") - - -def historical(ticker: str, other_args: List[str]) -> None: - command_description = f""" - {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to - generate hourly metrics on over 2,000 stocks. Sentiment provides volume and - sentiment metrics powered by proprietary NLP models. - - The {Style.BRIGHT}historical{Style.RESET_ALL} command plots the past week of data for a selected metric, one of: - - {Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL} - --- - AHI is a measure of how much people are talking about a stock on social media. - It is calculated by dividing the total number of mentions for the chosen stock - on a social network by the mean number of mentions any stock receives on that - social medium. - - {Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL} - --- - RHI is a measure of whether people are talking about a stock more or less than - usual, calculated by dividing the mean AHI for the past day by the mean AHI for - for the past week for that stock. - - {Style.BRIGHT}Sentiment Score{Style.RESET_ALL} - --- - Sentiment score is the percentage of people talking positively about the stock. - For each social network the number of positive posts/comments is divided by the - total number of both positive and negative posts/comments. - - {Style.BRIGHT}SGP (Standard General Perception){Style.RESET_ALL} - --- - SGP is a measure of whether people are more or less positive about a stock than - usual. It is calculated by averaging the past day of sentiment values and then - dividing it by the average of the past week of sentiment values. - """ - - parser = argparse.ArgumentParser( - add_help=False, - prog="historical", - formatter_class=argparse.RawDescriptionHelpFormatter, - description=textwrap.dedent(command_description), - ) - parser.add_argument( - "-t", - "--ticker", - action="store", - dest="ticker", - type=str, - default=ticker, - help="ticker for which to fetch data", - ) - parser.add_argument( - "-s", - "--sort", - action="store", - type=str, - default="date", - help="the parameter to sort output table by", - dest="sort_param", - nargs="?", - choices=["date", "value"], - ) - parser.add_argument( - "-d", - "--direction", - action="store", - type=str, - default="desc", - help="the direction to sort the output table", - dest="sort_dir", - nargs="?", - choices=["asc", "desc"], - ) - parser.add_argument( - "metric", - type=str, - action="store", - default="sentiment", - nargs="?", - choices=["sentiment", "AHI", "RHI", "SGP"], - help="the metric to plot", - ) - - try: - - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - logging.error("There was an error in parsing the command-line arguments.") - return - - if not sentipy.supported(ns_parser.ticker): - print("This stock is not supported by the SentimentInvestor API.") - return - - data = sentipy.historical( - ns_parser.ticker, - ns_parser.metric, - int(time.time() - 60 * 60 * 24 * 7), - int(time.time()), - ) - df = pd.DataFrame.from_dict( - { - "date": map(datetime.datetime.utcfromtimestamp, data.keys()), - ns_parser.metric: data.values(), - } - ) - - df.sort_index(ascending=True, inplace=True) - - if df.empty: - logging.error("The dataset is empty, something must have gone wrong") - return - - _customise_plot() - - # use seaborn to lineplot - ax = sns.lineplot( - data=df, - x="date", - y=ns_parser.metric, - legend=False, - label=[ns_parser.metric], - ) - - # always show zero on the y-axis - plt.ylim(bottom=0) - - # set the x-axis date formatting - ax.xaxis.set_major_formatter(mdates.DateFormatter("%x")) - - # scale the plot appropriately - plt.gcf().set_size_inches(plot_autoscale()) - plt.gcf().set_dpi(PLOT_DPI) - plt.gcf().autofmt_xdate() - - # fill below the line - plt.fill_between(df.date, df[ns_parser.metric], alpha=0.3) - - # add title e.g. AAPL sentiment since 22/07/21 - plt.title( - f"{ns_parser.ticker} {ns_parser.metric} since {min(df.date).strftime('%x')}" - ) - - plt.show() - - ### - - boundary = _Boundary( - 0, max(df[ns_parser.metric].max(), 2 * df[ns_parser.metric].mean()) - ) - - # average for each day - aggregated = df.resample("D", on="date").mean() - - # reverse the ordering if requested - aggregated.sort_values( - ns_parser.metric - if ns_parser.sort_param == "value" - else ns_parser.sort_param, - axis=0, - ascending=ns_parser.sort_dir == "asc", - inplace=True, - ) - - # format the date according to user's locale - aggregated.index = aggregated.index.strftime("%x") - - # apply coloring to every value - aggregated[ns_parser.metric] = [ - boundary.categorise(value)[0] + str(value) + Style.RESET_ALL - for value in aggregated[ns_parser.metric] - ] - - print( - tabulate.tabulate( - aggregated, - headers=["Day", f"average {ns_parser.metric}"], - tablefmt="psql", - floatfmt=".3f", - ) - ) - print() - - except Exception as e: - logging.error(e) - print(e, "\n") diff --git a/gamestonk_terminal/common/behavioural_analysis/stocktwits_model.py b/gamestonk_terminal/common/behavioural_analysis/stocktwits_model.py new file mode 100644 index 00000000000..cd3653e76f6 --- /dev/null +++ b/gamestonk_terminal/common/behavioural_analysis/stocktwits_model.py @@ -0,0 +1,117 @@ +"""Stocktwits Model""" +__docformat__ = "numpy" + +from typing import Tuple, List, Dict + +import pandas as pd +import requests + + +def get_bullbear(ticker: str) -> Tuple[int, int, int, int]: + """Gets bullbear sentiment for ticker [Source: stocktwits] + + Parameters + ---------- + ticker : str + Ticker to look at + + Returns + ------- + int + Watchlist count + int + Number of cases found for ticker + int + Number of bullish statements + int + Number of bearish statements + """ + result = requests.get( + f"https://api.stocktwits.com/api/2/streams/symbol/{ticker}.json" + ) + if result.status_code == 200: + watchlist_count = result.json()["symbol"]["watchlist_count"] + n_cases = 0 + n_bull = 0 + n_bear = 0 + for message in result.json()["messages"]: + if message["entities"]["sentiment"]: + n_cases += 1 + n_bull += message["entities"]["sentiment"]["basic"] == "Bullish" + n_bear += message["entities"]["sentiment"]["basic"] == "Bearish" + + return watchlist_count, n_cases, n_bull, n_bear + return 0, 0, 0, 0 + + +def get_messages(ticker: str, limit: int = 30) -> List[str]: + """Get last messages for a given ticker [Source: stocktwits] + + Parameters + ---------- + ticker : str + Stock ticker + limit : int + Number of messages to get + + Returns + ------- + List[str] + List of messages + """ + result = requests.get( + f"https://api.stocktwits.com/api/2/streams/symbol/{ticker}.json" + ) + messages = [] + if result.status_code == 200: + for idx, message in enumerate(result.json()["messages"]): + messages.append(message["body"]) + if idx > limit - 1: + break + return messages + + +def get_trending() -> pd.DataFrame: + """Get trending tickers from stocktwits [Source: stocktwits] + + Returns + ------- + pd.DataFrame + Dataframe of trending tickers and watchlist count + """ + result = requests.get("https://api.stocktwits.com/api/2/trending/symbols.json") + if result.status_code == 200: + l_symbols = [] + for symbol in result.json()["symbols"]: + l_symbols.append( + [symbol["symbol"], symbol["watchlist_count"], symbol["title"]] + ) + + df_trending = pd.DataFrame( + l_symbols, columns=["Ticker", "Watchlist Count", "Name"] + ) + return df_trending + + return pd.DataFrame() + + +def get_stalker(user: str, limit: int = 30) -> List[Dict]: + """Gets messages from given user [Source: stocktwits] + + Parameters + ---------- + user : str + User to get posts for + limit : int, optional + Number of posts to get, by default 30 + """ + result = requests.get(f"https://api.stocktwits.com/api/2/streams/user/{user}.json") + if result.status_code == 200: + messages = [] + for idx, message in enumerate(result.json()["messages"]): + messages.append(message) + if idx > limit - 1: + break + return messages + + return [] diff --git a/gamestonk_terminal/common/behavioural_analysis/stocktwits_view.py b/gamestonk_terminal/common/behavioural_analysis/stocktwits_view.py index 8f2a6a26f97..8e83f3552a6 100644 --- a/gamestonk_terminal/common/behavioural_analysis/stocktwits_view.py +++ b/gamestonk_terminal/common/behavioural_analysis/stocktwits_view.py @@ -1,226 +1,89 @@ -import argparse -from typing import List -import requests +"""Stocktwits View""" +__docformat__ = "numpy" + import pandas as pd -from gamestonk_terminal.helper_funcs import check_positive, parse_known_args_and_warn + +from tabulate import tabulate +from gamestonk_terminal import feature_flags as gtff +from gamestonk_terminal.common.behavioural_analysis import stocktwits_model -def bullbear(other_args: List[str], ticker: str): +def display_bullbear(ticker: str): """ Print bullbear sentiment based on last 30 messages on the board. Also prints the watchlist_count. [Source: Stocktwits] Parameters ---------- - other_args: List[str] - Arguments for argparse ticker: str Stock ticker """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="bullbear", - description=""" - Print bullbear sentiment based on last 30 messages on the board. - Also prints the watchlist_count. [Source: Stocktwits] - """, - ) - parser.add_argument( - "-t", - "--ticker", - action="store", - dest="ticker", - type=str, - default=ticker, - help="ticker to gather sentiment from.", - ) - - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - result = requests.get( - f"https://api.stocktwits.com/api/2/streams/symbol/{ns_parser.ticker}.json" - ) - if result.status_code == 200: - print(f"Watchlist count: {result.json()['symbol']['watchlist_count']}") - n_cases = 0 - n_bull = 0 - n_bear = 0 - for message in result.json()["messages"]: - if message["entities"]["sentiment"]: - n_cases += 1 - n_bull += message["entities"]["sentiment"]["basic"] == "Bullish" - n_bear += message["entities"]["sentiment"]["basic"] == "Bearish" - if n_cases > 0: - print(f"\nOver {n_cases} sentiment messages:") - print(f"Bullish {round(100*n_bull/n_cases, 2)}%") - print(f"Bearish {round(100*n_bear/n_cases, 2)}%") - else: - print("Invalid symbol") - print("") - - except Exception as e: - print(e, "\n") + watchlist_count, n_cases, n_bull, n_bear = stocktwits_model.get_bullbear(ticker) + print(f"Watchlist count: {watchlist_count}") + if n_cases > 0: + print(f"\nLast {n_cases} sentiment messages:") + print(f"Bullish {round(100*n_bull/n_cases, 2)}%") + print(f"Bearish {round(100*n_bear/n_cases, 2)}%") + else: + print("No messages found") + print("") -def messages(other_args: List[str], ticker: str): +def display_messages(ticker: str, limit: int = 30): """Print up to 30 of the last messages on the board. [Source: Stocktwits] Parameters ---------- - other_args: List[str] - Arguments for argparse ticker: str Stock ticker + limit: int + Number of messages to get """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="messages", - description="""Print up to 30 of the last messages on the board. [Source: Stocktwits]""", - ) - parser.add_argument( - "-t", - "--ticker", - action="store", - dest="ticker", - type=str, - default=ticker, - help="get board messages from this ticker.", - ) - parser.add_argument( - "-l", - "--limit", - action="store", - dest="n_lim", - type=check_positive, - default=30, - help="limit messages shown.", - ) + messages = stocktwits_model.get_messages(ticker, limit) - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - result = requests.get( - f"https://api.stocktwits.com/api/2/streams/symbol/{ns_parser.ticker}.json" - ) - if result.status_code == 200: - for idx, message in enumerate(result.json()["messages"]): - print( - "------------------------------------------------------------------------------" - ) - print(message["body"]) - if idx > ns_parser.n_lim - 1: - break - else: - print("Invalid symbol") - print("") - - except Exception as e: - print(e, "\n") - - -def trending(other_args: List[str]): - """Stocks trending. [Source: Stocktwits] - - Parameters - ---------- - other_args: List[str] - Arguments for argparse - """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="trending", - description="""Stocks trending. [Source: Stocktwits]""", - ) - - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - result = requests.get("https://api.stocktwits.com/api/2/trending/symbols.json") - if result.status_code == 200: - l_symbols = [] - for symbol in result.json()["symbols"]: - l_symbols.append( - [symbol["symbol"], symbol["watchlist_count"], symbol["title"]] - ) - - pd.set_option("display.max_colwidth", None) - df_trending = pd.DataFrame( - l_symbols, columns=["Ticker", "Watchlist Count", "Name"] + if gtff.USE_TABULATE_DF: + print( + tabulate( + pd.DataFrame(messages), headers=[], tablefmt="grid", showindex=False ) - print(df_trending.to_string(index=False)) - else: - print("Error!") - print("") - - except Exception as e: - print(e, "\n") + ) + else: + for message in messages: + print(message, "\n") -def stalker(other_args: List[str]): - """Print up to the last 30 messages of a user. [Source: Stocktwits] +def display_trending(): + """Show trensing stocks on stocktwits""" + df_trending = stocktwits_model.get_trending() + if gtff.USE_TABULATE_DF: + print( + tabulate( + df_trending, + headers=df_trending.columns, + tablefmt="fancy_grid", + showindex=False, + ) + ) + else: + print(df_trending.to_string(index=False)) + print("") + + +def display_stalker(user: str, limit: int = 10): + """Show last posts for given user Parameters ---------- - other_args: List[str] - Arguments for argparse + user : str + Stocktwits username + limit : int, optional + Number of messages to show, by default 10 """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="stalker", - description="""Print up to the last 30 messages of a user. [Source: Stocktwits]""", - ) - parser.add_argument( - "-u", - "--user", - action="store", - dest="s_user", - type=str, - default="Newsfilter", - help="username.", - ) - parser.add_argument( - "-l", - "--limit", - action="store", - dest="n_lim", - type=check_positive, - default=30, - help="limit messages shown.", - ) - - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - result = requests.get( - f"https://api.stocktwits.com/api/2/streams/user/{ns_parser.s_user}.json" + messages = stocktwits_model.get_stalker(user, limit) + for message in messages: + print( + "------------------------------------------------------------------------------" ) - - if result.status_code == 200: - for idx, message in enumerate(result.json()["messages"]): - print( - "------------------------------------------------------------------------------" - ) - print(message["created_at"].replace("T", " ").replace("Z", "")) - print(message["body"]) - print("") - if idx > ns_parser.n_lim - 1: - break - else: - print("Invalid user") + print(message["created_at"].replace("T", " ").replace("Z", "")) + print(message["body"]) print("") - - except Exception as e: - print(e, "\n") diff --git a/gamestonk_terminal/common/behavioural_analysis/twitter_model.py b/gamestonk_terminal/common/behavioural_analysis/twitter_model.py new file mode 100644 index 00000000000..c19d7e2709c --- /dev/null +++ b/gamestonk_terminal/common/behavioural_analysis/twitter_model.py @@ -0,0 +1,93 @@ +"""Twitter Model""" +__docformat__ = "numpy" + +from typing import Optional + +import pandas as pd +import requests +from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer + +from gamestonk_terminal import config_terminal as cfg +from gamestonk_terminal.helper_funcs import clean_tweet, get_data + +analyzer = SentimentIntensityAnalyzer() + + +def load_analyze_tweets( + ticker: str, + count: int, + start_time: Optional[str] = "", + end_time: Optional[str] = "", +) -> pd.DataFrame: + """Load tweets from twitter API and analyzes using VADER + + Parameters + ---------- + ticker: str + Ticker to search twitter for + count: int + Number of tweets to analyze + start : Optional[str] + If given, the start time to get tweets from + end : Optional[str] + If given, the end time to get tweets from + + Returns + ------- + df_tweet: pd.DataFrame + Dataframe of tweets and sentiment + """ + params = { + "query": fr"(\${ticker}) (lang:en)", + "max_results": str(count), + "tweet.fields": "created_at,lang", + } + + if start_time: + # Assign from and to datetime parameters for the API + params["start_time"] = start_time + if end_time: + params["end_time"] = end_time + + # Request Twitter API + response = requests.get( + "https://api.twitter.com/2/tweets/search/recent", + params=params, # type: ignore + headers={"authorization": "Bearer " + cfg.API_TWITTER_BEARER_TOKEN}, + ) + + # Create dataframe + df_tweets = pd.DataFrame() + + # Check that the API response was successful + if response.status_code == 200: + for tweet in response.json()["data"]: + row = get_data(tweet) + df_tweets = df_tweets.append(row, ignore_index=True) + elif response.status_code == 401: + print("Twitter API Key provided is incorrect\n") + return pd.DataFrame() + elif response.status_code == 400: + print( + "Status Code 400. This means you are requesting data from beyond the API's 7 day limit" + ) + return pd.DataFrame() + + sentiments = [] + pos = [] + neg = [] + neu = [] + + for s_tweet in df_tweets["text"].to_list(): + tweet = clean_tweet(s_tweet, ticker) + sentiments.append(analyzer.polarity_scores(tweet)["compound"]) + pos.append(analyzer.polarity_scores(tweet)["pos"]) + neg.append(analyzer.polarity_scores(tweet)["neg"]) + neu.append(analyzer.polarity_scores(tweet)["neu"]) + # Add sentiments to tweets dataframe + df_tweets["sentiment"] = sentiments + df_tweets["positive"] = pos + df_tweets["negative"] = neg + df_tweets["neutral"] = neu + + return df_tweets diff --git a/gamestonk_terminal/common/behavioural_analysis/twitter_view.py b/gamestonk_terminal/common/behavioural_analysis/twitter_view.py index 370e5283446..dc46b181812 100644 --- a/gamestonk_terminal/common/behavioural_analysis/twitter_view.py +++ b/gamestonk_terminal/common/behavioural_analysis/twitter_view.py @@ -1,337 +1,182 @@ """Twitter view""" __docformat__ = "numpy" -import argparse -from typing import List, Optional + +import os from datetime import datetime, timedelta -import requests -from dateutil import parser as dparse -import pandas as pd -from pandas.core.frame import DataFrame -import numpy as np + + import matplotlib.pyplot as plt -from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer -from gamestonk_terminal import config_terminal as cfg -from gamestonk_terminal.helper_funcs import ( - get_data, - clean_tweet, - parse_known_args_and_warn, - plot_autoscale, - check_int_range, -) -import gamestonk_terminal.config_plot as cfg_plot +import numpy as np +import pandas as pd + +from dateutil import parser as dparse + from gamestonk_terminal import feature_flags as gtff - -analyzer = SentimentIntensityAnalyzer() +from gamestonk_terminal.common.behavioural_analysis import twitter_model +from gamestonk_terminal.helper_funcs import export_data, plot_autoscale +import gamestonk_terminal.config_plot as cfg_plot -def load_analyze_tweets( - ticker: str, - count: int, - start_time: Optional[str] = "", - end_time: Optional[str] = "", -) -> DataFrame: - """ - Load tweets from twitter API and analyzes using VADER - Parameters - ---------- - ticker: str - Ticker to search twitter for - count: int - Number of tweets to analyze - start : Optional[str] - If given, the start time to get tweets from - end : Optional[str] - If given, the end time to get tweets from - - Returns - ------- - de_tweet: pd.DataFrame - Dataframe of tweets and sentiment - """ - params = { - "query": fr"(\${ticker}) (lang:en)", - "max_results": str(count), - "tweet.fields": "created_at,lang", - } - - if start_time: - # Assign from and to datetime parameters for the API - params["start_time"] = start_time - if end_time: - params["end_time"] = end_time - - # Request Twitter API - response = requests.get( - "https://api.twitter.com/2/tweets/search/recent", - params=params, # type: ignore - headers={"authorization": "Bearer " + cfg.API_TWITTER_BEARER_TOKEN}, - ) - - # Create dataframe - df_tweets = pd.DataFrame() - - # Check that the API response was successful - if response.status_code == 200: - for tweet in response.json()["data"]: - row = get_data(tweet) - df_tweets = df_tweets.append(row, ignore_index=True) - elif response.status_code == 401: - print("Twitter API Key provided is incorrect\n") - return pd.DataFrame() - elif response.status_code == 400: - print( - "Status Code 400. This means you are requesting data from beyond the API's 7 day limit" - ) - return pd.DataFrame() - - sentiments = [] - pos = [] - neg = [] - neu = [] - - for s_tweet in df_tweets["text"].to_list(): - tweet = clean_tweet(s_tweet, ticker) - sentiments.append(analyzer.polarity_scores(tweet)["compound"]) - pos.append(analyzer.polarity_scores(tweet)["pos"]) - neg.append(analyzer.polarity_scores(tweet)["neg"]) - neu.append(analyzer.polarity_scores(tweet)["neu"]) - # Add sentiments to tweets dataframe - df_tweets["sentiment"] = sentiments - df_tweets["positive"] = pos - df_tweets["negative"] = neg - df_tweets["neutral"] = neu - - return df_tweets - - -def inference(other_args: List[str], ticker: str): +def display_inference(ticker: str, num: int, export: str = ""): """Infer sentiment from past n tweets Parameters ---------- - other_args: List[str] - Arguments for argparse ticker: str Stock ticker + num: int + Number of tweets to analyze + export: str + Format to export tweet dataframe """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="infer", - description=""" - Print quick sentiment inference from last tweets that contain the ticker. - This model splits the text into character-level tokens and uses vader sentiment analysis. - [Source: Twitter] - """, + df_tweets = twitter_model.load_analyze_tweets(ticker, num) + + if df_tweets.empty: + return + + # Parse tweets + dt_from = dparse.parse(df_tweets["created_at"].values[-1]) + dt_to = dparse.parse(df_tweets["created_at"].values[0]) + print(f"From: {dt_from.strftime('%Y-%m-%d %H:%M:%S')}") + print(f"To: {dt_to.strftime('%Y-%m-%d %H:%M:%S')}") + + print(f"{len(df_tweets)} tweets were analyzed.") + dt_delta = dt_to - dt_from + n_freq = dt_delta.total_seconds() / len(df_tweets) + print(f"Frequency of approx 1 tweet every {round(n_freq)} seconds.") + + pos = df_tweets["positive"] + neg = df_tweets["negative"] + + percent_pos = len(np.where(pos > neg)[0]) / len(df_tweets) + percent_neg = len(np.where(pos < neg)[0]) / len(df_tweets) + total_sent = np.round(np.sum(df_tweets["sentiment"]), 2) + mean_sent = np.round(np.mean(df_tweets["sentiment"]), 2) + print(f"The summed compound sentiment of {ticker} is: {total_sent}") + print(f"The average compound sentiment of {ticker} is: {mean_sent}") + print( + f"Of the last {len(df_tweets)} tweets, {100*percent_pos:.2f} % had a higher positive sentiment" ) - parser.add_argument( - "-n", - "--num", - action="store", - dest="n_num", - type=check_int_range(10, 100), - default=100, - help="num of latest tweets to infer from.", + print( + f"Of the last {len(df_tweets)} tweets, {100*percent_neg:.2f} % had a higher negative sentiment" ) - - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: - return - - df_tweets = load_analyze_tweets(ticker, ns_parser.n_num) - - if df_tweets.empty: - return - - # Parse tweets - dt_from = dparse.parse(df_tweets["created_at"].values[-1]) - dt_to = dparse.parse(df_tweets["created_at"].values[0]) - print(f"From: {dt_from.strftime('%Y-%m-%d %H:%M:%S')}") - print(f"To: {dt_to.strftime('%Y-%m-%d %H:%M:%S')}") - - print(f"{len(df_tweets)} tweets were analyzed.") - dt_delta = dt_to - dt_from - n_freq = dt_delta.total_seconds() / len(df_tweets) - print(f"Frequency of approx 1 tweet every {round(n_freq)} seconds.") - - pos = df_tweets["positive"] - neg = df_tweets["negative"] - - percent_pos = len(np.where(pos > neg)[0]) / len(df_tweets) - percent_neg = len(np.where(pos < neg)[0]) / len(df_tweets) - total_sent = np.round(np.sum(df_tweets["sentiment"]), 2) - mean_sent = np.round(np.mean(df_tweets["sentiment"]), 2) - print(f"The summed compound sentiment of {ticker} is: {total_sent}") - print(f"The average compound sentiment of {ticker} is: {mean_sent}") - print( - f"Of the last {len(df_tweets)} tweets, {100*percent_pos:.2f} % had a higher positive sentiment" - ) - print( - f"Of the last {len(df_tweets)} tweets, {100*percent_neg:.2f} % had a higher negative sentiment" - ) - print("") - - except Exception as e: - print(e, "\n") + print("") + export_data(export, os.path.dirname(os.path.abspath(__file__)), "infer", df_tweets) -def sentiment(other_args: List[str], ticker: str): +def display_sentiment(ticker: str, n_tweets: int, n_days_past: int, export: str = ""): """Plot sentiments from ticker Parameters ---------- - other_args: List[str] - Argparse arguments ticker: str Stock to get sentiment for + n_tweets: int + Number of tweets to get per hour + n_days_past: int + Number of days to extract tweets for + export: str + Format to export tweet dataframe """ - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="sentiment", - description=""" - Plot in-depth sentiment predicted from tweets from last days - that contain pre-defined ticker. [Source: Twitter] - """, - ) - # in reality this argument could be 100, but after testing it takes too long - # to compute which may not be acceptable - parser.add_argument( - "-n", - "--num", - action="store", - dest="n_tweets", - type=check_int_range(10, 62), - default=15, - help="number of tweets to extract per hour.", - ) - parser.add_argument( - "-d", - "--days", - action="store", - dest="n_days_past", - type=check_int_range(1, 6), - default=6, - help="number of days in the past to extract tweets.", + # Date format string required by twitter + dtformat = "%Y-%m-%dT%H:%M:%SZ" + + # Algorithm to extract + dt_recent = datetime.now() - timedelta(seconds=20) + dt_old = dt_recent - timedelta(days=n_days_past) + print( + f"From {dt_recent.date()} retrieving {n_tweets*24} tweets ({n_tweets} tweets/hour)" ) - try: - ns_parser = parse_known_args_and_warn(parser, other_args) - if not ns_parser: + df_tweets = pd.DataFrame( + columns=[ + "created_at", + "text", + "sentiment", + "positive", + "negative", + "neutral", + ] + ) + while True: + # Iterate until we haven't passed the old number of days + if dt_recent < dt_old: + break + # Update past datetime + dt_past = dt_recent - timedelta(minutes=60) + + temp = twitter_model.load_analyze_tweets( + ticker, + n_tweets, + start_time=dt_past.strftime(dtformat), + end_time=dt_recent.strftime(dtformat), + ) + + if temp.empty: return - # Date format string required by twitter - dtformat = "%Y-%m-%dT%H:%M:%SZ" + df_tweets = pd.concat([df_tweets, temp]) - # Algorithm to extract - dt_recent = datetime.now() - timedelta(seconds=20) - dt_old = dt_recent - timedelta(days=ns_parser.n_days_past) - print( - f"From {dt_recent.date()} retrieving {ns_parser.n_tweets*24} tweets ({ns_parser.n_tweets} tweets/hour)" - ) - - df_tweets = pd.DataFrame( - columns=[ - "created_at", - "text", - "sentiment", - "positive", - "negative", - "neutral", - ] - ) - while True: - # Iterate until we haven't passed the old number of days - if dt_recent < dt_old: - break - # Update past datetime - dt_past = dt_recent - timedelta(minutes=60) - - temp = load_analyze_tweets( - ticker, - ns_parser.n_tweets, - start_time=dt_past.strftime(dtformat), - end_time=dt_recent.strftime(dtformat), + if dt_past.day < dt_recent.day: + print( + f"From {dt_past.date()} retrieving {n_tweets*24} tweets ({n_tweets} tweets/hour)" ) - if temp.empty: - return + # Update recent datetime + dt_recent = dt_past - df_tweets = pd.concat([df_tweets, temp]) + # Sort tweets per date + df_tweets.sort_index(ascending=False, inplace=True) + df_tweets["cumulative_compound"] = df_tweets["sentiment"].cumsum() + df_tweets["prob_sen"] = 1 - if dt_past.day < dt_recent.day: - print( - f"From {dt_past.date()} retrieving {ns_parser.n_tweets*24} tweets ({ns_parser.n_tweets} tweets/hour)" - ) + # df_tweets.to_csv(r'notebooks/tweets.csv', index=False) + df_tweets.reset_index(inplace=True) + df_tweets["Month"] = pd.to_datetime(df_tweets["created_at"]).apply( + lambda x: x.month + ) + df_tweets["Day"] = pd.to_datetime(df_tweets["created_at"]).apply(lambda x: x.day) + df_tweets["date"] = pd.to_datetime(df_tweets["created_at"]) + df_tweets = df_tweets.sort_values(by="date") + df_tweets["cumulative_compound"] = df_tweets["sentiment"].cumsum() + _, ax = plt.subplots(2, 1, figsize=plot_autoscale(), dpi=cfg_plot.PLOT_DPI) + ax[0].plot( + pd.to_datetime(df_tweets["created_at"]), + df_tweets["cumulative_compound"].values, + lw=3, + c="cyan", + ) + ax[0].set_ylabel("Cumulative VADER Sentiment") + xlocations = [] + xlabels = [] + 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") + ax[0].plot(day_df["time"], day_df["sentiment"].cumsum(), c="tab:blue") + xlocations.append(day_df.time.values[0]) + xlabels.append(day_df["time"].apply(lambda x: x.strftime("%m-%d")).values[0]) - # Update recent datetime - dt_recent = dt_past + ax[1].bar(df_tweets["date"], df_tweets["positive"], color="green", width=0.02) + ax[1].bar(df_tweets["date"], -1 * df_tweets["negative"], color="red", width=0.02) + ax[0].grid(b=True, which="major", color="#666666", linestyle="-", lw=1.5, alpha=0.5) + ax[0].minorticks_on() + ax[0].grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) + ax[0].set_xticks(xlocations) + ax[0].set_xticklabels(xlabels) - # Sort tweets per date - df_tweets.sort_index(ascending=False, inplace=True) - df_tweets["cumulative_compound"] = df_tweets["sentiment"].cumsum() - df_tweets["prob_sen"] = 1 - - # df_tweets.to_csv(r'notebooks/tweets.csv', index=False) - df_tweets.reset_index(inplace=True) - df_tweets["Month"] = pd.to_datetime(df_tweets["created_at"]).apply( - lambda x: x.month - ) - df_tweets["Day"] = pd.to_datetime(df_tweets["created_at"]).apply( - lambda x: x.day - ) - df_tweets["date"] = pd.to_datetime(df_tweets["created_at"]) - df_tweets = df_tweets.sort_values(by="date") - df_tweets["cumulative_compound"] = df_tweets["sentiment"].cumsum() - _, ax = plt.subplots(2, 1, figsize=plot_autoscale(), dpi=cfg_plot.PLOT_DPI) - ax[0].plot( - pd.to_datetime(df_tweets["created_at"]), - df_tweets["cumulative_compound"].values, - lw=3, - c="cyan", - ) - ax[0].set_ylabel("Cumulative VADER Sentiment") - xlocations = [] - xlabels = [] - 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") - ax[0].plot(day_df["time"], day_df["sentiment"].cumsum(), c="tab:blue") - xlocations.append(day_df.time.values[0]) - xlabels.append( - day_df["time"].apply(lambda x: x.strftime("%m-%d")).values[0] - ) - - ax[1].bar( - df_tweets["date"], df_tweets["positive"], color="green", width=0.02 - ) - ax[1].bar( - df_tweets["date"], -1 * df_tweets["negative"], color="red", width=0.02 - ) - ax[0].grid( - b=True, which="major", color="#666666", linestyle="-", lw=1.5, alpha=0.5 - ) - ax[0].minorticks_on() - ax[0].grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) - ax[0].set_xticks(xlocations) - ax[0].set_xticklabels(xlabels) - - ax[1].grid( - b=True, which="major", color="#666666", linestyle="-", lw=1.5, alpha=0.5 - ) - ax[1].minorticks_on() - ax[1].grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) - ax[1].set_ylabel("VADER Polarity Scores") - ax[1].set_xticks(xlocations) - ax[1].set_xticklabels(xlabels) - plt.suptitle( - f"Twitter's {ticker} total compound sentiment over time is {np.sum(df_tweets['sentiment'])}" - ) - if gtff.USE_ION: - plt.ion() - plt.show() - print("") - - except Exception as e: - print(e, "\n") + ax[1].grid(b=True, which="major", color="#666666", linestyle="-", lw=1.5, alpha=0.5) + ax[1].minorticks_on() + ax[1].grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) + ax[1].set_ylabel("VADER Polarity Scores") + ax[1].set_xticks(xlocations) + ax[1].set_xticklabels(xlabels) + plt.suptitle( + f"Twitter's {ticker} total compound sentiment over time is {np.sum(df_tweets['sentiment'])}" + ) + if gtff.USE_ION: + plt.ion() + plt.show() + print("") + export_data( + export, os.path.dirname(os.path.abspath(__file__)), "sentiment", df_tweets + ) diff --git a/gamestonk_terminal/cryptocurrency/due_diligence/finbrain_crypto_view.py b/gamestonk_terminal/cryptocurrency/due_diligence/finbrain_crypto_view.py index 8b3bdef08f3..d6a7a53566a 100644 --- a/gamestonk_terminal/cryptocurrency/due_diligence/finbrain_crypto_view.py +++ b/gamestonk_terminal/cryptocurrency/due_diligence/finbrain_crypto_view.py @@ -5,10 +5,10 @@ import os import pandas as pd from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.common.behavioural_analysis.finbrain_view import ( - get_sentiment, plot_sentiment, sentiment_coloring, ) +from gamestonk_terminal.common.behavioural_analysis.finbrain_model import get_sentiment from gamestonk_terminal.helper_funcs import export_data PATH = os.path.dirname(os.path.abspath(__file__)) diff --git a/gamestonk_terminal/forex/behavioural_analysis/ba_controller.py b/gamestonk_terminal/forex/behavioural_analysis/ba_controller.py index 3e3c4f4082c..04a646e758d 100644 --- a/gamestonk_terminal/forex/behavioural_analysis/ba_controller.py +++ b/gamestonk_terminal/forex/behavioural_analysis/ba_controller.py @@ -1,43 +1,68 @@ """Behavioural Analysis Controller Module""" __docformat__ = "numpy" +# pylint:disable=too-many-lines import argparse import os from typing import List from datetime import datetime +import textwrap from prompt_toolkit.completion import NestedCompleter - +from colorama import Style +import pandas as pd from gamestonk_terminal import feature_flags as gtff -from gamestonk_terminal.helper_funcs import get_flair +from gamestonk_terminal.helper_funcs import ( + get_flair, + parse_known_args_and_warn, + check_int_range, + valid_date, + check_positive, +) from gamestonk_terminal.menu import session from gamestonk_terminal.common.behavioural_analysis import ( google_view, + reddit_view, + stocktwits_view, + finbrain_view, + finnhub_view, + sentimentinvestor_view, + twitter_view, ) +from gamestonk_terminal.stocks.stocks_helper import load class BehaviouralAnalysisController: """Behavioural Analysis Controller class""" # Command choices - CHOICES = [ - "?", - "cls", - "help", - "q", - "quit", - ] - + CHOICES = ["?", "cls", "help", "q", "quit", "load"] CHOICES_COMMANDS = [ + "watchlist", + "spac", + "spac_c", + "wsb", + "popular", + "bullbear", + "messages", + "trending", + "stalker", "infer", "sentiment", "mentions", "regions", "queries", "rise", + "finbrain", + "stats", + "metrics", + "social", + "historical", + "emerging", + "popular", + "popularsi", + "getdd", ] - CHOICES += CHOICES_COMMANDS - def __init__(self, ticker: str, start: datetime): """Constructor""" self.ticker = ticker @@ -45,28 +70,55 @@ class BehaviouralAnalysisController: self.ba_parser = argparse.ArgumentParser(add_help=False, prog="ba") self.ba_parser.add_argument( "cmd", - choices=self.CHOICES, + choices=self.CHOICES + self.CHOICES_COMMANDS, ) - @staticmethod - def print_help(): - """Print help""" - print("\nBehavioural Analysis:") - print(" cls clear screen") - print(" ?/help show this menu again") - print(" q quit this menu, and shows back to main menu") - print(" quit quit to abandon program") - print("") - print("Twitter:") - print(" infer infer about stock's sentiment from latest tweets") - print(" sentiment in-depth sentiment prediction from tweets over time") - print("") - print("Google:") - print(" mentions interest over time based on stock's mentions") - print(" regions regions that show highest interest in stock") - print(" queries top related queries with this stock") - print(" rise top rising related queries with stock") - print("") + def print_help(self): + dim = Style.DIM if not self.ticker else "" + res = Style.RESET_ALL + help_string = f""" +>>>Behavioural Analysis:<<< + +What would you like to do? + cls clear screen + ?/help show this menu again + q quit this menu, and shows back to main menu + quit quit to abandon program + +Ticker: {self.ticker.upper() or None} + +Finbrain:{dim} + finbrain sentiment from 15+ major news headlines {res} +Finnhub:{dim} + stats sentiment stats including comparison with sector{res} +Reddit: + wsb show what WSB gang is up to in subreddit wallstreetbets + watchlist show other users watchlist + popular show popular tickers + spac_c show other users spacs announcements from subreddit SPACs community + spac show other users spacs announcements from other subs{dim} + getdd gets due diligence from another user's post{res} +Stocktwits:{dim} + bullbear estimate quick sentiment from last 30 messages on board + messages output up to the 30 last messages on the board{res} + trending trending stocks + stalker stalk stocktwits user's last messages +Twitter:{dim} + infer infer about stock's sentiment from latest tweets + sentiment in-depth sentiment prediction from tweets over time{res} +Google:{dim} + mentions interest over time based on stock's mentions + regions regions that show highest interest in stock + queries top related queries with this stock + rise top rising related queries with stock{res} +SentimentInvestor: + popularsi show most popular stocks on social media right now + emerging show stocks that are being talked about more than usual{dim} + metrics core social sentiment metrics for this stock + social social media figures for stock popularity + historical plot the past week of data for a selected metric{res} + """ + print(help_string) def switch(self, an_input: str): """Process and dispatch input @@ -111,61 +163,863 @@ class BehaviouralAnalysisController: """Process Quit command - quit the program""" return True + def _check_ticker(self): + """Checks if ticker loaded""" + if not self.ticker: + print("No ticker loaded. Please load using 'load '\n") + return False + return True + + def call_load(self, other_args: List[str]): + """Process load command""" + self.ticker, self.start, _, _ = load( + other_args, self.ticker, "", "1440min", pd.DataFrame() + ) + if "." in self.ticker: + self.ticker = self.ticker.split(".")[0] + + def call_watchlist(self, other_args: List[str]): + """Process watchlist command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="watchlist", + description="""Print other users watchlist. [Source: Reddit]""", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=5, + help="limit of posts with watchlists retrieved.", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + reddit_view.display_watchlist(num=ns_parser.n_limit) + + except Exception as e: + print(e, "\n") + + def call_spac(self, other_args: List[str]): + """Process spac command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="spac", + description="""Show other users SPACs announcement. [Source: Reddit]""", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=5, + help="limit of posts with SPACs retrieved.", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + reddit_view.display_spac(limit=ns_parser.n_limit) + + except Exception as e: + print(e, "\n") + + def call_spac_c(self, other_args: List[str]): + """Process spac_c command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="spac_c", + description="""Print other users SPACs announcement under subreddit 'SPACs'. [Source: Reddit]""", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=10, + help="limit of posts with SPACs retrieved", + ) + parser.add_argument( + "-p", + "--popular", + action="store_true", + default=False, + dest="b_popular", + help="popular flag, if true the posts retrieved are based on score rather than time", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + reddit_view.display_spac_community( + limit=ns_parser.n_limit, popular=ns_parser.b_popular + ) + + except Exception as e: + print(e, "\n") + + def call_wsb(self, other_args: List[str]): + """Process wsb command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="wsb", + description="""Print what WSB gang are up to in subreddit wallstreetbets. [Source: Reddit]""", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=10, + help="limit of posts to print.", + ) + parser.add_argument( + "--new", + action="store_true", + default=False, + dest="b_new", + help="new flag, if true the posts retrieved are based on being more recent rather than their score.", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + reddit_view.display_wsb_community( + limit=ns_parser.n_limit, new=ns_parser.b_new + ) + + except Exception as e: + print(e, "\n") + + def call_popular(self, other_args: List[str]): + """Process popular command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="popular", + description="""Print latest popular tickers. [Source: Reddit]""", + ) + parser.add_argument( + "-n", + "--number", + action="store", + dest="n_top", + type=check_positive, + default=10, + help="display top N tickers", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=50, + help="limit of posts retrieved per sub reddit.", + ) + parser.add_argument( + "-s", + "--sub", + action="store", + dest="s_subreddit", + type=str, + help=""" + subreddits to look for tickers, e.g. pennystocks,stocks. + Default: pennystocks, RobinHoodPennyStocks, Daytrading, StockMarket, stocks, investing, + wallstreetbets + """, + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + reddit_view.display_popular_tickers( + n_top=ns_parser.n_top, + posts_to_look_at=ns_parser.n_limit, + subreddits=ns_parser.s_subreddit, + ) + + except Exception as e: + print(e, "\n") + + def call_getdd(self, other_args: List[str]): + """Process getdd command""" + parser = argparse.ArgumentParser( + add_help=False, + prog="getdd", + description=""" + Print top stock's due diligence from other users. [Source: Reddit] + """, + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=5, + help="limit of posts to retrieve.", + ) + parser.add_argument( + "-d", + "--days", + action="store", + dest="n_days", + type=check_positive, + default=3, + help="number of prior days to look for.", + ) + parser.add_argument( + "-a", + "--all", + action="store_true", + dest="b_all", + default=False, + help=""" + search through all flairs (apart from Yolo and Meme), otherwise we focus on + specific flairs: DD, technical analysis, Catalyst, News, Advice, Chart""", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + reddit_view.display_due_diligence( + ticker=self.ticker, + limit=ns_parser.n_limit, + n_days=ns_parser.n_days, + show_all_flairs=ns_parser.b_all, + ) + except Exception as e: + print(e, "\n") + + def call_bullbear(self, other_args: List[str]): + """Process bullbear command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="bullbear", + description=""" + Print bullbear sentiment based on last 30 messages on the board. + Also prints the watchlist_count. [Source: Stocktwits] + """, + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + stocktwits_view.display_bullbear(ticker=self.ticker) + + except Exception as e: + print(e, "\n") + + def call_messages(self, other_args: List[str]): + """Process messages command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="messages", + description="""Print up to 30 of the last messages on the board. [Source: Stocktwits]""", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_lim", + type=check_positive, + default=30, + help="limit messages shown.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + stocktwits_view.display_messages( + ticker=self.ticker, limit=ns_parser.n_lim + ) + except Exception as e: + print(e, "\n") + + def call_trending(self, other_args: List[str]): + """Process trending command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="trending", + description="""Stocks trending. [Source: Stocktwits]""", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + stocktwits_view.display_trending() + + except Exception as e: + print(e, "\n") + + def call_stalker(self, other_args: List[str]): + """Process stalker command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="stalker", + description="""Print up to the last 30 messages of a user. [Source: Stocktwits]""", + ) + parser.add_argument( + "-u", + "--user", + action="store", + dest="s_user", + type=str, + default="Newsfilter", + help="username.", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_lim", + type=check_positive, + default=30, + help="limit messages shown.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + stocktwits_view.display_stalker( + user=ns_parser.s_user, limit=ns_parser.n_lim + ) + except Exception as e: + print(e, "\n") + def call_mentions(self, other_args: List[str]): """Process mentions command""" - google_view.mentions(other_args, self.ticker, self.start) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="mentions", + description=""" + Plot weekly bars of stock's interest over time. other users watchlist. [Source: Google] + """, + ) + parser.add_argument( + "-s", + "--start", + type=valid_date, + dest="start", + default=self.start, + help="starting date (format YYYY-MM-DD) from when we are interested in stock's mentions.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + google_view.display_mentions( + ticker=self.ticker, start=self.start, export=ns_parser.export + ) + + except Exception as e: + print(e, "\n") def call_regions(self, other_args: List[str]): """Process regions command""" - google_view.regions(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="regions", + description="""Plot bars of regions based on stock's interest. [Source: Google]""", + ) + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_num", + type=check_positive, + default=10, + help="number of regions to plot that show highest interest.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + google_view.display_regions( + ticker=self.ticker, num=ns_parser.n_num, export=ns_parser.export + ) + except Exception as e: + print(e, "\n") def call_queries(self, other_args: List[str]): """Process queries command""" - google_view.queries(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="queries", + description="""Print top related queries with this stock's query. [Source: Google]""", + ) + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_num", + type=check_positive, + default=10, + help="number of top related queries to print.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + google_view.display_queries( + ticker=self.ticker, num=ns_parser.n_num, export=ns_parser.export + ) + except Exception as e: + print(e, "\n") def call_rise(self, other_args: List[str]): """Process rise command""" - google_view.rise(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="rise", + description="""Print top rising related queries with this stock's query. [Source: Google]""", + ) + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_num", + type=check_positive, + default=10, + help="number of top rising related queries to print.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + google_view.display_rise( + ticker=self.ticker, num=ns_parser.n_num, export=ns_parser.export + ) + except Exception as e: + print(e, "\n") def call_infer(self, other_args: List[str]): """Process infer command""" - if not gtff.ENABLE_PREDICT: - print("Predict is not enabled in feature_flags.py") - print("Twitter inference menu is disabled", "\n") - return + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="infer", + description=""" + Print quick sentiment inference from last tweets that contain the ticker. + This model splits the text into character-level tokens and uses vader sentiment analysis. + [Source: Twitter] + """, + ) + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_num", + type=check_int_range(10, 100), + default=100, + help="num of latest tweets to infer from.", + ) try: - # pylint: disable=import-outside-toplevel - from gamestonk_terminal.common.behavioural_analysis import twitter_view - except ModuleNotFoundError as e: - print("Optional packages need to be installed") - print(e, "\n") - return + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + if self._check_ticker(): + twitter_view.display_inference(ticker=self.ticker, num=ns_parser.n_num) except Exception as e: print(e, "\n") - return - - twitter_view.inference(other_args, self.ticker) def call_sentiment(self, other_args: List[str]): """Process sentiment command""" - if not gtff.ENABLE_PREDICT: - print("Predict is not enabled in feature_flags.py") - print("Twitter inference menu is disabled", "\n") - return - + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="sentiment", + description=""" + Plot in-depth sentiment predicted from tweets from last days + that contain pre-defined ticker. [Source: Twitter] + """, + ) + # in reality this argument could be 100, but after testing it takes too long + # to compute which may not be acceptable + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_tweets", + type=check_int_range(10, 62), + default=15, + help="number of tweets to extract per hour.", + ) + parser.add_argument( + "-d", + "--days", + action="store", + dest="n_days_past", + type=check_int_range(1, 6), + default=6, + help="number of days in the past to extract tweets.", + ) try: - # pylint: disable=import-outside-toplevel - from gamestonk_terminal.common.behavioural_analysis import twitter_view - except ModuleNotFoundError as e: - print("Optional packages need to be installed") - print(e, "\n") - return + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + twitter_view.display_sentiment( + ticker=self.ticker, + n_tweets=ns_parser.n_tweets, + n_days_past=ns_parser.n_days_past, + export=ns_parser.export, + ) except Exception as e: print(e, "\n") - return - twitter_view.sentiment(other_args, self.ticker) + def call_finbrain(self, other_args: List[str]): + """Process finbrain command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + 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.FinBrain Technologies develops deep learning + algorithms for financial analysis and prediction, which currently serves + traders from more than 150 countries all around the world. + [Source: https://finbrain.tech]""", + ) + parser.add_argument( + "--export", + choices=["csv", "json", "xlsx"], + default="", + type=str, + dest="export", + help="Export dataframe data to csv,json,xlsx file", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + finbrain_view.display_sentiment_analysis( + ticker=self.ticker, export=ns_parser.export + ) + except Exception as e: + print(e, "\n") + + def call_stats(self, other_args: List[str]): + """Process stats command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="stats", + description=""" + Sentiment stats which displays buzz, news score, articles last week, articles weekly average, + bullish vs bearish percentages, sector average bullish percentage, and sector average news score. + [Source: https://finnhub.io] + """, + ) + parser.add_argument( + "--export", + choices=["csv", "json", "xlsx"], + default="", + type=str, + dest="export", + help="Export dataframe data to csv,json,xlsx file", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + if self._check_ticker(): + finnhub_view.display_sentiment_stats( + ticker=self.ticker, export=ns_parser.export + ) + + except Exception as e: + print(e, "\n") + + def call_metrics(self, other_args: List[str]): + """Process metrics command""" + command_description = f""" + {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to + generate hourly metrics on over 2,000 stocks. Sentiment provides volume and + sentiment metrics powered by proprietary NLP models. + + The {Style.BRIGHT}metrics{Style.RESET_ALL} command prints the following realtime metrics: + + {Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL} + --- + AHI is a measure of how much people are talking about a stock on social media. + It is calculated by dividing the total number of mentions for the chosen stock + on a social network by the mean number of mentions any stock receives on that + social medium. + + {Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL} + --- + RHI is a measure of whether people are talking about a stock more or less than + usual, calculated by dividing the mean AHI for the past day by the mean AHI for + for the past week for that stock. + + {Style.BRIGHT}Sentiment Score{Style.RESET_ALL} + --- + Sentiment score is the percentage of people talking positively about the stock. + For each social network the number of positive posts/comments is divided by the + total number of both positive and negative posts/comments. + + {Style.BRIGHT}SGP (Standard General Perception){Style.RESET_ALL} + --- + SGP is a measure of whether people are more or less positive about a stock than + usual. It is calculated by averaging the past day of sentiment values and then + dividing it by the average of the past week of sentiment values. + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="metrics", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=textwrap.dedent(command_description), + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + if self._check_ticker(): + sentimentinvestor_view.display_metrics(ticker=self.ticker) + + except Exception as e: + print(e, "\n") + + def call_social(self, other_args: List[str]): + """Process social command""" + command_description = f""" + {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to + generate hourly metrics on over 2,000 stocks. Sentiment provides volume and + sentiment metrics powered by proprietary NLP models. + + The {Style.BRIGHT}social{Style.RESET_ALL} command prints the raw data for a given stock, including the number + of mentions it has received on social media in the last hour and the sentiment + score of those comments. + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="social", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=textwrap.dedent(command_description), + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + if self._check_ticker(): + sentimentinvestor_view.display_social(ticker=self.ticker) + + except Exception as e: + print(e, "\n") + + def call_historical(self, other_args: List[str]): + """Process historical command""" + command_description = f""" + {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to + generate hourly metrics on over 2,000 stocks. Sentiment provides volume and + sentiment metrics powered by proprietary NLP models. + + The {Style.BRIGHT}historical{Style.RESET_ALL} command plots the past week of data for a selected metric, one of: + + {Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL} + --- + AHI is a measure of how much people are talking about a stock on social media. + It is calculated by dividing the total number of mentions for the chosen stock + on a social network by the mean number of mentions any stock receives on that + social medium. + + {Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL} + --- + RHI is a measure of whether people are talking about a stock more or less than + usual, calculated by dividing the mean AHI for the past day by the mean AHI for + for the past week for that stock. + + {Style.BRIGHT}Sentiment Score{Style.RESET_ALL} + --- + Sentiment score is the percentage of people talking positively about the stock. + For each social network the number of positive posts/comments is divided by the + total number of both positive and negative posts/comments. + + {Style.BRIGHT}SGP (Standard General Perception){Style.RESET_ALL} + --- + SGP is a measure of whether people are more or less positive about a stock than + usual. It is calculated by averaging the past day of sentiment values and then + dividing it by the average of the past week of sentiment values. + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="historical", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=textwrap.dedent(command_description), + ) + parser.add_argument( + "-s", + "--sort", + action="store", + type=str, + default="date", + help="the parameter to sort output table by", + dest="sort_param", + nargs="?", + choices=["date", "value"], + ) + parser.add_argument( + "-d", + "--direction", + action="store", + type=str, + default="desc", + help="the direction to sort the output table", + dest="sort_dir", + nargs="?", + choices=["asc", "desc"], + ) + parser.add_argument( + "metric", + type=str, + action="store", + default="sentiment", + nargs="?", + choices=["sentiment", "AHI", "RHI", "SGP"], + help="the metric to plot", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + sentimentinvestor_view.display_historical( + ticker=self.ticker, + sort_param=ns_parser.sort_param, + sort_dir=ns_parser.sort_dir, + metric=ns_parser.metric, + ) + except Exception as e: + print(e, "\n") + + def call_popularsi(self, other_args: List[str]): + """Process popular command""" + command_description = f""" + The {Style.BRIGHT}popular{Style.RESET_ALL} command prints the stocks with highest Average Hype Index right now. + + {Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL} + --- + AHI is a measure of how much people are talking about a stock on social media. + It is calculated by dividing the total number of mentions for the chosen stock + on a social network by the mean number of mentions any stock receives on that + social medium. + + === + + {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to + generate hourly metrics on over 2,000 stocks. Sentiment provides volume and + sentiment metrics powered by proprietary NLP models. + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="popularsi", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=textwrap.dedent(command_description), + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="limit", + type=int, + default=10, + help="the maximum number of stocks to retrieve", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + sentimentinvestor_view.display_top(metric="AHI", limit=ns_parser.limit) + except Exception as e: + print(e, "\n") + + def call_emerging(self, other_args: List[str]): + """Process emerging command""" + command_description = f""" + The {Style.BRIGHT}emerging{Style.RESET_ALL} command prints the stocks with highest Relative Hype Index right now. + + {Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL} + --- + RHI is a measure of whether people are talking about a stock more or less than + usual, calculated by dividing the mean AHI for the past day by the mean AHI for + for the past week for that stock. + + === + + {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to + generate hourly metrics on over 2,000 stocks. Sentiment provides volume and + sentiment metrics powered by proprietary NLP models. + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="popular", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=textwrap.dedent(command_description), + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="limit", + type=int, + default=10, + help="the maximum number of stocks to retrieve", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + sentimentinvestor_view.display_top(metric="RHI", limit=ns_parser.limit) + except Exception as e: + print(e, "\n") def menu(ticker: str, start: datetime): diff --git a/gamestonk_terminal/helper_funcs.py b/gamestonk_terminal/helper_funcs.py index 5e800a04fdf..127d3b58c6d 100644 --- a/gamestonk_terminal/helper_funcs.py +++ b/gamestonk_terminal/helper_funcs.py @@ -1,6 +1,7 @@ """Helper functions""" __docformat__ = "numpy" import argparse +from argparse import ArgumentError from typing import List from datetime import datetime, timedelta, time as Time import os @@ -9,7 +10,6 @@ import re import sys import pandas as pd from pytz import timezone -from prettytable import PrettyTable import iso8601 import matplotlib import matplotlib.pyplot as plt @@ -315,6 +315,7 @@ def long_number_format(num) -> str: def clean_data_values_to_float(val: str) -> float: + """Cleans data to float based on string ending""" # Remove any leading or trailing parentheses and spaces val = val.strip("( )") if val == "-": @@ -322,19 +323,14 @@ def clean_data_values_to_float(val: str) -> float: # Convert percentage to decimal if val.endswith("%"): - val_as_float = float(val[:-1]) / 100.0 - # Convert from billions - elif val.endswith("B"): - val_as_float = float(val[:-1]) * 1_000_000_000 - # Convert from millions - elif val.endswith("M"): - val_as_float = float(val[:-1]) * 1_000_000 - # Convert from thousands - elif val.endswith("K"): - val_as_float = float(val[:-1]) * 1000 - else: - val_as_float = float(val) - return val_as_float + return float(val[:-1]) / 100.0 + if val.endswith("B"): + return float(val[:-1]) * 1_000_000_000 + if val.endswith("M"): + return float(val[:-1]) * 1_000_000 + if val.endswith("K"): + return float(val[:-1]) * 1000 + return float(val) def int_or_round_float(x) -> str: @@ -361,7 +357,7 @@ def get_next_stock_market_days(last_stock_day, n_next_days) -> list: year = last_stock_day.date().year if year not in years: years.append(year) - holidays = holidays + us_market_holidays(year) + holidays += us_market_holidays(year) # Check if it is a weekend if last_stock_day.date().weekday() > 4: continue @@ -384,13 +380,8 @@ def get_data(tweet): "%Y-%m-%d %H:%M:%S" ) - if "full_text" in tweet.keys(): - s_text = tweet["full_text"] - else: - s_text = tweet["text"] - - data = {"created_at": s_datetime, "text": s_text} - return data + s_text = tweet["full_text"] if "full_text" in tweet.keys() else tweet["text"] + return {"created_at": s_datetime, "text": s_text} def clean_tweet(tweet: str, s_ticker: str) -> str: @@ -509,7 +500,17 @@ def parse_known_args_and_warn(parser: argparse.ArgumentParser, other_args: List[ parser.add_argument( "-h", "--help", action="store_true", help="show this help message" ) - + try: + parser.add_argument( + "--export", + choices=["png", "jpg", "pdf", "svg", "csv", "json", "xlsx"], + default="", + type=str, + dest="export", + help="Export plot to png,jpg,pdf,svg file or export dataframe to csv,json,xlsx", + ) + except ArgumentError: + pass if gtff.USE_CLEAR_AFTER_CMD: os.system("cls||clear") @@ -530,14 +531,10 @@ def financials_colored_values(val: str) -> str: if val == "N/A" or str(val) == "nan": val = f"{Fore.YELLOW}N/A{Style.RESET_ALL}" elif sum(c.isalpha() for c in val) < 2: - if "%" in val: - if "-" in val: - val = f"{Fore.RED}{val}{Style.RESET_ALL}" - else: - val = f"{Fore.GREEN}{val}{Style.RESET_ALL}" - elif "(" in val: + if "%" in val and "-" in val or "%" not in val and "(" in val: val = f"{Fore.RED}{val}{Style.RESET_ALL}" - + elif "%" in val: + val = f"{Fore.GREEN}{val}{Style.RESET_ALL}" return val @@ -626,48 +623,6 @@ def plot_autoscale(): return x, y -def print_and_record_reddit_post(submissions_dict, submission): - # Refactor data - s_datetime = datetime.utcfromtimestamp(submission.created_utc).strftime( - "%d/%m/%Y %H:%M:%S" - ) - s_link = f"https://old.reddit.com{submission.permalink}" - s_all_awards = "" - for award in submission.all_awardings: - s_all_awards += f"{award['count']} {award['name']}\n" - s_all_awards = s_all_awards[:-2] - # Create dictionary with data to construct dataframe allows to save data - submissions_dict[submission.id] = { - "created_utc": s_datetime, - "subreddit": submission.subreddit, - "link_flair_text": submission.link_flair_text, - "title": submission.title, - "score": submission.score, - "link": s_link, - "num_comments": submission.num_comments, - "upvote_ratio": submission.upvote_ratio, - "awards": s_all_awards, - } - # Print post data collected so far - print(f"{s_datetime} - {submission.title}") - print(f"{s_link}") - t_post = PrettyTable( - ["Subreddit", "Flair", "Score", "# Comments", "Upvote %", "Awards"] - ) - t_post.add_row( - [ - submission.subreddit, - submission.link_flair_text, - submission.score, - submission.num_comments, - f"{round(100 * submission.upvote_ratio)}%", - s_all_awards, - ] - ) - print(t_post) - print("\n") - - def get_last_time_market_was_open(dt): # Check if it is a weekend if dt.date().weekday() > 4: @@ -682,23 +637,6 @@ def get_last_time_market_was_open(dt): return dt -def find_tickers(submission): - ls_text = [] - ls_text.append(submission.selftext) - ls_text.append(submission.title) - - submission.comments.replace_more(limit=0) - for comment in submission.comments.list(): - ls_text.append(comment.body) - - l_tickers_found = [] - for s_text in ls_text: - for s_ticker in set(re.findall(r"([A-Z]{3,5} )", s_text)): - l_tickers_found.append(s_ticker.strip()) - - return l_tickers_found - - def export_data( export_type: str, dir_path: str, func_name: str, df: pd.DataFrame = pd.DataFrame() ): diff --git a/gamestonk_terminal/stocks/behavioural_analysis/ba_controller.py b/gamestonk_terminal/stocks/behavioural_analysis/ba_controller.py index 22e1dee5600..858b16a9dd6 100644 --- a/gamestonk_terminal/stocks/behavioural_analysis/ba_controller.py +++ b/gamestonk_terminal/stocks/behavioural_analysis/ba_controller.py @@ -1,14 +1,23 @@ """Behavioural Analysis Controller Module""" __docformat__ = "numpy" +# pylint:disable=too-many-lines import argparse import os from typing import List from datetime import datetime +import textwrap from prompt_toolkit.completion import NestedCompleter - +from colorama import Style +import pandas as pd from gamestonk_terminal import feature_flags as gtff -from gamestonk_terminal.helper_funcs import get_flair +from gamestonk_terminal.helper_funcs import ( + get_flair, + parse_known_args_and_warn, + check_int_range, + valid_date, + check_positive, +) from gamestonk_terminal.menu import session from gamestonk_terminal.common.behavioural_analysis import ( google_view, @@ -17,19 +26,17 @@ from gamestonk_terminal.common.behavioural_analysis import ( finbrain_view, finnhub_view, sentimentinvestor_view, + twitter_view, ) +from gamestonk_terminal.stocks.stocks_helper import load class BehaviouralAnalysisController: """Behavioural Analysis Controller class""" # Command choices - CHOICES = [ - "?", - "cls", - "help", - "q", - "quit", + CHOICES = ["?", "cls", "help", "q", "quit", "load"] + CHOICES_COMMANDS = [ "watchlist", "spac", "spac_c", @@ -45,7 +52,7 @@ class BehaviouralAnalysisController: "regions", "queries", "rise", - "finbrain", + "headlines", "stats", "metrics", "social", @@ -63,56 +70,55 @@ class BehaviouralAnalysisController: self.ba_parser = argparse.ArgumentParser(add_help=False, prog="ba") self.ba_parser.add_argument( "cmd", - choices=self.CHOICES, + choices=self.CHOICES + self.CHOICES_COMMANDS, ) - @staticmethod - def print_help(): - """Print help""" - print("\nBehavioural Analysis:") - print(" cls clear screen") - print(" ?/help show this menu again") - print(" q quit this menu, and shows back to main menu") - print(" quit quit to abandon program") - print("") - print("Finbrain:") - print(" finbrain sentiment from 15+ major news headlines") - print(" stats sentiment stats including comparison with sector") - print("Reddit:") - print( - " wsb show what WSB gang is up to in subreddit wallstreetbets" - ) - print(" watchlist show other users watchlist") - print(" popular show popular tickers") - print( - " spac_c show other users spacs announcements from subreddit SPACs community" - ) - print(" spac show other users spacs announcements from other subs") - print(" getdd gets due diligence from another user's post") - print("Stocktwits:") - print( - " bullbear estimate quick sentiment from last 30 messages on board" - ) - print(" messages output up to the 30 last messages on the board") - print(" trending trending stocks") - print(" stalker stalk stocktwits user's last messages") - print("Twitter:") - print(" infer infer about stock's sentiment from latest tweets") - print(" sentiment in-depth sentiment prediction from tweets over time") - print("Google:") - print(" mentions interest over time based on stock's mentions") - print(" regions regions that show highest interest in stock") - print(" queries top related queries with this stock") - print(" rise top rising related queries with stock") - print("SentimentInvestor:") - print(" popularsi show most popular stocks on social media right now") - print( - " emerging show stocks that are being talked about more than usual" - ) - print(" metrics core social sentiment metrics for this stock") - print(" social social media figures for stock popularity") - print(" historical plot the past week of data for a selected metric") - print("") + def print_help(self): + dim = Style.DIM if not self.ticker else "" + res = Style.RESET_ALL + help_string = f""" +>>>Behavioural Analysis:<<< + +What would you like to do? + cls clear screen + ?/help show this menu again + q quit this menu, and shows back to main menu + quit quit to abandon program + +Ticker: {self.ticker.upper() or None} + +Finbrain:{dim} + headlines sentiment from 15+ major news headlines {res} +Finnhub:{dim} + stats sentiment stats including comparison with sector{res} +Reddit: + wsb show what WSB gang is up to in subreddit wallstreetbets + watchlist show other users watchlist + popular show popular tickers + spac_c show other users spacs announcements from subreddit SPACs community + spac show other users spacs announcements from other subs{dim} + getdd gets due diligence from another user's post{res} +Stocktwits:{dim} + bullbear estimate quick sentiment from last 30 messages on board + messages output up to the 30 last messages on the board{res} + trending trending stocks + stalker stalk stocktwits user's last messages +Twitter:{dim} + infer infer about stock's sentiment from latest tweets + sentiment in-depth sentiment prediction from tweets over time{res} +Google:{dim} + mentions interest over time based on stock's mentions + regions regions that show highest interest in stock + queries top related queries with this stock + rise top rising related queries with stock{res} +SentimentInvestor: + popularsi show most popular stocks on social media right now + emerging show stocks that are being talked about more than usual{dim} + metrics core social sentiment metrics for this stock + social social media figures for stock popularity + historical plot the past week of data for a selected metric{res} + """ + print(help_string) def switch(self, an_input: str): """Process and dispatch input @@ -157,129 +163,863 @@ class BehaviouralAnalysisController: """Process Quit command - quit the program""" return True + def _check_ticker(self): + """Checks if ticker loaded""" + if not self.ticker: + print("No ticker loaded. Please load using 'load '\n") + return False + return True + + def call_load(self, other_args: List[str]): + """Process load command""" + self.ticker, self.start, _, _ = load( + other_args, self.ticker, "", "1440min", pd.DataFrame() + ) + if "." in self.ticker: + self.ticker = self.ticker.split(".")[0] + def call_watchlist(self, other_args: List[str]): """Process watchlist command""" - reddit_view.watchlist(other_args) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="watchlist", + description="""Print other users watchlist. [Source: Reddit]""", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=5, + help="limit of posts with watchlists retrieved.", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + reddit_view.display_watchlist(num=ns_parser.n_limit) + + except Exception as e: + print(e, "\n") def call_spac(self, other_args: List[str]): """Process spac command""" - reddit_view.spac(other_args) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="spac", + description="""Show other users SPACs announcement. [Source: Reddit]""", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=5, + help="limit of posts with SPACs retrieved.", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + reddit_view.display_spac(limit=ns_parser.n_limit) + + except Exception as e: + print(e, "\n") def call_spac_c(self, other_args: List[str]): """Process spac_c command""" - reddit_view.spac_community(other_args) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="spac_c", + description="""Print other users SPACs announcement under subreddit 'SPACs'. [Source: Reddit]""", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=10, + help="limit of posts with SPACs retrieved", + ) + parser.add_argument( + "-p", + "--popular", + action="store_true", + default=False, + dest="b_popular", + help="popular flag, if true the posts retrieved are based on score rather than time", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + reddit_view.display_spac_community( + limit=ns_parser.n_limit, popular=ns_parser.b_popular + ) + + except Exception as e: + print(e, "\n") def call_wsb(self, other_args: List[str]): """Process wsb command""" - reddit_view.wsb_community(other_args) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="wsb", + description="""Print what WSB gang are up to in subreddit wallstreetbets. [Source: Reddit]""", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=10, + help="limit of posts to print.", + ) + parser.add_argument( + "--new", + action="store_true", + default=False, + dest="b_new", + help="new flag, if true the posts retrieved are based on being more recent rather than their score.", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + reddit_view.display_wsb_community( + limit=ns_parser.n_limit, new=ns_parser.b_new + ) + + except Exception as e: + print(e, "\n") def call_popular(self, other_args: List[str]): """Process popular command""" - reddit_view.popular_tickers(other_args) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="popular", + description="""Print latest popular tickers. [Source: Reddit]""", + ) + parser.add_argument( + "-n", + "--number", + action="store", + dest="n_top", + type=check_positive, + default=10, + help="display top N tickers", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=50, + help="limit of posts retrieved per sub reddit.", + ) + parser.add_argument( + "-s", + "--sub", + action="store", + dest="s_subreddit", + type=str, + help=""" + subreddits to look for tickers, e.g. pennystocks,stocks. + Default: pennystocks, RobinHoodPennyStocks, Daytrading, StockMarket, stocks, investing, + wallstreetbets + """, + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + reddit_view.display_popular_tickers( + n_top=ns_parser.n_top, + posts_to_look_at=ns_parser.n_limit, + subreddits=ns_parser.s_subreddit, + ) + + except Exception as e: + print(e, "\n") def call_getdd(self, other_args: List[str]): """Process getdd command""" - reddit_view.get_due_diligence(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + prog="getdd", + description=""" + Print top stock's due diligence from other users. [Source: Reddit] + """, + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_limit", + type=check_positive, + default=5, + help="limit of posts to retrieve.", + ) + parser.add_argument( + "-d", + "--days", + action="store", + dest="n_days", + type=check_positive, + default=3, + help="number of prior days to look for.", + ) + parser.add_argument( + "-a", + "--all", + action="store_true", + dest="b_all", + default=False, + help=""" + search through all flairs (apart from Yolo and Meme), otherwise we focus on + specific flairs: DD, technical analysis, Catalyst, News, Advice, Chart""", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + reddit_view.display_due_diligence( + ticker=self.ticker, + limit=ns_parser.n_limit, + n_days=ns_parser.n_days, + show_all_flairs=ns_parser.b_all, + ) + except Exception as e: + print(e, "\n") def call_bullbear(self, other_args: List[str]): """Process bullbear command""" - stocktwits_view.bullbear(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="bullbear", + description=""" + Print bullbear sentiment based on last 30 messages on the board. + Also prints the watchlist_count. [Source: Stocktwits] + """, + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + stocktwits_view.display_bullbear(ticker=self.ticker) + + except Exception as e: + print(e, "\n") def call_messages(self, other_args: List[str]): """Process messages command""" - stocktwits_view.messages(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="messages", + description="""Print up to 30 of the last messages on the board. [Source: Stocktwits]""", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_lim", + type=check_positive, + default=30, + help="limit messages shown.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + stocktwits_view.display_messages( + ticker=self.ticker, limit=ns_parser.n_lim + ) + except Exception as e: + print(e, "\n") def call_trending(self, other_args: List[str]): """Process trending command""" - stocktwits_view.trending(other_args) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="trending", + description="""Stocks trending. [Source: Stocktwits]""", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + stocktwits_view.display_trending() + + except Exception as e: + print(e, "\n") def call_stalker(self, other_args: List[str]): """Process stalker command""" - stocktwits_view.stalker(other_args) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="stalker", + description="""Print up to the last 30 messages of a user. [Source: Stocktwits]""", + ) + parser.add_argument( + "-u", + "--user", + action="store", + dest="s_user", + type=str, + default="Newsfilter", + help="username.", + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="n_lim", + type=check_positive, + default=30, + help="limit messages shown.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + stocktwits_view.display_stalker( + user=ns_parser.s_user, limit=ns_parser.n_lim + ) + except Exception as e: + print(e, "\n") def call_mentions(self, other_args: List[str]): """Process mentions command""" - google_view.mentions(other_args, self.ticker, self.start) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="mentions", + description=""" + Plot weekly bars of stock's interest over time. other users watchlist. [Source: Google] + """, + ) + parser.add_argument( + "-s", + "--start", + type=valid_date, + dest="start", + default=self.start, + help="starting date (format YYYY-MM-DD) from when we are interested in stock's mentions.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + google_view.display_mentions( + ticker=self.ticker, start=self.start, export=ns_parser.export + ) + + except Exception as e: + print(e, "\n") def call_regions(self, other_args: List[str]): """Process regions command""" - google_view.regions(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="regions", + description="""Plot bars of regions based on stock's interest. [Source: Google]""", + ) + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_num", + type=check_positive, + default=10, + help="number of regions to plot that show highest interest.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + google_view.display_regions( + ticker=self.ticker, num=ns_parser.n_num, export=ns_parser.export + ) + except Exception as e: + print(e, "\n") def call_queries(self, other_args: List[str]): """Process queries command""" - google_view.queries(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="queries", + description="""Print top related queries with this stock's query. [Source: Google]""", + ) + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_num", + type=check_positive, + default=10, + help="number of top related queries to print.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + google_view.display_queries( + ticker=self.ticker, num=ns_parser.n_num, export=ns_parser.export + ) + except Exception as e: + print(e, "\n") def call_rise(self, other_args: List[str]): """Process rise command""" - google_view.rise(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="rise", + description="""Print top rising related queries with this stock's query. [Source: Google]""", + ) + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_num", + type=check_positive, + default=10, + help="number of top rising related queries to print.", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + google_view.display_rise( + ticker=self.ticker, num=ns_parser.n_num, export=ns_parser.export + ) + except Exception as e: + print(e, "\n") def call_infer(self, other_args: List[str]): """Process infer command""" - if not gtff.ENABLE_PREDICT: - print("Predict is not enabled in feature_flags.py") - print("Twitter inference menu is disabled", "\n") - return + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="infer", + description=""" + Print quick sentiment inference from last tweets that contain the ticker. + This model splits the text into character-level tokens and uses vader sentiment analysis. + [Source: Twitter] + """, + ) + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_num", + type=check_int_range(10, 100), + default=100, + help="num of latest tweets to infer from.", + ) try: - # pylint: disable=import-outside-toplevel - from gamestonk_terminal.common.behavioural_analysis import twitter_view - except ModuleNotFoundError as e: - print("Optional packages need to be installed") - print(e, "\n") - return + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + if self._check_ticker(): + twitter_view.display_inference(ticker=self.ticker, num=ns_parser.n_num) except Exception as e: print(e, "\n") - return - - twitter_view.inference(other_args, self.ticker) def call_sentiment(self, other_args: List[str]): """Process sentiment command""" - if not gtff.ENABLE_PREDICT: - print("Predict is not enabled in feature_flags.py") - print("Twitter inference menu is disabled", "\n") - return - + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="sentiment", + description=""" + Plot in-depth sentiment predicted from tweets from last days + that contain pre-defined ticker. [Source: Twitter] + """, + ) + # in reality this argument could be 100, but after testing it takes too long + # to compute which may not be acceptable + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_tweets", + type=check_int_range(10, 62), + default=15, + help="number of tweets to extract per hour.", + ) + parser.add_argument( + "-d", + "--days", + action="store", + dest="n_days_past", + type=check_int_range(1, 6), + default=6, + help="number of days in the past to extract tweets.", + ) try: - # pylint: disable=import-outside-toplevel - from gamestonk_terminal.common.behavioural_analysis import twitter_view - except ModuleNotFoundError as e: - print("Optional packages need to be installed") - print(e, "\n") - return + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + twitter_view.display_sentiment( + ticker=self.ticker, + n_tweets=ns_parser.n_tweets, + n_days_past=ns_parser.n_days_past, + export=ns_parser.export, + ) except Exception as e: print(e, "\n") - return - twitter_view.sentiment(other_args, self.ticker) - - def call_finbrain(self, other_args: List[str]): + def call_headlines(self, other_args: List[str]): """Process finbrain command""" - finbrain_view.sentiment_analysis(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + 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.FinBrain Technologies develops deep learning + algorithms for financial analysis and prediction, which currently serves + traders from more than 150 countries all around the world. + [Source: https://finbrain.tech]""", + ) + parser.add_argument( + "--export", + choices=["csv", "json", "xlsx"], + default="", + type=str, + dest="export", + help="Export dataframe data to csv,json,xlsx file", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + finbrain_view.display_sentiment_analysis( + ticker=self.ticker, export=ns_parser.export + ) + except Exception as e: + print(e, "\n") def call_stats(self, other_args: List[str]): """Process stats command""" - finnhub_view.sentiment_stats(other_args, self.ticker) + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="stats", + description=""" + Sentiment stats which displays buzz, news score, articles last week, articles weekly average, + bullish vs bearish percentages, sector average bullish percentage, and sector average news score. + [Source: https://finnhub.io] + """, + ) + parser.add_argument( + "--export", + choices=["csv", "json", "xlsx"], + default="", + type=str, + dest="export", + help="Export dataframe data to csv,json,xlsx file", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + if self._check_ticker(): + finnhub_view.display_sentiment_stats( + ticker=self.ticker, export=ns_parser.export + ) + + except Exception as e: + print(e, "\n") def call_metrics(self, other_args: List[str]): """Process metrics command""" - sentimentinvestor_view.metrics(self.ticker, other_args) + command_description = f""" + {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to + generate hourly metrics on over 2,000 stocks. Sentiment provides volume and + sentiment metrics powered by proprietary NLP models. + + The {Style.BRIGHT}metrics{Style.RESET_ALL} command prints the following realtime metrics: + + {Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL} + --- + AHI is a measure of how much people are talking about a stock on social media. + It is calculated by dividing the total number of mentions for the chosen stock + on a social network by the mean number of mentions any stock receives on that + social medium. + + {Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL} + --- + RHI is a measure of whether people are talking about a stock more or less than + usual, calculated by dividing the mean AHI for the past day by the mean AHI for + for the past week for that stock. + + {Style.BRIGHT}Sentiment Score{Style.RESET_ALL} + --- + Sentiment score is the percentage of people talking positively about the stock. + For each social network the number of positive posts/comments is divided by the + total number of both positive and negative posts/comments. + + {Style.BRIGHT}SGP (Standard General Perception){Style.RESET_ALL} + --- + SGP is a measure of whether people are more or less positive about a stock than + usual. It is calculated by averaging the past day of sentiment values and then + dividing it by the average of the past week of sentiment values. + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="metrics", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=textwrap.dedent(command_description), + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + if self._check_ticker(): + sentimentinvestor_view.display_metrics(ticker=self.ticker) + + except Exception as e: + print(e, "\n") def call_social(self, other_args: List[str]): """Process social command""" - sentimentinvestor_view.socials(self.ticker, other_args) + command_description = f""" + {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to + generate hourly metrics on over 2,000 stocks. Sentiment provides volume and + sentiment metrics powered by proprietary NLP models. + + The {Style.BRIGHT}social{Style.RESET_ALL} command prints the raw data for a given stock, including the number + of mentions it has received on social media in the last hour and the sentiment + score of those comments. + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="social", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=textwrap.dedent(command_description), + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + if self._check_ticker(): + sentimentinvestor_view.display_social(ticker=self.ticker) + + except Exception as e: + print(e, "\n") def call_historical(self, other_args: List[str]): """Process historical command""" - sentimentinvestor_view.historical(self.ticker, other_args) + command_description = f""" + {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to + generate hourly metrics on over 2,000 stocks. Sentiment provides volume and + sentiment metrics powered by proprietary NLP models. + + The {Style.BRIGHT}historical{Style.RESET_ALL} command plots the past week of data for a selected metric, one of: + + {Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL} + --- + AHI is a measure of how much people are talking about a stock on social media. + It is calculated by dividing the total number of mentions for the chosen stock + on a social network by the mean number of mentions any stock receives on that + social medium. + + {Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL} + --- + RHI is a measure of whether people are talking about a stock more or less than + usual, calculated by dividing the mean AHI for the past day by the mean AHI for + for the past week for that stock. + + {Style.BRIGHT}Sentiment Score{Style.RESET_ALL} + --- + Sentiment score is the percentage of people talking positively about the stock. + For each social network the number of positive posts/comments is divided by the + total number of both positive and negative posts/comments. + + {Style.BRIGHT}SGP (Standard General Perception){Style.RESET_ALL} + --- + SGP is a measure of whether people are more or less positive about a stock than + usual. It is calculated by averaging the past day of sentiment values and then + dividing it by the average of the past week of sentiment values. + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="historical", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=textwrap.dedent(command_description), + ) + parser.add_argument( + "-s", + "--sort", + action="store", + type=str, + default="date", + help="the parameter to sort output table by", + dest="sort_param", + nargs="?", + choices=["date", "value"], + ) + parser.add_argument( + "-d", + "--direction", + action="store", + type=str, + default="desc", + help="the direction to sort the output table", + dest="sort_dir", + nargs="?", + choices=["asc", "desc"], + ) + parser.add_argument( + "metric", + type=str, + action="store", + default="sentiment", + nargs="?", + choices=["sentiment", "AHI", "RHI", "SGP"], + help="the metric to plot", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if self._check_ticker(): + sentimentinvestor_view.display_historical( + ticker=self.ticker, + sort_param=ns_parser.sort_param, + sort_dir=ns_parser.sort_dir, + metric=ns_parser.metric, + ) + except Exception as e: + print(e, "\n") def call_popularsi(self, other_args: List[str]): """Process popular command""" - sentimentinvestor_view.sort_sentiment("AHI", other_args, "popularsi") + command_description = f""" + The {Style.BRIGHT}popular{Style.RESET_ALL} command prints the stocks with highest Average Hype Index right now. + + {Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL} + --- + AHI is a measure of how much people are talking about a stock on social media. + It is calculated by dividing the total number of mentions for the chosen stock + on a social network by the mean number of mentions any stock receives on that + social medium. + + === + + {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to + generate hourly metrics on over 2,000 stocks. Sentiment provides volume and + sentiment metrics powered by proprietary NLP models. + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="popularsi", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=textwrap.dedent(command_description), + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="limit", + type=int, + default=10, + help="the maximum number of stocks to retrieve", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + sentimentinvestor_view.display_top(metric="AHI", limit=ns_parser.limit) + except Exception as e: + print(e, "\n") def call_emerging(self, other_args: List[str]): """Process emerging command""" - sentimentinvestor_view.sort_sentiment("RHI", other_args, "emerging") + command_description = f""" + The {Style.BRIGHT}emerging{Style.RESET_ALL} command prints the stocks with highest Relative Hype Index right now. + + {Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL} + --- + RHI is a measure of whether people are talking about a stock more or less than + usual, calculated by dividing the mean AHI for the past day by the mean AHI for + for the past week for that stock. + + === + + {Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to + generate hourly metrics on over 2,000 stocks. Sentiment provides volume and + sentiment metrics powered by proprietary NLP models. + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="popular", + formatter_class=argparse.RawDescriptionHelpFormatter, + description=textwrap.dedent(command_description), + ) + parser.add_argument( + "-l", + "--limit", + action="store", + dest="limit", + type=int, + default=10, + help="the maximum number of stocks to retrieve", + ) + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + sentimentinvestor_view.display_top(metric="RHI", limit=ns_parser.limit) + except Exception as e: + print(e, "\n") def menu(ticker: str, start: datetime): diff --git a/gamestonk_terminal/stocks/stocks_controller.py b/gamestonk_terminal/stocks/stocks_controller.py index 97eb0cae60e..cbd201633bb 100644 --- a/gamestonk_terminal/stocks/stocks_controller.py +++ b/gamestonk_terminal/stocks/stocks_controller.py @@ -105,7 +105,8 @@ class StocksController: stock_text = f"{s_intraday} Stock: {self.ticker} (from {self.start.strftime('%Y-%m-%d')})" else: stock_text = f"{s_intraday} Stock: {self.ticker}" - + dim_if_no_ticker = Style.DIM if not self.ticker else "" + reset_style_if_no_ticker = Style.RESET_ALL if not self.ticker else "" help_text = f""" >> STOCKS << @@ -120,11 +121,11 @@ What do you want to do? {stock_text} Market {('CLOSED', 'OPEN')[b_is_stock_market_open()]} -{Style.DIM if not self.ticker else ''} +{dim_if_no_ticker} quote view the current price for a specific stock ticker candle view a candle chart for a specific stock ticker news latest news of the company [News API] -{Style.RESET_ALL if not self.ticker else ''} +{reset_style_if_no_ticker} >> options go into options context {'with ' if self.ticker else ''}{self.ticker} > disc discover trending stocks, \t e.g. map, sectors, high short interest @@ -132,17 +133,17 @@ Market {('CLOSED', 'OPEN')[b_is_stock_market_open()]} > scr screener stocks, \t\t e.g. overview/performance, using preset filters > ins insider trading, \t e.g.: latest penny stock buys, top officer purchases > gov government menu, \t\t e.g. house trading, contracts, corporate lobbying -> report generate automatic report, \t e.g.: dark pool, due diligence{Style.DIM if not self.ticker else ''} +> report generate automatic report, \t e.g.: dark pool, due diligence +> ba behavioural analysis, \t from: reddit, stocktwits, twitter, google{dim_if_no_ticker} > fa fundamental analysis, \t e.g.: income, balance, cash, earnings > res research web page, \t e.g.: macroaxis, yahoo finance, fool > dd in-depth due-diligence, \t e.g.: news, analyst, shorts, insider, sec > ca comparison analysis, \t e.g.: historical, correlation, financials > bt strategy backtester, \t e.g.: simple ema, ema cross, rsi strategies > ta technical analysis, \t e.g.: ema, macd, rsi, adx, bbands, obv -> ba behavioural analysis, \t from: reddit, stocktwits, twitter, google > qa quantitative analysis, \t e.g.: decompose, cusum, residuals analysis > pred prediction techniques, \t e.g.: regression, arima, rnn, lstm -{Style.RESET_ALL if not self.ticker else ''}""" +{reset_style_if_no_ticker}""" print(help_text) def switch(self, an_input: str): @@ -438,10 +439,6 @@ Market {('CLOSED', 'OPEN')[b_is_stock_market_open()]} def call_ba(self, _): """Process ba command""" - if not self.ticker: - print("Use 'load ' prior to this command!", "\n") - return - ret = ba_controller.menu( self.ticker, self.start, diff --git a/website/content/stocks/behavioural_analysis/bullbear/_index.md b/website/content/stocks/behavioural_analysis/bullbear/_index.md index 786adcacdb5..17cdd0e329c 100755 --- a/website/content/stocks/behavioural_analysis/bullbear/_index.md +++ b/website/content/stocks/behavioural_analysis/bullbear/_index.md @@ -1,13 +1,11 @@ ``` -usage: bullbear [-t TICKER] [-h] +usage: bullbear [-h] ``` Print bullbear sentiment based on last 30 messages on the board. Also prints the watchlist_count. [Source: Stocktwits] ``` optional arguments: - -t TICKER, --ticker TICKER - ticker to gather sentiment from. (default: AAPL) -h, --help show this help message (default: False) ``` diff --git a/website/content/stocks/behavioural_analysis/emerging/_index.md b/website/content/stocks/behavioural_analysis/emerging/_index.md index 1491bf765ab..242452f1bf3 100755 --- a/website/content/stocks/behavioural_analysis/emerging/_index.md +++ b/website/content/stocks/behavioural_analysis/emerging/_index.md @@ -6,15 +6,35 @@ The emerging command prints the stocks with highest Relative Hype Index right no RHI (Relative Hype Index) --- -RHI is a measure of whether people are talking about a stock more or less than usual, calculated by dividing the mean AHI for the past day by the mean AHI for the past week for that stock. +RHI is a measure of whether people are talking about a stock more or less than +usual, calculated by dividing the mean AHI for the past day by the mean AHI for +for the past week for that stock. === -Sentiment Investor analyzes data from four major social media platforms to generate hourly metrics on over 2,000 stocks. Sentiment provides volume and sentiment metrics powered by proprietary NLP models. +Sentiment Investor analyzes data from four major social media platforms to +generate hourly metrics on over 2,000 stocks. Sentiment provides volume and +sentiment metrics powered by proprietary NLP models. ``` optional arguments: -l LIMIT, --limit LIMIT the maximum number of stocks to retrieve -h, --help show this help message -``` + ``` + + ``` + (✨) (stocks)>(ba)> emerging + Rank Ticker RHI +------ -------- ----- + 1 FINV 6.432 + 2 GOVX 6.282 + 3 JZXN 5.368 + 4 GOGO 5.311 + 5 GWW 4.993 + 6 SHW 4.937 + 7 EYES 4.772 + 8 FSD 4.387 + 9 NUAN 4.019 + 10 JNUG 3.970 + ``` diff --git a/website/content/stocks/behavioural_analysis/getdd/_index.md b/website/content/stocks/behavioural_analysis/getdd/_index.md index d94ab5fd6ea..d9a2877c03e 100755 --- a/website/content/stocks/behavioural_analysis/getdd/_index.md +++ b/website/content/stocks/behavioural_analysis/getdd/_index.md @@ -10,9 +10,10 @@ optional arguments: limit of posts to retrieve. -d N_DAYS, --days N_DAYS number of prior days to look for. - -a, --all search through all flairs (apart from Yolo and Meme), otherwise we focus on specific flairs: DD, technical analysis, - Catalyst, News, Advice, Chart + -a, --all search through all flairs (apart from Yolo and Meme), otherwise we focus on specific flairs: DD, technical + analysis, Catalyst, News, Advice, Chart -h, --help show this help message ``` + popular diff --git a/website/content/stocks/behavioural_analysis/finbrain/_index.md b/website/content/stocks/behavioural_analysis/headlines/_index.md similarity index 97% rename from website/content/stocks/behavioural_analysis/finbrain/_index.md rename to website/content/stocks/behavioural_analysis/headlines/_index.md index daede196b79..20dda92a5d9 100755 --- a/website/content/stocks/behavioural_analysis/finbrain/_index.md +++ b/website/content/stocks/behavioural_analysis/headlines/_index.md @@ -1,5 +1,5 @@ ``` -usage: finbrain [-h] +usage: headlines [-h] ``` 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. FinBrain Technologies develops deep learning algorithms for financial analysis and prediction, which currently serves traders from more than 150 countries all around the world. [Source: See https://finbrain.tech] diff --git a/website/content/stocks/behavioural_analysis/historical/_index.md b/website/content/stocks/behavioural_analysis/historical/_index.md index c558027de73..9390e43136a 100755 --- a/website/content/stocks/behavioural_analysis/historical/_index.md +++ b/website/content/stocks/behavioural_analysis/historical/_index.md @@ -1,5 +1,5 @@ ``` -usage: historical [-t TICKER] [-s [{date,value}]] [-d [{asc,desc}]] [-h] [{sentiment,AHI,RHI,SGP}] +usage: historical [-s [{date,value}]] [-d [{asc,desc}]] [-h] [{sentiment,AHI,RHI,SGP}] ``` Sentiment Investor analyzes data from four major social media platforms to generate hourly metrics on over 2,000 stocks. Sentiment provides volume and sentiment metrics powered by proprietary NLP models. @@ -30,8 +30,6 @@ positional arguments: the metric to plot optional arguments: - -t TICKER, --ticker TICKER - ticker for which to fetch data -s [{date,value}], --sort [{date,value}] the parameter to sort output table by -d [{asc,desc}], --direction [{asc,desc}] diff --git a/website/content/stocks/behavioural_analysis/metrics/_index.md b/website/content/stocks/behavioural_analysis/metrics/_index.md index 3d1f712f670..383114c1e48 100755 --- a/website/content/stocks/behavioural_analysis/metrics/_index.md +++ b/website/content/stocks/behavioural_analysis/metrics/_index.md @@ -1,5 +1,5 @@ ``` -usage: metrics [-h] [ticker] +usage: metrics [-h] ``` Sentiment Investor analyzes data from four major social media platforms to @@ -34,9 +34,6 @@ usual. It is calculated by averaging the past day of sentiment values and then dividing it by the average of the past week of sentiment values. ``` -positional arguments: - ticker ticker to use instead of the loaded one - optional arguments: -h, --help show this help message ``` diff --git a/website/content/stocks/behavioural_analysis/social/_index.md b/website/content/stocks/behavioural_analysis/social/_index.md index 8bb1324dbc2..25deb23d830 100755 --- a/website/content/stocks/behavioural_analysis/social/_index.md +++ b/website/content/stocks/behavioural_analysis/social/_index.md @@ -1,5 +1,5 @@ ``` -usage: social [-h] [ticker] +usage: social [-h] ``` Sentiment Investor analyzes data from four major social media platforms to generate hourly metrics on over 2,000 stocks. Sentiment provides volume and sentiment metrics powered by proprietary NLP models. @@ -7,9 +7,6 @@ Sentiment Investor analyzes data from four major social media platforms to gener The social command prints the raw data for a given stock, including the number of mentions it has received on social media in the last hour and the sentiment score of those comments. ``` -positional arguments: - ticker ticker to use instead of the loaded one - optional arguments: -h, --help show this help message ``` diff --git a/website/data/menu/main.yml b/website/data/menu/main.yml index fcdde35e745..051c91d7ccb 100755 --- a/website/data/menu/main.yml +++ b/website/data/menu/main.yml @@ -420,8 +420,8 @@ main: - name: behavioural analysis ref: "/stocks/behavioural_analysis" sub: - - name: finbrain - ref: "/stocks/behavioural_analysis/finbrain" + - name: headlines + ref: "/stocks/behavioural_analysis/headlines" - name: stats ref: "/stocks/behavioural_analysis/stats" - name: wsb