Chapter 2 · Build and stress

Backtesting without time travel

A faithful backtest is a replay of past information states, not merely a sorted split.

65–90 min4 key conceptsReviewed 26 Aug 2026
01 · Production proposition

Regional demand shifts through promotions, holidays, and drift.

This chapter moves from mirror the release cadence to keep the distribution of outcomes. We will make the idea concrete in a small code example before placing it back inside a production system with available before staffing decisions.

Decision

Report error by origin and horizon with uncertainty; a mean alone hides whether one regime accounts for the apparent gain.

Evidence

Verify the behavior illustrated in rolling_origins.py, then measure decision utility, slice reliability, and system latency.

Failure consequence

Training uses realized future weather and random folds, producing a forecast impossible to reproduce at origin time. An unsafe release must degrade to a named baseline or the last known-good version.

02 · Guided chapter

Build the idea one layer at a time.

One train/test split tells one historical story. Rolling-origin backtesting asks the production question repeatedly: what would we have predicted from each past decision point using only knowledge then available?

At every origin, training data must end before the validation horizon begins. Expanding windows retain all history; sliding windows limit training to a recent regime. A gap may also be required when labels mature late or feature computation crosses the split boundary.

Preprocessing and tuning live inside each backtest fold. Fitting a scaler on all dates, choosing hyperparameters from the final window, or materializing rolling features before splitting can leak the future even when row indices appear chronological. Aggregate fold results only after retaining horizon and slice detail.

Keep in view
  • rolling backtests
  • direct vs recursive
  • quantiles
  • coverage
WORKED PATH

Follow the reasoning before touching the code.

  1. 01

    Mirror the release cadence

    Choose origins, training-window length, gap, and forecast horizon to match how often production retrains and how far ahead it predicts.

  2. 02

    Rebuild state per origin

    Refit transforms, feature statistics, and model parameters using only rows whose values and labels were mature at that origin.

  3. 03

    Keep the distribution of outcomes

    Report error by origin and horizon with uncertainty; a mean alone hides whether one regime accounts for the apparent gain.

pythonrolling_origins.py
def rolling_origins(size, first_origin, horizon, step):
    for origin in range(first_origin, size - horizon + 1, step):
        train = list(range(0, origin))
        valid = list(range(origin, origin + horizon))
        yield origin, train, valid

for origin, train, valid in rolling_origins(12, 6, 2, 2):
    assert max(train) < min(valid)
    print('origin', origin, 'train', train, 'valid', valid)

Generate expanding-window train and validation indices.

READ THE EXAMPLE

What to notice

  • Each validation window sits strictly after its training rows, reproducing the direction in which production forecasts move.
  • Later folds have more training history; use a sliding window instead if the deployed model deliberately forgets old regimes.
YOUR TURN Pause and predict before revealing the answer.

Add a one-period label-maturity gap between training and validation. What should the last training index be for origin 6?

Need a hint?

An index immediately before origin is not yet eligible when the gap is one.

Check your reasoning

The last training index should be 4, leaving index 5 excluded as the maturity gap before validation starts at 6.

Bring forward

Lessons 1, 2 in this course.

03 · Formal treatment

Connect the chapter to the course’s quantitative spine.

A faithful backtest is a replay of past information states, not merely a sorted split. The quantile forecast objective below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.

Formal treatment
q^τ=arg min⁡q∑max⁡ ⁣(τ(y−q),(τ−1)(y−q))\hat{q}_\tau = \operatorname*{arg\,min}_q \sum \max\!\left(\tau(y-q),(\tau-1)(y-q)\right)

Quantile forecast objective

Symbol, shape or unit contract
SymbolMeaning / shape / unit
τtarget quantile
q̂_τpredicted quantile
yobserved value
Open derivation and numerical substitution

Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.

  1. Write the named inputs: τ, q̂_τ, y.
  2. Substitute one small, hand-checkable batch before vectorizing.
  3. Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c07(inputs)
assert is_finite(value)
04 · Deterministic lab

Change one assumption and make the tradeoff visible.

Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.

Simplified simulation

Rolling-window backtest

Change history length and inspect bias, error, and interval coverage.

weeks
Primary12.1 MAE
Secondary83.2%
DiagnosisBalanced

Assumption: Seasonal demand with one simulated regime change at week 30.

Open nonvisual data table
ItemComputed stateInterpretation
h+112.5 MAE87.8%
h+613.6 MAE86.7%
h+1215.0 MAE85.4%
h+1816.3 MAE84.0%
h+2417.6 MAE82.7%
05 · Production implications

Trace the complete operating path.

Carry the chapter’s central idea into the system: A faithful backtest is a replay of past information states, not merely a sorted split. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.

  1. 01

    Turn “Mirror the release cadence” into a written invariant and a failing test.

  2. 02

    Promote rolling_origins.py from illustration to a versioned implementation with representative fixtures.

  3. 03

    Use “Keep the distribution of outcomes” as the release checkpoint: Report error by origin and horizon with uncertainty; a mean alone hides whether one regime accounts for the apparent gain.

  4. 04

    Serve or materialize behind explicit available before staffing decisions.

  5. 05

    Join telemetry to mature outcomes and retain a rollback path.

Observability

Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.

Cost

Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.

Failure modes

Training uses realized future weather and random folds, producing a forecast impossible to reproduce at origin time. Add a detector, owner, mitigation, and stop condition for this class of failure.

Alternatives

Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.

06 · Check understanding

Explain the contract, not just the vocabulary.

Browser-graded checkpointPass ≥ 80%
01What should a calibrated 90% interval do?
02Why specify forecast lead time?
03Why use rolling origins?
07 · Apply in production

Regional demand forecast

Build a 24-hour pipeline with naive, statistical, and boosted baselines plus interval forecasts.

  • Forecast contract
  • Rolling-origin evaluation
  • Horizon and coverage report
  • Drift/retrain/fallback policy
Open assignment and rubric
08 · Sources & next depth

Read primary material with a purpose.

09 · Production resolution

Return to the opening failure.

Monitor horizon-level error, bias, interval coverage, freshness, reconciliation, and a seasonal-naive fallback.

For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce rolling validation, statistical baselines, boosted forecasts, and uncertainty bands.