Quantitative Investment × AI: A Learning Path from Zero to Live Trading
A systematic learning path for myself: six stages, eleven diagrams, and a set of self-assessment graduation criteria. The core idea is simple—AI makes rigorous research faster and more rigorous, and mediocre research faster and more mediocre.
1. First, Look at the Big Picture
Diagram 3 emphasizes the first point I want to make. Most career changers have a capability profile like the orange dashed line: they can code well and use models effectively, but they lack intuition about "why this backtest might be false." Closing this gap is much more important than learning another new framework.
2. Think Clearly About Three Things Before Getting Started
What Money Does Quantitative Trading Make
| Source of Income | Description | Example | Sustainability |
|---|---|---|---|
| Beta | Returns from bearing overall market risk | Buying index funds | Long-term existence |
| Risk Premium (Smart Beta) | Returns from bearing certain types of systematic risk | Value factor, momentum factor | Relatively durable, but will decay |
| Alpha | Profiting from pricing errors | Statistical arbitrage, event-driven | Can be consumed by competition, requires continuous exploration |
Alpha is a zero-sum or even negative-sum game—after costs, what you earn comes from your opponents' losses, and those opponents include top-tier institutions with PhD teams. Maintain a sense of awe.
What Can AI Actually Do in Quantitative Trading
| What AI Can Do Well | What AI Cannot Do Well |
|---|---|
| Learn nonlinear relationships from hundreds of features | Predict tomorrow's price movements out of thin air (signal-to-noise ratio too low) |
| Extract sentiment and events from news/research reports/announcements | Take responsibility for your research methodology |
| Write data cleaning code, read papers, review backtests | Scenarios with very few samples (e.g., macro monthly data) |
| Factor synthesis, anomaly detection, risk control alerts | Fully automated "AI money printer" |
The characteristics of financial data are low signal-to-noise ratio, non-stationarity, and limited samples, which are the opposite of image recognition (high signal-to-noise ratio, stable distribution, massive samples). Therefore, "throwing stock prices into deep learning" is essentially an illusion. The correct approach for AI is: to enhance specific parts within a rigorously designed human framework.
What Is Your End Goal
- A. Go to an Institution: Focus on strengthening math, ML, and programming skills, and practice interview questions.
- B. Personal Quantitative Trading: Focus on strategy development, backtesting, risk control, and execution, being extremely cost-sensitive.
- C. Pure Interest: Can take a more relaxed approach.
The following path primarily focuses on B (while also considering A), as it covers the entire process from research to live trading.
3. Stage 1: Three Foundations (3–6 Months)
Programming: Python is the Universal Language of Quantitative Trading
| Module | Must Master | Self-Assessment Criteria |
|---|---|---|
| Python Basics | Data types, functions, comprehensions, exception handling | Independently complete 20 simple LeetCode problems |
| NumPy | Vectorization, broadcasting, matrix operations | Calculate rolling returns for 100 stocks without for loops |
| Pandas | DataFrame, groupby, merge, resampling, rolling | Given a minute-level CSV, calculate daily, weekly, and 20-day moving averages within 10 minutes |
| Matplotlib | Candlestick charts, net value curves, drawdown charts | Reproduce a net value comparison chart from a research report |
| SQL | Join, window functions | Extract "the top 10 stocks by market capitalization each month" |
A crucial mindset shift to establish—vectorization:
import numpy as np, pandas as pd
# Simulated prices for 1000 days × 500 stocks
prices = pd.DataFrame(np.random.lognormal(0, 0.02, (1000, 500)).cumprod(axis=0))
# ✗ Novice approach: Double loop to calculate daily returns, slow by dozens of times
# for i in range(1, len(prices)):
# for j in range(prices.shape[1]):
# ret[i][j] = prices.iloc[i, j] / prices.iloc[i-1, j] - 1
# ✓ Quantitative approach: One line
returns = prices.pct_change()
momentum_20d = prices.pct_change(20) # 20-day momentum factor, also one line
Backtesting often involves processing thousands of stocks over decades of data; a vectorized mindset determines your research efficiency.
Mathematics: Understand to the Point of Being Able to Calculate
| Module | Key Content | Application in Quantitative Trading |
|---|---|---|
| Probability and Statistics (Most Important) | Distribution and expectation, hypothesis testing, regression | Determine whether a strategy is genuinely effective or just lucky |
| Linear Algebra | Matrix operations, eigenvalues, PCA, covariance matrix | The foundation for ML and risk models |
| Time Series | Stationarity, ACF, ARIMA, GARCH | Understand the "temperament" of financial data |
| Optimization | Mean-variance, Lagrange multipliers, convex optimization | Determine how much to buy of each stock |
Remember the three temperaments of financial time series: prices are non-stationary, returns are approximately stationary (hence modeling uses returns); volatility clustering (large fluctuations are followed by large fluctuations); distribution has heavy tails (extreme market conditions occur much more frequently than predicted by normal distribution, so risk control cannot rely solely on standard deviation).
Finance: Know What You Are Trading
| Topic | Core Content | Why It Matters |
|---|---|---|
| Market Structure | Trading hours, price limits, T+1, auction, order book | Mistakes in backtest rules lead to completely wrong results |
| Trading Costs | Commissions, stamp duty, slippage, impact costs | The culprit behind "backtest profits but real trading losses" for high turnover strategies |
| Financial Statements | Three major statements, ROE, PE/PB, cash flow | The raw materials for fundamental factors |
| Classic Theories | EMH, CAPM, behavioral finance | Alpha comes from the cracks in the efficient market hypothesis |
4. Stage 2: Core Quantitative Skills (4–8 Months)
This is the critical stage of transforming from "someone who can code" to "quantitative researcher."
Data
Data sources available for beginners: AkShare (free, open-source, preferred), Tushare (points system), yfinance (US stocks), JoinQuant / BigQuant (online platforms with integrated data and backtesting). Institutions like Wind can be skipped for personal use.
Backtesting
During the learning phase, you must write a vectorized backtest from scratch before using Backtrader, VectorBT, or Qlib. The following code is the first lesson of Stage 2, with two details hiding two professional habits:
import numpy as np, pandas as pd
def backtest_ma_cross(price: pd.Series, fast=20, slow=60, cost_rate=0.0015) -> pd.DataFrame:
"""Vectorized backtest for dual moving average strategy (including transaction costs). Price must be the adjusted daily closing price."""
df = pd.DataFrame({"price": price})
df["ma_fast"] = price.rolling(fast).mean()
df["ma_slow"] = price.rolling(slow).mean()
df["signal"] = (df["ma_fast"] > df["ma_slow"]).astype(int)
df["position"] = df["signal"].shift(1).fillna(0) # ① The signal calculated from today's close can only be executed tomorrow
df["ret"] = price.pct_change().fillna(0)
df["trade"] = df["position"].diff().abs().fillna(0)
df["strategy_ret"] = df["position"] * df["ret"] - df["trade"] * cost_rate # ② Costs deducted on the day of rebalancing
df["nav"] = (1 + df["strategy_ret"]).cumprod()
df["benchmark"] = (1 + df["ret"]).cumprod()
return df
def performance(nav: pd.Series) -> dict:
ret = nav.pct_change().dropna()
annual = nav.iloc[-1] ** (252 / len(nav)) - 1
vol = ret.std() * np.sqrt(252)
return {"Annual Return": f"{annual:.2%}", "Annual Volatility": f"{vol:.2%}",
"Sharpe Ratio": f"{(annual - 0.02) / vol:.2f}", "Max Drawdown": f"{(nav / nav.cummax() - 1).min():.2%}"}
① Removing shift(1) will cause the backtest returns to falsely soar—this is the most common lookahead bias. ② Adjusting cost_rate from 0 to 0.003 will give you a tangible sense of cost sensitivity.
| Metric | Meaning | Experience Reference |
|---|---|---|
| Annual Return | (End/Start)^(252/days) − 1 | Meaningless on its own; must be viewed with risk |
| Max Drawdown | The maximum drop from peak to trough in net value | Personal strategy recommendation < 20% |
| Sharpe Ratio | (Annual Return − Risk-Free Rate) / Annual Volatility | > 1 is passing, > 2 is excellent, > 3 should raise suspicion of overfitting |
| Calmar Ratio | Annual Return / Max Drawdown | > 1 is good |
| Win Rate × Profit-Loss Ratio | Proportion of profitable trades × Average profit-loss | Trend strategies often have low win rates but high profit-loss ratios |
Factors
Factor = A computable indicator that can distinguish between good and bad stocks in the future. Classic families: value (inverse PE/PB, dividend yield), momentum (past 1–12 month returns, noting A-shares tend to reverse), size, quality (ROE, gross margin), low volatility, liquidity.
The standard process for single-factor testing involves three steps: calculate factor values for the entire market → IC analysis (cross-sectional correlation coefficient between factor values and next period returns) → layered backtesting.
Implement at least one of each type of strategy: dual moving average trend, momentum/reversal rotation, multi-factor stock selection, pairs trading, grid (understanding how it can get fully trapped in a one-sided decline).
5. Stage 3: AI / Machine Learning (4–8 Months)
Why Tree Models (Not Deep Learning) Are the Mainstay of Quantitative ML
| Dimension | GBDT (LightGBM / XGBoost) | Deep Neural Networks |
|---|---|---|
| Tabular Factor Data | Extremely proficient | Average |
| Sample Size Requirement | Moderate | Massive |
| Overfitting Control | Relatively easy | Difficult |
| Interpretability | Feature importance / SHAP | Black box |
| Actual Industry Use | Mainstream for cross-sectional stock selection | High-frequency / alternative data |
Conclusion: Master LightGBM first before touching neural networks.
Three Major Differences Between Financial ML and Ordinary ML
The third difference is that the market evolves: a model that is effective in 2018 may become ineffective in 2024, requiring models to be retrained periodically and monitoring factor crowding.
Paradigm 1: Machine Learning Factor Synthesis
Traditional multi-factor models use linear weighting: score = 0.3×value + 0.3×momentum + 0.4×quality, with weights determined manually. The value of ML lies in learning nonlinear combinations that are difficult for humans to enumerate—patterns like "small cap and low volatility and reversal." The standard process:
- Features: N factor values for each stock in each period, standardized using cross-sectional z-scores
- Labels: Next period's excess return or return ranking
- Training: Rolling window, training with the past 3–5 years each month to predict the next month
- Portfolio: Go long on the top 10% based on predicted values (short the bottom 10% for hedging)
- Attribution: Use SHAP to see what the model is actually using, preventing it from learning market cap/industry exposure by accident
model = lgb.LGBMRegressor(
n_estimators=200, max_depth=4, # Trees should be shallow—financial noise is high
learning_rate=0.05, subsample=0.8,
colsample_bytree=0.8, reg_lambda=10, # Regularization should be strong
)
Paradigm 2: Using LLM as a Research Assistant
This is currently the most cost-effective AI application: generating backtest functions that include costs and slippage, compressing papers into "factor construction + data + conclusions + reproduction steps," generating cleaning scripts based on the appearance of dirty data, and writing experiment records according to templates. One of the most valuable tasks is having it specifically review biases:
You are a quantitative code review expert. Please check the following backtest code for:
1. Lookahead bias (shift direction errors, label leakage)
2. Survivorship bias (does the stock pool include delisted stocks)
3. Cost omissions (transaction fees / slippage / stamp duty)
4. Timing data issues (did financial data use information after the announcement date)
5. Errors in adjustment processing
For each item: point out specific lines of code, explain the risks, and provide modification suggestions.
Reinforcement learning has real applications in order execution, but "end-to-end learning of trading strategies" generally performs poorly in low-frequency domains. Save it for the expert stage.
6. Stage 4: Engineering and Simulated Live Trading (3–6 Months)
There is an engineering gap between research and live trading. The minimum architecture for a personal quantitative system:
Scheduled Tasks (cron)
│
▼
Data Module ──▶ Signal Module ──▶ Risk Control Module ──▶ Execution Module
Fetching·Storage Factors·Prediction Positions·Stop Loss Orders·Returns
Validation Circuit Breaker
│ │ │ │
└──────────┴──────────┴──────────┘
│
Monitoring and Logging (error alerts to phone)
Essential engineering skills to learn: Git (for experiment traceability), scheduled tasks, logging and alerts, starting with SQLite databases, pytest.
Three layers of risk control (personal version): Single Position Level—single stock position ≤ 10%, stop-loss line; Portfolio Level—total position limit, industry concentration, reduce position by half at 15% drawdown, liquidate and reflect at 20% drawdown; System Level—automatically stop on data anomalies, retry failed orders with manual confirmation.
7. Stage 5: Becoming an Expert
| Dimension | Skilled Worker | Expert |
|---|---|---|
| Source of Strategies | Reproduce strategies found online | Have their own hypothesis generation system |
| Attitude Towards Backtesting | Trust good-looking backtests | Assume good-looking backtests are wrong, first look for bugs |
| Research Method | Single-point experiments | Experimental pipelines + strict out-of-sample discipline |
| Response to Failure | Panic and adjust parameters | Strategy lifecycle management and multi-strategy configuration |
Daily habits of experts: maintain an idea pool; each experiment has a number, configuration, and conclusion that can be fully reproduced; regularly conduct strategy health checks (IC decay, crowding, attribution); fixed weekly inputs (papers, Quantocracy), and regular outputs (research notes). Choose one or two advanced directions to delve into based on interest: portfolio optimization and risk models, microstructure and high frequency, derivatives and volatility, alternative data, time series transformers and graph neural networks.
8. 12-Month Streamlined Plan
The shortest viable path requires 2–3 hours a day; a complete depth is still recommended for 18–30 months.
| Month | Main Tasks | Milestone Outputs |
|---|---|---|
| 1–2 | Python + Pandas + Financial Knowledge | Use AkShare to fetch and clean daily data for the entire A-share market |
| 3 | Statistical Basics + Handwritten Backtesting | Complete dual moving average backtest and performance function |
| 4–5 | Factor Research Methodology | IC analysis and layered backtest report for 5 classic factors |
| 6 | Multi-Factor Portfolio | Linear scoring monthly rebalancing strategy, including cost backtesting |
| 7–8 | ML Basics + LightGBM | ML factor synthesis, comparing with linear synthesis benchmarks |
| 9 | Financial ML Methodology + Qlib | Reproduce Alpha158 workflow using Qlib |
| 10 | NLP / LLM Applications | News sentiment factor prototype; LLM prompt template library |
| 11 | Engineering | Strategy runs automatically (scheduled + logging + alerts), start simulated trading |
| 12 | Simulated Trading Review | Monthly report for simulated trading; annual research summary |
9. The Ten Most Common Pitfalls for Beginners
- Lookahead Bias—All signals
shift(1), financial data aligned by announcement date. - Survivorship Bias—Using a stock pool that includes delisted stocks.
- Overfitting / Data Snooping—Strict out-of-sample; few parameters; only look at the same test set once; if Sharpe > 3, suspect yourself.
- Ignoring Costs and Liquidity—Add costs, limit transaction volume, exclude illiquid stocks.
- Using 5 Years of Bull Market for Backtesting—At least cover one full bull-bear cycle; for A-shares, recommend ≥ 10 years.
- Confusing Correlation with Causation—Each factor should have a hypothesis before verification, not the other way around.
- Randomly Splitting Training and Testing Sets—Time series must be cut by time.
- Running Naked Without Risk Control—Write risk control first, then write the strategy.
- Doubling Down After Failure—Set predefined failure standards, such as stopping use and reviewing if drawdown exceeds 1.5 times the historical maximum drawdown.
- Reinventing the Wheel—Read papers and communities weekly, and output regularly.
10. Graduation Standards
To determine if you can graduate from a stage, self-assess using these criteria:
- Stage 1: Write a max drawdown function without checking references; explain why returns are modeled instead of prices; clarify all costs involved in a single trade in A-shares.
- Stage 2: Independently complete a full backtest that includes costs and prevents lookahead bias; perform IC analysis and layered backtesting for any factor and interpret the results; upon seeing a backtest with a Sharpe of 3.5, your first reaction should be to list five biases to check.
- Stage 3: Explain what problem Purged K-Fold solves; conduct an ML stock selection experiment with rolling training and perform SHAP attribution; establish your own LLM research assistant workflow.
- Stage 4: Run a strategy unattended for a month without unhandled exceptions; explain deviations between simulated trading and backtesting; write down formal risk control rules and failure exit standards.
Selected Resources
| Stage | Book | Others |
|---|---|---|
| Introduction | "Unlocking the Black Box of Quantitative Investment" "Data Analysis with Python" | Kaggle Learn, Investopedia |
| Core | "Factor Investing: Methods and Practice" "Introduction to Statistical Learning" (ISL, free on the official website) | Kenneth French Factor Database, awesome-quant |
| AI Quant | Jansen "Machine Learning for Algorithmic Trading", López de Prado "Advances in Financial Machine Learning" | Microsoft Qlib, SSRN, arXiv q-fin |
| Advanced | Grinold & Kahn "Active Portfolio Management", Hull "Options, Futures, and Other Derivatives" | Quantocracy, QuantConnect Forum |
Conclusion
The truth of this path is: AI makes mediocre research faster and more mediocre, and rigorous research faster and more rigorous. Methodology—preventing biases, out-of-sample discipline, economic logic—is the "1," and AI efficiency is the subsequent "0." Establish the "1" firmly, and only then can AI serve as a lever rather than an illusion amplifier.
Where am I on this journey? The "Stage 4" of this path is quant-agent: a trading agent that only runs paper trades, where the model can only suggest intentions, and rules make the decisions. It is currently in a multi-month observation period—why I wrote that review.