Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Having trouble creating trading signals with Pipeline

Hi,

I am trying to create a simple strategy that buys AAPL when the 50 day Simple Moving Average (SMA) crosses above the 100 day SMA (as much as possible with available cash) and sells AAPL (all positions) when the 50 day SMA crosses below the 100 day SMA. In the code below, the log output shows the correct calculations for the moving averages each day and shows that they barely cross each other, as expected. However, the algorithm is erroneously trading very frequently, every couple of days. I think that there is something wrong with the reference to the moving average calculations, which are calculated using Pipeline.

Looking at the log output of the attached backtest, the algorithm should create the following transactions; these are the only times that the moving averages cross:
Buy 1/5/15
Sell 8/5/15
Buy 12/9/15
Sell 1/15/16

Would anyone be able to help? Thank you! Much appreciated :)

-Tommy

3 responses

You could also add record(SMA_diff=context.sma_short-context.sma_long) inside trading (not handle_data) and see when it crosses 0.

Hi Andre,

When I tried that, I got the following error:

ValueError: Record only supports numeric values. Non-numeric value passed for key 'SMA_diff'  

I get the same error when trying to record context.sma_short and context.sma_long directly. I wonder if these are variables are arrays and I need to be referencing some element of the arrays?

Yes, you may have to use float(context.sma_short) and likewise with sma_long. Each factor in Pipeline output is a pandas.Series indexed by securities; when you only have one security, it's still a one-element Series, but you can convert it to a regular float as above.