Estrategia de cruce de dos medias móviles

El autor:¿ Qué pasa?, Fecha: 2024-01-12 14:59:18
Las etiquetas:

img

Resumen general

La estrategia de cruce de la media móvil doble es una estrategia típica de seguimiento de tendencias. Utiliza dos líneas de EMA con períodos diferentes y va largo cuando la EMA del período más corto cruza la EMA del período más largo y va corto cuando el cruce opuesto captura inversiones de tendencia.

Principios

Los indicadores centrales de esta estrategia son dos líneas de EMA, una de 30 períodos y la otra de 60 períodos.

emaLen1 = emaFuncOne(close, lenMA1)
emaLen2 = emaFuncTwo(close, lenMA2)  

Las señales de negociación se generan a partir del cruce de las dos líneas EMA:

currentState = if emaLen2 > emaLen1
    0
else 
    1

previousState = if emaLastLen2 > emaLastLen1 
    0
else
    1

convergence = if currentState != previousState
    1  
else
    0

Cuando la EMA de período más corto cruza la EMA de período más largo, el estado actual no es igual al estado anterior, se activa una señal de cruce, vaya largo. Cuando la EMA del período más corto se cruza por debajo de la EMA del período más largo, el estado actual no es igual al estado anterior, se activa una señal de cruce, corta.

Análisis de ventajas

Las ventajas de esta estrategia son:

  1. La lógica es simple e intuitiva, fácil de entender e implementar
  2. Aplaza las fluctuaciones de precios con la EMA y filtra el ruido del mercado
  3. Sigue automáticamente las tendencias, evita perder operaciones

Análisis de riesgos

También hay algunos riesgos con esta estrategia:

  1. Las señales de cruce pueden retrasarse y no capturar las reversiones de manera oportuna
  2. Las señales Whipsaw pueden ocurrir con frecuencia durante los mercados variados
  3. El mal ajuste de los parámetros puede causar hipersensibilidad o retrasos.

La optimización se puede hacer ajustando los períodos de EMA o añadiendo filtros.

Direcciones de optimización

Esta estrategia se puede optimizar a partir de los siguientes aspectos:

  1. Prueba de diferentes combinaciones de períodos de EMA
  2. Añadir filtros de volumen o volatilidad para reducir las señales falsas
  3. Incorporar otros indicadores como el MACD para confirmar las tendencias
  4. Optimice la gestión del dinero con stop loss y take profit

Conclusión

La estrategia de cruce de promedio móvil dual es una estrategia simple y práctica de seguimiento de tendencias en general. Es sencilla, fácil de implementar y puede rastrear automáticamente las tendencias. Pero existen algunos riesgos como retraso y señales falsas. Con el ajuste de parámetros y la adición de filtros, se puede mejorar aún más para convertirse en una de las estrategias comerciales algorítmicas fundamentales.


/*backtest
start: 2024-01-10 00:00:00
end: 2024-01-11 00:00:00
period: 1m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=2
strategy("ParkerMAStrat", overlay=true)

lenMA1=input(title="Length 1", defval=30)
lenMA2=input(title="Length 2",  defval=60)

x = 0

checkLines(current, last) =>

    if current > last
        x = 1
    else
        x = 0
    x
    

//plot ema based on len1
emaFuncOne(src, time_period) =>

    alpha = 2 / (time_period + 1)
    // we have defined the alpha function above
    ema = 0.0
    // this is the initial declaration of ema, since we dont know the first ema we will declare it to 0.0 [as a decimal]
    ema := alpha * src + (1 - alpha) * nz(ema[1])
    // this returns the computed ema at the current time
    // notice the use of : (colon) symbol before =, it symbolises, that we are changing the value of ema,
    // since the ema was previously declared to 0
    // this is called mutable variale declaration in pine script
    ema
    // return ema from the function

emaLen1 = emaFuncOne(close, lenMA1)

    
plot(emaLen1, color=green, transp=0, linewidth=2)
// now we plot the _10_period_ema

//plot ema based on len2
emaFuncTwo(src, time_period) =>

    alpha = 2 / (time_period + 1)
    // we have defined the alpha function above
    ema = 0.0
    // this is the initial declaration of ema, since we dont know the first ema we will declare it to 0.0 [as a decimal]
    ema := alpha * src + (1 - alpha) * nz(ema[1])
    // this returns the computed ema at the current time
    // notice the use of : (colon) symbol before =, it symbolises, that we are changing the value of ema,
    // since the ema was previously declared to 0
    // this is called mutable variale declaration in pine script
    ema
    // return ema from the function

//plot ema based on len2
emaFuncOneLast(src, time_period) =>

    alpha = 2 / (time_period + 1)
    // we have defined the alpha function above
    ema = 0.0
    // this is the initial declaration of ema, since we dont know the first ema we will declare it to 0.0 [as a decimal]
    ema := alpha * src + (1 - alpha) * nz(ema[0])
    // this returns the computed ema at the current time
    // notice the use of : (colon) symbol before =, it symbolises, that we are changing the value of ema,
    // since the ema was previously declared to 0
    // this is called mutable variale declaration in pine script
    ema
    // return ema from the function

//plot ema based on len2
emaFuncTwoLast(src, time_period) =>

    alpha = 2 / (time_period + 1)
    // we have defined the alpha function above
    ema = 0.0
    // this is the initial declaration of ema, since we dont know the first ema we will declare it to 0.0 [as a decimal]
    ema := alpha * src + (1 - alpha) * nz(ema[0])
    // this returns the computed ema at the current time
    // notice the use of : (colon) symbol before =, it symbolises, that we are changing the value of ema,
    // since the ema was previously declared to 0
    // this is called mutable variale declaration in pine script
    ema
    // return ema from the function



emaLastLen1 = emaFuncOneLast(close, lenMA1)
emaLastLen2 = emaFuncTwoLast(close, lenMA2)
emaLen2 = emaFuncTwo(close, lenMA2)

    
plot(emaLen2, color=red, transp=30, linewidth=2)
// now we plot the _10_period_ema

//now we compare the two and when green crosses red we buy/sell (line1 vs line2)

previousState = if emaLastLen2 > emaLastLen1
    0
else
    1

currentState = if emaLen2 > emaLen1
    0
else
    1

convergence = if currentState != previousState
    1
else
    0

    
lineCheck = if convergence == 1 
    checkLines(currentState, previousState)
    
if lineCheck == 1
    strategy.entry("Long", strategy.long)
else
    strategy.entry("Short", strategy.short)


Más.