Hi,
Thank you for your excellent work.
I want to take advantage of the new Fetcher and upload my own signals. In testing the framework for that, I create a simple random DataFrame and try to access it in handle_data(). But in trying to access a member of the DataFrame in handle_data(), I get "Error Runtime exception: KeyError:".
Here is the relevant code (sorry, I did not figure out how to link directly to my algo). I have a few ugly diagnostics to try to figure out the problem. 3 lines are indicated as causing an error (one of which is a bonus for this post: a simple assert statement does not work).
# Cloned from "Dual Moving Averages version 0.2"
# https://www.quantopian.com/posts/dual-moving-averages-version-0-dot-2
import pandas as pd
import numpy as npy
START = '2012-01-01'
END = '2012-12-31'
index = pd.date_range(START, END, freq='B')
THRESH = 0.1
def initialize(context):
print pd.version.version
# define portfolio
context.sids = [sid(24), sid(3766), sid(5061), sid(22802),
sid(26578)]
context.N = len(context.sids)
# init dict to track whether we invested in a particular sid
context.invested = {}
context.sig = {}
for cur_sid in context.sids:
context.invested[cur_sid] = False
context.sig = pd.DataFrame(
npy.random.rand(len(index), len(context.sids)),
index=index, columns=context.sids)
# This confirms that my pandas syntax is correct.
print context.sig[context.sids[0]][index[0]]
def handle_data(context, data):
sig = context.sig
for cur_sid in context.sids:
# skip non-existant sids
if cur_sid not in data:
continue
t = pd.Timestamp(data[context.sids[0]].datetime.date())
log.critical('*, %s' % str(t))
print type(t)
cash_per_sid = context.portfolio.starting_cash / context.N
#print sig[cur_sid]
i = sig[cur_sid].index == t
dti = sig[cur_sid].index[i]
print dti
print len(dti) # output is 1
#assert len(dti) == 1 # <----------- UNCOMMENT LINE will crash
print type(dti)
#print sig[cur_sid][t] # <-------- UNCOMMENT LINE will crash
# buy if sig exceeds threshold.
if (sig[cur_sid].ix[t] > THRESH): # and not context.invested[cur_sid]: # raises error
order_in_cash(data, cur_sid, cash_per_sid)
context.invested[cur_sid] = True
Thank you for any help.
Ryan