Machine Learning For Trading
Code for Machine Learning for Trading, 3rd edition — from data sourcing to live execution.
Install / Use
npx skills add stefan-jansen/machine-learning-for-tradingInstalls into whichever agent you are using.
README
Machine Learning for Trading — 3rd Edition
Build, test, and deploy ML-driven trading strategies — from data sourcing to live execution.
This repository hosts the code for Machine Learning for Trading, 3rd Edition by Stefan Jansen — a ground-up rebuild, organized around one end-to-end workflow: how you define a research idea and develop it iteratively into a strategy you can actually run, and keep running, in a live market.
- Nine case studies illustrate the workflow throughout the 27 chapters of the book, from raw data through features, models, backtests, costs, and risk to deployment.
- Generative AI and autonomous agents are new to this edition and cut across that workflow, bringing retrieval-augmented generation, knowledge graphs, and multi-agent systems to financial research.
- The companion website features 112 primers, 61 agent skills, and six production Python libraries that facilitate substantial parts of the workflow.
Start here: Installation walks a blank Linux, Windows or macOS machine to a running notebook, prerequisites included. The short version is under Quick Start below.
<p align="center"> <a href="https://amzn.to/4eigy2F"><img src="assets/cover.png" width="45%" alt="Machine Learning for Trading, 3rd Edition"></a> </p>Free reader's guide: Join Navigate ML for Trading, 3rd Edition on July 30, 2026 at 11:00 AM ET for a 30-minute map of the book, case studies, code, and companion resources. See all current courses and workshops; the cohort courses are listed under Courses below.
What's New in the Third Edition
The whole book traces one path: from data infrastructure and strategy research, across an evidence boundary that separates tuning from evaluation, to deployment and monitoring — with a feedback loop that retrains, pauses, or retires a strategy as its edge decays.
<p align="center"> <img src="assets/workflow.png" width="90%" alt="The ML4T workflow: data infrastructure and strategy research, an evidence boundary separating tuning from evaluation, and deployment with a retrain/pause/retire feedback loop"> </p>Where earlier editions moved technique by technique, the third edition runs that one process end to end — and adds substantial new material:
- A wider model toolkit: from gradient boosting (XGBoost, LightGBM, CatBoost) to deep time-series architectures (PatchTST, iTransformer, TSMixer, TCN, Mamba) and newer tabular and latent-factor models (TabPFN, TabM, conditional and supervised autoencoders).
- Dedicated strategy-design chapters: transaction costs and risk management are now full chapters, neither of which existed before, joining portfolio construction and strategy synthesis so a raw signal is carried through to a sized, cost- and risk-aware portfolio.
- A full production track: live trading systems (Interactive Brokers, Alpaca, QuantConnect), MLOps and governance (drift detection, safe rollout, circuit breakers, feature stores, experiment tracking), and the operational reality of running strategies, not just building them.
- Generative AI: retrieval-augmented generation grounded in SEC filings, knowledge graphs and Graph RAG, and autonomous, multi-agent research systems.
- Causal machine learning: Double ML, Bayesian structural time series, and causal discovery for separating real effects from spurious correlation.
- Reinforcement learning: optimal execution, market making with inventory, and deep hedging.
- Synthetic financial data: TimeGAN, Tail-GAN, Sig-CWGAN, and diffusion-based generators for validation when history is short.
Methodological rigor is treated as a first-class topic rather than an afterthought. The book draws an explicit line between exploration and confirmation — the evidence boundary — uses walk-forward cross-validation throughout, and confronts the multiple-testing and overfitting problems that quietly invalidate most backtests, with tools like the Deflated Sharpe Ratio, the Rademacher Anti-Serum, and White's Reality Check, plus conformal prediction for honest uncertainty estimates.
The data layer moves to Polars for fast, expression-based manipulation, and every chapter ships in reproducible Docker environments so results repeat across machines; PyTorch, LightGBM, Optuna, and Plotly round out the modeling and visualization stack.
Nine Case Studies
The structural centerpiece of the third edition is nine case studies that run the length of the book. ETFs, crypto perpetuals, intraday equities, options, FX, futures, and equity factor panels are each carried through the same pipeline — from raw data and labels to features, models, backtests, costs, risk overlays, and a final deployment assessment. One disciplined process applied to nine very different markets shows where it works, where it breaks, and why.
| Case Study | Asset Class | Frequency | What It Explores | |-------------------------------------------------------------------------|--------------------|-----------|------------------------------------------------------------------------------| | ETFs | Multi-asset ETFs | Daily | Cross-asset momentum and mean-reversion across 100 ETFs | | Crypto Perps | Crypto | 8-hourly | Funding-rate arbitrage on perpetual futures | | NASDAQ-100 | Equities | 15-min | Intraday microstructure signals from order flow and the LOB | | S&P 500 Equity + Options | Equities + Options | Daily | Equity selection enhanced with implied-volatility features | | US Firm Characteristics | Equities | Monthly | Firm-level characteristics panel (size, value, momentum, quality) | | FX Pairs | FX | Daily | Carry and momentum across major currency pairs | | CME Futures | Futures | Daily | Term-structure and roll-yield signals across commodity and financial futures | | S&P 500 Options | Options | Daily | Options-only strategies (straddles, delta-hedged positions) | | US Equities | Equities | Daily | Broad cross-section of US stocks with classic factor exposures |
112 Primer Topics
Free concept explainers for every idea the book relies on. Each part links to its full list; a few topics show the range:
- Foundations: 8 topics spanning limit order book mechanics, bitemporal data models, and the stylized facts a simulator must reproduce.
- Research Design and Feature Engineering: 21 topics, including multiple testing in factor research, fractional differencing, and path signatures for financial sequences.
- Model Development: 22 topics, among them regularization geometry, conformal prediction in finance, and the mechanism behind double machine learning.
- Strategy Implementation: 27 topics, from the deflated Sharpe ratio and hierarchical risk parity to Almgren-Chriss optimal execution.
- Advanced AI: 8 topics such as Markov decision processes, the policy-gradient theorem, and proper scoring rules for event forecasts.
- Production: 2 topics, champion-challenger evaluation and training-serving skew with feature stores.
- Cross-cutting concepts: 24 building blocks referenced across chapters, for example momentum and mean reversion, the bias-variance tradeoff, and walk-forward validation.
61 Agent Skills
Reusable, guard-railed tasks for coding agents, each with built-in defenses against lookahead bias, data leakage, and multiple-testing errors. Each category links to its full set; a few skills show the range:
- Concepts: 10 skills, including lookahead bias, data leakage, and the information coefficient.
- Data Acquisition: 7 skills spanning fetching data, building bars, and data validation.
- Feature Engineering: 10 skills, among them computing features, triple-barrier labels, and feature selection.
- Evaluation & Validation: 8 skills, from walk-forward CV and purging-and-embargo to the deflated Sharpe ratio.
- Backtesting: 5 skills such as running backtests, cost models, and tear sheets.
- Portfolio Management: 5 skills, including position sizing, risk metrics, and kill switches.
- Infrastructure: 4 skills, for example the canonical schema, the registry system, and Polars patterns.
- Workflows: 5 skills covering factor research, mod
Related Skills
node-connect
385.5kDiagnose OpenClaw Android, iOS, or macOS node pairing, QR/setup code, route, auth, and connection failures.
blender-python-addon
40.5kBlender Python add-on rules for operators, panels, properties, registration, testing, and API-safe scripting
flutter-development-guidelines-cursorrules-prompt-file
40.5kCursor rules for Flutter development with MVVM architecture, Riverpod state management, Material widgets, and Dart style guidelines.
commit-push-pr
140.6kCommit, push, and open a PR
Languages
Security Score
Audited on Aug 7, 2026
