4. Two moving average crossover: the dual strategy
Level 5: Momentum, Mean-Reversion and Pairs Trading Strategies
The single moving average strategy has a practical problem: a fixed average (100 days, say) reacts just as slowly no matter what is happening in the market right now. The dual crossover strategy solves this by using two moving averages of different lengths at once, and basing the signal on their relationship with each other, not on each one's relationship with the price.
The logic, boiled down to essentials, has four steps: compute a short average (for example, 5 days), compute a long average (for example, 20 days), go long when the short average rises above or equals the long one, and go short when the short average falls below the long one.
def cruce_doble(simbolo, periodo_corto, periodo_largo, inicio="2021-01-01"):
datos = yf.download(simbolo, start=inicio, progress=False)
datos["SMA_corta"] = datos["Close"].rolling(window=periodo_corto).mean()
datos["SMA_larga"] = datos["Close"].rolling(window=periodo_largo).mean()
datos["Señal"] = 0
datos.loc[datos["SMA_corta"] > datos["SMA_larga"], "Señal"] = 1
datos.loc[datos["SMA_corta"] < datos["SMA_larga"], "Señal"] = -1
datos["Posicion"] = datos["Señal"] - datos["Señal"].shift(1)
return datosThis variant tends to generate fewer false signals than the single-average one, precisely because it requires two averages of different speeds to agree, not merely the price to cross a single line — the price, by its nature, oscillates more and crosses a single average far more often than two already smoothed averages cross each other.
The same pattern — compute indicators, generate a signal column, detect the change of signal as an event — repeats almost identically if you swap the moving averages for any other pair of indicators: Bollinger Bands (an average with two standard deviation bands around it), or the RSI compared against its overbought/oversold levels. The pandas-ta library, which you already used in the screening level, computes more than 130 indicators of this kind without you having to program each formula from scratch.
To go deeper into this lesson
- Momentumin the glossary
- Z-scorein the glossary
- Momentum investing: what it is and its S&P 500 recordguide