Estratégia de inversão da tendência do padrão dinâmico

Autora:ChaoZhang, Data: 2023-12-13 16:52:34
Tags:

img

Resumo

A estratégia de inversão de tendência de padrão dinâmico usa regressão linear para prever preços e linhas médias móveis para formar padrões para gerar sinais de negociação.

Estratégia lógica

  1. Calcular a regressão linear do preço das ações com base no volume de negociação para obter o preço previsto
  2. Calcular médias móveis em diferentes condições
  3. Gerar sinal de compra quando o preço previsto cruza a média móvel para cima
  4. Gerar sinal de venda quando o preço previsto cruza a média móvel descendente
  5. Incorporar o indicador MACD para determinar o momento da inversão da tendência

A combinação dos sinais acima com confirmações múltiplas evita falhas e melhora a precisão.

Análise das vantagens

  • Utilize regressão linear para prever a tendência de preços, melhorando a precisão do sinal
  • Capturar inversões de tendência através de padrões de médias móveis
  • A regressão baseada no volume de negociação tem melhor significado económico
  • Confirmações múltiplas pelo MACD etc. reduzem os falsos sinais

Análise de riscos

  • Os parâmetros da regressão linear têm um impacto significativo nos resultados
  • As configurações da média móvel também afetam a qualidade do sinal
  • Apesar de ter confirmações, sinais falsos continuam a ser um risco
  • O código pode ser otimizado para reduzir a frequência de negociação e melhorar a taxa de lucro

Orientações de otimização

  • Otimizar parâmetros de regressão linear e médias móveis
  • Adicionar mais condições de confirmação para reduzir as taxas de sinal falso
  • Incorporar mais fatores para avaliar a qualidade das inversões de tendência
  • Melhorar as estratégias de stop loss para reduzir os riscos para as operações individuais

Conclusão

A estratégia de inversão de tendência de padrão dinâmico integra previsão de regressão linear e padrões de média móvel para capturar inversões de tendência.


/*backtest
start: 2023-12-05 00:00:00
end: 2023-12-12 00:00:00
period: 1m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © stocktechbot
//@version=5
strategy("Linear Cross", overlay=true, margin_long=100, margin_short=0)

//Linear Regression

vol = volume

// Function to calculate linear regression
linregs(y, x, len) =>
    ybar = math.sum(y, len)/len
    xbar = math.sum(x, len)/len
    b = math.sum((x - xbar)*(y - ybar),len)/math.sum((x - xbar)*(x - xbar),len)
    a = ybar - b*xbar
    [a, b]

// Historical stock price data
price = close

// Length of linear regression
len = input(defval = 21, title = 'Strategy Length')
linearlen=input(defval = 9, title = 'Linear Lookback')
[a, b] = linregs(price, vol, len)

// Calculate linear regression for stock price based on volume
//eps = request.earnings(syminfo.ticker, earnings.actual)
//MA For double confirmation

out = ta.sma(close, 200)
outf = ta.sma(close, 50)
outn = ta.sma(close, 90)
outt = ta.sma(close, 21)
outthree = ta.sma(close, 9)

// Predicted stock price based on volume
predicted_price = a + b*vol

// Check if predicted price is between open and close
is_between = open < predicted_price and predicted_price < close

//MACD
//[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)

// Plot predicted stock price
plot(predicted_price, color=color.rgb(65, 59, 150), linewidth=2, title="Predicted Price")
plot(ta.sma(predicted_price,linearlen), color=color.rgb(199, 43, 64), linewidth=2, title="MA Predicted Price")
//offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
plot(out, color=color.blue, title="MA200")
[macdLine, signalLine, histLine] = ta.macd(predicted_price, 12, 26, 9)

//BUY Signal

longCondition=false
mafentry =ta.sma(close, 50) > ta.sma(close, 90)
//matentry = ta.sma(close, 21) > ta.sma(close, 50)
matwohun = close > ta.sma(close, 200)
twohunraise = ta.rising(out, 2)
twentyrise = ta.rising(outt, 2)
macdrise = ta.rising(macdLine,2)
macdlong = ta.crossover(predicted_price, ta.wma(predicted_price,linearlen))  and (signalLine < macdLine)
if macdlong and macdrise
    longCondition := true

if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long)
//Sell Signal
lastEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
daysSinceEntry = len
daysSinceEntry := int((time - strategy.opentrades.entry_time(strategy.opentrades - 1)) / (24 * 60 * 60 * 1000))
percentageChange = (close - lastEntryPrice) / lastEntryPrice * 100
//trailChange = (ta.highest(close,daysSinceEntry) - close) / close * 100

//label.new(bar_index, high, color=color.black, textcolor=color.white,text=str.tostring(int(trailChange)))
shortCondition=false
mafexit =ta.sma(close, 50) < ta.sma(close, 90)
matexit = ta.sma(close, 21) < ta.sma(close, 50)
matwohund = close < ta.sma(close, 200)
twohunfall = ta.falling(out, 3)
twentyfall = ta.falling(outt, 2)
shortmafall = ta.falling(outthree, 1)
macdfall = ta.falling(macdLine,1)
macdsell = macdLine < signalLine
if macdfall and macdsell and (macdLine < signalLine) and ta.falling(low,2)
    shortCondition := true

if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short)




Mais.