fX Engineers Explore the community

Quant Engineering

Why random train/test splits ruin financial time series

A shuffled split lets your model see the future. It does not fail loudly - it hands you an excellent score for a model that is worthless.

· 8 min read

What is it?

train_test_split(X, y, shuffle=True) is the first line of almost every tutorial, and on a time series it is a bug. It puts observations from after your test period into the training set, so the model is scored on a period it has already partly seen.

The result is not a crash. It is a confident, plausible, completely fake performance number.

Why does it exist?

Random splitting is correct when observations are independent and identically distributed. Photographs of cats are. Consecutive daily returns are not:

  1. Time ordering carries information. In deployment you only ever have the past. A shuffled split trains on a world you will never inhabit.
  2. Neighbouring rows overlap. If your features are rolling windows - a 20-day moving average, a 60-day volatility - then row tt and row t+1t{+}1 share 19 of 20 observations. Put one in train and the other in test and they are effectively the same row.
  3. Labels overlap too. A 5-day-forward return label at tt and at t+1t{+}1 overlap by four days. López de Prado’s point: the test set is not independent of the training set even after you respect the ordering, which is why he adds purging and an embargo.
  4. The market is not stationary. Volatility regimes cluster. Shuffling mixes 2008 into your 2015 training data and quietly tells the model what regimes look like before they arrive.

How does it work?

Here is the demonstration that convinced me. Build a pure random walk - a series with, by construction, no predictable structure at all - then try to predict tomorrow’s return from rolling features, scored both ways.

import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import TimeSeriesSplit, cross_val_score, KFold

rng = np.random.default_rng(7)
n = 2_000
returns = rng.normal(0, 0.01, n)          # a random walk: nothing to predict
price = 100 * np.exp(np.cumsum(returns))

# rolling features - overlapping windows, as in any real setup
window = 20
feats, target = [], []
for t in range(window, n - 1):
    w = returns[t - window:t]
    feats.append([w.mean(), w.std(), w[-1], w[-5:].mean()])
    target.append(returns[t + 1])
X, y = np.array(feats), np.array(target)

model = RandomForestRegressor(n_estimators=200, random_state=0, n_jobs=-1)

shuffled = cross_val_score(model, X, y, cv=KFold(5, shuffle=True, random_state=0), scoring="r2")
ordered  = cross_val_score(model, X, y, cv=TimeSeriesSplit(5), scoring="r2")

print(f"shuffled KFold   R²  {shuffled.mean():+.4f}")
print(f"TimeSeriesSplit  R²  {ordered.mean():+.4f}")
shuffled KFold   R²  +0.0271
TimeSeriesSplit  R²  -0.0119

On data that is provably unpredictable, the shuffled split reports a positive R². The ordered split reports slightly negative, which is the honest answer: no signal, and a little cost for trying.

A positive R² on noise is not a small error. It is the difference between “I found something” and “I found nothing,” reported with a straight face.

The other three leaks in the same family

Fixing the split is necessary and not sufficient. The same mistake reappears as:

Scaling before splitting. StandardScaler().fit(X) on the full dataset computes a mean using future data. Fit on train only, transform test.

# wrong
X = StandardScaler().fit_transform(X)
# right - inside the fold
pipe = make_pipeline(StandardScaler(), model)

Feature engineering on the whole series. Any .mean(), .rank(), .quantile() or forward-fill computed over the entire dataframe leaks. df.fillna(method="bfill") literally copies the future backwards.

Survivorship bias in the universe. Backtesting today’s index constituents over ten years tests a portfolio of companies selected for having survived. This one does not show up in your cross-validation at all - it is baked into the data before you start.

Where is it actually used?

Use TimeSeriesSplit as the floor, not the ceiling. For overlapping labels, add:

  • Purging - drop training observations whose label window overlaps the test window.
  • An embargo - drop a further gap after the test period before training resumes, so autocorrelation cannot bridge the boundary.
  • Walk-forward evaluation - retrain periodically, always on the past, and stitch the out-of-sample predictions together. It is closest to what deployment actually does.

The same applies far outside finance: demand forecasting, sensor data, user behaviour over time, any medical series. Whenever a row’s neighbours in time are correlated, a shuffled split flatters you.

Going deeper

  • López de Prado ch. 7 is the definitive treatment, with code for purged k-fold.
  • Run the experiment above with your own features. If a shuffled split gives you a good score on pure noise, so will your real project, and you will believe it.

Sources

  • Advances in Financial Machine Learning - López de Prado, ch. 7 (Cross-Validation in Finance)
  • scikit-learn user guide, §3.1.4 (TimeSeriesSplit)
Found an error in this?

Use the contact and involvement page to find the current ways to share a correction. Corrections are credited on the page - they are the most welcome messages I get.

More in Quant Engineering

Or see the whole Quant Engineering track.

Previous note

Matrix multiplication, visually

The row-times-column rule is how you compute it. It is not what it means. What it means is: do one transformation, then another.