Is there a way to shorten this code so that I don't have 4 different SMA's? I tried combining context.xly & context.xlf into a list but wasn't able to get the " if sma_1_20 > sma_1_50:" line to run. Thanks!
def initialize(context):
context.xly = sid(19662)
context.xlf = sid(19656)
schedule_function(ma_crossover_handling, date_rules.every_day(), time_rules.market_close(hours=1, minutes=0))
#calls ma_crossover function once a day, 1 hour after open
def ma_crossover_handling(context, data):
hist_1 = data.history(context.xly, 'price', 50, '1d')
hist_2 = data.history(context.xlf, 'price', 50, '1d')
#gives 50 periods of 1minute data for apple
sma_1_50 = hist_1.mean()
sma_1_20 = hist_1[-20].mean()
sma_2_50 = hist_2.mean()
sma_2_20 = hist_2[-20].mean()
open_orders = get_open_orders()
# ****************************1**************************
if sma_1_20 > sma_1_50:
if context.xly not in open_orders:
#this prevents from double buying, to limit leverage
order_target_percent(context.xly, 0.5)
elif sma_1_20 < sma_1_50:
if context.xly not in open_orders:
order_target_percent(context.xly, -0.5)
# ****************************2**************************
if sma_2_20 > sma_2_50:
if context.xlf not in open_orders:
#this prevents from double buying, to limit leverage
order_target_percent(context.xlf, 0.5)
elif sma_2_20 < sma_2_50:
if context.xlf not in open_orders:
order_target_percent(context.xlf, -0.5)