The above interactive graph displays the real-time intraday stock data for one of my favored tech corporation Square, Inc. Thanks to the awesome tools Alpha Vantage and Plotly, we could freely and easily complete the graph online with python.
In this article I will demonstrate how to fulfil the task with jupyter notebook. Before start, alpha_vantage and plotly should be installed with the pip install []. And you shold also claim a free alpha-vantage API key. Then all the initial preparations are done. Let's start!
xxxxxxxxxx
import pandas as pd
import plotly.plotly as py
import plotly.graph_objs as go
import datetime
from alpha_vantage.timeseries import TimeSeries
Stock Data Acessing
Apply the alpha_vantage API TimeSeries() to acess the real-time intraday stock data, detailed API functionality is provided in the documentation. The argument we choose is stock code and time interval (stock frequency).
I specifically pick up the SQ for Square Inc., with 1-minute and 5-minute as frequency. Note the 5-miute frequency is added to make the candlestick pattern more prominent.
xxxxxxxxxx
# TS data acessor
ts = TimeSeries(key='', # the individual API key
output_format='pandas')
stock_code = 'SQ'
def read_stock(stock_code, interval = '5min'):
df, _ = ts.get_intraday(symbol= stock_code,
interval=interval,
outputsize='full')
# trim the df
df.rename(index= pd.to_datetime,
columns = lambda x : x.split(' ')[-1],
inplace = True)
return df
xxxxxxxxxx
# 5-minutes interval
df_5min = read_stock(stock_code)
# 1-minute interval
df_1min = read_stock(stock_code, interval= '1min')
Visualization
Plotly is a powerful online data visualization library easily communicating with jupyter notebook. I use the plotly to enable both interactive and real-time functionality. By posting my graph online into the plotly repository, it could be shared online and autonomously updated.
To keep the data up-to-date, we need to update the current date. And Python datetime do the task.
xxxxxxxxxx
# acess current date
cur_dt = datetime.datetime.now()
# convert into string
dt_str = cur_dt.strftime('%Y-%m-%d')
xxxxxxxxxx
# respective current date df
df_5 = df_5min[dt_str:]
df_1 = df_1min[dt_str:]
Plotly in Python is basically consisted of two major components: the data argument which is a list of trace object stroing graph data (x and y), and the layout argument which defines the formatting of the plot and magic functionality like animation, interactivity... A full tutorial is well presented for comprehensive understanding. Here I present a interactive graph with customized button.
To begin with, I create the trace items to specifically store candlestick, closed price, low price and high price plot. There is also a default Candlestick plot in plotly. Lastly I gather them together in a list called data.
xxxxxxxxxx
trace = go.Candlestick(x=df_5.index,
open=df_5.open,
high=df_5.high,
low=df_5.low,
close=df_5.close,
name = 'Candlestick')
trace_close = go.Scatter(x=list(df_1.index),
y=list(df_1.close),
name='Close',
line=dict(color='#87CEFA'))
trace_high = go.Scatter(x=list(df_1.index),
y=list(df_1.high),
visible = False,
name='High',
line=dict(color='#33CFA5'))
trace_low = go.Scatter(x=list(df_1.index),
y=list(df_1.low),
visible = False,
name='Low',
line=dict(color='#F06A6A'))
data = [trace, trace_high, trace_low, trace_close]
I set up updatemenus for the customized button objects, which is a specific feature in layout. xanchor and yanchor with x and y are included to make the button properly located the graph. Layout is then completed with desired feature.
xxxxxxxxxx
updatemenus = list([
dict(type="buttons",
active=99,
x = 0.05,
y = 0.99,
bgcolor = '#000000',
bordercolor = '#FFFFFF',
font = dict( color='#FFFFFF', size=11 ),
direction = 'left',
xanchor = 'left',
yanchor = 'top',
buttons=list([
dict(label = 'Close',
method = 'update',
args = [{'visible': [False, False, False, True]},
{'title': 'Minute Trading Data for Square, Inc.'}]),
dict(label = 'Candlestick',
method = 'update',
args = [{'visible': [True, False, False, False]},
{'title': stock_code + ' Candlestick'}]),
dict(label = 'High',
method = 'update',
args = [{'visible': [False, True, False, False]},
{'title': stock_code + ' High'}]),
dict(label = 'Low',
method = 'update',
args = [{'visible': [False, False, True, False]},
{'title': stock_code + ' Low'}]),
dict(label = 'All',
method = 'update',
args = [{'visible': [False, True, True, True]},
{'title': stock_code}]),
dict(label = 'Reset',
method = 'update',
args = [{'visible': [True, False, False, True]},
{'title': 'Minute Trading Data for Square, Inc.'}])
]),
)
])
layout = go.Layout(
title='Minute Trading Data for Square, Inc.',
autosize = True,
plot_bgcolor = '#000000',
showlegend=False,
updatemenus=updatemenus
)
Finally, a fig dictionary is combined with data and layout, thus calling iplot to draw the graph. And we uploaded this jupyter notebook file into the user's plotly repository, then the plotly graph will be automatically generated in the website.
xxxxxxxxxx
fig = dict(data=data,
layout=layout)
py.iplot(fig, filename='minute_candlestick')
By using the sharing link at the bottom of plotly website, the iframe or html code could be derived for online share.
In this way, an online interactive real-time stock graph is cooked. Hurray!