I'm a noob. This code doesn't appear to deliver the desired result, what am I doing wrong?
# simple 50/200 MA strategy, all-in long when bullish and all-in short when bearish
def initialize(context):
context.etf_long = sid(8554)
context.etf_short = sid(32268)
context.price_long={}
context.price_short={}
context.invested_long = False
context.invested_short = False
def handle_data(context, data):
price_long = data[context.etf_long].price
price_short = data[context.etf_short].price
fastMA = data[context.etf_long].mavg(50)
slowMA = data[context.etf_long].mavg(200)
if (fastMA > slowMA ):
if (context.invested_short):
log.info("liquidating short")
order(context.etf_short,-(context.portfolio.positions[context.etf_short].amount))
context.invested_short = False
if (not context.invested_long):
log.info("going long")
order(context.etf_long , round(context.portfolio.cash/price_long))
context.invested_long = True
else:
if (context.invested_long):
log.info("liquidating long")
order(context.etf_long,-(context.portfolio.positions[context.etf_long].amount))
context.invested_long = False
if (not context.invested_short):
log.info("going short")
order(context.etf_short , round(context.portfolio.cash/price_short))
context.invested_short = True