How do I split a time series into folds with TimeSeriesSplit?
Split twelve trading days into training and test folds that always run forward in time with scikit-learn’s TimeSeriesSplit, leave a gap for labels that look ahead, cap the training rows, and see why KFold trains on later days.
After this lesson, you can split a time series into folds that always train on the past and test on the future.
Which positions go into each fold?
TimeSeriesSplit(n_splits=3, test_size=2) makes three folds, each testing the next two days after its training days, and every training set starts at the first day. On twelve days, the first fold trains on positions 0 to 5 and tests 6 and 7.
TimeSeriesSplit counts positions, so the rows must be in date order. .split(days) gives one pair of position arrays per fold, training first and test second, and enumerate numbers the folds from 0. show_folds prints each fold’s positions, so each setting below is one call.
The following box splits twelve trading days into three folds.
Each fold adds the previous fold’s test days to its training days.
How do I leave a gap or cap the training days?
gap=2 leaves out the two days before each test, and max_train_size=4 keeps only the last four training days. A gap is needed when a label looks ahead, as in the lesson on chronological splits. A label of the next two days on position 5 uses the returns of positions 6 and 7, which are test days.
The following box prints the folds with the gap and with the cap.
With the gap, the first fold trains on positions 0 to 3. With the cap, each fold trains on the four days before its test.
Why does KFold train on later days?
KFold(n_splits=3) uses each block of four days once as the test and the other two blocks as training, so two of its three folds train on days that come after the test.
When it tests positions 4 to 7, KFold trains on 0 to 3 and 8 to 11, so a forecast would learn from the future.
Your turn
Make two folds that test three days each and train on at most four days. You should see training positions 2 to 5 for the first fold and 5 to 8 for the second.
TipShow answer
test_size=3 and max_train_size=4 go into one TimeSeriesSplit.