Time-Series Backtesting
A demand forecast is trained on the past and used on the future. Random cross-validation ignores that: it trains on days from next month to predict days from last month, and a day's neighbours in time (which are very similar to it) sit in the training folds. The result is an optimistic score that will not survive deployment. Backtesting evaluates a forecaster the way it will be used: train on everything up to a cut-off, predict the period after it, move the cut-off forward, repeat. It is also called walk-forward or rolling-origin evaluation. The leakage side of this is covered in The Leakage Rules and the splitter mechanics in Split Strategies.
Expanding window, sliding window, gap
- Expanding window: each fold trains on everything before the cut-off. Uses all history; good when old data is still relevant.
- Sliding (rolling) window: each fold trains on the last periods only. Mimics a model retrained on recent data; good when the world drifts and old data misleads.
- Gap: leave out the periods between training and test that would not be available at prediction time (labels that arrive late, a forecast made a week ahead), and the periods whose features overlap the test period (rolling averages).
- Horizon: the test period should have the length you forecast in production (the next day, the next 4 weeks).
scikit-learn's TimeSeriesSplit implements all of them; drawn as text, T = train, . = gap, V = test, - = unused:
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
def show(cv, n=20):
for trn, tst in cv.split(np.zeros(n)):
row = np.array(["-"] * n)
row[trn] = "T"
row[min(trn.max() + 1, tst.min()):tst.min()] = "."
row[tst] = "V"
print(" " + "".join(row), f" train {len(trn):2d} test {len(tst)}")
print("expanding:"); show(TimeSeriesSplit(n_splits=4))
print("sliding (max_train_size=8):"); show(TimeSeriesSplit(n_splits=4, max_train_size=8))
print("gap=2, test_size=3:"); show(TimeSeriesSplit(n_splits=4, gap=2, test_size=3))expanding:
TTTTVVVV------------ train 4 test 4
TTTTTTTTVVVV-------- train 8 test 4
TTTTTTTTTTTTVVVV---- train 12 test 4
TTTTTTTTTTTTTTTTVVVV train 16 test 4
sliding (max_train_size=8):
TTTTVVVV------------ train 4 test 4
TTTTTTTTVVVV-------- train 8 test 4
----TTTTTTTTVVVV---- train 8 test 4
--------TTTTTTTTVVVV train 8 test 4
gap=2, test_size=3:
TTTTTT..VVV--------- train 6 test 3
TTTTTTTTT..VVV------ train 9 test 3
TTTTTTTTTTTT..VVV--- train 12 test 3
TTTTTTTTTTTTTTT..VVV train 15 test 3
By default the test blocks have length and the training part grows by one block per fold. max_train_size turns it into a sliding window of at most 8 rows; gap=2 drops the two rows before each test block from training. The last fold always ends at the last row, so the most recent data is always tested.
Random folds lie about forecasts
A synthetic daily sales series (three years: trend, weekly pattern, slowly wandering noise), a random forest with two feature sets, a calendar (the day number and the weekday) and lag features (sales 1, 2 and 7 days earlier, plus the weekday), and three estimates of each one's error: shuffled 5-fold CV, a 5-fold backtest, and the truth on the last 120 days that neither of them saw.
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import KFold, TimeSeriesSplit, cross_val_score
rng = np.random.default_rng(0)
n = 3 * 365
t = np.arange(n)
wander = np.cumsum(rng.normal(0, 1.0, n)) # slow random-walk component
sales = 100 + 0.05 * t + 8 * np.sin(2 * np.pi * t / 7) + wander + rng.normal(0, 2, n)
lags = [1, 2, 7]
features = {
"calendar (day number, weekday)": np.column_stack([t, t % 7]),
"lags (1, 2, 7 days) + weekday": np.column_stack([np.r_[np.full(k, np.nan), sales[:-k]] for k in lags] + [t % 7]),
}
mae = "neg_mean_absolute_error"
for name, X in features.items():
X, y = X[7:], sales[7:] # drop the first week (no lags yet)
X_dev, y_dev, X_fut, y_fut = X[:-120], y[:-120], X[-120:], y[-120:]
model = RandomForestRegressor(n_estimators=100, min_samples_leaf=3, random_state=0)
shuffled = -cross_val_score(model, X_dev, y_dev, cv=KFold(5, shuffle=True, random_state=0), scoring=mae)
backtest = -cross_val_score(model, X_dev, y_dev, cv=TimeSeriesSplit(5, test_size=60), scoring=mae)
future = np.mean(np.abs(model.fit(X_dev, y_dev).predict(X_fut) - y_fut))
print(f"{name}:")
print(f" shuffled 5-fold CV MAE {shuffled.mean():5.2f} backtest MAE {backtest.mean():5.2f} next 120 days {future:5.2f}")calendar (day number, weekday):
shuffled 5-fold CV MAE 2.42 backtest MAE 4.32 next 120 days 7.30
lags (1, 2, 7 days) + weekday:
shuffled 5-fold CV MAE 2.52 backtest MAE 2.48 next 120 days 2.47
The calendar model looks as good as the lag model under shuffled CV (MAE 2.42), because a random validation day always has training days on both sides, and the forest just interpolates between them. The backtest exposes it (4.32), and on the real future it is worse still (7.30): a forest cannot extrapolate the trend or the wandering level beyond the last training day, and the further ahead, the worse. The lag model carries the recent level in its features, so all three of its estimates agree (2.52, 2.48, 2.47). Shuffled CV cannot tell these two models apart; the backtest can, and its ranking matches the future.
Walk-forward with a baseline
A backtest needs a yardstick. For daily data with a weekly pattern, the seasonal naive forecast "same as 7 days ago" costs nothing and is often hard to beat. Here is a walk-forward loop written out, retraining every 4 weeks on a sliding window of two years and forecasting one day ahead, compared with that baseline and with a linear model on the same lags:
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.ensemble import RandomForestRegressor
rng = np.random.default_rng(0)
n = 3 * 365
t = np.arange(n)
wander = np.cumsum(rng.normal(0, 1.0, n))
sales = 100 + 0.05 * t + 8 * np.sin(2 * np.pi * t / 7) + wander + rng.normal(0, 2, n)
lags = [1, 2, 7]
X = np.column_stack([sales[7 - k:n - k] for k in lags] + [np.eye(7)[t[7:] % 7]]) # lags + one-hot weekday
y = sales[7:]
window, step = 730, 28
errors = {"seasonal naive": [], "ridge": [], "random forest": []}
for cut in range(window, len(y) - step + 1, step): # cut = first day of the test block
trn = slice(cut - window, cut)
tst = slice(cut, cut + step)
errors["seasonal naive"].append(np.mean(np.abs(X[tst, 2] - y[tst]))) # column 2 = sales 7 days ago
for name, m in [("ridge", Ridge(1.0)), ("random forest", RandomForestRegressor(100, min_samples_leaf=3, random_state=0))]:
m.fit(X[trn], y[trn])
errors[name].append(np.mean(np.abs(m.predict(X[tst]) - y[tst])))
print("test blocks:", len(errors["ridge"]), "of", step, "days")
for name, e in errors.items():
print(f"{name:15s} MAE {np.mean(e):.2f} worst block {np.max(e):.2f}")test blocks: 12 of 28 days
seasonal naive MAE 2.92 worst block 4.41
ridge MAE 2.05 worst block 2.36
random forest MAE 2.39 worst block 3.00
Over 12 blocks of 28 days, both models beat the seasonal naive forecast (MAE 2.92), and the simple ridge regression (2.05) beats the random forest (2.39), with a smaller worst block too. Linear models extrapolate a trend that a forest cannot follow, which matters here because the level keeps moving. Report the spread of the blocks, not only the mean: a forecaster that is good on average but awful in one month in twelve may be unacceptable.
Pitfalls
- Features computed with the future. A rolling mean centred on the day, a scaler fitted on the whole series, or a target-encoded store id from all dates leak the test period. Compute every feature from data available at prediction time, and fit preprocessing inside each training window.
- Ignoring the horizon. A one-day-ahead backtest says nothing about a 30-day-ahead forecast, which cannot use the last 29 days as lags. Shift features to match the horizon.
- One cut-off only. A single train/test cut may land in an unusual period (a holiday, a promotion). Use several folds and look at their spread.
- Tuning on the final period. Keep the last stretch of data as the test, and tune on backtests that end before it.
Practice
TimeSeriesSplit(n_splits=3, test_size=10)on 100 rows. Which rows does each fold test, and how many training rows does each fold use?
Answer
The test blocks are the last 30 rows, in order: rows 70 to 79, 80 to 89, 90 to 99. The training parts are everything before each block: 70, 80 and 90 rows.
- A model predicts tomorrow's electricity demand from a feature "mean demand over the 7 days centred on the day". Why is a backtest with this feature misleading?
Answer
The centred window includes the next three days, which are not known at prediction time; the feature leaks the target's neighbourhood. Use a trailing window (the 7 days ending yesterday).
Test yourself
Why is shuffled k-fold cross-validation usually optimistic for time series?
- It uses less data
- Training folds contain days just before and after each validation day, and later data, which a real forecast never has
- It ignores the target
- It always overfits
When is a sliding window preferable to an expanding one?
- When old data no longer reflects the current behaviour of the system
- When there is little data
- Always
- When the series has no trend
What is the purpose of a gap between the training and test periods?
- To speed up training
- To exclude periods whose labels or features would not be available at prediction time
- To balance classes
- To increase the test size
Your model's backtest MAE is 3.1; the seasonal naive forecast's is 3.0. What should you conclude?
- The model is good: 3.1 is small
- The model adds nothing over 'same as last week' and should not be shipped as is
- The backtest is broken
- Use the model, MAE differences do not matter