Definition
Suppose the target at date t is the outcome over the next h periods, for example a return over 20 days or the demand over a lead time. The targets of two dates less than h apart are computed from common data. If one is in the training set and the other in the test fold, the test is no longer unseen.
López de Prado describes two corrections. Purging drops from the training set every observation whose label window overlaps the label window of a test observation. The embargo drops a further stretch right after the test fold, to cover features that carry memory of the recent past. Folds are contiguous blocks of time and are never shuffled.
Worked example
The target is the sum of the next 20 values of a white noise: it cannot be predicted. The features are four slowly varying series, independent of the noise. Four schemes score the same nearest-neighbour model.
import numpy as np
from sklearn.metrics import r2_score
from sklearn.neighbors import KNeighborsRegressor
rng = np.random.default_rng(1)
n, h = 2000, 20
noise = rng.normal(size=n + h)
y = np.array([noise[t + 1:t + 1 + h].sum() for t in range(n)]) # label spans the next 20 periods
smooth = lambda: np.convolve(rng.normal(size=n + 49), np.ones(50) / 50, mode="valid")
X = np.column_stack([smooth() for _ in range(4)]) # four slow series, unrelated to the noise
def cv_r2(folds, purge=0):
pred = np.empty(n)
for test in folds:
train = np.setdiff1d(np.arange(n), test)
if purge:
train = train[(train < test.min() - purge) | (train > test.max() + purge)]
pred[test] = KNeighborsRegressor(n_neighbors=5).fit(X[train], y[train]).predict(X[test])
return r2_score(y, pred)
blocks5, blocks40 = np.array_split(np.arange(n), 5), np.array_split(np.arange(n), 40)
print(f"shuffled 5-fold: R2 = {cv_r2(np.array_split(rng.permutation(n), 5)):+.2f}")
print(f"5 contiguous blocks, no purge: R2 = {cv_r2(blocks5):+.2f}")
print(f"40 contiguous blocks, no purge: R2 = {cv_r2(blocks40):+.2f}")
print(f"40 contiguous blocks, purged: R2 = {cv_r2(blocks40, purge=h):+.2f}")Output, produced by running the code above when this page was built:
shuffled 5-fold: R2 = +0.47 5 contiguous blocks, no purge: R2 = -0.56 40 contiguous blocks, no purge: R2 = -0.34 40 contiguous blocks, purged: R2 = -0.50
With shuffled folds the model finds, for each test date, training dates a few days away whose labels share most of their terms, and the score is clearly positive although nothing is predictable. With contiguous blocks the leak is confined to the edges of each block: it is small with five long blocks and visible with forty short ones, where the purge removes it. The honest score is negative, as it should be for a model that had nothing to learn.
Where it misleads
- The purge must be at least as long as the label window, and the embargo as long as the memory of the features. Too short and the leak stays; the scheme then looks rigorous and is not.
- A fold in the middle of the sample is tested by a model trained partly on later data. This is acceptable to estimate skill under a stable process, not to simulate a deployment in time, which walk-forward validation does.
- Purging shrinks the training set. With long labels and few observations, little is left.
In our work
We choose the scheme from the structure of the data. In a controlled experiment, purged 5-fold with an embargo reported an R² of +0.074 where the true value was +0.073, and random k-fold was optimistic by up to +0.41.
Service: machine learning and model validation Research note: time series cross-validation, measured
References
- López de Prado, M. (2018). Advances in financial machine learning. Wiley, Hoboken.
- Bergmeir, C., Hyndman, R. J., Koo, B. (2018). A note on the validity of cross-validation for evaluating autoregressive time series prediction. Computational Statistics and Data Analysis, 120, 70-83. doi:10.1016/j.csda.2017.11.003
- Roberts, D. R., Bahn, V., Ciuti, S., et al. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography, 40(8), 913-929. doi:10.1111/ecog.02881