범위를 돌파하는 이중 이동 평균 필터링 전략

저자:차오장, 날짜: 2023-11-27 17:03:08
태그:

img

전반적인 설명

이 전략은 트렌드 판단을 위해 이동 평균과 볼링거 밴드를 활용하고, 브레이크아웃 필터링 및 스톱 로스 원칙과 결합하여 트렌드 변화가 있을 때 신호를 적시에 캡처하고, 이중 이동 평균 필터링을 통해 잘못된 신호를 줄이고, 스톱 로스를 설정함으로써 위험을 제어할 수 있습니다.

전략 원칙

이 전략은 다음과 같은 주요 부분으로 구성됩니다.

  1. 트렌드 판단: MACD를 사용하여 가격 추세를 판단하고 상승 추세와 하락 추세를 구별합니다.

  2. 범위 필터링: 가격 변동 범위를 판단하고 범위를 통과하지 않는 신호를 필터링하기 위해 볼링거 밴드를 사용하십시오.

  3. 이중 이동 평균 확인: 빠른 EMA와 느린 EMA는 트렌드 신호를 확인하기 위해 이중 이동 평균을 형성합니다. 빠른 EMA > 느린 EMA에서만 구매 신호가 생성됩니다.

  4. 스톱 로스 메커니즘: 스톱 로스 포인트를 설정합니다. 가격이 불리한 방향으로 스톱 로스 포인트를 통과 할 때 포지션을 닫습니다.

입력 신호의 논리는 다음과 같습니다.

  1. MACD는 상승 추세를 판단합니다.
  2. 가격이 볼링거 밴드의 상단 레일을 통과합니다.
  3. 빠른 EMA는 느린 EMA보다 높습니다.

세 가지 조건이 동시에 충족되면 구매 신호가 생성됩니다.

두 가지 유형의 클로징 포지션이 있습니다. 수익을 취하고 손실을 중지합니다. 수익을 취하는 지점은 특정 비율로 곱한 입상 가격이며 손실을 중지하는 지점은 특정 비율로 곱한 입상 가격입니다. 가격이 어느 지점을 넘으면 포지션을 닫습니다.

이점 분석

이 전략의 장점은 다음과 같습니다.

  1. 트렌드 변화를 적당한 시간에 추적할 수 있습니다.
  2. 이중 이동 평균으로 필터링하여 잘못된 신호를 줄이고 신호 품질을 향상시킵니다.
  3. 스톱 손실 메커니즘은 단일 손실을 효과적으로 제어합니다.
  4. 최적 상태로 조정할 수 있는 큰 매개 변수 최적화 공간

위험 분석

이 전략에는 몇 가지 위험도 있습니다.

  1. 옆 시장에서 발생하는 잘못된 신호는 손실로 이어질 수 있습니다.
  2. 스톱 손실의 부적절한 설정은 불필요한 손실로 이어질 수 있습니다.
  3. 부적절한 매개 변수는 전략 성과가 좋지 않을 수 있습니다.

이러한 위험을 해결하기 위해 전략은 매개 변수를 조정하고 스톱 로스 포지션을 설정하여 최적화 할 수 있습니다.

최적화 방향

이 전략은 다음과 같은 측면에서 최적화 될 수 있습니다.

  1. 이중 이동 평균 길이를 조정해서 최적의 매개 변수 조합을 찾아보세요.
  2. 트레일링 스톱 로스, 오시일레이팅 스톱 로스 등 다양한 스톱 로스 방법을 테스트합니다.
  3. 최적의 설정을 찾기 위해 MACD 매개 변수를 테스트합니다.
  4. 자동화된 매개 변수 최적화를 위해 머신러닝을 사용하세요.
  5. 필터 신호에 추가 조건을 추가합니다.

다른 매개 변수 설정을 테스트하고 수익률과 샤프 비율을 평가함으로써 전략의 최적 상태를 찾을 수 있습니다.

결론

이 전략은 트렌드 판단, 범위 필터링, 이중 이동 평균 확인 및 스톱 로스 아이디어를 활용한 양적 전략입니다. 트렌드 방향을 효과적으로 결정하고 이익 극대화와 위험 통제 사이의 균형을 잡을 수 있습니다. 매개 변수 최적화, 기계 학습 및 기타 방법을 통해 전략은 더 나은 결과를 달성하기 위해 개선 할 수있는 많은 공간을 가지고 있습니다.


/*backtest
start: 2022-11-20 00:00:00
end: 2023-11-26 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy(title="Range Filter Buy and Sell Strategies", shorttitle="Range Filter Strategies", overlay=true,pyramiding = 5)

// Original Script > @DonovanWall
// Adapted Version > @guikroth
// 
// Updated PineScript to version 5
// Republished by > @tvenn
// Strategizing by > @RonLeigh
//////////////////////////////////////////////////////////////////////////
// Settings for 5min chart, BTCUSDC. For Other coin, change the parameters
//////////////////////////////////////////////////////////////////////////



SS = input.bool(false,"Percentage Take Profit Stop Loss")


longProfitPerc = input.float(title='LongProfit(%)', minval=0.0, step=0.1, defval=1.5) * 0.01

shortProfitPerc = input.float(title='ShortProfit(%)', minval=0.0, step=0.1, defval=1.5) * 0.01


longLossPerc = input.float(title='LongStop(%)', minval=0.0, step=0.1, defval=1.5) * 0.01

shortLossPerc = input.float(title='ShortStop(%)', minval=0.0, step=0.1, defval=1.5) * 0.01


// Color variables
upColor   = color.white
midColor  = #90bff9
downColor = color.blue

// Source
src = input(defval=close, title="Source")

// Sampling Period
// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters
per = input.int(defval=100, minval=1, title="Sampling Period")

// Range Multiplier
mult = input.float(defval=3.0, minval=0.1, title="Range Multiplier")

// Smooth Average Range
smoothrng(x, t, m) =>
    wper = t * 2 - 1
    avrng = ta.ema(math.abs(x - x[1]), t)
    smoothrng = ta.ema(avrng, wper) * m
    smoothrng
smrng = smoothrng(src, per, mult)

// Range Filter
rngfilt(x, r) =>
    rngfilt = x
    rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r : 
       x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
    rngfilt
filt = rngfilt(src, smrng)

// Filter Direction
upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])

// Target Bands
hband = filt + smrng
lband = filt - smrng

// Colors
filtcolor = upward > 0 ? upColor : downward > 0 ? downColor : midColor
barcolor = src > filt and src > src[1] and upward > 0 ? upColor :
   src > filt and src < src[1] and upward > 0 ? upColor : 
   src < filt and src < src[1] and downward > 0 ? downColor : 
   src < filt and src > src[1] and downward > 0 ? downColor : midColor

filtplot = plot(filt, color=filtcolor, linewidth=2, title="Range Filter")

// Target
hbandplot = plot(hband, color=color.new(upColor, 70), title="High Target")
lbandplot = plot(lband, color=color.new(downColor, 70), title="Low Target")

// Fills
fill(hbandplot, filtplot, color=color.new(upColor, 90), title="High Target Range")
fill(lbandplot, filtplot, color=color.new(downColor, 90), title="Low Target Range")

// Bar Color
barcolor(barcolor)

// Break Outs
longCond = bool(na)
shortCond = bool(na)
longCond := src > filt and src > src[1] and upward > 0 or 
   src > filt and src < src[1] and upward > 0
shortCond := src < filt and src < src[1] and downward > 0 or 
   src < filt and src > src[1] and downward > 0

CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
longCondition = longCond and CondIni[1] == -1
shortCondition = shortCond and CondIni[1] == 1



// alertcondition(longCondition, title="Buy alert on Range Filter", message="Buy alert on Range Filter")
// alertcondition(shortCondition, title="Sell alert on Range Filter", message="Sell alert on Range Filter")
// alertcondition(longCondition or shortCondition, title="Buy and Sell alert on Range Filter", message="Buy and Sell alert on Range Filter")


////////////// 副

sensitivity = input(150, title='Sensitivity')
fastLength = input(20, title='FastEMA Length')
slowLength = input(40, title='SlowEMA Length')
channelLength = input(20, title='BB Channel Length')
multt = input(2.0, title='BB Stdev Multiplier')

DEAD_ZONE = nz(ta.rma(ta.tr(true), 100)) * 3.7

calc_macd(source, fastLength, slowLength) =>
    fastMA = ta.ema(source, fastLength)
    slowMA = ta.ema(source, slowLength)
    fastMA - slowMA

calc_BBUpper(source, length, multt) =>
    basis = ta.sma(source, length)
    dev = multt * ta.stdev(source, length)
    basis + dev

calc_BBLower(source, length, multt) =>
    basis = ta.sma(source, length)
    dev = multt * ta.stdev(source, length)
    basis - dev

t1 = (calc_macd(close, fastLength, slowLength) - calc_macd(close[1], fastLength, slowLength)) * sensitivity

e1 = calc_BBUpper(close, channelLength, multt) - calc_BBLower(close, channelLength, multt)

trendUp = t1 >= 0 ? t1 : 0
trendDown = t1 < 0 ? -1 * t1 : 0

duoad = trendUp > 0 and trendUp > e1

kongad = trendDown > 0 and trendDown > e1



duo =  longCondition and duoad

kong = shortCondition and kongad


//Alerts
plotshape(longCondition  and trendUp > e1 and  trendUp > 0 , title="Buy Signal", text="Buy", textcolor=color.white, style=shape.labelup, size=size.small, location=location.belowbar, color=color.new(#aaaaaa, 20))
plotshape(shortCondition  and trendDown > e1 and  trendDown > 0 , title="Sell Signal", text="Sell", textcolor=color.white, style=shape.labeldown, size=size.small, location=location.abovebar, color=color.new(downColor, 20))




if  longCondition and trendUp > e1 and  trendUp > 0 
    strategy.entry('Long',strategy.long, comment = "buy" )

if  shortCondition and trendDown > e1 and  trendDown > 0 
    strategy.entry('Short',strategy.short, comment = "sell" )




longlimtPrice  = strategy.position_avg_price * (1 + longProfitPerc)
shortlimtPrice = strategy.position_avg_price * (1 - shortProfitPerc)
   
longStopPrice  = strategy.position_avg_price * (1 - longLossPerc)
shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)



if (strategy.position_size > 0)  and SS == true
    
    strategy.exit(id="Long",comment_profit = "Profit",comment_loss = "StopLoss", stop=longStopPrice,limit = longlimtPrice)
    

if (strategy.position_size < 0)  and SS == true
    
    strategy.exit(id="Short",comment_profit = "Profit",comment_loss = "StopLoss", stop=shortStopPrice,limit = shortlimtPrice)


더 많은