From 7a27f2ff118cf2204000c4c3a6049722ef9baa7b Mon Sep 17 00:00:00 2001 From: Matt Chan Date: Thu, 25 Jun 2020 14:30:47 -0700 Subject: [PATCH] Added bokeh plot builder. --- ticker.py | 111 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 ticker.py diff --git a/ticker.py b/ticker.py new file mode 100644 index 000000000..4e6228676 --- /dev/null +++ b/ticker.py @@ -0,0 +1,111 @@ +"""Render the bokeh visualization of the stock time series.""" +import json +import pandas as pd +import requests +import sys +import bokeh.plotting as bkp +from bokeh.embed import json_item +from bokeh.models import HoverTool +from bokeh.models.tickers import DatetimeTicker + + +KEY = 'Q7JC95BEFD22FQDA' + + +def get_data(symbol): + """Get stock data given symbol from api, return json.""" + url = (f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&" + f"symbol={symbol}&apikey={KEY}") + response = requests.get(url) + data = response.json() + + return data + + +def get_df(data): + """Return formatted dataframe from json data.""" + df = pd.DataFrame(data['Time Series (Daily)']).T + df.index = pd.to_datetime(df.index) + df = df.sort_index().copy() + df.columns = df.columns.str.replace(r'\d+\.\s', '') + df.columns = map(str.title, df.columns) + df = df.drop('Volume', axis=1).astype(float).copy() + + return df + + +def ticker(symbol): + """Render the boken html file.""" + data = get_data(symbol) + df = get_df(data) + + monthago = df.index[-20] + now = df.index[-1] + high = df.loc[monthago:now].max().max() + 5 + low = df.loc[monthago:now].min().min() - 5 + + p = bkp.figure(title=f'{symbol} Stock Price', + y_axis_label='Dollars', + x_axis_type='datetime', + plot_width=800, + plot_height=400, + x_range=(monthago, now), + y_range=(low, high), + toolbar_location="below", + tools="pan,box_zoom,wheel_zoom,reset,save", + active_drag="pan", + ) + p.circle(df.index, + df['Open'], + size=8, + color='olive', + alpha=0.6, + legend_label='Open', + ) + p.circle(df.index, + df['Close'], + size=8, + color='orange', + alpha=0.6, + legend_label='Close', + ) + p.line(df.index, + df['High'], + line_width=2, + color='steelblue', + legend_label='High', + ) + p.line(df.index, + df['Low'], + line_width=2, + color='firebrick', + legend_label='Low', + ) + p.xaxis.ticker = DatetimeTicker(desired_num_ticks=20) + hover = HoverTool(tooltips=[('Date', '@x{%F}'), + ('Price', '$@y{0.00 a}'), + ], + formatters={'@x': 'datetime'}) + p.add_tools(hover) + p.toolbar.active_inspect = hover + + return p + + +def main(): + """Return raw json text from plot with given ticker symbol argument. + + Default ticker symbol is 'IBM'. + """ + if len(sys.argv) == 1: + symbol = 'IBM' + + else: + symbol = sys.argv[1] + + p = ticker(symbol) + print(json.dumps(json_item(p, f'{symbol}_stocks'))) + + +if __name__ == '__main__': + main()