ml-strategy
它能做什么
这项技能训练简单的机器学习模型,预测价格会上涨还是下跌。适合希望使用数据驱动交易信号的分析师。
适用场景
- ✓当你想测试一个用于预测股票或加密货币收益的机器学习模型的时候。
- ✓当你需要一个由动量、波动率和成交量特征构成的信号的时候。
- ✓当你想在不让模型偷看未来数据的前提下检验模型的时候。
技能链接
https://github.com/HKUDS/Vibe-Trading/blob/main/agent/src/skills/ml-strategy/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“请构建一个机器学习模型,预测这只股票下周是否会上涨。”
每周 5 个新技能,1 分钟读完。
工作原理
它会根据价格和成交量数据构建动量、RSI 等特征。然后它只在过去的窗口上训练模型,并逐日向前滚动,因此永远不会看到未来的数据。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Machine-Learning Predictive Strategy
Purpose
Use sklearn machine-learning models (RandomForest / GradientBoosting / Ridge) to predict the direction of future returns and generate trading signals. Walk-forward training is used to avoid future data leakage, and feature engineering extracts useful factors from OHLCV data.
Signal Logic
- Validate input: check OHLCV columns, minimum row count, NaN ratio — skip symbols that fail
- Feature engineering: build multi-dimensional factors from raw OHLCV data (momentum, volatility, RSI, moving-average ratios, volume ratio, and more). All features are sanitized (inf removed, division-by-zero guarded)
- Label construction: future N-day return > 0 is the positive class (
1), < 0 is the negative class (0) - Walk-forward training: use an expanding or sliding window, train on historical data only, and roll forward day by day for prediction
- Signal generation: map
predict_proba[:, 1]to[-1.0, 1.0], or use discrete signals frompredictin{-1, 0, 1}. Output is guaranteed clean (no NaN, clipped to range)
Complete SignalEngine Example
This is the recommended full pipeline. Copy and customise — safety is built in.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
def validate_data(df: pd.DataFrame, min_rows: int = 300) -> bool:
"""Check that OHLCV data meets minimum quality for ML training.
Args:
df: DataFrame with DatetimeIndex.
min_rows: Minimum number of rows required.
Returns:
True if data is usable.
"""
required = {"open", "high", "low", "close", "volume"}
if not required.issubset(df.columns):
return False
if len(df) < min_rows:
return False
if df["close"].isnull().mean() > 0.2:
return False
return True
def build_features(df: pd.DataFrame) -> pd.DataFrame:
"""Build a machine-learning feature matrix from OHLCV data.
All features are guarded against division-by-zero and sanitized
(inf replaced with NaN) so downstream code never sees inf values.
Args:
df: DataFrame containing open, high, low, close, and volume columns.
Returns:
DataFrame with feature columns prefixed by 'f_'.
"""
c = df["close"]
v = df["volume"]
ret = c.pct_change(fill_method=None)
features = pd.DataFrame(index=df.index)
features["f_ret_5d"] = c.pct_change(5, fill_method=None)
features["f_ret_20d"] = c.pct_change(20, fill_method=None)
features["f_vol_20d"] = ret.rolling(20).std()
features["f_ma_ratio"] = c / c.rolling(20).mean()
features["f_volume_ratio"] = v / v.rolling(20).mean()
# RSI(14) — guard: loss=0 in zero-volatility periods produces inf
delta = c.diff()
gain = delta.clip(lower=0).rolling(14).mean()
loss = (-delta.clip(upper=0)).rolling(14).mean()
rs = gain / loss.replace(0, np.nan)
features["f_rsi_14"] = 100 - (100 / (1 + rs))
# Bollinger Band position — guard: bb_upper == bb_lower when std=0
ma20 = c.rolling(20).mean()
std20 = c.rolling(20).std()
bb_upper = ma20 + 2 * std20
bb_lower = ma20 - 2 * std20
bb_range = (bb_upper - bb_lower).replace(0, np.nan)
features["f_bb_position"] = (c - bb_lower) / bb_range
# Intraday features
features["f_high_low_ratio"] = (df["high"] - df["low"]) / c
features["f_close_open_ratio"] = (c - df["open"]) / df["open"]
features["f_skew_20d"] = ret.rolling(20).skew()
# Sanitize: replace all inf with NaN (NaN handled by walk-forward)
features = features.replace([np.inf, -np.inf], np.nan)
return features
def walk_forward_predict(
features: pd.DataFrame,
labels: pd.Series,
min_train_size: int = 252,
retrain_freq: int = 20,
model_type: str = "random_forest",
window_type: str = "expanding",
sliding_size: int = 504,
prediction_horizon: int = 5,
) -> pd.Series:
"""Walk-forward training and prediction to avoid future data leakage.
Args:
features: Feature matrix aligned with labels by row index.
labels: Binary labels (0/1), representing the direction of future N-day returns.
min_train_size: Minimum training-set size in trading days.
retrain_freq: Retrain the model every N days.
model_type: One of "random_forest" / "gradient_bo
常见问题
它使用哪些模型?
它使用 scikit-learn 中的模型,例如 RandomForest、GradientBoosting 和 Ridge。
什么是滚动前向训练?
它只在过去的数据上训练,并随时间向前推进,因此每次测试使用的都是模型从未见过的数据。
这能保证好的结果吗?
不能。预测具有不确定性,在信任任何信号之前都应仔细检验结果。
详情
作者的原始描述
Machine-learning predictive strategy based on sklearn walk-forward training, feature engineering, and signal generation. Suitable for any OHLCV data.
repo: HKUDS/Vibe-Trading
热度
- GitHub 星标
- 37k
- 排名
- #7533
- 许可证
- MIT
- 更新时间
- 2026/11/1
评论
- …