By letting myself struggle a bit for many hours, I was able to get over some humps and learn a lot in the process. The hang up I'm having now is when setuniverse isn't used to define the universe of stocks and instead I define them in initialize with:
def initialize(context):
context.targets = sid(24), sid(33748)
context.rsize = 1000
context.minuts_b4start = 30
schedule_function( heavy_calcs, date_rules.every_day(), time_rules.market_open(minutes= 1), half_days = True )
schedule_function( gap_calcs, date_rules.every_day(), time_rules.market_open(minutes= 5), half_days = True )
schedule_function( EOD_Exit, date_rules.every_day(), time_rules.market_close(minutes= 32), half_days = True )
set_slippage(slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1))
set_commission(commission.PerTrade(cost=6.00))
I have a function that runs once after the open via schedule function that calculates the average range and the standard deviation of the range:
def heavy_calcs (context, data):
targets = context.targets
for stock in targets:
Range = history(30, '1d', 'high')[stock] - history(30, '1d', 'low')[stock]
context.AvgRange = Range.mean()
context.SD = Range.std()
return
When debugging I added a print function to make sure the Range and SD are returning the expected values and they are. I want to use these values in the handle_data function:
def handle_data(context, data):
exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')
for stock in context.targets:
close = data[stock].price
HOD = history(1, '1d', 'high')[stock]
LOD = history(1, '1d', 'low')[stock]
# the first time this runs, context.sd isn't yet defined in the heavy_calcs function
# and since we don't need it until 30 minutes after the open, this fixes that and
# prevents an error from being thrown
if exchange_time.hour >= 10 and exchange_time.minute >= 0:
Unit = context.SD
In the handle_data function, how do I reference which stock I'm referring to when I use Unit = context.SD? Since it's still in for for loop, I tried:
Unit = context[stock].SD or
Unit = context.SD[stock] ?
Both of these throw and error and I know I'm missing something here, just not sure what. In this example the two targets are AAPL and RSX. However in for loop, I want just the standard deviation value for either AAPL or RSX, not the entire contents of context.SD
Tony