Python Master Course V2 — 194. Portfolio Capstone: Demand Forecasting
Lesson 194: Portfolio Capstone: Demand Forecasting
This alternative portfolio track forecasts seven days of generated demand from information available at each forecast origin. It compares persistence, a weekly seasonal baseline and a regularized learned model. The data contains a deliberate regime change, so a useful report includes periods where the methods fail. No sales account, remote dataset or paid forecasting service is needed.
Estimated study time: 200 minutes, including the practical work. Use a local Python 3.11+ environment; no paid service, API key or public deployment is required.
Before you start
- 078: dates
- 139: forecasting
- 185: drift
- 191: scoping
Learning objectives
- Choose a forecast horizon and chronological evaluation design
- Compare naive, seasonal and learned forecasting methods
- Report performance across periods and explain uncertainty limits
Concepts and worked implementation
State exactly what is known when predicting
An origin is the first day not yet observed. At origin 140, the training history contains indices 0 through 139 and the forecast covers 140 through 146. This convention prevents off-by-one leakage. The horizon is seven days, and the complete seven-day forecast is issued at once. It cannot use the true demand from the first forecast day to predict the second.
Persistence repeats the last observed value. A seven-day seasonal baseline repeats the corresponding observed day from the previous week. Both are credible references for a series with weekly structure. A learned model must improve over them under the same origin, horizon and error definition. Comparing a one-day rolling model against a seven-day fixed-origin baseline would be an unfair change of task.
The generated series combines a trend, weekly seasonality, noise and a level increase at day 224. The analyst knows the generator for documentation, but the model receives no future regime-change flag. This lets you study delayed adaptation. Knowing the simulated ground truth should not tempt you to add features unavailable in the actual forecast contract.
Implement direct multi-horizon forecasts
Install numpy and scikit-learn locally. Save as forecast.py. For each horizon position, a separate Ridge model learns from earlier origins whose targets are already observed. StandardScaler stays inside the fitted pipeline. Calendar features for a future target date are allowed because the calendar is known in advance; future demand is not.
from pathlib import Path
import json
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
rng = np.random.default_rng(194)
day = np.arange(336)
demand = np.maximum(0, 40 + 0.04 * day + 8 * np.sin(2 * np.pi * day / 7)
+ 18 * (day >= 224) + rng.normal(0, 3, len(day)))
HORIZON = 7
ORIGINS = [140, 168, 196, 224, 252, 280]
def features(history, origin, target_day):
if origin < 7 or len(history) != origin:
raise ValueError('history must end immediately before the origin')
return [history[-1], history[-7], np.mean(history[-7:]),
target_day, np.sin(2 * np.pi * target_day / 7),
np.cos(2 * np.pi * target_day / 7)]
def forecast_at(series, origin):
history = series[:origin]
persistence = np.repeat(history[-1], HORIZON)
seasonal = history[-7:].copy()
learned = []
for horizon in range(HORIZON):
past_origins = list(range(14, origin - horizon))
X_train = np.array([features(series[:s], s, s + horizon) for s in past_origins])
y_train = np.array([series[s + horizon] for s in past_origins])
assert max(s + horizon for s in past_origins) < origin
model = make_pipeline(StandardScaler(), Ridge(alpha=10.0))
model.fit(X_train, y_train)
x = np.array([features(history, origin, origin + horizon)])
learned.append(max(0.0, float(model.predict(x)[0])))
return {'persistence': persistence, 'seasonal_7': seasonal,
'ridge_direct': np.array(learned)}
rows = []
for origin in ORIGINS:
predictions = forecast_at(demand, origin)
for method, values in predictions.items():
for horizon, prediction in enumerate(values, start=1):
target_index = origin + horizon - 1
truth = float(demand[target_index])
rows.append({'origin': origin, 'horizon': horizon, 'method': method,
'truth': truth, 'prediction': float(prediction),
'absolute_error': abs(truth - float(prediction))})
summary = {}
for method in ['persistence', 'seasonal_7', 'ridge_direct']:
selected = [r for r in rows if r['method'] == method]
summary[method] = {
'MAE': float(np.mean([r['absolute_error'] for r in selected])),
'MAE_by_origin': {str(o): float(np.mean([r['absolute_error'] for r in selected if r['origin'] == o]))
for o in ORIGINS},
'MAE_by_horizon': {str(h): float(np.mean([r['absolute_error'] for r in selected if r['horizon'] == h]))
for h in range(1, HORIZON + 1)}}
report = {'horizon_days': HORIZON, 'fixed_alpha': 10.0,
'origins': ORIGINS, 'summary': summary, 'predictions': rows,
'limitations': ['generated demand', 'few origins', 'regime change not known to model']}
Path('forecast-results.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print(json.dumps(summary, indent=2))
Expected structure: six origins, three methods and seven horizon positions produce 126 prediction records. MAE is expressed in demand units. Actual values and the winning method must be computed locally. The regularization value and origin list are fixed for this exercise; if you tune them after reading the report, that report becomes development evidence and you need a later untouched evaluation window.
Inspect the failure periods
Mean absolute error averages absolute differences and remains interpretable in the target’s units. It does not emphasize large misses as strongly as squared error. Percentage errors can misbehave near zero demand, so this project uses MAE and describes its limitation. Report overall, per-origin and per-horizon errors instead of compressing the regime change into one flattering average.
The seasonal baseline has no mechanism to anticipate an unannounced level shift. The learned model may also fail immediately after the change because its training targets contain only the earlier regime. That is a meaningful finding about information availability, not necessarily a programming defect. Later adaptation depends on the training window and features. Compare expanding and recent-window fits only under a new predeclared validation plan.
Test that future values cannot affect a forecast
A powerful leakage test modifies values at and after the origin while leaving the history fixed. The predictions issued at that origin should remain unchanged. The following block belongs in a separate test module after moving the starter’s main execution under a main guard.
import numpy as np
from forecast import forecast_at, demand
origin = 196
changed = demand.copy()
changed[origin:] += 1000
before = forecast_at(demand, origin)
after = forecast_at(changed, origin)
for method in before:
np.testing.assert_allclose(before[method], after[method])
assert all(len(values) == 7 for values in before.values())
This test does not prove the whole experiment is leakage-free, but it directly checks an important contract. Also inspect how dates, rolling statistics and any revised source data are constructed. A historical value revised after the forecast date may not have been available then, even if its timestamp looks old.
Describe uncertainty honestly
An empirical error band from previous forecast origins can summarize past errors if computed using only already available outcomes. With few origins, dependence across horizons and a regime change, it is not a guarantee of future coverage. Do not present a fixed ±10% band as a statistical interval without a method. State whether a band is descriptive, model-based or calibrated, which assumptions it needs and how coverage would be checked on new periods.
Guided lab and evidence
Add a plot with observed demand, issued forecasts and a marked regime-change date, plus a text summary of the worst origin. Preserve a prediction ledger with one row per method, origin and horizon. Add tests for seven outputs, nonnegative predictions, exact history boundaries and invariance to changed future values.
Score out of 100: 25 for time-aware feature and target construction, 20 for comparable baselines, 20 for period and horizon error analysis, 20 for reproducibility and tests, and 15 for uncertainty and scope limitations. Deliver a short operational note specifying when forecasts are issued, what data must have arrived, and what alert might trigger investigation after a distribution shift. Do not imply the synthetic exercise validates a real inventory decision.
Questions worth reasoning through
Why can a future calendar feature be legitimate?
The day of week is known at the origin, unlike future demand. The key question is availability at prediction time, not whether a feature references a future date. Document every feature’s information source and timing.
Why fit one model per horizon position?
Direct models target each lead time without feeding predicted values recursively into later steps. They cost more fitting work and share less information, but make the seven-day information boundary explicit in this small CPU exercise.
Can overlapping forecast errors be treated as independent samples?
Often not. Forecasts may share targets, training data and shocks. Dependence affects uncertainty calculations. This starter uses separated origins but still does not claim independence of every horizon error or universal confidence coverage.
Why include a seasonal baseline?
Weekly structure can make a simple previous-week forecast surprisingly competitive. Comparing only against a weak constant or persistence method can exaggerate the value of a learned model.
Does a poor regime-change forecast prove the model is useless?
It shows a failure under the available information and specified change. Report severity and recovery behavior. Whether the method is useful depends on the actual decision costs, alternative methods and ability to detect or respond to such changes.
Exercises and worked answers
Exercise 1
At origin 100 with a seven-day fixed forecast, may the day-102 prediction use actual day-101 demand?
Worked answer and reasoning
No. The entire forecast is issued before day 100 is observed. Actual day-101 demand would become available later and would define a different rolling-update task. Use only history through day 99 and known future covariates.
Exercise 2
A model wins overall MAE but loses badly at the last two origins. What belongs in the conclusion?
Worked answer and reasoning
Report the overall improvement and the recent failures, with per-origin values and their timing. Investigate possible regime change and stale training assumptions. Do not recommend the model solely from the pooled average; the recent operational context may matter more than historical average performance.
Recap
Forecasting requires an exact information boundary, fixed horizon and comparable baselines. Preserve origin-level evidence, test future invariance and explain failed periods. Uncertainty and deployment assumptions belong beside the score, not in a hidden footnote.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.