项目 / stefan-jansen/machine-learning-for-trading
Code for Machine Learning for Trading, 3rd edition — from data sourcing to live execution.
本站整理,非 GitHub 官方 description。
官方快照(gh_history.db,2026-11-25):总榜 未进 Top50 · 日榜 未进 Top50 · 周榜未满 7 天基线(官方不生成) · 月榜暂无官方口径;下方四卡为站内趋势聚合(周卡按上榜次数,非官方 7 日增量窗)。
以下三段按该项目自己的 GitHub README 章节摘录(可合理截断并标明);README 没有对应章节的留空,不编造。
仓库为新访者提供了按顺序阅读的三篇入门文章,作为上手入口。
项目强调先界定交易问题,再把数据加工为模型可用的信号,涵盖研究设计、标签、特征及决定模型学习上限的评估环节。
来自 GitHub 仓库 README / 主页介绍正文,正文较长,已截断:保留前 20000 字符(原始 31,588 字节),完整内容见 GitHub 仓库。
# Machine Learning for Trading, 3rd Edition **Build, test, and deploy ML-driven trading strategies, from data sourcing to live execution.** The code for [*Machine Learning for Trading, 3rd Edition*](https://amzn.to/4eigy2F) by [Stefan Jansen](https://www.linkedin.com/in/applied-ai/): 27 chapters and nine case studies, rebuilt from the ground up around one end-to-end workflow. How a research idea becomes a strategy you can run, and keep running, in a live market. <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> **Looking for the second edition?** It is complete and stable on the `second-edition` branch: `git checkout second-edition`, and everything is exactly where that book describes it. ## Contents - [What's new in the third edition](#whats-new-in-the-third-edition) - [Nine case studies](#nine-case-studies), the structural centerpiece of this edition - [Courses and workshops](#courses-and-workshops) - [The code, chapter by chapter](#the-code-chapter-by-chapter), 27 chapter guides - [Quick start](#quick-start): install, download the data, run your first notebook - [Companion resources](#companion-resources): primers, agent skills, and the six libraries - [Repository layout](#repository-layout) --- ## 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](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](case_studies/etfs/) | Multi-asset ETFs | Daily | Cross-asset momentum and mean-reversion across 100 ETFs | | [Crypto Perps](case_studies/crypto_perps_funding/) | Crypto | 8-hourly | Funding-rate arbitrage on perpetual futures | | [NASDAQ-100](case_studies/nasdaq100_microstructure/) | Equities | 15-min | Intraday microstructure signals from order flow and the LOB | | [S&P 500 Equity + Options](case_studies/sp500_equity_option_analytics/) | Equities + Options | Daily | Equity selection enhanced with implied-volatility features | | [US Firm Characteristics](case_studies/us_firm_characteristics/) | Equities | Monthly | Firm-level characteristics panel (size, value, momentum, quality) | | [FX Pairs](case_studies/fx_pairs/) | FX | Daily | Carry and momentum across major currency pairs | | [CME Futures](case_studies/cme_futures/) | Futures | Daily | Term-structure and roll-yield signals across commodity and financial futures | | [S&P 500 Options](case_studies/sp500_options/) | Options | Daily | Options-only strategies (straddles, delta-hedged positions) | | [US Equities](case_studies/us_equities_panel/) | Equities | Daily | Broad cross-section of US stocks with classic factor exposures | --- ## Courses and Workshops Live cohorts, one-day workshops, and free sessions, all scheduled on [Maven](https://maven.com/stefan-jansen?utm_source=github&utm_medium=readme&utm_campaign=ml4t_resources&utm_content=readme_resources_stefan_jansen). The listing below is generated daily from that schedule. <!-- offerings:all start --> ### Machine Learning for Trading The workflow this repository implements, taught end to end. | When | Offering | What you leave with | |------|----------|---------------------| | Self-paced | [Foundations](https://maven.com/stefan-jansen/ml4t-foundations?utm_source=github&utm_medium=readme&utm_campaign=foundations_self_paced&utm_content=readme_offering_ml4t_foundations) | Build the ML for Trading pipeline yourself, end to end, and the evidence to say what it does and does not establish. | | Dec 3 – Feb 18, 2027 · Feb 11 – Apr 29, 2027 | [Research to Production](https://maven.com/stefan-jansen/research-to-production?utm_source=github&utm_medium=readme&utm_campaign=r2p&utm_content=readme_offering_research_to_production) | Take one research idea from a question to a costed, monitored strategy, with the evidence trail that makes the result checkable. | | Dec 12, 2026 · Jan 23, 2027 | [ML for Trading in the Age of AI Agents](https://maven.com/stefan-jansen/ml4t-ai-agents?promoCode=ML4T-WS-50&utm_source=github&utm_medium=readme&utm_campaign=trading_workshop&utm_content=readme_offering_ml4t_ai_agents) | Work through an ETF strategy from idea to a realistic trading simulation. | **Free live sessions**, with the recording sent to everyone who registers: [Open-Source Tools for ML Trading Research](https://maven.com/p/bb56cd?utm_source=github&utm_medium=readme&utm_campaign=trading_ll_20261125&utm_content=readme_lesson_bb56cd) (Wed, Nov 25, 11:00 AM ET / 16:00 UTC) · [ML for Trading, 3rd Edition: From Data to AI Agents](https://maven.com/p/71e502?utm_source=github&utm_medium=readme&utm_campaign=lesson_71e502&utm_content=readme_lesson_71e502) (Wed, Dec 23, 11:00 AM ET / 16:00 UTC) · [Build ML for Trading Strategies with AI Agents](https://maven.com/p/f4e7f5?utm_source=github&utm_medium=readme&utm_campaign=lesson_f4e7f5&utm_content=readme_lesson_f4e7f5) (Thu, Jan 21, 11:00 AM ET / 16:00 UTC) ### Agentic systems Designing multi-agent systems whose reasoning can be audited. | When | Offering | What you leave with | |------|----------|---------------------| | Feb 6, 2027 | [Agent Engineering: Build, Evaluate, and Deploy AI Agents](https://maven.com/stefan-jansen/agent-engineering?utm_source=github&utm_medium=readme&utm_campaign=agent_workshop_20270206&utm_content=readme_offering_agent_engineering) | Go from agent fundamentals to a live multi-agent system, with an evaluation harness that says whether it works. | **Free live sessions**, with the recording sent to everyone who registers: [How to Evaluate AI Agents: From Traces to Release Decisions](https://maven.com/p/1829d6?utm_source=github&utm_medium=readme&utm_campaign=lesson_1829d6&utm_content=readme_lesson_1829d6) (Thu, Dec 10, 11:00 AM ET / 16:00 UTC) · [How to Build AI Agents with ReAct, Reflection and Planning](https://maven.com/p/c08373?utm_source=github&utm_medium=readme&utm_campaign=lesson_c08373&utm_content=readme_lesson_c08373) (Thu, Jan 7, 11:00 AM ET / 16:00 UTC) **Free lesson series:** [Build a Research Agent: Decisions, Workflows and Tools](https://maven.com/lls/4a6aef?utm_source=github&utm_medium=readme&utm_campaign=lesson_4a6aef&utm_content=readme_lesson_4a6aef) *Between cohorts, the [**Insights** newsletter](https://insights.ml4trading.io/?utm_source=github&utm_medium=readme&utm_campaign=ml4t_resources&utm_content=readme_resources_home) covers the same ground weekly, source by source.* <!-- offerings:all end --> --- ## The Code, Chapter by Chapter One directory per chapter, each opening with a guide that maps the chapter's sections onto the notebooks that implement them and lists the data each one needs. The book carries no code listings, so these guides are where a chapter's implementation lives: read a chapter, then open its directory. An introduction and a closing chapter bookend six workflow-aligned parts. ### Introduction | Chapter | What it covers | |---------|----------------| | **[1. The Process Is Your Edge](01_process_is_edge/)** | Why process discipline beats model sophistication: the ML4T workflow as a research-to-production system, regime detection on factor returns and macro indicators, and the evidence boundary that separates exploration from confirmation. | ### Part I - Financial Data (Chapters 2-5) The markets, instruments, and infrastructure the rest of the book builds on: a taxonomy of sources, raw exchange messages turned into feature-ready bars, point-in-time fundamentals, and synthetic histories for robust validation. | Chapter | What it covers | |---------|----------------| | **[2. The Financial Data Universe](02_financial_data_universe/)** | Eight asset classes surveyed, survivorship bias quantified, storage formats benchmarked (Parquet, DuckDB, kdb+, TimescaleDB), and the data-quality framework used throughout the book. | | **[3. Market Microstructure](03_market_microstructure/)** | NASDAQ ITCH parsing, limit order book reconstruction from several sources, Lee-Ready trade classification validated, and bar-sampling methods compared; dollar bars deliver the best return normality. | | **[4. Fundamental and Alternative Data](04_fundamental_alternative_data/)** | Point-in-time SEC EDGAR pipelines, entity resolution across identifier systems, macro and commodity fundamentals, and alternative-data evaluation including on-chain crypto and prediction markets (Kalshi, Polymarket). | | **[5. Synthetic Financial Data](05_synthetic_data/)** | TimeGAN, Tail-GAN, Sig-CWGAN, Diffusion-TS, and LLM-based tabular generation, each evaluated through a fidelity, utility, and privacy framework. | ### Part II - Research Design and Feature Engineering (Chapters 6-10) Define the trading problem, then turn data into model-ready signals: research design, labels, features, and the evaluation that determines what any model can learn. | Chapter | What it covers | |---------|----------------| | **[6. Strategy Research Framework](06_strategy_definition/)** | Universe rules, decision schedule, cost model, evaluation protocol, and run logging. Introduces the nine case studies and the walk-forward cross-validation discipline that anchors Chapters 7 to 20. | | **[7. Defining the Learning Task](07_defining_the_learning_task/)** | Forward-return, triple-barrier, and trend-scanning labels; information coefficients, quantile analysis, and feasibility screens; multiple-testing control with BH-FDR and the Deflated Sharpe Ratio; causal plausibility checks. | | **[8. Financial Feature Engineering](08_financial_features/)** | Five feature families from price (momentum, reversal, volatility, liquidity, microstructure), structural and cross-instrument features, macro and calendar context, and selection with robustness testing. | | **[9. Model-Based Feature Extraction](09_model_based_features/)** | Features from fitted models: stationarity diagnostics, Kalman filters, Fourier and wavelet spectral features, GARCH volatility, and HMM regime probabilities, all point-in-time correct. | | **[10. Text Feature Engineering](10_text_feature_engineering/)** | Bag-of-words through transformers: TF-IDF, Word2Vec and GloVe embeddings, LSTM sequence models, FinBERT sentiment, financial NER fine-tuning, and news-return signal construction. | ### Part III - Model Development (Chapters 11-15) Five model families applied to the same nine case studies, each building on the linear baseline. | Chapter | What it covers | |---------|----------------| | **[11. The ML Pipeline](11_ml_pipeline/)** | Ridge, LASSO, and Elastic Net as the baseline every later model must beat, logistic regression for direction, SHAP interpretability, conformal prediction for uncertainty, and a comparison across all nine case studies. | | **[12. Gradient Boosting and Advanced Tabular Models](12_gradient_boosting/)** | XGBoost, LightGBM, and CatBoost with Optuna multi-objective tuning, plus the deep tabular alternatives TabPFN and TabM. TreeSHAP explainability, and gradient boosting the strongest tabular model in most case studies. | | **[13. Deep Learning for Time Series](13_dl_time_series/)** | LSTM, N-BEATS, PatchTST, iTransformer, TFT, TSMixer, TCN, and Mamba set against the LTSF-Linear debate, with a selection framework and cross-dataset evidence on when depth helps. | | **[14. Latent Factor Models](14_latent_factors/)** | PCA eigenportfolios, IPCA with time-varying loadings, conditional and supervised autoencoders, adversarial SDF estimation, and yield-curve decomposition. | | **[15. Causal Machine Learning](15_causal_estimation/)** | Double Machine Learning for isolating factor treatment effects, Bayesian Structural Time Series for event impact, and causal discovery with PCMCI, NOTEARS, and VAR-LiNGAM. | ### Part IV - Strategy Implementation (Chapters 16-20) From predictions to deployable strategies: backtesting, portfolio construction, costs, risk, and synthesis. | Chapter | What it covers | |---------|----------------| | **[16. Strategy Simulation](16_strategy_simulation/)** | Backtesting as falsification: trading-protocol specification, vectorized against event-driven engines, an ETF baseline, regime diagnostics, and overfitting control with the Deflated Sharpe Ratio, the Rademacher Anti-Serum, and White's Reality Check. | | **[17. Portfolio Construction](17_portfolio_construction/)** | From scores to portfolios: mean-variance optimization and its pitfalls, Hierarchical Risk Parity, the Kelly criterion, conformal position sizing, deep allocation, and a controlled allocator comparison. | | **[18. Transaction Costs](18_transaction_costs/)** | Cost taxonomy, spread estimation, market-impact calibration, execution algorithms (VWAP, TWAP, Almgren-Chriss), transaction-cost analysis, and breakeven costs that vary widely by asset class. | | **[19. Risk Management](19_risk_management/)** | VaR and CVaR tail measurement, drawdown and path-risk controls, factor and sector decomposition, stress testing, adaptive risk overlays, deep hedging, and kill switches; overlay effectiveness turns out to be strategy-specific. | | **[20. Strategy Synthesis](20_strategy_synthesis/)** | What nine experiments reveal about turning predictions into strategies: IC-Sharpe decorrelation, Fundamental Law diagnostics, the model-family cascade, cost-survival analysis, and holdout failure modes. | ### Part V - Advanced AI (Chapters 21-24) Reinforcement learning, large language models, knowledge graphs, and autonomous agents for finance. | Chapter | What it covers | |---------|----------------| | **[21. Reinforcement Learning for Execution and Hedging](21_rl_execution_hedging/)** | MDP formulation for finance, DQN, PPO and SAC, optimal execution, market making with inventory management, deep hedging with PFHedge, inverse RL for strategy recovery, and the sim-to-real gap. | | **[22. RAG for Financial Research](22_rag_financial_research/)** | Retrieval-augmented generation grounded in SEC filings: ingestion, domain-specific embeddings, hybrid retrieval with re-ranking, constraint-based prompting, evaluation and failure diagnostics, and the move to agentic workflows. | | **[23. Knowledge Graphs](23_knowledge_graphs/)** | When graphs earn their infrastructure cost: construction from SEC filings, Graph RAG for multi-hop reasoning, GNN embeddings and centrality as ML features, financial networks, and temporal-leakage prevention. | | **[24. Autonomous Agents](24_autonomous_agents/)** | ReAct, Tree of Thoughts, and Reflexion architectures, memory systems, tool contracts, the engineering stack (LangGraph, Claude SDK), a stateful equity-research agent, multi-agent forecasting with adversarial debate, and production reliability. | ### Part VI - Production (Chapters 25-26) Taking strategies live: trading systems and the operational infrastructure that keeps them running. | Chapter | What it covers | |---------|----------------| | **[25. Live Trading Systems](25_live_trading/)** | A framework bridging research and production: Interactive Brokers and Alpaca integration, managed platforms (QuantConnect), order-lifecycle management, pipeline verification, and operational readiness. | | **[26. MLOps and Governance](26_mlops_governance/)** | A failure taxonomy separating pipeline divergence from performance decay, drift detection, safe model rollout, circuit breakers, feature stores, and experiment tracking. | ### Conclusion | Chapter | What it covers | |---------|----------------| | **[27. The Systematic Edge](27_systematic_edge/)** | The systematic philosophy, quant career paths, learning resources, research frontiers, and how to build your own edge. The closing bookend to Chapter 1: the process is the edge. | --- ## Quick Start **New here? Read these three, in order.** 1. **[What this repository is, and what it is not](docs/what-this-is.md)** - what reproduces with one command, what a configuration change buys you, what needs real compute or licensed data, and what is not promised. Five minutes, before you install anyt