Back to Community
rewriting some MAVG to rolling_mean()

I have the below code and I need to rewrite it so that it doesnt use mavg...Of course, just substituting mavg with rolling_mean doesn't work (it would have been too easy). I need to apparently substitute data[context.security] with data.current but then data.current doesnt have a rolling_mean().....Can anyone tell me how to rewrite the below so that it works? As a beginner, I find quantopian remarkably difficult to use

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

def handle_data(context, data):
MA1 = data[context.security].mavg(50)
MA2 = data[context.security].mavg(200)

current_price = data[context.security].price  
current_positions = context.portfolio.positions[symbol('SPY')].amount  
cash = context.portfolio.cash  

if (MA1 > MA2) and current_positions == 0:  
    number_of_shares = int(cash/current_price)  
    order(context.security, number_of_shares)  
    log.info("Buying shares")  

elif (MA1 < MA2) and current_positions != 0:  
    order_target(context.security, 0)  
    log.info("Selling shares")  


record(MA1 = MA1, MA2 = MA2, Price= current_price)  
2 responses

Tisho,

Try this:

security = symbol('SPY')

def initialize(context):  
    schedule_function(trade, date_rules.every_day(), time_rules.market_open(minutes = 65))

def trade(context, data):  
    MA1 = data.history(security, 'price', 50, '1d').mean()  
    MA2 = data.history(security, 'price', 200, '1d').mean()  
    current_price = data.current(security, 'price')  
    current_positions = context.portfolio.positions[security].amount  
    cash = context.portfolio.cash  

    if (MA1 > MA2) and current_positions == 0:  
        number_of_shares = int(cash/current_price)  
        order(security, number_of_shares)  

    elif (MA1 < MA2) and current_positions != 0:  
        order_target(security, 0)  

    record(MA1 = MA1, MA2 = MA2, Price = current_price)  
    record(leverage = context.account.leverage)  

Thanks Vladiimir,

it does work but I have the following questions:

1) Why do I need to schedule function?Why is minutes =65? what does this do?
2) Why are you using mean() rather than rolling mean?
3) What does record(leverage = context.account.leverage) do and is it needed?

Does anyone have a good suggestion on how to getstarted with Quantopian...I cant even find a decent example online that actually works (Most of the examples are outdated (using f-ns that are deprecated))?