Chapter 1 · Frame and baseline

Trend, seasonality, and known-future signals

A temporal feature is valid only if its value could be reconstructed exactly at the forecast origin.

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

Regional demand shifts through promotions, holidays, and drift.

This chapter moves from sketch the generating rhythms to ablate feature families. 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

Remove trend, seasonal, lag, and known-future groups one at a time in rolling backtests to learn which mechanism genuinely helps each horizon.

Evidence

Verify the behavior illustrated in safe_time_features.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.

Time series repeat, drift, and react to planned events. Good features describe those mechanisms without smuggling the future into the training row.

Trend represents a changing level; seasonality represents patterns tied to a stable cycle. Lags and rolling summaries encode recent history, while sine and cosine pairs express cyclical position without making Sunday artificially far from Monday. Differencing can remove level but changes the target interpretation.

Covariates belong to one of two classes: observed history or known future. Calendar fields and a published promotion plan may be available for future timestamps; realized weather or final price usually is not. Availability must be checked at each simulated origin, not inferred from a column name.

Keep in view
  • seasonal naive
  • lag features
  • rolling backtests
  • direct vs recursive
WORKED PATH

Follow the reasoning before touching the code.

  1. 01

    Sketch the generating rhythms

    Plot the series at operational granularity and mark plausible daily, weekly, annual, launch, and holiday effects before manufacturing features.

  2. 02

    Create origin-safe predictors

    Shift observed values before rolling, encode cyclic calendar positions, and join only covariate versions published by the forecast origin.

  3. 03

    Ablate feature families

    Remove trend, seasonal, lag, and known-future groups one at a time in rolling backtests to learn which mechanism genuinely helps each horizon.

pythonsafe_time_features.py
import numpy as np
import pandas as pd

frame = pd.DataFrame({'hour': range(8), 'demand': [5, 7, 8, 6, 5, 9, 11, 8]})
frame['lag_1'] = frame['demand'].shift(1)
frame['mean_3'] = frame['demand'].shift(1).rolling(3).mean()
angle = 2 * np.pi * frame['hour'] / 24
frame['hour_sin'] = np.sin(angle)
frame['hour_cos'] = np.cos(angle)
print(frame.dropna().round(2))

Build lagged and cyclic features without reading the target row.

READ THE EXAMPLE

What to notice

  • The rolling mean shifts before aggregation, so demand at the target timestamp cannot contribute to its own feature.
  • The sine/cosine pair makes hours near midnight geometrically close despite their numeric values wrapping from 23 to 0.
YOUR TURN Pause and predict before revealing the answer.

What leakage appears if shift(1) is removed from mean_3?

Need a hint?

Inspect which demand values the rolling window for the current row contains.

Check your reasoning

The current target enters its own predictor, giving the model information unavailable when that target is still in the future.

Bring forward

Lessons 1 in this course.

03 · Formal treatment

Connect the chapter to the course’s quantitative spine.

A temporal feature is valid only if its value could be reconstructed exactly at the forecast origin. 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 temporal feature is valid only if its value could be reconstructed exactly at the forecast origin. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.

  1. 01

    Turn “Sketch the generating rhythms” into a written invariant and a failing test.

  2. 02

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

  3. 03

    Use “Ablate feature families” as the release checkpoint: Remove trend, seasonal, lag, and known-future groups one at a time in rolling backtests to learn which mechanism genuinely helps each horizon.

  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%
01Why use rolling origins?
02What should a calibrated 90% interval do?
03Why specify forecast lead time?
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.