Skip to content

Commit

Permalink
Refactored quote command (#3304)
Browse files Browse the repository at this point in the history
* Refactored quote command

* gotchu colin

* Test

Co-authored-by: James Maslek <jmaslek11@gmail.com>
  • Loading branch information
colin99d and jmaslek authored Nov 5, 2022
1 parent 0a4dcd5 commit 5c975cf
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 65 deletions.
2 changes: 1 addition & 1 deletion openbb_terminal/sdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -1894,7 +1894,7 @@
"model": "openbb_terminal.stocks.stocks_helper.process_candle"
},
"stocks.search": {"model": "openbb_terminal.stocks.stocks_helper.search"},
"stocks.quote": {"model": "openbb_terminal.stocks.stocks_helper.quote"},
"stocks.quote": {"model": "openbb_terminal.stocks.stocks_models.load_quote"},
"stocks.tob": {"model": "openbb_terminal.stocks.cboe_model.get_top_of_book"},
"stocks.candle": {"model": "openbb_terminal.stocks.stocks_helper.display_candle"},
"crypto.load": {
Expand Down
3 changes: 2 additions & 1 deletion openbb_terminal/stocks/stocks_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
translate,
)
from openbb_terminal.stocks import stocks_helper
from openbb_terminal.stocks import stocks_views

# pylint: disable=R1710,import-outside-toplevel,R0913,R1702,no-member

Expand Down Expand Up @@ -368,7 +369,7 @@ def call_quote(self, other_args: List[str]):
other_args.insert(0, "-t")
ns_parser = self.parse_known_args_and_warn(parser, other_args)
if ns_parser:
stocks_helper.quote(ns_parser.s_ticker)
stocks_views.display_quote(ns_parser.s_ticker)

@log_start_end(log=logger)
def call_codes(self, _):
Expand Down
60 changes: 0 additions & 60 deletions openbb_terminal/stocks/stocks_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
from requests.exceptions import ReadTimeout

import yfinance as yf
from numpy.core.fromnumeric import transpose
from plotly.subplots import make_subplots
from scipy import stats

Expand Down Expand Up @@ -721,65 +720,6 @@ def display_candle(
return data


def quote(symbol: str) -> pd.DataFrame:
"""Ticker quote.
Parameters
----------
symbol : str
Ticker
"""
ticker = yf.Ticker(symbol)

try:
quote_df = pd.DataFrame(
[
{
"Symbol": ticker.info["symbol"],
"Name": ticker.info["shortName"],
"Price": ticker.info["regularMarketPrice"],
"Open": ticker.info["regularMarketOpen"],
"High": ticker.info["dayHigh"],
"Low": ticker.info["dayLow"],
"Previous Close": ticker.info["previousClose"],
"Volume": ticker.info["volume"],
"52 Week High": ticker.info["fiftyTwoWeekHigh"],
"52 Week Low": ticker.info["fiftyTwoWeekLow"],
}
]
)

quote_df["Change"] = quote_df["Price"] - quote_df["Previous Close"]
quote_df["Change %"] = quote_df.apply(
lambda x: f'{((x["Change"] / x["Previous Close"]) * 100):.2f}%',
axis="columns",
)
for c in [
"Price",
"Open",
"High",
"Low",
"Previous Close",
"52 Week High",
"52 Week Low",
"Change",
]:
quote_df[c] = quote_df[c].apply(lambda x: f"{x:.2f}")
quote_df["Volume"] = quote_df["Volume"].apply(lambda x: f"{x:,}")

quote_df = quote_df.set_index("Symbol")

quote_data = transpose(quote_df)

print_rich_table(quote_data, title="Ticker Quote", show_index=True)
return quote_data

except KeyError:
logger.exception("Invalid stock ticker")
console.print(f"Invalid stock ticker: {symbol}")
return ""


def load_ticker(
ticker: str, start_date: Union[str, datetime], end_date: Union[str, datetime] = ""
) -> pd.DataFrame:
Expand Down
63 changes: 62 additions & 1 deletion openbb_terminal/stocks/stocks_models.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import os
from datetime import datetime

import logging
import pyEX
import requests
import pandas as pd
import yfinance as yf
from alpha_vantage.timeseries import TimeSeries
from openbb_terminal.decorators import check_api_key

from openbb_terminal.decorators import check_api_key
from openbb_terminal.rich_config import console
from openbb_terminal import config_terminal as cfg

# pylint: disable=unsupported-assignment-operation,no-member

logger = logging.getLogger(__name__)


def load_stock_av(
symbol: str, start_date: datetime, end_date: datetime
Expand Down Expand Up @@ -225,3 +228,61 @@ def load_stock_polygon(
df_stock_candidate = df_stock_candidate.sort_values(by="date")
df_stock_candidate = df_stock_candidate.set_index("date")
return df_stock_candidate


def load_quote(symbol: str) -> pd.DataFrame:
"""Ticker quote. [Source: YahooFinance]
Parameters
----------
symbol : str
Ticker
"""
ticker = yf.Ticker(symbol)

try:
quote_df = pd.DataFrame(
[
{
"Symbol": ticker.info["symbol"],
"Name": ticker.info["shortName"],
"Price": ticker.info["regularMarketPrice"],
"Open": ticker.info["regularMarketOpen"],
"High": ticker.info["dayHigh"],
"Low": ticker.info["dayLow"],
"Previous Close": ticker.info["previousClose"],
"Volume": ticker.info["volume"],
"52 Week High": ticker.info["fiftyTwoWeekHigh"],
"52 Week Low": ticker.info["fiftyTwoWeekLow"],
}
]
)

quote_df["Change"] = quote_df["Price"] - quote_df["Previous Close"]
quote_df["Change %"] = quote_df.apply(
lambda x: f'{((x["Change"] / x["Previous Close"]) * 100):.2f}%',
axis="columns",
)
for c in [
"Price",
"Open",
"High",
"Low",
"Previous Close",
"52 Week High",
"52 Week Low",
"Change",
]:
quote_df[c] = quote_df[c].apply(lambda x: f"{x:.2f}")
quote_df["Volume"] = quote_df["Volume"].apply(lambda x: f"{x:,}")

quote_df = quote_df.set_index("Symbol")

quote_data = quote_df.T

return quote_data

except KeyError:
logger.exception("Invalid stock ticker")
console.print(f"Invalid stock ticker: {symbol}")
return pd.DataFrame()
14 changes: 14 additions & 0 deletions openbb_terminal/stocks/stocks_views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import pandas as pd
from openbb_terminal.stocks import stocks_models
from openbb_terminal.helper_funcs import print_rich_table


def display_quote(symbol: str) -> pd.DataFrame:
"""Display quote from YahooFinance"""
quote_data = stocks_models.load_quote(symbol)
if quote_data is None:
return pd.DataFrame()
if quote_data.empty:
return pd.DataFrame()
print_rich_table(quote_data, title="Ticker Quote", show_index=True)
return quote_data
2 changes: 1 addition & 1 deletion tests/openbb_terminal/stocks/test_stocks_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def test_call_func_expect_queue(expected_queue, func, queue):
(
"call_quote",
[],
"stocks_helper.quote",
"stocks_views.display_quote",
[],
dict(),
),
Expand Down
3 changes: 2 additions & 1 deletion tests/openbb_terminal/stocks/test_stocks_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

# IMPORTATION INTERNAL
from openbb_terminal.stocks import stocks_helper
from openbb_terminal.stocks import stocks_views
from openbb_terminal import helper_funcs


Expand All @@ -26,7 +27,7 @@ def vcr_config():

@pytest.mark.vcr
def test_quote():
stocks_helper.quote("GME")
stocks_views.display_quote("GME")


@pytest.mark.default_cassette("test_search")
Expand Down

0 comments on commit 5c975cf

Please sign in to comment.