Estratégia de cruzamento de média móvel dupla

Autora:ChaoZhang, Data: 2024-01-12 14:59:18
Tags:

img

Resumo

A estratégia de cruzamento de média móvel dupla é uma estratégia típica de tendência. Ela usa duas linhas de EMA com períodos diferentes e vai longo quando o EMA de período mais curto cruza o EMA de período mais longo e vai curto quando a travessia oposta acontece para capturar inversões de tendência.

Princípios

Os indicadores principais desta estratégia são duas linhas EMA, uma de 30 períodos e a outra de 60 períodos.

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

Os sinais de negociação são gerados a partir do cruzamento das duas linhas EMA:

currentState = if emaLen2 > emaLen1
    0
else 
    1

previousState = if emaLastLen2 > emaLastLen1 
    0
else
    1

convergence = if currentState != previousState
    1  
else
    0

Quando a EMA de período mais curto cruza a EMA de período mais longo, o currentState não é igual ao previousState, um sinal de cruzamento é desencadeado, vá longo. Quando a EMA de período mais curto cruza abaixo da EMA de período mais longo, o currentState não é igual ao previousState, um sinal de cruzamento é desencadeado, vá curto.

Análise das vantagens

As vantagens desta estratégia são as seguintes:

  1. A lógica é simples e intuitiva, fácil de entender e implementar
  2. Suaviza as flutuações de preços com a EMA e filtra o ruído do mercado
  3. Segue automaticamente as tendências, evita trocas perdidas

Análise de riscos

Há também alguns riscos com esta estratégia:

  1. Os sinais de cruzamento podem demorar e não conseguir capturar reversões em tempo útil
  2. Os sinais Whipsaw podem ocorrer com frequência durante os mercados variáveis
  3. Mal ajuste dos parâmetros pode causar hipersensibilidade ou atrasos

A otimização pode ser feita ajustando os períodos de EMA ou adicionando filtros.

Orientações de otimização

Esta estratégia pode ser otimizada a partir dos seguintes aspectos:

  1. Teste diferentes combinações de períodos da EMA
  2. Adicionar filtros de volume ou volatilidade para reduzir sinais falsos
  3. Incorporar outros indicadores como o MACD para confirmar as tendências
  4. Otimizar a gestão de dinheiro com stop loss e take profit

Conclusão

A estratégia de cruzamento de média móvel dupla é uma estratégia simples e prática de seguir tendências em geral. É direta, fácil de implementar e pode rastrear automaticamente tendências. Mas existem alguns riscos como atraso e sinais falsos. Com ajuste de parâmetros e adição de filtros, pode ser melhorada para se tornar uma das estratégias de negociação algorítmica fundamentais.


/*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)


Mais.