Time Series Cross-Validation
Part of the Machine Learning Roadmap
In short
Shuffling rows into random folds lets a forecasting model peek at the future. Time series cross-validation keeps time in order, so your backtest matches how forecasts are really used.
With time-ordered data you must never train on the future to predict the past. Time series cross-validation uses expanding or rolling windows so each fold trains on earlier data and validates on later data.

Think of it like this
Practising with past papers in order
To predict what this year's board paper looks like, you study the 2019 to 2021 papers and test yourself on 2022. Then you add 2022 and test on 2023. You never use 2024's paper to 'predict' 2023. Time only runs forwards.
Watch it happen
Expanding-window folds over 10 months
1/5Ten months of data in time order. Each fold trains on the past and tests on the next stretch.
The big ideas
What you need to know
Train past, test future
Each fold respects time order. No future rows ever reach training.
Expanding or sliding
Expanding windows keep all history. Sliding windows keep a fixed length, useful when old data is stale.
Match the horizon
If you forecast 2 weeks ahead in production, make each test window 2 weeks long.
Watch for leaks
Lag features and rolling averages must be built only from data before each prediction date.
See it in code
Walk through the code
1import numpy as np2from sklearn.model_selection import TimeSeriesSplit3 4X = np.arange(10).reshape(-1, 1) # 10 months in order5 6tscv = TimeSeriesSplit(n_splits=3, test_size=2)7for fold, (train_idx, test_idx) in enumerate(tscv.split(X)):8 print(fold, "train:", train_idx, "test:", test_idx)1/3Ten rows standing in for ten months, already sorted by date.
Prints the same three folds as the scene: train 0 to 3 then test 4 and 5, and so on.
Save yourself the pain
Common mistakes
Oops
Using KFold with shuffle=True on time-ordered data.
Do this instead
Use TimeSeriesSplit, or manual date-based cut-offs, so tests are always in the future.
Oops
Computing a rolling mean over the whole series before splitting.
Do this instead
Build lag and rolling features inside each fold, or with shift() so they only use the past.
Your mission
Random vs time-ordered folds
Quick check
Why is shuffled k-fold cross-validation risky for forecasting?
Go deeper
- 1Use TimeSeriesSplit and print the train and test date ranges for each fold.
- 2Compare scores from a random KFold and a TimeSeriesSplit on the same data.
- 3Add a gap between train and test windows when features use recent history.
Also part of these roadmaps
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.