diff --git a/gamestonk_terminal/common/behavioural_analysis/google_view.py b/gamestonk_terminal/common/behavioural_analysis/google_view.py index 215c5f3a7ab..6be11767870 100644 --- a/gamestonk_terminal/common/behavioural_analysis/google_view.py +++ b/gamestonk_terminal/common/behavioural_analysis/google_view.py @@ -4,6 +4,7 @@ __docformat__ = "numpy" import logging import os from typing import Optional, List +import pandas as pd import matplotlib.pyplot as plt @@ -81,6 +82,76 @@ def display_mentions( ) +@log_start_end(log=logger) +def display_correlation_interest( + ticker: str, + df_data: pd.DataFrame, + words: List[str], + export: str = "", + external_axes: Optional[List[plt.Axes]] = None, +): + """Plot interest over time of words/sentences versus stock price. [Source: Google] + + Parameters + ---------- + ticker : str + Ticker to check price + df_data : pd.DataFrame + Data dataframe + words : List[str] + Words to check for interest for + export: str + Format to export data + external_axes : Optional[List[plt.Axes]], optional + External axes (1 axis is expected in the list), by default None + """ + + # This plot has 1 axis + if external_axes is None: + _, ax = plt.subplots( + figsize=plot_autoscale(), + dpi=PLOT_DPI, + nrows=2, + ncols=1, + sharex=True, + gridspec_kw={"height_ratios": [1, 2]}, + ) + else: + if len(external_axes) != 1: + logger.error("Expected list of one axis item.") + console.print("[red]Expected list of one axis item./n[/red]") + return + (ax,) = external_axes + ax[0].set_title( + f"{ticker.upper()} stock price and interest over time on {','.join(words)}" + ) + ax[0].plot( + df_data.index, + df_data["Adj Close"].values, + c="#FCED00", + ) + ax[0].set_ylabel("Stock Price") + ax[0].set_xlim(df_data.index[0], df_data.index[-1]) + + colors = theme.get_colors()[1:] + for idx, word in enumerate(words): + df_interest = google_model.get_mentions(word) + ax[1].plot(df_interest.index, df_interest[word], "-", color=colors[idx]) + + ax[1].set_ylabel("Interest [%]") + ax[1].set_xlim(df_data.index[0], df_data.index[-1]) + ax[1].legend(words) + theme.style_primary_axis(ax[0]) + theme.style_primary_axis(ax[1]) + + if external_axes is None: + theme.visualize_output() + + export_data( + export, os.path.dirname(os.path.abspath(__file__)), "interest", df_interest + ) + + @log_start_end(log=logger) def display_regions( ticker: str, diff --git a/gamestonk_terminal/stocks/behavioural_analysis/ba_controller.py b/gamestonk_terminal/stocks/behavioural_analysis/ba_controller.py index da81dbdd6d1..204cb5aa40e 100644 --- a/gamestonk_terminal/stocks/behavioural_analysis/ba_controller.py +++ b/gamestonk_terminal/stocks/behavioural_analysis/ba_controller.py @@ -6,6 +6,7 @@ import logging from datetime import datetime, timedelta from typing import List +import yfinance as yf from prompt_toolkit.completion import NestedCompleter from gamestonk_terminal import feature_flags as gtff @@ -64,6 +65,7 @@ class BehaviouralAnalysisController(StockBaseController): "hist", "trend", "snews", + "interest", ] historical_sort = ["date", "value"] @@ -112,6 +114,7 @@ class BehaviouralAnalysisController(StockBaseController): [src][Google][/src] mentions interest over time based on stock's mentions regions regions that show highest interest in stock + interest interest over time of sentences versus stock price queries top related queries with this stock rise top rising related queries with stock{has_ticker_end} [src][SentimentInvestor][/src] @@ -514,6 +517,67 @@ class BehaviouralAnalysisController(StockBaseController): else: console.print("No ticker loaded. Please load using 'load '\n") + @log_start_end(log=logger) + def call_interest(self, other_args: List[str]): + """Process interest command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="interest", + description=""" + Plot interest over time of words/sentences versus stock price. [Source: Google] + """, + ) + parser.add_argument( + "-s", + "--start", + type=valid_date, + dest="start", + default=(datetime.now() - timedelta(days=2 * 366)).strftime("%Y-%m-%d"), + help="starting date (format YYYY-MM-DD) of interest", + ) + parser.add_argument( + "-w", + "--words", + help="Select multiple sentences/words separated by commas. E.g. COVID,WW3,NFT", + dest="words", + type=lambda s: [str(item) for item in s.split(",")], + default=None, + ) + if other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-w") + ns_parser = parse_known_args_and_warn( + parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES + ) + if ns_parser: + if self.ticker: + if ns_parser.words: + df_stock = yf.download( + self.ticker, + start=ns_parser.start.strftime("%Y-%m-%d"), + progress=False, + ) + + if not df_stock.empty: + google_view.display_correlation_interest( + ticker=self.ticker, + df_data=df_stock, + words=ns_parser.words, + export=ns_parser.export, + ) + else: + console.print( + "[red]Ticker provided doesn't exist, load another one.\n[/red]" + ) + else: + console.print( + "[red]Words or sentences to be correlated against with, need to be provided.\n[/red]" + ) + else: + console.print( + "[red]No ticker loaded. Please load using 'load '.\n[/red]" + ) + @log_start_end(log=logger) def call_queries(self, other_args: List[str]): """Process queries command""" diff --git a/scripts/test_stocks_ba.gst b/scripts/test_stocks_ba.gst index afda5fc16f5..163a55cd769 100644 --- a/scripts/test_stocks_ba.gst +++ b/scripts/test_stocks_ba.gst @@ -24,4 +24,5 @@ emerging metrics social historical +interest exit \ No newline at end of file diff --git a/tests/gamestonk_terminal/stocks/behavioural_analysis/txt/test_ba_controller/test_print_help.txt b/tests/gamestonk_terminal/stocks/behavioural_analysis/txt/test_ba_controller/test_print_help.txt index 1d1bffed68d..5517e5b5f4f 100644 --- a/tests/gamestonk_terminal/stocks/behavioural_analysis/txt/test_ba_controller/test_print_help.txt +++ b/tests/gamestonk_terminal/stocks/behavioural_analysis/txt/test_ba_controller/test_print_help.txt @@ -25,6 +25,7 @@ Ticker: TSLA [Google] mentions interest over time based on stock's mentions regions regions that show highest interest in stock + interest interest over time of sentences versus stock price queries top related queries with this stock rise top rising related queries with stock [SentimentInvestor] diff --git a/website/content/stocks/behavioural_analysis/interest/_index.md b/website/content/stocks/behavioural_analysis/interest/_index.md new file mode 100755 index 00000000000..5657c1d4204 --- /dev/null +++ b/website/content/stocks/behavioural_analysis/interest/_index.md @@ -0,0 +1,19 @@ +```text +usage: interest [-s START] [-w WORDS] [-h] [--export {csv,json,xlsx,png,jpg,pdf,svg}] +``` + +Plot interest over time of words/sentences versus stock price. [Source: Google] + +``` +optional arguments: + -s START, --start START + starting date (format YYYY-MM-DD) of interest (default: 2020-03-08) + -w WORDS, --words WORDS + Select multiple sentences/words separated by commas. E.g. COVID,WW3,NFT (default: None) + -h, --help show this help message (default: False) + --export {csv,json,xlsx,png,jpg,pdf,svg} + Export raw data into csv, json, xlsx and figure into png, jpg, pdf, svg (default: ) +``` + +![interest](https://user-images.githubusercontent.com/25267873/157575723-23c55e4e-9e87-4647-b8fa-8ed9643f471f.png) + diff --git a/website/data/menu/main.yml b/website/data/menu/main.yml index ea73ea37040..3f872097345 100755 --- a/website/data/menu/main.yml +++ b/website/data/menu/main.yml @@ -516,6 +516,8 @@ main: ref: "/common/behavioural_analysis/stats" - name: snews ref: "/stocks/behavioural_analysis/snews" + - name: interest + ref: "/stocks/behavioural_analysis/interest" - name: wsb ref: "/common/behavioural_analysis/wsb" - name: watchlist