In [8]:
from datetime import timedelta
import requests
from io import StringIO
import numpy as np
import pandas as pd
from bokeh.io import gridplot
from bokeh.plotting import figure, show, output_notebook
In [9]:
symbols = ['AAPL', 'GOOG']
In [10]:
def get_data(symbol):
url = 'http://chartapi.finance.yahoo.com/instrument/1.0/{}/chartdata;type=quote;range=1d/csv'.format(symbol)
raw = requests.get(url).text
lines = raw.splitlines()
field_names = []
header_lines = list(filter(lambda line:':' in line, lines))
for line in header_lines:
if line.startswith('values:'):
field_names = line.split(':')[1].split(',')
data = pd.read_csv(StringIO(raw), header=len(header_lines), names=field_names)
data['time'] = data['Timestamp'].astype('M8[s]') - timedelta(hours=4)
del data['Timestamp']
start = data['close'][0]
data['chg'] = (data['close'] / start - 1.0) * 100.0
return data
In [11]:
data = list(map(get_data, symbols))
In [12]:
p1 = figure(x_axis_type="datetime", title="Today's % Change", plot_width=400, plot_height=400)
p1.grid.grid_line_alpha=0.3
p1.xaxis.axis_label = 'Time'
p1.yaxis.axis_label = '% Change'
p1.line(data[0]['time'], data[0]['chg'], color='#A6CEE3', legend=symbols[0])
p1.line(data[1]['time'], data[1]['chg'], color='#B2DF8A', legend=symbols[1])
p1.legend.location = "top_left"
In [13]:
p2 = figure(title="% Change Comparison", plot_width=400, plot_height=400)
p2.grid.grid_line_alpha = 0
p2.xaxis.axis_label = '{} % Change'.format(symbols[0])
p2.yaxis.axis_label = '{} % Change'.format(symbols[1])
p2.circle(data[0]['chg'], data[1]['chg'], size=4, legend='change',
color='darkgrey', alpha=.5)
p2.legend.location = "top_left"
In [14]:
output_notebook()
show(gridplot([[p1,p2]]))
Out[14]: