ML Pipeline
Unified skill for the complete ML pipeline within a quant trading research system.
Consolidates eight prior skills into a single authoritative reference covering
the full lifecycle: data validation, feature creation, selection,
transformation, anti-leakage checks, pipeline automation, deep learning optimization, and deployment.
1. When to Use
Activate this skill when the task involves any of the following:
- - Creating, selecting, or transforming features for an ML-driven strategy.
- Auditing an existing feature pipeline for data leakage or overfitting risk.
- Automating an end-to-end ML pipeline (data prep through model export).
- Evaluating feature importance, scaling, encoding, or interaction effects.
- Integrating features with a feature store (Feast, Tecton, custom Parquet store).
- Explaining core ML concepts (bias-variance, cross-validation, regularisation)
in the context of feature engineering decisions.
2. Inputs to Gather
Before starting work, collect or confirm:
| Input | Details |
|---|
| Objective | Target metric (Sharpe, accuracy, RMSE ...), constraints, time horizon. |
| Data |
Symbols / instruments, timeframe, bar type, sampling frequency, data sources. |
|
Leakage risks | Point-in-time concerns, survivorship bias, look-ahead in labels or features. |
|
Compute budget | CPU/GPU limits, wall-clock budget for AutoML search. |
|
Latency | Online vs. offline inference, acceptable prediction latency. |
|
Interpretability | Regulatory or research need for explainable features / models. |
|
Deployment target | Where the model will run (notebook, backtest harness, live engine). |
3. Feature Creation Patterns
3.1 Numerical Features
- - Interaction terms:
price * volume, high / low, close - open. - Rolling statistics: mean, std, skew, kurtosis over configurable windows.
- Polynomial / log transforms:
log(volume + 1), spread^2. - Binning / discretisation: equal-width, quantile-based, or domain-driven bins.
3.2 Categorical Features
- - One-hot encoding: for low-cardinality categoricals (sector, exchange).
- Target encoding: mean-target per category with smoothing (careful of leakage -- use only in-fold means).
- Ordinal encoding: when categories have a natural order (credit rating).
3.3 Time-Series Specific
- - Lag features:
return_{t-1}, return_{t-5}, etc. - Calendar features: day-of-week, month, quarter, options-expiry flag.
- Rolling z-score:
(x - rolling_mean) / rolling_std for stationarity. - Fractional differentiation: preserve memory while achieving stationarity (Lopez de Prado).
3.4 Feature Selection Techniques
- - Filter methods: mutual information, variance threshold, correlation pruning.
- Wrapper methods: recursive feature elimination (RFE), forward/backward selection.
- Embedded methods: L1 regularisation, tree-based importance, SHAP values.
- Permutation importance: model-agnostic; run on out-of-fold predictions.
4. Anti-Leakage Checks
Data leakage is the single most common cause of inflated backtest results.
Apply these checks at every pipeline stage:
4.1 Label Leakage
- - Labels must be computed from future returns relative to the feature
timestamp. Verify that the label window does not overlap the feature window.
- - Use purging and embargo when labels span multiple bars.
4.2 Feature Leakage
- - No feature may use information from time
t+1 or later at prediction time t. - Rolling statistics must use a closed left window:
df['feat'].rolling(20).mean().shift(1). - Target-encoded categoricals must be computed on the training fold only.
4.3 Cross-Validation Leakage
- - Use purged k-fold or walk-forward CV for time-series. Never use random
k-fold on ordered data.
- - Insert an embargo gap between train and test folds to prevent bleed-through
from autocorrelation.
4.4 Survivorship & Selection Bias
- - Ensure the universe of instruments at time
t reflects what was actually
tradable at that time (delisted stocks, halted symbols removed later).
- - Backfill from point-in-time databases where available.
4.5 Validation Checklist
Run before every backtest:
CODEBLOCK0
5. Pipeline Automation (AutoML)
5.1 Prerequisites
- - Python environment with one or more AutoML libraries:
Auto-sklearn, TPOT, H2O AutoML, PyCaret, Optuna, or custom Optuna pipelines.
- - Training data in CSV / Parquet / database.
- Problem type identified: classification, regression, or time-series forecasting.
5.2 Pipeline Steps
| Step | Action |
|---|
| 1. Define requirements | Problem type, evaluation metric, time/resource budget, interpretability needs. |
| 2. Data infrastructure |
Load data, quality assessment, train/val/test split strategy, define feature transforms. |
|
3. Configure AutoML | Select framework, define algorithm search space, set preprocessing steps, choose tuning strategy (Bayesian, random, Hyperband). |
|
4. Execute training | Run automated feature engineering, model selection, hyperparameter optimisation, cross-validation. |
|
5. Analyse & export | Compare models, extract best config, feature importance, visualisations, export for deployment. |
5.3 Pipeline Configuration Template
CODEBLOCK1
5.4 Output Artifacts
- -
automl_config.py -- pipeline configuration. - INLINECODE13 /
.joblib / .onnx -- serialised model. - INLINECODE16 -- fitted preprocessing + feature transforms.
- INLINECODE17 -- metrics, confusion matrix / residuals, feature rankings.
- INLINECODE18 -- prediction API code, input validation, requirements.txt.
6. Core ML Fundamentals (Feature-Engineering Context)
6.1 Bias-Variance Trade-off
- - More features increase model capacity (lower bias) but risk overfitting (higher variance).
- Use regularisation (L1/L2), feature selection, or dimensionality reduction to manage.
6.2 Evaluation Strategy
- - Walk-forward validation: the gold standard for time-series strategies.
Roll a fixed-width training window forward; test on the next out-of-sample period.
- - Monte Carlo permutation tests: shuffle labels and re-evaluate to estimate
the probability that observed performance is due to chance.
- - Combinatorial purged CV (CPCV): generate many train/test combinations with
purging for more robust performance estimates.
6.3 Feature Scaling
- - Fit scalers (StandardScaler, MinMaxScaler, RobustScaler) on the training set only.
- Apply the same fitted scaler to validation and test sets.
- RobustScaler is often preferred for financial data due to heavy tails.
6.4 Handling Missing Data
- - Forward-fill then backward-fill for price data (be aware of leakage on backfill).
- Indicator column for missingness can itself be informative.
- Tree-based models can handle NaN natively; linear models cannot.
7. Workflow
For any feature engineering task, follow this sequence:
- 1. Restate the task in measurable terms (metric, constraints, deadline).
- Enumerate required artifacts: datasets, feature definitions, configs, scripts, reports.
- Propose a default approach and 1-2 alternatives with trade-offs.
- Implement feature pipeline with anti-leakage checks built in.
- Validate with walk-forward CV, Monte Carlo, and the leakage checklist above.
- Deliver repo-ready code, documentation, and a run command.
8. Deep Learning Optimization
8.1 Optimizer Selection
| Optimizer | Best For | Learning Rate |
|---|
| Adam | Most cases, adaptive | 1e-3 to 1e-4 |
| AdamW |
Transformers, weight decay | 1e-4 to 1e-5 |
| SGD + Momentum | Large batches, fine-tuning | 1e-2 to 1e-3 |
| RAdam | Stability without warmup | 1e-3 |
8.2 Learning Rate Scheduling
- - OneCycleLR: Best for short training, fast convergence
- CosineAnnealing: Smooth decay, good generalization
- ReduceOnPlateau: Adaptive when validation loss plateaus
- Warmup + Decay: Standard for transformers
8.3 Regularization Techniques
- - Dropout: 0.1-0.5 for fully connected layers
- L2 (Weight Decay): 1e-4 to 1e-2
- Batch Normalization: Stabilizes training
- Early Stopping: Monitor validation loss, patience 5-10 epochs
8.4 PyTorch Lightning Integration
CODEBLOCK2
8.5 Financial Reinforcement Learning
- - State: Market features, portfolio state, position
- Action: Buy/Sell/Hold, position sizing
- Reward: Risk-adjusted returns (Sharpe, Sortino)
- Frameworks: Stable-Baselines3, RLlib, FinRL
9. Error Handling
| Problem | Cause | Fix |
|---|
| AutoML search finds no good model | Insufficient time budget or poor features | Increase budget, engineer better features, expand algorithm search space. |
| Out of memory during training |
Dataset too large for available RAM | Downsample, use incremental learning, simplify feature engineering. |
| Model accuracy below threshold | Weak signal or overfitting | Collect more data, add domain-driven features, regularise, adjust metric. |
| Feature transforms produce NaN/Inf | Division by zero, log of negative | Add guards:
np.where(denom != 0, ...),
np.log1p(np.abs(x)). |
| Optimiser fails to converge | Bad hyperparameter ranges | Tighten search bounds, increase iterations, exclude unstable algorithms. |
10. Bundled Scripts
All scripts live in scripts/ within this skill directory.
| Script | Purpose |
|---|
| INLINECODE22 | Validate input data quality before pipeline execution. |
| INLINECODE23 |
Evaluate trained model performance and generate reports. |
|
pipeline_deployment.py | Deploy a trained pipeline to a target environment with rollback support. |
|
feature_engineering_pipeline.py | End-to-end feature engineering: load, clean, transform, select, train. |
|
feature_importance_analyzer.py | Analyse feature importance (permutation, SHAP, tree-based). |
|
data_visualizer.py | Visualise feature distributions and relationships to target. |
|
feature_store_integration.py | Integrate with feature stores (Feast, Tecton) for online/offline serving. |
11. Resources
Frameworks
- - scikit-learn -- preprocessing, feature selection, pipelines.
- Auto-sklearn / TPOT / H2O AutoML / PyCaret -- automated pipeline search.
- Optuna -- flexible hyperparameter optimisation.
- SHAP -- model-agnostic feature importance.
- Feast / Tecton -- feature store management.
- PyTorch Lightning -- https://lightning.ai/docs/pytorch/stable/
- Stable-Baselines3 -- https://stable-baselines3.readthedocs.io/
- FinRL -- https://github.com/AI4Finance-Foundation/FinRL
Key References
- - Lopez de Prado, Advances in Financial Machine Learning (2018) -- purged CV, fractional differentiation, meta-labelling.
- Hastie, Tibshirani & Friedman, The Elements of Statistical Learning -- bias-variance, regularisation, model selection.
- scikit-learn user guide: feature extraction, preprocessing, model selection.
Best Practices
- - Always start with a simple baseline before running AutoML.
- Balance automation with domain knowledge -- blind search rarely beats informed priors.
- Monitor resource consumption; set hard timeouts.
- Validate on true out-of-sample holdout data, not just cross-validation.
- Document every pipeline decision for reproducibility.
ML Pipeline
量化交易研究系统中完整ML管道的统一技能。
将八个先前的技能整合为一个权威参考,涵盖
完整生命周期:数据验证、特征创建、选择、
转换、防泄漏检查、管道自动化、深度学习优化和部署。
1. 何时使用
当任务涉及以下任何内容时,激活此技能:
- - 为ML驱动的策略创建、选择或转换特征。
- 审计现有特征管道是否存在数据泄漏或过拟合风险。
- 自动化端到端ML管道(从数据准备到模型导出)。
- 评估特征重要性、缩放、编码或交互效应。
- 将特征与特征存储(Feast、Tecton、自定义Parquet存储)集成。
- 在特征工程决策的背景下解释核心ML概念(偏差-方差、交叉验证、正则化)。
2. 需要收集的输入
开始工作前,收集或确认:
| 输入 | 详情 |
|---|
| 目标 | 目标指标(夏普比率、准确率、RMSE...)、约束条件、时间范围。 |
| 数据 |
标的/工具、时间框架、K线类型、采样频率、数据来源。 |
|
泄漏风险 | 时点问题、幸存者偏差、标签或特征中的前瞻性。 |
|
计算预算 | CPU/GPU限制、AutoML搜索的挂钟时间预算。 |
|
延迟 | 在线与离线推理、可接受的预测延迟。 |
|
可解释性 | 监管或研究对可解释特征/模型的需求。 |
|
部署目标 | 模型将运行的位置(笔记本、回测框架、实盘引擎)。 |
3. 特征创建模式
3.1 数值特征
- - 交互项:价格 * 成交量、最高价 / 最低价、收盘价 - 开盘价。
- 滚动统计量:可配置窗口上的均值、标准差、偏度、峰度。
- 多项式/对数变换:log(成交量 + 1)、价差^2。
- 分箱/离散化:等宽、基于分位数或领域驱动的分箱。
3.2 分类特征
- - 独热编码:用于低基数分类变量(行业、交易所)。
- 目标编码:每个类别的平滑均值目标(注意泄漏——仅使用折内均值)。
- 序数编码:当类别具有自然顺序时(信用评级)。
3.3 时间序列特定
- - 滞后特征:return{t-1}、return{t-5}等。
- 日历特征:星期几、月份、季度、期权到期标志。
- 滚动Z分数:(x - 滚动均值) / 滚动标准差用于平稳性。
- 分数阶差分:在实现平稳性的同时保留记忆(Lopez de Prado)。
3.4 特征选择技术
- - 过滤方法:互信息、方差阈值、相关性剪枝。
- 包装方法:递归特征消除(RFE)、前向/后向选择。
- 嵌入方法:L1正则化、基于树的重要性、SHAP值。
- 排列重要性:模型无关;在折外预测上运行。
4. 防泄漏检查
数据泄漏是导致回测结果膨胀的最常见原因。
在每个管道阶段应用这些检查:
4.1 标签泄漏
验证标签窗口不与特征窗口重叠。
4.2 特征泄漏
- - 在预测时间t,任何特征不得使用时间t+1或之后的信息。
- 滚动统计量必须使用闭合左窗口:df[feat].rolling(20).mean().shift(1)。
- 目标编码的分类变量必须仅在训练折上计算。
4.3 交叉验证泄漏
- - 对时间序列使用清除k折或滚动前向交叉验证。切勿在有序数据上使用随机k折。
- 在训练折和测试折之间插入禁运间隔,以防止自相关导致的渗透。
4.4 幸存者与选择偏差
- - 确保时间t的标的池反映了当时实际可交易的内容(已退市股票、稍后移除的停牌标的)。
- 在可用时从时点数据库回溯填充。
4.5 验证检查清单
每次回测前运行:
text
[ ] 标签严格从未来收益计算(不与特征重叠)
[ ] 所有滚动特征至少偏移1个K线
[ ] 目标编码仅使用折内均值
[ ] 使用滚动前向或清除交叉验证(时间序列上无随机洗牌)
[ ] 禁运间隔 >= max(标签周期, 自相关滞后)
[ ] 标的池是时点的(无幸存者偏差)
[ ] 未在完整数据集上拟合全局缩放(在训练集上拟合,在测试集上变换)
5. 管道自动化(AutoML)
5.1 前提条件
- - 包含一个或多个AutoML库的Python环境:
Auto-sklearn、TPOT、H2O AutoML、PyCaret、Optuna或自定义Optuna管道。
- - CSV/Parquet/数据库格式的训练数据。
- 已识别的问题类型:分类、回归或时间序列预测。
5.2 管道步骤
| 步骤 | 操作 |
|---|
| 1. 定义需求 | 问题类型、评估指标、时间/资源预算、可解释性需求。 |
| 2. 数据基础设施 |
加载数据、质量评估、训练/验证/测试集划分策略、定义特征变换。 |
|
3. 配置AutoML | 选择框架、定义算法搜索空间、设置预处理步骤、选择调优策略(贝叶斯、随机、Hyperband)。 |
|
4. 执行训练 | 运行自动化特征工程、模型选择、超参数优化、交叉验证。 |
|
5. 分析与导出 | 比较模型、提取最佳配置、特征重要性、可视化、导出用于部署。 |
5.3 管道配置模板
python
pipeline_config = {
tasktype: classification, # 或 regression, timeseries
timebudgetseconds: 3600,
algorithms: [rf, xgboost, catboost, lightgbm],
preprocessing: [scaling, encoding, imputation],
tuning_strategy: bayesian, # 或 random, hyperband
cv_folds: 5,
cvtype: purgedkfold, # 或 walk_forward
embargo_bars: 10,
earlystoppingrounds: 50,
metric: sharpe_ratio, # 领域特定指标
}
5.4 输出产物
- - automlconfig.py -- 管道配置。
- bestmodel.pkl / .joblib / .onnx -- 序列化模型。
- featurepipeline.pkl -- 拟合的预处理+特征变换。
- evaluationreport.json -- 指标、混淆矩阵/残差、特征排名。
- deployment/ -- 预测API代码、输入验证、requirements.txt。
6. 核心ML基础(特征工程上下文)
6.1 偏差-方差权衡
- - 更多特征增加模型容量(降低偏差)但存在过拟合风险(增加方差)。
- 使用正则化(L1/L2)、特征选择或降维来管理。
6.2 评估策略
将固定宽度的训练窗口向前滚动;在下一个样本外周期上测试。
- - 蒙特卡洛排列测试:打乱标签并重新评估,以估计观察到的表现由偶然因素导致的概率。
- 组合清除交叉验证(CPCV):生成许多带有清除的训练/测试组合,以获得更稳健的表现估计。
6.3 特征缩放
- - 仅在训练集上拟合缩放器(StandardScaler、MinMaxScaler、RobustScaler)。
- 将相同的拟合缩放器应用于验证集和测试集。
- 由于金融数据的重尾特性,RobustScaler通常是首选。
6.4 处理缺失数据
- - 对价格数据先向前填充再向后填充(注意回溯填充的泄漏)。
- 缺失指示列本身可能具有信息价值。
- 基于树的模型可以原生处理NaN;线性模型则不能。
7. 工作流程
对于任何特征工程任务,遵循以下顺序:
- 1. 重新表述任务为可衡量的术语(指标、约束、截止日期)。
- 列举所需产物:数据集、特征定义、配置、脚本、报告。
- 提出默认