Hello guys today I want to share how you can build a moving average crossover signal on jupyter notebook.
The algorithm consist in 4 differents prices which are 2 moving average and 2 lagged moving average. For example, if you want to find the crossover moment for the SMA50 and SMA200 (to go long) you can not just set SMA50>SMA200, you must also need to use the one period lagged SMA50 and SMA200 in order to spot the right moment of the crossover situation.
In order to find the SMA50 and SMA200, you can just takes the built in quantopian factor SimpleMovingAverage:
sma50 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=50 )
sma200 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=200 )
But if you want to find the lagged information you must create a custom factor that will transform the variable to his lagged version. I did found this custom factor here:
class Factor_N_Days_Ago(CustomFactor):
def compute(self, today, assets, out, input_factor):
out[:] = input_factor[0]
In order to lag the SimpleMovingAverage, you must create a custom factor with window_safe = True as is explained How to make factors be the input of CustomFactor calculation? and here ExponentialWeightedMovingAverage inside CustomFactors of the SimpleMovingAverage in order to no get an error:
class sma(CustomFactor):
window_safe = True
sma50 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=50 )
sma200 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=200 )
inputs = [sma50,sma200]
window_length = 1
outputs = ["sma50","sma200"]
def compute(self, today, assets, out, sma50, sma200):
out.sma50[:] = sma50
out.sma200[:] = sma200
In your pipeline you must place the SimpleMovingAverage with window_safe = True, as an input to the custom factor that lag one period the variables:
sma50_1, sma200_1 = sma()
sma200_lagged = Factor_N_Days_Ago([sma200_1], window_length=2)
sma50_lagged = Factor_N_Days_Ago([sma50_1], window_length=2)
Finally you place the condition described at the beggining to be used as a filter to select the stocks that accomplish that condition.
If you run Alphalens you will see that the moving average crossover signal is not good for entries if you dont place other conditions tu take betters stocks.