Trend, seasonality, and known-future signals
A temporal feature is valid only if its value could be reconstructed exactly at the forecast origin.
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.
Remove trend, seasonal, lag, and known-future groups one at a time in rolling backtests to learn which mechanism genuinely helps each horizon.
Verify the behavior illustrated in safe_time_features.py, then measure decision utility, slice reliability, and system latency.
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.
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.
- seasonal naive
- lag features
- rolling backtests
- direct vs recursive
Follow the reasoning before touching the code.
- 01
Sketch the generating rhythms
Plot the series at operational granularity and mark plausible daily, weekly, annual, launch, and holiday effects before manufacturing features.
- 02
Create origin-safe predictors
Shift observed values before rolling, encode cyclic calendar positions, and join only covariate versions published by the forecast origin.
- 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.
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.
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.
Lessons 1 in this course.
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.
Quantile forecast objective
| Symbol | Meaning / shape / unit |
|---|---|
τ | target quantile |
q̂_τ | predicted quantile |
y | observed 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.
- Write the named inputs: τ, q̂_τ, y.
- Substitute one small, hand-checkable batch before vectorizing.
- 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)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.
Rolling-window backtest
Change history length and inspect bias, error, and interval coverage.
Assumption: Seasonal demand with one simulated regime change at week 30.
Open nonvisual data table
| Item | Computed state | Interpretation |
|---|---|---|
| h+1 | 12.5 MAE | 87.8% |
| h+6 | 13.6 MAE | 86.7% |
| h+12 | 15.0 MAE | 85.4% |
| h+18 | 16.3 MAE | 84.0% |
| h+24 | 17.6 MAE | 82.7% |
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.
- 01
Turn “Sketch the generating rhythms” into a written invariant and a failing test.
- 02
Promote safe_time_features.py from illustration to a versioned implementation with representative fixtures.
- 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.
- 04
Serve or materialize behind explicit available before staffing decisions.
- 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.
Explain the contract, not just the vocabulary.
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
Read primary material with a purpose.
Forecasting: Principles and Practice
90 min · last checked 26 Aug 2026
↗RECOMMENDED · Official docsscikit-learn lagged forecasting example
25 min · last checked 26 Aug 2026
↗DEEP DIVE · INDEXFind a primary implementation or benchmark
30–90 min · verify task, dataset, and evaluation match
↗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.