Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to caculate the periods (bars count) to date from the most recent day on which MA(20)cross MA(60)?

I am struggled with this question. Does anyone can help me out? Thanks!

2 responses

This may help.

# ---------------------------------------  
stock, ma_f, ma_s = symbol('SPY'), 20, 60  
# ---------------------------------------  
def initialize(context):  
    schedule_function(bars_count, date_rules.every_day(), time_rules.market_close(minutes = 5))  
    context.days_since_mac = 0

def bars_count(context, data):  
    mavg_f = data.history(stock, 'price', ma_f, '1d').mean()  
    mavg_s = data.history(stock, 'price', ma_s, '1d').mean()

    if mavg_f > mavg_s:  
        context.days_since_mac += 1  
    else:  
        context.days_since_mac = 0

def before_trading_start(context, data):  
    record(bars_since_mac = context.days_since_mac)  

@ Vladimir

Thank you very much. I will try it