When the average closing price of previous 5 days is higher than that of 60 days, the stock price has a rise tendency, buy. Vice versa.
I try to write the code myself according to api instructions, but there's always mistake. So finally I cloned from the instruction, which works pretty fine.
Here's the algorithm unable to run backtest:
def initialize(context):
context.security=sid(24)
schedule_function(rebalance,date_rule=date_rules.every_day())
def rebalance(context,data):
hist1 = data.history(context.security,field='price',bar_count=5,frequency='1d')
hist2 = data.history(context.security,field='price',bar_count=60,frequency='1d')
MA5 = hist1.mean()
MA60 = hist2.mean()
if data.can_trade(context.security):
if MA5 > MA60:
order_target_percent(context.security,1.0)
elif MA5 < MA60:
order_target_percent(context.security,0)