Shuffle the rows of a stock panel, hold out a fifth, and a model that is handed the month number looks 9.2% better than the average. Test it the way it will be used, on the months after its training, and it is 6.7% better, no better than without the month number. The shuffle was lending it the answer.
Why a random split flatters
Where we are. The last topic asked what the model learned. This one asks whether it learned anything that lasts, and the answer depends on how you test. The usual recipe, cross-validation, shuffles the rows, cuts them into folds and tests each fold on a model trained on the others. For rows that are independent, such as photographs, that is fine. Stock rows are not independent: the 56 stocks of one month share the same market, the same mood and the same volatility regime.
Worked example 1. *Problem:* how different are the months from each other? *Plan:* take the average size of the next month's move across the stocks for every month and look at how it varies. *Steps:* below.
panel = build_panel(load_close())monthly = panel.groupby("date")["move"].mean()1print(monthly.describe().round(4).loc[["min", "50%", "max"]].to_dict())print(monthly.loc["2008-10-31"].round(4), monthly.loc["2017-06-30"].round(4))
{'min': 0.0253, '50%': 0.0526, 'max': 0.1441}
0.11 0.0356- 1One number per month: the average size of the move across the stocks.
*Check:* the typical month has an average move of 0.0526, the calmest 0.0253 and the wildest 0.1441; October 2008 gave 0.11 and June 2017 0.0356. *What to notice:* a month is a regime: when the market is wild, all its stocks move a lot. Under a shuffle, a test row from October 2008 is surrounded by training rows from October 2008, and a model that can tell the month (or something that identifies it, such as a volatility reading) predicts "wild" without having forecast anything.
Walk-forward: train on the past, test on the next block
Cut the time line into blocks. Fold 1 trains on the early months and tests on the next block; fold 2 trains on everything up to a later point (the window expands) and tests on the block after it; and so on. Every test block comes after all of its training months, as in real use.
With M months and n folds, use blocks of M // (n + 1) months. Fold i tests on block i and trains on all the months before it, except for a gap of embargo months at the end, explained next. The first block is never a test block: the model needs history.
Worked example 2. *Problem:* the splits for 12 months and for the real panel's 307 months, 3 and 5 folds. *Plan:* walk_forward_splits with an embargo of 1. *Steps:* below.
for train, test in walk_forward_splits(np.arange(12), 3, 1): print(train.tolist(), test.tolist())months = np.sort(panel["date"].unique())for train, test in walk_forward_splits(months, 5, 1): print(len(train), str(train[-1])[:7], "->", len(test), str(test[0])[:7], str(test[-1])[:7])
[0, 1] [3, 4, 5] [0, 1, 2, 3, 4] [6, 7, 8] [0, 1, 2, 3, 4, 5, 6, 7] [9, 10, 11] 50 2005-02 -> 51 2005-04 2009-06 101 2009-05 -> 51 2009-07 2013-09 152 2013-08 -> 51 2013-10 2017-12 203 2017-11 -> 51 2018-01 2022-03 254 2022-02 -> 51 2022-04 2026-06
*Check:* with 12 months the folds test on months 3 to 5, 6 to 8 and 9 to 11, and train on 0, 1, then 0 to 4, then 0 to 7: the training window grows and month 2, 5 and 8 are skipped. With 307 months the blocks have 51 months and the training sets 50, 101, 152, 203 and 254. *What to notice:* the first fold tests April 2005 to June 2009, the last April 2022 to June 2026; the five folds cover different market regimes, so the five scores will differ, and the average of five is more honest than a single split.
The label that reaches ahead
A label is not a point in time. The row of a month-end m has features known at m and a label that is the return of the next month, so the label ends at m + 1 month. If the last training month is just before the first test month, its label covers the first test month: the training rows already contain the outcome of the period you are testing. That is a leak.
The cure is an embargo: leave out the last embargo months before the test block. Worked example 3. *Problem:* how many training months leak with no embargo and with an embargo of 1? *Plan:* for every training month, add one month-end to find where its label ends, and compare with the first test month. *Steps:* leaking_months on the five folds.
for embargo in (0, 1): folds = walk_forward_splits(months, 5, embargo) print(embargo, [leaking_months(train, test) for train, test in folds])first = walk_forward_splits(months, 5, 0)[0]print(str(first[0][-1])[:10], "+ 1 month =", (pd.Timestamp(first[0][-1]) + pd.offsets.MonthEnd(1)).date(), "| first test month", str(first[1][0])[:10])
0 [1, 1, 1, 1, 1] 1 [0, 0, 0, 0, 0] 2005-03-31 + 1 month = 2005-04-30 | first test month 2005-04-30
*Check:* with no embargo, every fold has exactly 1 leaking month (the last one), with an embargo of one month none. The first fold's last training month is 31 March 2005 and its label ends on 30 April 2005, the first test month. *What to notice:* a single month of embargo is enough here, since the label spans one month. If the label spanned a year, say a 12-month return, you would need an embargo of a year.
A feature built from the last 12 months (like vol here) is also not independent from one row to the next. Embargoes protect the label; they do not remove the shared history inside the features. Prefer more months of gap to fewer when in doubt.
Months, rows, folds, scores
The splits are of months; the model needs rows. rows_for_months gives the positions of the rows whose date is among some months, in panel order. For the shuffled alternative, random_row_splits permutes the row numbers and cuts them into parts, as the usual k-fold does. Then evaluate fits one model per split and scores it against the plain average of its own training rows, and improvement turns the folds into one number: the average of 1 - rmse / baseline.
Worked example 4. *Problem:* how much do the training and the test rows overlap in time under each scheme? *Plan:* for the first fold of each, take the months of the test rows and count how many of them also appear among the months of the training rows. *Steps:* below.
shuffled = random_row_splits(len(panel), 5)folds = walk_forward_splits(months, 5, 1)walking = [(rows_for_months(panel, train), rows_for_months(panel, test)) for train, test in folds]for name, splits in (("random", shuffled), ("walk", walking)): train, test = splits[0] shared = set(panel["date"].iloc[test]) & set(panel["date"].iloc[train]) print(name.ljust(7), len(train), len(test), len(shared), "of", panel["date"].iloc[test].nunique(), "test months also in train")
random 13660 3415 307 of 307 test months also in train walk 2700 2842 0 of 51 test months also in train
*Check:* under the shuffle the first fold tests on 3,415 rows, and all 307 of their months also appear in the training rows. Under walk-forward the first fold trains on 2,700 rows and tests on 2,842 rows from 51 months, and none of those months is in the training rows. *What to notice:* the shuffle tests on months the model has already seen 56-fold; the walk-forward test is on a period the model has not seen.
Random against walk-forward
Worked example 5. *Problem:* does a random split overstate a model, and does a column that identifies the period make it worse? *Plan:* run both validations with the three price features and with the same plus the month number t, and report the improvement over the plain average. *Steps:* study.
result = study(panel)print(result["train_months"], result["leaking"])for kind in ("random", "walk"): print(kind.ljust(7), round(result[kind]["plain"], 4), round(result[kind]["with_t"], 4))
[50, 101, 152, 203, 254] {'embargo_0': 5, 'embargo_1': 0}
random 0.0793 0.092
walk 0.0692 0.0673*Check:* the shuffled folds say the model with price features is 7.9 % better than the average, and 9.2 % better when it also gets the month number. Walk-forward says 6.9 % and 6.7 %. *What to notice:* the month number is worth 1.3 points under the shuffle (the model uses it to interpolate between the neighbouring months) and nothing under walk-forward, where it can only extrapolate. Even without the month number the shuffle is a point too optimistic (7.9 % against 6.9 %).
What you will build
The lab follows the lecture. Task 1 builds the walk-forward splits and task 2 counts the months whose label leaks into the test period. Task 3 turns months into rows and task 4 makes the shuffled folds. Task 5 scores a model on each split and task 6 turns the scores into one number. Task 7 compares the two ways of validating on the real panel.
Next topic: the model is now judged honestly. The next topic, Speed: histograms and model size, looks at how XGBoost finds its splits so quickly, and what that costs in precision and in the size of the saved model.
Lab · what's graded
7 tasks · 100 pts- Walk-forward splits25 pts
- Count the leaks5 pts
- Months to rows5 pts
- Shuffled folds15 pts
- Score on every split20 pts
- One number5 pts
- Random against walk-forward25 pts