Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
EWMA crossover algo doing opposite... help!

I'm writing my first algorithm and I'm trying to modify the result of the pipeline tutorial to select stocks to long/short based on an ExponentialWeightedMovingAverage (EWMA) crossover. But for some reason, it's as if the main criteria gets completely ignored or flipped. Here's a snippet of my code:

def make_pipeline():  
...
# Find stocks that are trending up or down  
    ewma_10 = ExponentialWeightedMovingAverage(inputs=[USEquityPricing.close], window_length=10, decay_rate=0.94, mask=base_universe)  
    ewma_30 = ExponentialWeightedMovingAverage(inputs=[USEquityPricing.close], window_length=30, decay_rate=0.94, mask=base_universe)  
    percent_difference = (ewma_10 - ewma_30) / ewma_30  
    # Create filters to select securities to short and long.  
    trending_up = ewma_10 > ewma_30  
    trending_down = ewma_10 < ewma_30  
    longs = trending_up & True  # force convert to boolean  
    shorts = trending_down & True

    securities_to_trade = (shorts | longs)

    pipe = Pipeline(  
        screen = securities_to_trade,  
        columns = {  
            'dollar_volume': dollar_volume,  
            '10_day_ewma_close': ewma_10,  
            '30_day_ewma_close': ewma_30,  
            'latest_close_price': latest_close,  
            'percent_difference': percent_difference,  
            'longs': longs,  
            'shorts': shorts  
        }  
    )  
    return pipe  

And an example output of a stock that gets bought long is this:

2016-01-04 05:45 my_assign_weights:181 INFO 589 longs: ABMD, TAP, ADBE, ADM...
2016-01-04 05:45 PRINT Equity(53 [ABMD])
2016-01-04 05:45 PRINT dollar_volume = 3890037027.53
2016-01-04 05:45 PRINT 10_day_ewma_close = 107.355376287
2016-01-04 05:45 PRINT 30_day_ewma_close = 111.151362922
2016-01-04 05:45 PRINT latest_close_price = 105.23
2016-01-04 05:45 PRINT percent_difference = -0.0341515077781

As you can see, 10_day_ewma_close is not greater than 30_day_ewma_close, as I had specified. What am I doing wrong? Why is the filter doing the exact opposite of what I'm intending to do? Thanks ahead for any help!

1 response

Never mind, I figured out the bug... I had been printing out the details of a shorted stock, not a long. Adding this code snippet where I print details reveals the truth:

        print "long? " + str(context.output['longs'][0])  
        print "short? " + str(context.output['shorts'][0])  

I still think it's interesting how beautiful the cumulative performance curve is, if I would just flip it upside down. But that goes completely against intuition, to buy long in a downtrend and short in an uptrend! Any thoughts?