Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Wait for next MA crossover

I'm creating my first algo and wondering how you implement a "wait" for the next moving average crossover trigger.

Upon deployment, the code below would immediately perform a buy even if the crossover occurred a long time ago. I'm trying to avoid opening a position immediately and only want it to execute on the first occurrence of the MA crossover since it has gone live.

def initialize(context):

    context.security_list = symbols('SPY') #just 1 security for now  
def handle_data(context, data):  
    for security in context.security_list:

        price_hist = data.history(security, 'price', 200, '1d')

        # Create 50-day and 200-day trailing windows  
        prices_50 = price_hist[-50:]  
        prices_200 = price_hist

        # 50-day and 200-day simple moving average (SMA)  
        sma_50 = prices_50.mean()  
        sma_200 = prices_200.mean()  
        current_positions = context.portfolio.positions[security].amount  
        if (sma_50 > sma_200) and (current_positions == 0):  
            order_target_percent(security, 1)  
        elif (sma_50 < sma_200) and current_positions != 0:  
            order_target(security, 0)  
1 response

solved by creating a simple "counter" variable in the initialize section which gets updated in handle_data..