Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to rebalance every month based on a 10 months simple moving average rule ?

Hi, I'm just getting started on quantopian.
I would like to test a simple strategy based on a monthly timeframe :

At the beginning of each month :
• If the SPY is >= to it's 10 months simple moving average we buy it.

• Else we exit all of our positions

I don't manage to get the monthly SMA(10) to test it...
How can I manage this ?

Thank you

4 responses

Here is a sample algorithm which does something close to what you are asking. See if it makes sense.

Good luck!

Thank you very much Dan.
So we must use a daily timeframe ?
We cannot change the timeframe to another basis like weekly or monthly ?

olivier,

You may get any time frame from Quantopian data.history() using .resample()
Hope this simple code will help you.

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

def trade(context, data):  
    #---------------------------------------------  
    stock, TimeFrame, ma = symbol('SPY'), '1M', 10  
    #---------------------------------------------  
    bars = ma*21  
    if get_open_orders(): return 

    curr_price = data.current(stock, 'price')  
    daily_prices = data.history(stock, 'price',  bars, '1d')  
    monthly_prices = daily_prices.resample(TimeFrame).last()  
    print monthly_prices  
    mavg = monthly_prices.mean() 

    if data.can_trade(stock):  
        if curr_price >= mavg:  
            order_target_percent(stock, 1.0)  
        else:  
            order_target_percent(stock, 0)

    record(price = curr_price, mavg = mavg)  

Thank you very much Vladimir.