From fab1e40e43e15db14b4226f375ef69fdfde784c0 Mon Sep 17 00:00:00 2001 From: Jeroen Bouma Date: Mon, 15 Nov 2021 18:29:36 +0100 Subject: [PATCH] Add search function to the stocks menu (#945) * Add search function to find company tickers * Add search function to stocks menu * Update _index.md * Delete img.png * Add empty return statement if you call -h * No blank spaces between parser arguments --- .../stocks/stocks_controller.py | 41 ++++++++++++ gamestonk_terminal/stocks/stocks_helper.py | 63 ++++++++++++++++++- website/content/stocks/search/_index.md | 15 +++++ website/data/menu/main.yml | 2 + 4 files changed, 118 insertions(+), 3 deletions(-) create mode 100644 website/content/stocks/search/_index.md diff --git a/gamestonk_terminal/stocks/stocks_controller.py b/gamestonk_terminal/stocks/stocks_controller.py index bc2fce6c2b0..8e346d12d08 100644 --- a/gamestonk_terminal/stocks/stocks_controller.py +++ b/gamestonk_terminal/stocks/stocks_controller.py @@ -18,6 +18,7 @@ from gamestonk_terminal.helper_funcs import ( from gamestonk_terminal.menu import session from gamestonk_terminal.stocks.stocks_helper import ( display_candle, + search, load, quote, process_candle, @@ -52,6 +53,7 @@ class StocksController: ] CHOICES_COMMANDS = [ + "search", "load", "quote", "candle", @@ -113,6 +115,7 @@ What do you want to do? quit quit to abandon the program reset reset terminal and reload configs + search search a specific stock ticker for analysis load load a specific stock ticker for analysis {stock_text} @@ -189,6 +192,44 @@ Market {('CLOSED', 'OPEN')[b_is_stock_market_open()]} return MENU_RESET # COMMANDS + @try_except + def call_search(self, other_args: List[str]): + """Process search command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="search", + description="Show companies matching the search query.", + ) + parser.add_argument( + "-q", + "--query", + action="store", + dest="query", + type=str.lower, + required="-h" not in other_args, + help="The search term used to find company tickers.", + ) + parser.add_argument( + "-a", + "--amount", + default=10, + type=int, + dest="amount", + help="Enter the number of Equities you wish to see in the Tabulate window.", + ) + + if other_args and "-q" not in other_args and "-h" not in other_args: + other_args.insert(0, "-q") + + ns_parser = parse_known_args_and_warn(parser, other_args) + + if not ns_parser: + return + + search(query=ns_parser.query, amount=ns_parser.amount) + + @try_except def call_load(self, other_args: List[str]): """Process load command""" self.ticker, self.start, self.interval, self.stock = load( diff --git a/gamestonk_terminal/stocks/stocks_helper.py b/gamestonk_terminal/stocks/stocks_helper.py index 3ec3eb08262..851483b78ff 100644 --- a/gamestonk_terminal/stocks/stocks_helper.py +++ b/gamestonk_terminal/stocks/stocks_helper.py @@ -1,20 +1,23 @@ """Main helper""" __docformat__ = "numpy" import argparse +import json +import warnings from datetime import datetime, timedelta from typing import List, Union -import warnings -from scipy import stats + import matplotlib.pyplot as plt import mplfinance as mpf import pandas as pd +import plotly.graph_objects as go import pyEX import pytz +import requests import yfinance as yf from alpha_vantage.timeseries import TimeSeries from numpy.core.fromnumeric import transpose -import plotly.graph_objects as go from plotly.subplots import make_subplots +from scipy import stats from tabulate import tabulate from gamestonk_terminal import config_plot as cfgPlot @@ -83,6 +86,60 @@ def clear( return s_ticker, s_start, s_interval, df_stock +def search( + query: str, + amount: int, +): + """Search selected query for tickers. + + Parameters + ---------- + query : str + The search term used to find company tickers. + amount : int + The amount of companies shown. + + Returns + ------- + tabulate + Companies that match the query. + """ + equities_list = ( + "https://raw.githubusercontent.com/JerBouma/FinanceDatabase/master/" + "Database/Equities/Equities List.json" + ) + request = requests.get(equities_list) + equities = json.loads(request.text) + + equities_query = { + key: value + for key, value in equities.items() + if (query in key.lower()) or (query in value.lower()) + } + + equities_dataframe = pd.DataFrame( + equities_query.items(), + index=equities_query.values(), + columns=["Company", "Ticker"], + ) + + if equities_dataframe.empty: + raise ValueError("No companies found. \n") + + if gtff.USE_TABULATE_DF: + print( + tabulate( + equities_dataframe.iloc[:amount], + showindex=False, + headers=["Company", "Ticker"], + tablefmt="fancy_grid", + ), + "\n", + ) + else: + print(equities_dataframe.iloc[:amount].to_string(), "\n") + + def load( other_args: List[str], s_ticker: str, diff --git a/website/content/stocks/search/_index.md b/website/content/stocks/search/_index.md new file mode 100644 index 00000000000..fd9e32817bb --- /dev/null +++ b/website/content/stocks/search/_index.md @@ -0,0 +1,15 @@ +``` +usage: search [-q QUERY] [-a AMOUNT] [-h] +``` +``` +optional arguments: + -q QUERY, --query QUERY + The search term used to find company tickers. (default: None) + -a AMOUNT, --amount AMOUNT + Enter the number of Equities you wish to see in the Tabulate window (default: 10) + -h, --help show this help message (default: False) +``` +Search for company tickers based on a given query. This makes it easier to work fully from within the terminal +instead of needing to rely on Google to find specific company tickers. + +![image](https://user-images.githubusercontent.com/46355364/141761027-cef64364-e04b-4b18-84f3-2ffca4accbaf.png) diff --git a/website/data/menu/main.yml b/website/data/menu/main.yml index 6fd6e7a6e59..a1920a28490 100755 --- a/website/data/menu/main.yml +++ b/website/data/menu/main.yml @@ -3,6 +3,8 @@ main: - name: stocks ref: "/stocks" sub: + - name: search + ref: "/stocks/search" - name: load ref: "/stocks/load" - name: candle