6.1.9Algorithmic & Quant Trading

Understand machine learning in trading (caution)

3,825 words17 min readdifficulty · medium1 backlinks

The Promise vs. The Reality

What ML Can Actually Do

Machine learning in trading uses algorithms that learn patterns from historical data to make predictions about future price movements, trade timing, or risk.

Legitimate applications:

  1. Feature engineering - Transform raw price data into predictive signals
  2. Regime detection - Identify when market conditions change (volatility shifts, trend vs. mean-reversion)
  3. Execution optimization - Minimize market impact when placing large orders
  4. Risk modeling - Predict volatility, correlations, tail risks
  5. Alternative data processing - Extract signals from satellite images, credit card data, social sentiment

WHY these work: They solve well-defined problems with clear evaluation criteria and don't require predicting exact future prices.

The Fatal Traps

Derivation: Why Overfitting is Mathematically Guaranteed

Let's prove why complex models always overfit small datasets.

Setup: You have NN data points (e.g., 200 days of returns) and a model with PP parameters.

The Degrees of Freedom Problem

Derivation from first principles:

  1. Sample size: NN observations (e.g., 200 trading days)
  2. Model parameters: PP weights/features (e.g., 50 technical indicators)
  3. Effective degrees of freedom: DOF=NP\text{DOF} = N - P

WHY does this matter?

For the model to learn generalizable patterns rather than noise:

Required: NP10 to 20\text{Required: } \frac{N}{P} \geq 10 \text{ to } 20

Proof by example:

  • If P=NP = N: Your model has as many knobs as data points. It can fit any random sequence perfectly by assigning one parameter per point.
  • If P>NP > N: You have more parameters than data - infinitely many solutions exist, all fitting training data perfectly, most worthless.

The Bias-Variance Tradeoff

WHAT this means:

  • Bias = how far your model's average prediction is from truth (underfitting)
  • Variance = how much your model's predictions vary with different training sets (overfitting)
  • Irreducible error = randomness you can't predict

WHY complex models overfit:

As model complexity ↑:

  • Bias ↓ (fits training data better)
  • Variance ↑ (becomes unstable, changes wildly with small data changes)
  • At high complexity: Variance dominates, model fits noise

How to Use ML Responsibly in Trading

1. Walk-Forward Analysis

HOW to implement:

Training Window: [Year 1, Year 2, Year 3] → Test on [Year 4 Q1]
Roll forward:    [Year 2, Year 3, Year 4 Q1] → Test on [Year 4 Q2]
Continue rolling...

WHY this works: Simulates reality - you only know the past when making decisions.

2. Cross-Validation for Time Series

3. Sharpe Ratio as Evaluation Metric

4. Regularization Techniques

L1 Regularization (Lasso):

Loss=MSE+λi=1Pwi\text{Loss} = \text{MSE} + \lambda \sum_{i=1}^{P} |w_i|

WHY: Forces many weights to exactly zero, performs automatic feature selection. Prevents using100 features when 5 drive all signal.

L2 Regularization (Ridge):

Loss=MSE+λi=1Pwi2\text{Loss} = \text{MSE} + \lambda \sum_{i=1}^{P} w_i^2

WHY: Shrinks all weights toward zero, prevents any single feature from dominating. Reduces variance.

HOW to choose λ\lambda: Use cross-validation to find the penalty strength that minimizes out-of-sample error.

Worked Examples

The Right Way to Build ML Trading Systems

Phase 1: Hypothesis-Driven Development

Start with a theory, not data mining:

  1. Economic intuition: "Stocks with rising revenue growth and falling inventory growth tend to outperform" ← testable hypothesis
  2. NOT data mining: "Let me try500 features and see what correlates" ← guaranteed overfitting

WHY this matters: Hypothesis-driven research reduces multiple testing problems and builds on market logic.

Phase 2: Feature Engineering

Good features:

  • Based on economic theory
  • Stationary (statistical properties don't drift over time)
  • Available in real-time (no look-ahead bias)

Example features:

  • Momentumt=PtPt20Pt20\text{Momentum}_t = \frac{P_t - P_{t-20}}{P_{t-20}} (20-day return)
  • Volatilityt=std(Rt20:t)\text{Volatility}_t = \text{std}(R_{t-20:t}) (20-day return std)
  • Relative Strengtht=MomentumstockMomentumsector\text{Relative Strength}_t = \frac{\text{Momentum}_{\text{stock}}}{\text{Momentum}_{\text{sector}}}

Phase 3: Simple Models First

Model complexity hierarchy:

  1. Linear regression - Start here. If it doesn't work, complex models won't either.
  2. Regularized linear (Lasso, Ridge, Elastic Net)
  3. Tree-based (Random Forest, Gradient Boosting)
  4. Neural networks - Last resort, only if you have massive data

WHY simple first: Occam's Razor. Simpler models generalize better, are easier to interpret, and fail less catastrophically.

Phase 4: Validation Hell (This is Where You Live)

Validation protocol:

  1. Out-of-sample test: 20% of data never seen during development
  2. Walk-forward: Roll through time, retrain, test next period
  3. Cross-regime: Test during 2008 crisis, 2020 COVID, 2022 rate hikes
  4. Stress test: What happens if volatility doubles? Correlations break?
  5. Paper trade: 3-6 months simulated real-time trading

Only deploy if successful at ALL stages.

When ML Actually Works in Trading

Success stories (institutional level):

  1. Renaissance Technologies (Medallion Fund):
    • Uses massive alternative datasets
    • Extremely short holding periods (minutes to hours)
    • Statistical arbitrage on thousands of instruments
    • 66% annual returns for 30 years

WHY they succeed:

  • Huge data advantage (proprietary datasets)
  • PhD-level quant teams
  • Infrastructure to test billions of hypotheses rigorously
  • Capital to exploit tiny inefficiencies at scale
  1. Two Sigma, Citadel, DE Shaw:
    • Similar approaches: massive data, rigorous validation
    • Focus on execution optimization, risk management

What retail/small institutional can do:

  1. ML for risk management (easier than returns prediction)

    • Volatility forecasting
    • Correlation regime detection
    • Tail risk estimation
  2. Alternative data processing

    • Sentiment analysis from earnings calls
    • Satellite imagery of retail parking lots
    • Credit card transaction data
  3. Execution optimization

    • Optimal trade timing within the day
    • Minimizing market impact

WHY these work: They don't require predicting future prices exactly, just improving process efficiency or risk assessment.

Recall Explain to a 12-Year-Old

Imagine you're trying to predict tomorrow's weather by looking at the last 10 days. You notice that every time it was sunny for 3 days, it rained on the 4th day. So you create a rule: "3 sunny days → rain next."

But here's the problem: you only looked at 10 days. Maybe by pure luck, those 3 sunny stretches were followed by rain. If you look at 1000 days, the pattern might disappear. You memorized noise instead of learning real weather patterns.

Machine learning in trading makes this mistake constantly. Your computer finds patterns in stock prices (like "when Apple goes up 3 days, it drops on day 4"), but most of those patterns are just coincidences in the small amount of data you tested. When you try to use them with real money, they stop working.

The other big problem: imagine practicing basketball by watching videos of NBA games, but you skip all the videos where players missed shots. You'd think "everyone makes every shot!" Your practice is based on fake data.

That's survivorship bias - when you test trading strategies on companies that succeeded (like current S&P 500 members) but ignore all the companies that failed and disappeared. Your strategy might have lost all your money on those failed companies, but you never tested them!

ML can work in trading, but you have to be extremely careful to test it honestly, use simple strategies, and never trust patterns until you've seen them work in brand new data you never looked at before.

Key Formulas Summary

| Concept | Formula | When to Use | |---------|-------------| | Overfitting Check | NP10\frac{N}{P} \geq 10 | Before training any model | | Sharpe Ratio | E[RpRf]σp\frac{\mathbb{E}[R_p - R_f]}{\sigma_p} | Evaluating risk-adjusted returns | | Bias-Variance | Error=Bias2+Variance+Irreducible\text{Error} = \text{Bias}^2 + \text{Variance} + \text{Irreducible} | Understanding model tradeoffs | | L1 Regularization | Loss+λwi\text{Loss} + \lambda \sum \|w_i\| | Feature selection | | L2 Regularization | Loss+λwi2\text{Loss} + \lambda \sum w_i^2 | Reducing overfitting |

#flashcards/stock-market

What is overfitting in ML trading? :: When a model memorizes random patterns in training data (noise) instead of learning true underlying relationships, causing it to fail on new data.

Why is overfitting guaranteed when P > N?
A model with more parameters (P) than data points (N) can fit any random sequence perfectly, but has learned nothing generalizable. Need/P ≥ 10.
What is look-ahead bias?
Using information your model that would not have been available at the time of the trading decision, like using closing prices to make opening trades.
What is survivorship bias in backtesting?
Testing strategies only on companies that currently exist, excluding all the companies that failed/delisted, creating artificially good results.
What is the bias-variance tradeoff?
Total error = Bias² + Variance + Irreducible. As model complexity increases, bias decreases (fits training better) but variance increases (overfits), eventually making performance worse.
What is walk-forward analysis?
Training on a window of past data, testing on the next unseen period, then rolling the window forward. Simulates real-time trading where you only know the past.
Why is Sharpe ratio better than raw returns?
Sharpe = (Return - Risk-free) / Volatility. It penalizes strategies that achieve returns through excessive risk. A volatile20% return may be worse than a stable 10% return.
What is L1 regularization?
Adding λΣ|wᵢ| to the loss function forces many weights to exactly zero, performing automatic feature selection and preventing the model from using too many features.
What is data snooping (p-hacking)?
Testing many features/strategies until one appears significant by random chance. With 100 tests at 95% confidence, 5 will appear significant purely by luck.
What makes markets non-stationary?
Statistical properties change over time - volatility regimes shift, correlations break, Fed policy changes, new regulations appear. Past patterns may not repeat.
What transaction costs must you model?
Commission (fixed per trade), bid-ask spread (0.05-0.1%), slippage (market impact, 0.03-0.05%), and taxes. High-frequency strategies often lose all returns to costs.

Name three things ML can legitimately do in trading :: 1) Risk management (volatility/correlation forecasting), 2) Execution optimization (timing trades to minimize impact), 3) Alternative data processing (satellite imagery, sentiment).

What is the minimum out-of-sample Sharpe for deployment?
Generally > 1.0 for consideration, > 1.5 for live deployment, after accounting for all transaction costs and tested across multiple market regimes.
Why start with linear models instead of neural networks?
If simple linear models don't work, complex models won't either - they'll just overfit. Simple models generalize better, are interpretable, and fail less catastrophically.
What is feature engineering?
Transforming raw data (prices, volume) into predictive signals based on economic theory (momentum, volatility, relative strength) that are stationary and available real-time.

Connections

  • Technical Analysis Indicators - ML often uses these as features, but must validate they add predictive power
  • Backtesting Strategies - Proper validation protocol is critical before deploying ML
  • Risk Management Principles - ML predictions must feed into position sizing and stop-loss rules
  • High-Frequency Trading - Where ML transaction cost problems are most severe
  • Quantitative Factor Investing - Alternative to ML: simple, interpretable factors with economic rationale
  • Market Efficiency Hypothesis - ML strategies must identify genuine inefficiencies, not overfit noise
  • Alternative Data Sources - Where ML can add value: processing unstructured data
  • Portfolio Optimization - ML can improve mean-variance optimization inputs (return/risk estimates)

Remember: In trading, the graveyard is full of strategies that worked perfectly in backtests. ML is a powerful tool, but markets are adversarial environments designed to punish overfitted models. Validation, simplicity, and humility are your only defenses.

Concept Map

operates in

enables

risks

causes

erodes

includes

includes

includes

biggest killer

includes

includes

fits

worsens

fixed by

fixed by

fixed by

Machine Learning in Trading

Adversarial Markets

Legitimate Uses

Fatal Traps

Non-Stationarity

Vanishing Edge

Feature Engineering

Regime Detection

Execution & Risk Modeling

Overfitting

Look-Ahead Bias

Survivorship Bias

Random Noise

Walk-Forward & Regularization

Point-in-Time Data

Bias-Free Datasets

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, machine learning trading mein bahut powerful lagti hai kyunki idea simple hai - data se pattern seekho, price predict karo, aur profit kamao. Lekin yahan asli baat samajhne wali yeh hai ki market ek adversarial environment hai, matlab yahan aapke against dusre smart log actively khel rahe hain. Jaise hi aapko koi edge milta hai, dusre bhi wahi discover kar lete hain aur woh edge gayab ho jata hai. Upar se markets non-stationary hote hain - aaj jo pattern kaam kar raha hai, kal Fed policy change hone ya volatility shift hone par woh toot sakta hai. Isliye ML kaam toh karti hai, par sirf tab jab aap extreme discipline maintain karo.

Ab sabse bada dushman hai overfitting. Yeh tab hota hai jab aapka model historical data pe 95% accuracy deta hai, aur aapko lagta hai wah! perfect hai. Lekin actually model ne noise ko yaad kar liya hai, real pattern nahi seekha. Jaise "15 October 2018 ko tech stocks gire the" - yeh koi generalizable rule nahi, sirf random ek din ki baat hai. Agar aapke paas 200 data points hain aur 50 parameters, toh aap guaranteed noise fit kar rahe ho. Iske saath aur bhi traps hain - look-ahead bias (future ki info galti se use karna), survivorship bias (sirf jeetne walon pe test karna, jaise aaj ka S&P 500 jismein failed companies nahi hain), aur data snooping (100 features try karke jo chance se kaam kare use pakad lena).

Yeh sab why-matters isliye hai ki agar aap in traps ko nahi samjhoge, toh aapka backtest zabardast dikhega par real trading mein paisa dubega - kyunki backtest jhooth bol raha tha. Solution simple hai: walk-forward analysis karo, simple models use karo (kam parameters), transaction costs kabhi ignore mat karo, aur hold-out validation set rakho jise development ke dauraan chhuo hi mat. Yaad rakhna, ML mein asli skill prediction banane mein nahi, balki apne aap ko fool hone se bachane mein hai.

Test yourself — Algorithmic & Quant Trading

Connections