
La stratégie est un système de suivi de tendance paramétrable auto-adaptatif basé sur un algorithme d’apprentissage automatique K-nearest ((KNN)). La stratégie ajuste dynamiquement les paramètres de suivi de tendance grâce à l’algorithme KNN, en combinaison avec la génération de signaux de négociation sur des moyennes mobiles. Le système est capable d’ajuster automatiquement les paramètres de la stratégie en fonction des changements de l’environnement du marché, ce qui améliore l’adaptabilité et la stabilité de la stratégie.
Le principe central de la stratégie est d’utiliser l’algorithme KNN pour analyser les données historiques sur les prix et de prédire les mouvements des prix en calculant la similitude entre l’état actuel du marché et les données historiques. Les étapes de mise en œuvre sont les suivantes:
La stratégie utilise de manière innovante l’algorithme KNN dans les transactions de suivi de tendances, optimisant les stratégies d’analyse technique traditionnelles grâce à des méthodes d’apprentissage automatique. La stratégie possède une forte adaptabilité et une grande flexibilité, permettant d’ajuster les paramètres en fonction de la dynamique de l’environnement du marché. Bien qu’il existe des risques tels que la complexité élevée des calculs et la sensibilité aux paramètres, la stratégie a toujours une bonne valeur d’application grâce à des mesures d’optimisation et de contrôle des risques raisonnables.
/*backtest
start: 2024-10-01 00:00:00
end: 2024-10-31 23:59:59
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=6
strategy("Trend Following Strategy with KNN", overlay=true,commission_value=0.03,currency='USD', commission_type=strategy.commission.percent,default_qty_type=strategy.cash)
// Input parameters
k = input.int(5, title="K (Number of Neighbors)", minval=1) // Number of neighbors for KNN algorithm
window_size = input.int(20, title="Window Size", minval=1) // Window size for feature vector calculation
ma_length = input.int(50, title="MA Length", minval=1) // Length of the moving average
// Calculate moving average
ma = ta.sma(close, ma_length)
// Initialize variables
var float[] features = na
var float[] distances = na
var int[] nearest_neighbors = na
if bar_index >= window_size - 1 // Ensure there is enough historical data
features := array.new_float(0) // Keep only the current window data
for i = 0 to window_size - 1
array.push(features, close[i])
// Calculate distances
distances := array.new_float(0) // Clear the array for each calculation
for i = 0 to window_size - 1 // Calculate the distance between the current price and all prices in the window
var float distance = 0.0
for j = 0 to window_size - 1
distance += math.pow(close[j] - array.get(features, j), 2)
distance := math.sqrt(distance)
array.push(distances, distance)
// Find the nearest neighbors
if array.size(distances) > 0 and array.size(distances) >= k
nearest_neighbors := array.new_int(0)
for i = 0 to k - 1
var int min_index = -1
var float min_distance = na
for j = 0 to array.size(distances) - 1
if na(min_distance) or array.get(distances, j) < min_distance
min_index := j
min_distance := array.get(distances, j)
if min_index != -1
array.push(nearest_neighbors, min_index)
array.remove(distances, min_index) // Remove the processed neighbor
// Calculate the average price change of the neighbors
var float average_change = 0.0
if array.size(nearest_neighbors) > 0
for i = 0 to array.size(nearest_neighbors) - 1
var int index = array.get(nearest_neighbors, i)
// Ensure index + 1 is within range
if index + 1 < bar_index
average_change += (close[index] - close[index + 1])
average_change := average_change / array.size(nearest_neighbors)
// Generate trading signals
if average_change > 0 and close > ma
strategy.entry("Long", strategy.long)
else if average_change < 0 and close < ma
strategy.entry("Short", strategy.short)