Quant Modelling [HFT] All modules
8 Module 08

Machine Learning for Trading

Using historical data to predict returns — what a feature is, why validation is non-negotiable, and how overfitting quietly destroys strategies that look perfect on paper.

Exam: Feature Engineering & Validation Source: Session 8 Predictive Modelling

What problem is ML solving?

The question that drives every ML model in trading is simple: can historical data predict future returns? If past prices, volumes and volatility carry any repeatable structure, then a model can identify useful patterns and turn them into trading signals.

We already build signals by hand. Momentum, mean reversion and volume rules are explicit, human-written if/then statements. ML asks a different question: instead of writing the rule, can we let an algorithm learn the rule from the data?

DimensionRule-based signalsMachine learning
How the rule is madeHand-written by a researcherLearned from historical data
InputsOne or two indicatorsMany features at once
FlexibilityRigid, fixed logicCaptures complex, non-linear relationships
InterpretabilityEasy to explainHarder to interpret

What is machine learning?

Definition — Machine learning

Machine learning is the practice of learning patterns from historical data, using features as inputs to generate predictions about something we care about — here, future returns.

Quant firms lean on ML because the modern data environment plays to its strengths:

🗄️

Large datasets

Years of tick-level prices, volumes and quotes across thousands of assets.

🎛️

Many variables

Dozens or hundreds of candidate inputs that no human can weigh by hand.

🕸️

Complex relationships

Non-linear interactions a simple rule cannot express.

Scalable

One trained model can score the entire universe automatically.

ML does not replace the research workflow — it slots into one stage of it:

flowchart LR
  A([Data]) --> B([Features])
  B --> C([Model])
  C --> D([Prediction])
  D --> E([Backtest])
  E -.->|Refine features / model| B
  classDef s fill:#eef2ff,stroke:#4f46e5,stroke-width:1px,color:#3730a3;
  classDef d fill:#ecfdf5,stroke:#0d9488,color:#0d9488;
  class A,B,C,D s
  class E d
      
Where ML fits in research: raw data becomes features, a model maps features to a prediction, and the backtest decides whether to keep going.
Who does this

Firms built largely on data-driven and ML-style research include Renaissance Technologies, Two Sigma, Citadel and AQR.

Prediction vs explanation — and why ML is not magic

There is a genuine trade-off between the two approaches. A hand-written rule is easy to explain: "buy when the 20-day return is positive." An ML model is more flexible but harder to interpret — it may use fifty features in combinations no one can narrate.

ML is not magic
  • Markets are noisy — most price movement is random, not signal.
  • Relationships change — a pattern that held in 2020 can vanish by 2024.
  • No guaranteed profits — a fancy model is still a bet, not a certainty.
  • Validation is critical — without it, you cannot tell luck from skill.

Features: the inputs to a model

Definition — Feature

A feature is an input variable: a numerical representation of some piece of information the model uses to make a prediction. The thing being predicted (e.g. the next day's return) is the target.

Typical features are derived from raw OHLCV data:

📈

5-day return

Short-horizon momentum.

🗓️

20-day return

Medium-horizon trend.

🌊

Rolling volatility

Recent risk / dispersion of returns.

📊

Volume ratio

Today's volume vs its recent average.

A concrete setup might use return, volatility and volume ratio as features, with future return as the target.

Good features vs bad features

Good features

Relevant (plausibly linked to returns), stable (behave consistently over time), and intuitive (you can explain why they matter).

Bad features

Random (no real link), unstable (meaning shifts), or contain future information — the cardinal sin of leakage.

The trap: future information (leakage)

A feature must use only information available at decision time. "Tomorrow's return" is not a feature — it is the answer. Including any value that would not be known until after the trade leaks the future into the model and produces backtests that look brilliant and fail instantly when traded live.

Feature explosion

More features → more complexity → higher overfitting risk. Adding inputs is cheap, but every extra feature gives the model another way to fit noise. More is not better.

Validation: training data vs test data

Validation exists to answer one question: will this model work on data it has never seen? That property is called generalization, and it is the only thing that matters for live trading.

🎓

Training data

Historical examples the model learns from to build its rule.

🔒

Test data

Unseen data held back to evaluate performance and simulate the future.

Example split

Train on 2019–2023, then test on 2024–2025. The model never touches the 2024–2025 data while learning, so its performance there is an honest proxy for how it would have traded going forward.

Never peek into the future

No future information may enter training. This is information leakage, and it produces unrealistically good results that evaporate live. Validation only means something if the test set is genuinely untouched.

Overfitting: memorizing noise

Definition — Overfitting

Overfitting is when a model memorizes noise instead of learning real structure. The tell-tale signature is strong training performance with weak test performance — it generalizes poorly.

The core distinction is signal vs noise: a signal is a persistent pattern that recurs out of sample; noise is random variation that happens not to repeat. An overfit model has confused the second for the first.

Worked example Which model do you trust?
  1. Model A scores 95% on training but only 48% on test — a huge gap between what it learned and what it can repeat.
  2. Model B scores 60% on training and 58% on test — a tiny gap; its test performance nearly matches its training performance.
  3. A 95% → 48% collapse means Model A memorized the training set's noise; 48% is no better than a coin flip on unseen data.
  4. Model B's small train/test gap shows it captured a real, repeatable pattern.
Trust Model B. A lower-but-consistent score generalizes; a sky-high training score that craters on test data is the classic overfitting signature.
🐛

Why it happens

Too many features, small datasets, excessive model complexity — and markets that are inherently noisy (news, economic shocks, investor behaviour, randomness).

🛡️

How to reduce it

Use simpler models, gather more data, insist on out-of-sample testing, and engineer better features.

Out-of-sample testing & walk-forward validation

Out-of-sample testing evaluates the model on unseen, independent data, giving a realistic proxy for future performance. It is more honest than in-sample scores, validates better, and exposes overfitting early.

Walk-forward validation makes this repeatable: train on a window, test on the next slice, then roll the window forward and repeat. The model is always tested on data that came after its training window — exactly how it would face the real world.

flowchart LR
  subgraph R1[Round 1]
    A1([Train])-->B1([Test])
  end
  subgraph R2[Round 2]
    A2([Train])-->B2([Test])
  end
  subgraph R3[Round 3]
    A3([Train])-->B3([Test])
  end
  B1 -.->|move window| A2
  B2 -.->|move window| A3
  classDef s fill:#eef2ff,stroke:#4f46e5,stroke-width:1px,color:#3730a3;
  classDef d fill:#ecfdf5,stroke:#0d9488,color:#0d9488;
  class A1,A2,A3 s
  class B1,B2,B3 d
      
Walk-forward validation: train, test on the next window, move the window forward, repeat — so every test is genuinely out of sample.

Evaluating predictions: R², MAE, MSE

We measure prediction quality to compare models and detect overfitting. The common metrics are , MAE (mean absolute error) and MSE (mean squared error). The course focuses on .

Coefficient of determination $$ R^2 = 1 - \frac{SS_{res}}{SS_{tot}} $$

where the residual and total sums of squares are

Prediction error vs total variation $$ SS_{res} = \sum(\text{actual}-\text{predicted})^2 \qquad SS_{tot} = \sum(\text{actual}-\overline{\text{actual}})^2 $$
Reading R²
  • $R^2 = 1$ — perfect predictions ($SS_{res}=0$).
  • $R^2 = 0$ — no better than predicting the mean every time.
  • $R^2 < 0$ — worse than the mean; the model actively hurts.
Worked example Computing R² by hand
  1. Actual values $[10, 12, 14]$, predicted $[11, 12, 13]$. The mean of the actuals is $\overline{\text{actual}} = \tfrac{10+12+14}{3} = 12$.
  2. Residual sum of squares: $SS_{res} = (10-11)^2 + (12-12)^2 + (14-13)^2 = 1 + 0 + 1 = 2$.
  3. Total sum of squares: $SS_{tot} = (10-12)^2 + (12-12)^2 + (14-12)^2 = 4 + 0 + 4 = 8$.
  4. Combine: $R^2 = 1 - \dfrac{SS_{res}}{SS_{tot}} = 1 - \dfrac{2}{8}$.
$R^2 = 1 - 0.25 = \mathbf{0.75}$. The model explains 75% of the variation in the actual values — clearly better than just predicting the mean.

Models: regression and decision trees

Linear regression intuition

A linear regression takes feature inputs — momentum, volatility, volume — and combines them with learned weights to output a predicted return. For example: positive momentum, low volatility and high volume might combine into a positive predicted future return.

Linear prediction $$ \hat{r} = \beta_0 + \beta_1\,\text{momentum} + \beta_2\,\text{volatility} + \beta_3\,\text{volume} $$

Decision trees

A decision tree is a series of yes/no decisions arranged like a flowchart. It is easy to interpret — you can read the path that led to any decision.

flowchart TD
  A{Volume > average?} -->|Yes| B{Momentum positive?}
  A -->|No| H([Hold])
  B -->|Yes| C([Buy])
  B -->|No| H
  classDef s fill:#eef2ff,stroke:#4f46e5,stroke-width:1px,color:#3730a3;
  classDef d fill:#ecfdf5,stroke:#0d9488,color:#0d9488;
  class A,B s
  class C,H d
      
A simple decision tree: only when volume is above average and momentum is positive does it signal Buy; otherwise Hold.
AspectLinear regressionDecision trees
ComplexitySimpler, fasterMore flexible, more complex
RelationshipsLinear weighting of inputsNon-linear, rule-based splits
Overfitting riskLowerHigher (can split until it memorizes)
InterpretabilityCoefficients per featureReadable decision path

Why ML often fails in finance

The five reasons ML disappoints in markets
  • Noise — most movement is random, drowning real signal.
  • Regime changes — the relationship the model learned stops holding.
  • Overfitting — great in-sample, useless out-of-sample.
  • Transaction costs — fees, spread and slippage erase a thin edge.
  • Signal decay — once an edge is found and traded, it fades.
Self-check: Why might ML help when many candidate signals exist?
Because ML can weigh many features at once and capture complex, non-linear interactions between them — something hand-written rules with one or two indicators cannot do. With dozens of weak signals, a model can combine them into a stronger, scalable prediction.
Self-check: Is "tomorrow's return" a valid feature for predicting tomorrow's return?
No. It is not known at decision time — it is the answer itself. Using it is information leakage, which makes backtests look perfect and fail live. "Today's volume" is a valid feature; "tomorrow's return" is not.
Self-check: Model A scores 95% train / 48% test; Model B scores 60% / 58%. Which is overfit?
Model A. The large gap between training (95%) and test (48%) is the signature of overfitting — it memorized noise. Model B's small gap (60% vs 58%) shows it generalizes, so it is the trustworthy one despite the lower headline score.
Self-check: Why not just train on all available data?
Because then there is no unseen data left to test on. Without a held-out test set you cannot measure generalization, you risk training on the future (leakage), and you have no way to detect overfitting — so you get false confidence in a model that may not work live.

Key takeaways

Remember
  • Features matter — relevant, stable, intuitive, and never leaking the future.
  • Validation matters — test on unseen data; train/test splits exist to measure generalization.
  • Overfitting is dangerous — a big train/test gap means memorized noise, not signal.
  • Simpler can be better — fewer features and simpler models often generalize more.
  • ML is a tool, not magic — markets are noisy and there are no guaranteed profits.