
수량 거래 분야에서 수 년을 돌면서 저는 재미있는 현상을 발견했습니다. 대부분의 거래자들은 수십 년 전의 기술 지표를 사용하고 있지만, 급변하는 시장에서 초과 수익을 기대합니다. 이것은 계산기를 사용하여 미적분 문제를 해결하는 것과 같습니다.
오늘 우리가 분석할 고도의 KNN 거래 전략은 바로 양자 거래의 중요한 발전 방향을 나타냅니다.기계 학습 알고리즘과 전통적인 기술 분석을 결합하여 더 지능적인 거래 의사 결정 시스템을 구축합니다.。
KNN 알고리즘의 핵심 아이디어는 매우 간단하면서도 심오합니다.비슷한 시장 환경은 비슷한 가격 움직임을 낳을 수 있습니다.이 가설은 금융 시장에서 튼튼한 이론적 기반이 있고 시장 참여자의 행동 패턴이 일정하게 반복되고 예측 가능하다는 것을 의미한다.
이 전략의 특징은 7차원의 특징 공간을 구축하는 것입니다.
여기 중요한 기술적인 세부사항이 있습니다.특징 표준화Z-score 표준화 방법을 사용하여 모든 특징을 동일한 수치 범위로 변환하는 전략.
normalize(src, length) =>
mean_val = ta.sma(src, length)
std_val = ta.stdev(src, length)
std_val == 0 ? 0.0 : (src - mean_val) / std_val
전통적인 KNN 알고리즘은 보통 간단한 투표 메커니즘을 사용하지만, 이 전략은 보다 정교한무게중심 방법이 디자인은 중요한 금융 시장의 특징을 반영합니다:시장 상태의 유사성은 연속적인 것이지, 분리된 것이 아닙니다.。
무게 계산 공식:weight = 1.0 / (distance + 0.001)
이 가중치 메커니즘은:
기계 학습 거래 전략에 대한 제 연구 경험을 바탕으로, KNN 전략은 다음과 같은 시장 환경에서 일반적으로 더 잘 작동합니다.
주의할 점은, 이 전략은 좀 더 보수적인 위험 관리 파라미터를 설정했다: 2%의 상쇄, 4%의 상쇄, 이 1: 2의 위험 수익 비율은 전략 설계자가 위험 통제에 중점을 두는 것을 반영한다.
이 전략의 몇 가지 혁신은 다음과 같습니다:
하지만 동시에, 저는 개선할 수 있는 몇 가지 방안도 볼 수 있습니다.
실디 어플리케이션에서는 다음과 같은 점에 특히 주의를 기울여야 합니다.
이 KNN 전략은 양적 거래의 중요한 방향을 나타냅니다.간단한 규칙에서 지능적인 데이터로기계학습은 모든 것을 다룰 수 있는 것은 아니지만, 시장의 행동을 이해하고 예측하는 데 더 과학적이고 체계적인 방법을 제공합니다.
제 생각에는 미래의 양적 거래는 전통적인 금융 이론과 현대 통계학, 그리고 기계학습 기술의 심층적 융합이 될 것입니다. 이 KNN 전략은 단지 시작일 뿐이며, 더 많은 혁신과 돌파구가 도중에 있습니다.
/*backtest
start: 2025-01-01 00:00:00
end: 2025-09-03 00:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT","balance":500000}]
args: [["v_input_int_1",5],["v_input_int_2",40],["v_input_int_3",5],["v_input_int_4",5],["v_input_float_1",0.8]]
*/
//@version=6
strategy("Advanced KNN Trading Strategy", overlay=true, max_bars_back=500)
//输入参数配置:设置KNN算法和交易策略的各项参数
k = input.int(5, "KNN邻居数量", minval=3, maxval=50);//K最近邻算法中K值
lookback = input.int(40, "历史数据回望期", minval=50, maxval=500);//历史数据窗口大小
feature_length = input.int(5, "特征计算周期", minval=5, maxval=20);//技术指标计算周期
norm_length = input.int(5, "标准化计算周期", minval=20, maxval=100);//特征标准化周期
prediction_threshold = input.float(0.8, "预测阈值", minval=0.5, maxval=0.9, step=0.1);//交易信号阈值
stop_loss_pct = input.float(2.0, "止损百分比", minval=0.5, maxval=5.0, step=0.1);//止损比例
take_profit_pct = input.float(4.0, "止盈百分比", minval=1.0, maxval=10.0, step=0.1);//止盈比例
//特征工程函数:数据预处理和特征提取
//标准化函数:将原始数据转换为标准正态分布
normalize(src, length) =>
mean_val = ta.sma(src, length);//计算均值
std_val = ta.stdev(src, length);//计算标准差
std_val == 0 ? 0.0 : (src - mean_val) / std_val;//Z-score标准化
//原始技术特征计算:提取价格、成交量、波动率等基础特征
raw_price_momentum = (close - close[feature_length]) / close[feature_length] * 100;//价格动量
raw_rsi = ta.rsi(close, feature_length);//相对强弱指数
raw_volume_ratio = volume / ta.sma(volume, feature_length);//成交量比率
raw_volatility = ta.stdev(ta.change(close), feature_length) / close * 100;//价格波动率
//趋势特征计算:识别价格趋势强度
sma_short = ta.sma(close, 5);//短期均线
sma_long = ta.sma(close, 20);//长期均线
raw_trend_strength = (sma_short - sma_long) / sma_long * 100;//趋势强度
//MACD特征计算:动量指标
[macd_line, signal_line, histogram] = ta.macd(close, 12, 26, 9);//MACD指标
raw_macd_feature = macd_line - signal_line;//MACD差值
//布林带特征计算:价格相对位置
[bb_middle, bb_upper, bb_lower] = ta.bb(close, 20, 2);//布林带
raw_bb_position = (close - bb_lower) / (bb_upper - bb_lower);//价格在布林带中的位置
//特征标准化:将所有特征转换为相同量级
price_momentum = normalize(raw_price_momentum, norm_length);//标准化价格动量
rsi_feature = normalize(raw_rsi, norm_length);//标准化RSI
volume_ratio = normalize(raw_volume_ratio, norm_length);//标准化成交量比率
volatility = normalize(raw_volatility, norm_length);//标准化波动率
trend_strength = normalize(raw_trend_strength, norm_length);//标准化趋势强度
macd_feature = normalize(raw_macd_feature, norm_length);//标准化MACD
bb_position = normalize(raw_bb_position, norm_length);//标准化布林带位置
//目标变量定义:预测标签生成
future_return = (close - close[1]) / close[1] * 100;//未来收益率
target_label = future_return > 0 ? 1.0 : 0.0;//二分类标签:1为上涨,0为下跌
//KNN核心算法:K最近邻预测函数
knn_predict() =>
var historical_features = array.new<array<float>>();//历史特征向量存储
var historical_labels = array.new<float>();//历史标签存储
//当前样本特征向量:使用已知的历史数据避免未来函数
current_features = array.from<float>(
price_momentum[1], rsi_feature[1], volume_ratio[1], volatility[1],
trend_strength[1], macd_feature[1], bb_position[1]
)
//历史数据收集:维护固定大小的历史样本窗口
if bar_index >= lookback
//滑动窗口:移除最旧数据
if array.size(historical_features) >= lookback
array.shift(historical_features)
array.shift(historical_labels)
//添加新的历史样本:使用[2]期特征预测[1]期走势
hist_features = array.from<float>(
price_momentum[2], rsi_feature[2], volume_ratio[2], volatility[2],
trend_strength[2], macd_feature[2], bb_position[2]
)
array.push(historical_features, hist_features)
array.push(historical_labels, target_label[1])
//KNN预测计算:基于历史相似样本进行预测
prediction = 0.0
if array.size(historical_features) >= k
distances = array.new<float>();//距离存储数组
labels = array.new<float>();//对应标签存储数组
//距离计算:计算当前样本与所有历史样本的欧几里得距离
for i = 0 to array.size(historical_features) - 1
hist_point = array.get(historical_features, i)
distance = 0.0
//欧几里得距离计算:各维度差值平方和的平方根
for j = 0 to array.size(current_features) - 1
curr_val = array.get(current_features, j)
hist_val = array.get(hist_point, j)
distance += math.pow(curr_val - hist_val, 2)
distance := math.sqrt(distance)
array.push(distances, distance)
array.push(labels, array.get(historical_labels, i))
//K个最近邻选择:找出距离最小的K个样本
knn_predictions = array.new<float>();//K个最近邻的标签
knn_distances = array.new<float>();//K个最近邻的距离
for n = 0 to k - 1
min_dist = 999999.0
min_index = 0
//寻找最小距离的样本索引
for i = 0 to array.size(distances) - 1
if array.get(distances, i) < min_dist
min_dist := array.get(distances, i)
min_index := i
//保存K最近邻结果
array.push(knn_predictions, array.get(labels, min_index))
array.push(knn_distances, min_dist)
//标记已使用的样本,避免重复选择
array.set(distances, min_index, 999999.0)
//加权预测:距离越近的样本权重越大
weighted_sum = 0.0
weight_total = 0.0
for i = 0 to array.size(knn_predictions) - 1
distance = array.get(knn_distances, i)
weight = distance > 0 ? 1.0 / (distance + 0.001) : 1000.0;//反距离权重
weighted_sum += array.get(knn_predictions, i) * weight
weight_total += weight
prediction := weight_total > 0 ? weighted_sum / weight_total : 0.5
prediction
//获取KNN预测结果:执行预测算法
knn_prediction = knn_predict()
//交易信号生成:基于预测结果生成买卖信号
long_threshold = prediction_threshold;//多头信号阈值
short_threshold = 1 - prediction_threshold;//空头信号阈值
//交易信号判断:预测概率超过阈值时产生信号
long_signal = knn_prediction > long_threshold;//多头信号:预测上涨概率高
short_signal = knn_prediction < short_threshold;//空头信号:预测下跌概率高
//风险管理:计算止损止盈价格
long_stop_loss = strategy.position_avg_price * (1 - stop_loss_pct / 100);//多头止损价
long_take_profit = strategy.position_avg_price * (1 + take_profit_pct / 100);//多头止盈价
short_stop_loss = strategy.position_avg_price * (1 + stop_loss_pct / 100);//空头止损价
short_take_profit = strategy.position_avg_price * (1 - take_profit_pct / 100);//空头止盈价
//策略执行:开仓和平仓逻辑
//开仓条件:无持仓时根据信号开仓
if long_signal and strategy.position_size == 0
strategy.entry("Long", strategy.long, comment="KNN多头: " + str.tostring(knn_prediction, "#.##"))
if short_signal and strategy.position_size == 0
strategy.entry("Short", strategy.short, comment="KNN空头: " + str.tostring(knn_prediction, "#.##"))
//平仓条件:持仓时设置止损止盈
if strategy.position_size > 0
strategy.exit("Long Exit", "Long", stop=long_stop_loss, limit=long_take_profit)
if strategy.position_size < 0
strategy.exit("Short Exit", "Short", stop=short_stop_loss, limit=short_take_profit)
//图表可视化:在图表上显示预测结果和信号
plot(knn_prediction, "KNN预测", color=color.blue, linewidth=2);//预测值曲线
hline(prediction_threshold, "多头阈值", color=color.green, linestyle=hline.style_dashed);//多头阈值线
hline(1 - prediction_threshold, "空头阈值", color=color.red, linestyle=hline.style_dashed);//空头阈值线
hline(0.5, "中性线", color=color.gray, linestyle=hline.style_dotted);//中性参考线
//交易信号标记:在图表上标注买卖点
plotshape(long_signal, "多头信号", shape.triangleup, location.belowbar,
color=color.green, size=size.small);//多头信号标记
plotshape(short_signal, "空头信号", shape.triangledown, location.abovebar,
color=color.red, size=size.small);//空头信号标记
//交易提醒设置:配置交易信号的自动提醒
alertcondition(long_signal, title="KNN多头信号",
message="KNN预测多头信号,预测值: {{plot(\"KNN预测\")}}");//多头信号提醒
alertcondition(short_signal, title="KNN空头信号",
message="KNN预测空头信号,预测值: {{plot(\"KNN预测\")}}");//空头信号提醒