Chiến lược học máy KNN: Hệ thống giao dịch dự đoán xu hướng dựa trên thuật toán K lân cận gần nhất

KNN MA ATR
Ngày tạo: 2024-05-15 17:09:34 sửa đổi lần cuối: 2024-05-15 17:09:34
sao chép: 0 Số nhấp chuột: 1098
1
tập trung vào
1617
Người theo dõi

Chiến lược học máy KNN: Hệ thống giao dịch dự đoán xu hướng dựa trên thuật toán K lân cận gần nhất

Tổng quan

Chiến lược này sử dụng các thuật toán học máy học gần nhất (KNN) để dự đoán xu hướng giá. Bằng cách chọn các phương pháp tính toán giá khác nhau (như HL2, VWAP, SMA, v.v.) như giá trị đầu vào và chọn các giá trị mục tiêu khác nhau (như biến động giá, VWAP, tỷ lệ biến động, v.v.) như đối tượng đánh giá, sử dụng thuật toán KNN để tìm ra K điểm dữ liệu lịch sử gần nhất với trạng thái thị trường hiện tại và đưa ra dự báo đa không gian dựa trên xu hướng của K điểm dữ liệu này.

Nguyên tắc chiến lược

  1. Chọn phương pháp tính giá ((như HL2, VWAP, SMA, v.v.) như giá trị đầu vào của thuật toán KNN.
  2. Chọn mục tiêu đánh giá (như biến động giá, VWAP, tỷ lệ biến động, v.v.) làm mục tiêu của thuật toán KNN.
  3. Thiết lập số gần k và chu kỳ trơn để điều chỉnh độ nhạy của thuật toán KNN và độ trơn của kết quả dự đoán.
  4. Đối với mỗi điểm dữ liệu giá mới, KNN tìm ra K điểm dữ liệu gần nhất với trạng thái thị trường hiện tại trong dữ liệu lịch sử.
  5. Theo hướng xu hướng của các điểm dữ liệu K này, một dự đoán xu hướng của thị trường hiện tại được đưa ra.
  6. Kết quả dự báo được xử lý trơn tru bằng đường trung bình di chuyển để tăng tính ổn định của dự báo.
  7. Tạo tín hiệu giao dịch dựa trên kết quả dự đoán sau khi mài (bằng đầu hoặc đầu trống) và hiển thị trực quan dự báo xu hướng thị trường hiện tại bằng cách thay đổi màu nền.

Phân tích lợi thế

  1. Sử dụng thuật toán học máy, có thể học và dự đoán xu hướng giá từ dữ liệu lịch sử, có khả năng thích ứng và linh hoạt.
  2. Có thể tối ưu hóa hiệu suất của chiến lược và thích ứng với các tình trạng thị trường khác nhau bằng cách điều chỉnh các tham số như giá trị đầu vào, giá trị mục tiêu, số lượng hàng xóm gần nhất và chu kỳ trơn.
  3. Kết hợp kết quả dự báo với đường trung bình di chuyển giúp tăng tính ổn định và độ tin cậy của dự báo.
  4. Các dự báo xu hướng thị trường hiện tại được hiển thị trực quan thông qua sự thay đổi màu nền, giúp các nhà giao dịch nhanh chóng đánh giá tình trạng thị trường và đưa ra quyết định.

Phân tích rủi ro

  1. Hiệu suất dự đoán của thuật toán KNN phụ thuộc vào chất lượng và tính đại diện của dữ liệu lịch sử, nếu dữ liệu lịch sử không đầy đủ hoặc không đại diện, có thể dẫn đến kết quả dự đoán không chính xác.
  2. Hiệu suất của chiến lược có thể bị ảnh hưởng bởi cài đặt tham số, sự kết hợp tham số không phù hợp có thể gây ra hiệu suất kém hoặc quá phù hợp của chiến lược.
  3. Dự đoán dựa trên dữ liệu lịch sử có thể bị thất bại khi xu hướng thị trường thay đổi đột ngột hoặc khi có sự kiện thiên bạch đen, dẫn đến tín hiệu giao dịch sai của chiến lược.

Hướng tối ưu hóa

  1. Nhập nhiều chỉ số kỹ thuật hoặc dữ liệu cảm xúc thị trường như đầu vào cho thuật toán KNN để tăng độ chính xác và độ vững chắc của dự báo.
  2. Sử dụng cơ chế thích ứng để điều chỉnh các tham số chiến lược động để thích ứng với các tình trạng thị trường khác nhau và mức độ biến động.
  3. Kết hợp với các phương pháp phân tích kỹ thuật khác hoặc các biện pháp quản lý rủi ro để giảm lỗ hổng rủi ro của chiến lược và tăng tính ổn định của thu nhập.

Tóm tắt

Chiến lược này đã thể hiện cách sử dụng dữ liệu lịch sử và các phương pháp thống kê để nắm bắt xu hướng thị trường và tạo ra tín hiệu giao dịch bằng cách áp dụng thuật toán học máy KNN cho dự đoán xu hướng giá. Ưu điểm của chiến lược là khả năng thích ứng và linh hoạt, có thể tối ưu hóa hiệu suất và thích ứng với các tình trạng thị trường khác nhau thông qua điều chỉnh tham số. Tuy nhiên, rủi ro của chiến lược chủ yếu đến từ chất lượng và tính đại diện của dữ liệu lịch sử và tính hợp lý của các tham số.

Mã nguồn chiến lược
/*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)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}