σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
XGBoost skill›Module 4 · Reading and judging the model›Topic 4.2·~55 minAdvanced

Time-aware validation

Skill positionModule 4 of 4 · Topic 2 of 4
4.2 Time-aware validation
—Lab score— / 100Total XP—Streak—
Lecture0% read

7 min readCode examples: 5

  1. 01Why a random split flatters
  2. 02Walk-forward: train on the past, test on the next block
  3. 03The label that reaches ahead
  4. 04Months, rows, folds, scores
  5. 05Random against walk-forward
  6. 06What you will build

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.

01

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.

main.pyPython
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
  1. 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.

02

Walk-forward: train on the past, test on the next block

DefinitionWalk-forward validation

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.

main.pyPython
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.

03

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.

main.pyPython
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.

Overlap hides in rolling features too

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.

04

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.

main.pyPython
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.

05

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.

main.pyPython
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 the real data says56 US stocks, 307 months; 5 folds; model: 60 trees of depth 3
Training months per fold50 to 254the walk-forward windows expand; blocks of 51 test months
Leaking months5 / 0over the 5 folds, with embargo 0 / 1
Random split7.9% / 9.2%better than the average, without / with the month number
Walk-forward6.9% / 6.7%the same, tested only on later months

Key takeaways

  • Test on later months. Cut by time, train on the past, test on the next block; shuffled folds let the model see the period it is tested on.
  • Leave a gap. A label that spans a month reaches into the next period; an embargo at least as long as the label removes the leak.
  • Many folds, one average. Five blocks cover different regimes; their average is more honest than a single split, and their spread shows how stable the skill is.
  • Beware period markers. A column that identifies the period (a date, a month number) is rewarded by a random split and useless in use.
Quick check
Your turn. A panel has 120 months, you use 5 folds and an embargo of 2 months. How many months are in the training set of fold 3?
Pick an answer.
06

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
Explorer · lab-xg-09
▾ lab-xg-09
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-xg-09$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-xg-09 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes