다차원 K-최근접 이웃 알고리즘과 캔들스틱 패턴 볼륨 가격 분석 거래 전략

SMA KNN RSI VOL MA SD
생성 날짜: 2025-01-17 16:10:07 마지막으로 수정됨: 2025-01-17 16:10:07
복사: 0 클릭수: 436
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

다차원 K-최근접 이웃 알고리즘과 캔들스틱 패턴 볼륨 가격 분석 거래 전략

개요

이 전략은 K-최근접 이웃(KNN) 머신 러닝 알고리즘, 캔들스틱 패턴 인식, 거래량 분석을 결합한 포괄적인 거래 시스템입니다. 이 전략은 이동 평균 채널, 거래량 임계값 검증, 확률 통계를 포함한 다차원 분석 방법을 통해 시장에 대한 3차원 분석 프레임워크를 형성하여 잠재적인 거래 기회를 포착합니다.

전략 원칙

전략의 핵심 논리는 다음과 같은 핵심 요소에 기초합니다.

  1. 이동 평균(SMA)과 표준 편차를 사용하여 매수 과다 및 매도 과다 영역을 식별하기 위한 가격 채널을 구성합니다.
  2. 망치형, 유성형, 삼키기형 등을 포함하여 프로그래밍 방식으로 정의된 조건을 통해 9가지의 고전적인 촛대 패턴을 식별합니다.
  3. 과거 가격 추세를 학습하고 가능한 미래 가격 추세를 예측하기 위해 KNN 알고리즘을 소개합니다.
  4. 거래량을 신호 확인 지표로 사용하려면 신호가 트리거될 때 거래량이 설정된 임계값보다 높아야 합니다.
  5. 상승 및 하강의 확률 분포를 계산하여 신호 필터링 조건 중 하나로 활용

전략적 이점

  1. 다중 레벨 신호 확인 메커니즘으로 거래의 신뢰성이 크게 향상됩니다.
  2. KNN 알고리즘의 도입은 기존 기술 분석에 대한 머신 러닝 관점을 제공합니다.
  3. 볼륨 검증 메커니즘은 거짓 돌파구를 효과적으로 방지합니다.
  4. 지지선과 저항선을 동적으로 그리면 중요한 가격 수준을 식별하는 데 도움이 됩니다.
  5. 포괄적인 경고 시스템을 통해 중요한 거래 기회를 놓치지 않도록 보장합니다.
  6. 전략 매개변수는 매우 조정 가능하며 다양한 시장 환경에 적응할 수 있습니다.

전략적 위험

  1. KNN 알고리즘은 변동성이 큰 시장에서는 뒤떨어질 수 있습니다.
  2. 신호 필터링 조건이 너무 많으면 일부 거래 기회를 놓칠 수 있습니다.
  3. 고정 볼륨 임계값은 다른 기간에 동적으로 조정되어야 할 수도 있습니다.
  4. 측면 단계 중에 너무 많은 거짓 신호가 생성될 수 있습니다. 추천:
  • 알고리즘 매개변수를 동적으로 조정합니다
  • 시장환경 식별 메커니즘 소개
  • 최대 손실 한도를 설정하세요
  • 창고관리시스템 구축

전략 최적화 방향

  1. 시장 상황에 따라 전략이 매개변수를 자동으로 조정할 수 있도록 하는 적응형 매개변수 조정 메커니즘 도입
  2. 딥러닝 알고리즘을 통합하여 예측 정확도를 향상시킵니다.
  3. 더 많은 시장 미시구조 지표 추가
  4. 거래량 임계값 동적 계산 방식 최적화
  5. 보다 완벽한 위험관리체계 구축

요약하다

이 전략은 전통적인 기술 분석과 최신 머신 러닝 방법을 결합하여 강력한 거래 시스템을 구축합니다. 이 전략의 다차원적 분석 프레임워크와 엄격한 신호 확인 메커니즘은 거래 결정에 대한 신뢰할 수 있는 기반을 제공합니다. 지속적인 최적화와 위험 관리를 통해 이 전략은 다양한 시장 환경에서도 안정적인 성과를 유지할 것으로 기대됩니다.

전략 소스 코드
/*backtest
start: 2024-01-17 00:00:00
end: 2025-01-16 00:00:00
period: 2d
basePeriod: 2d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT","balance":49999}]
*/

//@version=6
strategy("Candle Pattern Analyzer with Volume", overlay=true)

// Input parameters
length = input.int(20, "Channel Length", minval=1)
mult = input.float(2.0, "Volatility Multiplier", minval=0.1)
candleLength = input.int(5, "Candle Length", minval=1)
k = input.int(5, "KNN Neighbors", minval=1)
volumeThreshold = input.int(100000, "Volume Threshold", minval=1)

// Calculate channel
basis = ta.sma(close, length)
dev = mult * ta.stdev(close, length)
upper = basis + dev
lower = basis - dev

// Plot channel
plot(basis, color=color.blue)
plot(upper, color=color.green)
plot(lower, color=color.red)

// Identify candle patterns
isBullish = close > open
isBearish = close < open

// Pre-calculate SMAs
smaLow = ta.sma(low, candleLength)
smaHigh = ta.sma(high, candleLength)
smaClose = ta.sma(close, candleLength)

// Hammer pattern
isHammer = isBullish and 
           low < smaLow and 
           close > smaClose and 
           (close - low) / (high - low) > 0.6 and
           low < low[1]

// Shooting Star pattern
isShootingStar = isBearish and 
                 high > smaHigh and 
                 close < smaClose and 
                 (high - close) / (high - low) > 0.6 and
                 high > high[1]

// Inverse Hammer pattern
isInverseHammer = isBullish and 
                   high > smaHigh and 
                   close < smaClose and 
                   (high - close) / (high - low) > 0.6 and
                   high > high[1]

// Bullish Engulfing pattern
isBullishEngulfing = isBullish and 
                      close > high[1] and 
                      open < low[1]

// Bearish Engulfing pattern
isBearishEngulfing = isBearish and 
                      close < low[1] and 
                      open > high[1]

// Morning Star pattern
isMorningStar = isBullish and close[2] < open[2] and close[1] < open[1] and  close > open[1]

// Evening Star pattern
isEveningStar = isBearish and  close[2] > open[2] and  close[1] > open[1] and  close < open[1]

// Three Black Crows pattern
isThreeBlackCrows = isBearish and 
                     close < close[1] and 
                     close[1] < close[2] and 
                     close[2] < close[3]

// Three White Soldiers pattern
isThreeWhiteSoldiers = isBullish and close > close[1] and  close[1] > close[2] and  close[2] > close[3]

// Compare previous candles
prevCandleUp = close[1] > open[1]
prevCandleDown = close[1] < open[1]

// Calculate probability
probUp = ta.sma(close > open ? 1 : 0, candleLength) / candleLength
probDown = ta.sma(close < open ? 1 : 0, candleLength) / candleLength

// Generate signals
buySignal = isHammer and prevCandleDown and probUp > probDown and volume > volumeThreshold
sellSignal = isShootingStar and prevCandleUp and probDown > probUp and volume > volumeThreshold

// Highlight patterns
color candleColor = na
if (isHammer)
    candleColor := color.green
    label.new(bar_index, high, "Hammer", color=color.green, style=label.style_label_up)

else if (isShootingStar)
    candleColor := color.red
    label.new(bar_index, low, "Shooting Star", color=color.red, style=label.style_label_down)
else if (isInverseHammer)
    candleColor := color.blue
    label.new(bar_index, high, "Inverse Hammer", color=color.blue, style=label.style_label_up)
else if (isBullishEngulfing)
    candleColor := color.yellow
    label.new(bar_index, high, "Bullish Engulfing", color=color.yellow, style=label.style_label_up)
else if (isBearishEngulfing)
    candleColor := color.purple
    label.new(bar_index, low, "Bearish Engulfing", color=color.purple, style=label.style_label_down)

else if (isMorningStar)
    candleColor := color.orange
    label.new(bar_index, high, "Morning Star", color=color.orange, style=label.style_label_up)

else if (isEveningStar)
    candleColor := color.new(color.red, 80)
    label.new(bar_index, low, "Evening Star", color=color.new(color.red, 80), style=label.style_label_down)

else if (isThreeBlackCrows)
    candleColor := color.black
    label.new(bar_index, low, "Three Black Crows", color=color.black, style=label.style_label_down)

else if (isThreeWhiteSoldiers)
    candleColor := color.white
    label.new(bar_index, high, "Three White Soldiers", color=color.white, style=label.style_label_up)


// Plot candles
barcolor(candleColor)

// KNN algorithm
var float[] knnData = array.new_float(k, na)
var float[] knnLabels = array.new_float(k, na) // Create an array to store KNN labels
array.set(knnLabels, 0, 1.0) // Label for "up" movement

// Shift KNN dataset to make room for new data point
for i = 1 to k-1
    array.set(knnData, i, array.get(knnData, i-1))
    array.set(knnLabels, i, array.get(knnLabels, i-1))

// Predict next movement using KNN algorithm
float prediction = 0.0
for i = 0 to k-1
    float distance = math.abs(close - array.get(knnData, i))
    prediction += array.get(knnLabels, i) / distance

prediction /= k

// Plot prediction
// line.new(bar_index, close, bar_index + 1, prediction, color=color.purple)

// Plot resistance and support lines
float resistance = ta.sma(high, length)
float support = ta.sma(low, length)
// line.new(bar_index, resistance, bar_index + 1, resistance, color=color.green, style=line.style_dashed)
// line.new(bar_index, support, bar_index + 1, support, color=color.red, style=line.style_dashed)

// Plot buy and sell signals with prices
if (buySignal)
    // label.new(bar_index, low, "Buy at " + str.tostring(low), color=color.green, style=label.style_label_up)
    strategy.entry("Buy", strategy.long, comment="Buy at " + str.tostring(low))
if (sellSignal)
    // label.new(bar_index, high, "Sell at " + str.tostring(high), color=color.red, style=label.style_label_down)
    strategy.entry("Sell", strategy.short, comment="Sell at " + str.tostring(high))

// Create alerts
alertcondition(buySignal, title="Buy Signal", message="Buy signal generated!")
alertcondition(sellSignal, title="Sell Signal", message="Sell signal generated!")