Back to Community
MAVG

Hi guys, I'm a bit new to this website and am in need of some help. I want to try and use a SMAVG to define long and short leverage. I have the code below...but its not working and I can't figure out why! Help would be greatly appreciated!

def initialize(context):
context.stock = symbol('SPY')

def record_mavg(context, data):
context.price = data.current(context.stock, 'price')
price_history = data.history(context.stock, 'price', 80, '1d')
short_mavg= price_history[-20].mean()
long_mavg = price_history.mean()

if (short_mavg < long_mavg):  
    context.short_leverage = -0.5  
    context.long_leverage = 1.0  

elif (short_mavg > long_mavg):  
    context.short_leverage = -1.0  
    context.long_leverage = 0.5

short_leverage and long_leverage are then used further on in the code, not trading the SPY but other stocks...but the leveraged is based on SPY market sentiment.