KNN 머신 러닝 전략: K 최근접 이웃 알고리즘을 기반으로 한 추세 예측 거래 시스템

KNN MA ATR
생성 날짜: 2024-05-15 17:09:34 마지막으로 수정됨: 2024-05-15 17:09:34
복사: 0 클릭수: 1098
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

KNN 머신 러닝 전략: K 최근접 이웃 알고리즘을 기반으로 한 추세 예측 거래 시스템

개요

이 전략은 K 근접한 KNN 기계 학습 알고리즘을 사용하여 가격 추세를 예측한다. 다른 가격 계산 방법을 선택하여 HL2, VWAP, SMA 등과 같은 입력값과 다른 목표값을 선택하여 가격 움직임, VWAP, 변동율 등과 같은 평가 대상을 선택하여 KNN 알고리즘을 사용하여 현재 시장 상태에 가장 가까운 K의 역사 데이터 포인트를 찾아내고 K의 데이터 포인트의 트렌드 방향을 기반으로 다중 공간 예측을 수행한다. 동시에, 전략은 예측의 안정성을 높이기 위해 이동 평균을 사용하여 예측 결과를 부드럽게 처리한다.

전략 원칙

  1. KNN 알고리즘의 입력값으로 가격 계산 방법을 선택하십시오.
  2. KNN 알고리즘의 목표값으로 평가 목표 (가격 움직임, VWAP, 변동률 등) 를 선택하십시오.
  3. KNN 알고리즘의 민감도와 예측 결과의 부드러움을 조정하기 위해 K의 근접수와 미끄러짐 주기를 설정한다.
  4. 각 새로운 가격 데이터 포인트에 대해, KNN 알고리즘을 통해 역사 데이터에서 현재 시장 상태에 가장 가까운 K 데이터 포인트를 찾습니다.
  5. 이 K 데이터 포인트의 트렌드 방향에 대한 투표를 통해 현재 시장의 트렌드 예측을 얻을 수 있다.
  6. 예측의 안정성을 높이기 위해 예측 결과를 이동 평균으로 부드럽게 처리한다.
  7. 평준화 후 예측 결과에 따라 거래 신호를 생성하고, 배경 색상의 변화에 따라 현재의 시장 추세 예측을 직관적으로 보여줍니다.

우위 분석

  1. 기계 학습 알고리즘을 사용하여 역사적 데이터에서 학습하고 가격 동향을 예측할 수 있으며 적응력과 유연성이 있습니다.
  2. 입력값, 목표값, 최근 이웃 수, 윤활주기와 같은 매개 변수를 조정하여 전략의 성능을 최적화하고 다른 시장 상황에 적응할 수 있다.
  3. 예측 결과를 이동 평균과 결합하여 예측의 안정성과 신뢰성을 향상시킵니다.
  4. 배경 색상의 변화를 통해 현재의 시장 추세 예측을 직관적으로 표시하여 거래자가 시장 상태를 신속하게 판단하고 결정을 내릴 수 있도록 도와줍니다.

위험 분석

  1. KNN 알고리즘의 예측 성능은 역사적 데이터의 품질과 대표성에 의존하며, 역사적 데이터가 부족하거나 대표적이지 않으면 예측 결과가 정확하지 않을 수 있습니다.
  2. 전략의 성능은 파라미터 설정에 영향을 받을 수 있으며, 부적절한 파라미터 조합은 전략의 부적절한 성능을 초래할 수 있습니다.
  3. 시장 추세가 급격히 변하거나 블랙 스윙 사건이 발생하면, 역사적인 데이터에 기반한 예측이 실패할 수 있으며, 전략이 잘못된 거래 신호를 발생시킬 수 있다.

최적화 방향

  1. 예측의 정확성과 안정성을 높이기 위해 KNN 알고리즘의 입력으로 더 많은 기술 지표 또는 시장 감정 데이터를 도입하십시오.
  2. 다양한 시장 상황과 변동 수준에 적응하기 위해 적응 메커니즘을 사용하여 전략 파라미터를 동적으로 조정합니다.
  3. 다른 기술 분석 방법이나 위험 관리 조치와 결합하여 전략의 위험 구멍을 줄이고 수익 안정성을 향상시킵니다.

요약하다

이 전략은 KNN 기계 학습 알고리즘을 가격 추세 예측에 적용하여, 역사적 데이터와 통계 방법을 사용하여 시장 추세를 파악하고 거래 신호를 생성하는 방법을 보여줍니다. 전략의 장점은 그것의 적응성과 유연성이며, 매개 변수를 조정하여 성능을 최적화하고 다양한 시장 상황에 적응할 수 있습니다. 그러나, 전략의 위험은 주로 역사적 데이터의 품질과 대표성, 그리고 매개 변수 설정의 합리성에서 비롯됩니다.

전략 소스 코드
/*backtest
start: 2023-05-09 00:00:00
end: 2024-05-14 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/


// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Blake_22 {

//@version=5
strategy('money printer part 1', overlay=true)

// ~~ Tooltips {
t1 ="PriceValue selects the method of price computation. \n\nSets the smoothing period for the PriceValue. \n\nAdjusting these settings will change the input values for the K-Nearest Neighbors algorithm, influencing how the trend is calculated."
t2 = "TargetValue specifies the target to evaluate. \n\nSets the smoothing period for the TargetValue."
t3 ="numberOfClosestValues sets the number of closest values that are considered when calculating the KNN Moving Average. Adjusting this number will affect the sensitivity of the trend line, with a higher value leading to a smoother line and a lower value resulting in a line that is more responsive to recent price changes."
t4 ="smoothingPeriod sets the period for the moving average applied to the KNN classifier. Adjusting the smoothing period will affect how rapidly the trend line responds to price changes, with a larger smoothing period leading to a smoother line that may lag recent price movements, and a smaller smoothing period resulting in a line that more closely tracks recent changes."
t5 ="This option controls the background color for the trend prediction. Enabling it will change the background color based on the prediction, providing visual cues on the direction of the trend. A green color indicates a positive prediction, while red indicates a negative prediction."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Inputs {
PriceValue   = input.string("hl2", options = ["hl2","VWAP", "sma", "wma", "ema", "hma"], group="", inline="Value")
maLen        = input.int(5, minval=2, maxval=200, title="", group="", inline="Value", tooltip=t1)
TargetValue  = input.string("Price Action", options = ["Price Action","VWAP", "Volatility", "sma", "wma", "ema", "hma"], group="", inline="Target")
maLen_       = input.int(5, minval=2, maxval=200, title="", group="", inline="Target", tooltip=t2)
// Input parameters for the KNN Moving Average
numberOfClosestValues = input.int(3, "Number of Closest Values", 2, 200, tooltip=t3) 
smoothingPeriod       = input.int(50, "Smoothing Period", 2, 500, tooltip=t4) 
windowSize            = math.max(numberOfClosestValues, 30) 

// knn Color
Upknn_col   = input.color(color.lime, title="", group="KNN Color", inline="knn col")
Dnknn_col   = input.color(color.red, title="", group="KNN Color", inline="knn col")
Neuknn_col  = input.color(color.orange, title="", group="KNN Color", inline="knn col")
// MA knn Color
Maknn_col   = input.color(color.teal, title="", group="MA KNN Color", inline="MA knn col")
// BG Color
bgcolor = input.bool(false, title="Trend Prediction Color", group="BG Color", inline="bg", tooltip=t5)
Up_col  = input.color(color.lime, title="", group="BG Color", inline="bg")
Dn_col  = input.color(color.red, title="", group="BG Color", inline="bg")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ kNN Classifier {
value_in = switch PriceValue
    "hl2"  => ta.sma(hl2,maLen)
    "VWAP" => ta.vwap(close[maLen])
    "sma" => ta.sma(close,maLen)
    "wma" => ta.wma(close,maLen)
    "ema" => ta.ema(close,maLen)
    "hma" => ta.hma(close,maLen)

meanOfKClosest(value_,target_) => 
    closestDistances = array.new_float(numberOfClosestValues, 1e10) 
    closestValues    = array.new_float(numberOfClosestValues, 0.0) 
    for i = 1 to windowSize 
        value = value_[i] 
        distance = math.abs(target_ - value) 
        maxDistIndex = 0 
        maxDistValue = closestDistances.get(0) 
        for j = 1 to numberOfClosestValues - 1 
            if closestDistances.get(j) > maxDistValue
                maxDistIndex := j
                maxDistValue := closestDistances.get(j)
        if distance < maxDistValue 
            closestDistances.set(maxDistIndex, distance)
            closestValues.set(maxDistIndex, value)
    closestValues.sum() / numberOfClosestValues 

// Choose the target input based on user selection
target_in = switch TargetValue
    "Price Action"  => ta.rma(close,maLen_) 
    "VWAP"          => ta.vwap(close[maLen_])
    "Volatility"    => ta.atr(14)
    "sma" => ta.sma(close,maLen_)
    "wma" => ta.wma(close,maLen_)
    "ema" => ta.ema(close,maLen_)
    "hma" => ta.hma(close,maLen_)

knnMA = meanOfKClosest(value_in,target_in)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ kNN Prediction {
// Function to calculate KNN Classifier
price = math.avg(knnMA, close)
c     = ta.rma(knnMA[1], smoothingPeriod) 
o     = ta.rma(knnMA, smoothingPeriod)

// Defines KNN function to perform classification
knn(price) => 
    Pos_count = 0 
    Neg_count = 0 
    min_distance = 10e10 
    nearest_index = 0 
    for j = 1 to 10 
        distance = math.sqrt(math.pow(price[j] - price, 2)) 
        if distance < min_distance 
            min_distance := distance
            nearest_index := j
            Neg = c[nearest_index] > o[nearest_index] 
            Pos = c[nearest_index] < o[nearest_index] 
            if Pos 
                Pos_count += 1
            if Neg 
                Neg_count += 1
    output = Pos_count>Neg_count?1:-1 

// Calls KNN function and smooths the prediction
knn_prediction_raw = knn(price) 
knn_prediction     = ta.wma(knn_prediction_raw, 3)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Plots {
// Plots for display on the chart
knnMA_          = ta.wma(knnMA,5)
knnMA_col       = knnMA_>knnMA_[1]?Upknn_col:knnMA_<knnMA_[1]?Dnknn_col:Neuknn_col
Classifier_Line = plot(knnMA_,"Knn Classifier Line", knnMA_col)
MAknn_          = ta.rma(knnMA, smoothingPeriod)
plot(MAknn_,"Average Knn Classifier Line" ,Maknn_col) 
green = knn_prediction < 0.5
red   = knn_prediction > -0.5 
bgcolor( green and bgcolor? color.new(Dn_col,80) : 
 red and bgcolor ? color.new(Up_col,80) : na) 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Alerts {
knnMA_cross_Over_Ma      = ta.crossover(knnMA_,MAknn_)
knnMA_cross_Under_Ma     = ta.crossunder(knnMA_,MAknn_)
knnMA_cross_Over_Close   = ta.crossover(knnMA_,close)
knnMA_cross_Under_Close  = ta.crossunder(knnMA_,close)
knnMA_Switch_Up          = knnMA_[1]<knnMA_ and knnMA_[1]<=knnMA_[2]
knnMA_Switch_Dn          = knnMA_[1]>knnMA_ and knnMA_[1]>=knnMA_[2]
knnMA_Neutral            = knnMA_col==Neuknn_col and knnMA_col[1]!=Neuknn_col
greenBG                  = green and not green[1]
redBG                    = red and not red[1]

alertcondition(knnMA_cross_Over_Ma,  title = "Knn Crossover Average Knn",  message = "Knn Crossover Average Knn")
alertcondition(knnMA_cross_Under_Ma, title = "Knn Crossunder Average Knn", message = "Knn Crossunder Average Knn")
alertcondition(knnMA_cross_Over_Close,  title = "Knn Crossover Close",  message = "Knn Crossover Close")
alertcondition(knnMA_cross_Under_Close, title = "Knn Crossunder Close", message = "Knn Crossunder Close")
alertcondition(knnMA_Switch_Up,  title = "Knn Switch Up",  message = "Knn Switch Up")
alertcondition(knnMA_Switch_Dn, title = "Knn Switch Dn", message = "Knn Switch Dn")
alertcondition(knnMA_Neutral, title = "Knn is Neutral", message = "Knn is Neutral")
alertcondition(greenBG, title = "Positive Prediction", message = "Positive Prediction")
alertcondition(redBG, title = "Negative Prediction", message = "Negative Prediction")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

//~~Trenddilo {



//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}



//~~ strategy { 1

LongCondtion = knnMA_[1]<knnMA_ and knnMA_[1]<=knnMA_[2]
ShortCondtion = knnMA_[1]>knnMA_ and knnMA_[1]>=knnMA_[2]


//SecondaryLongCondtion = col == color.lime
//SecondaryShortCondtion = col == color.red

strategy.entry("Long", strategy.long, when = LongCondtion)
strategy.close("Long", when =ShortCondtion)

strategy.entry("Short", strategy.short, when =ShortCondtion)
strategy.close("short", when =LongCondtion)


plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}