Last active
May 6, 2017 20:02
-
-
Save uberscientist/2136b153dea7d231b54becfa3a552033 to your computer and use it in GitHub Desktop.
display half-hourly returns of the SPX index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
from collections import defaultdict | |
from redis import StrictRedis | |
from activetick_http import ActiveTick | |
from datetime import datetime, timedelta | |
from bokeh.charts import Histogram, show | |
from bokeh.layouts import column, row | |
from bokeh.models import Range1d | |
from bokeh.models.widgets import Div | |
from bokeh.io import output_file | |
# Config | |
symbol = 'SPX' | |
intraday_minutes = 30 | |
db = StrictRedis(host='127.0.0.1') | |
at = ActiveTick(cache=db) | |
sample_range = pd.date_range('1/1/2014', '4/30/2017', freq='B') | |
df = pd.DataFrame() | |
times = defaultdict(list) | |
def chunks(l, n): | |
# For item i in a range that is a length of l, | |
for i in range(0, len(l), n): | |
# Create an index range for l of n items: | |
yield l[i:i+n] | |
x_range = Range1d(-25, 25) | |
y_range = Range1d(0, 120) | |
def getHistogram(data): | |
histogram = Histogram(data=df, | |
background_fill_color='grey', | |
color='chartreuse', | |
values=data, | |
ylabel='', | |
plot_height=150, | |
plot_width=200, | |
toolbar_location=None) | |
histogram.x_range = x_range | |
histogram.y_range = y_range | |
return histogram | |
for date in sample_range: | |
start = date + timedelta(hours=9, minutes=30) | |
end = date + timedelta(hours=16) | |
num_chunks = (end - start).total_seconds() / (60 * intraday_minutes) | |
data = at.barData(symbol, historyType='I', intradayMinutes=30, beginTime=start, endTime=end) | |
if len(data) != num_chunks + 1: | |
continue | |
diff = data.close - data.open | |
df = pd.concat([df, diff], axis=0) | |
df.index = df.index.to_datetime() | |
for data_row in df.itertuples(index=True): | |
times[data_row[0].strftime('%H:%M')].append(data_row[1]) | |
df = pd.DataFrame(times) | |
histograms = [getHistogram(col) for col in df.columns.values] | |
rows = chunks(histograms, 4) | |
rows = [row(list(r)) for r in rows] | |
rows = [Div(text='<h1>{symbol}</h1>'.format(symbol=symbol))] + rows | |
output_file(symbol + '_histograms', title=symbol + ' Histograms', mode='cdn') | |
show(column(rows)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment