40. Time series — Mini-project
The operations team of the store chain orders stock four weeks in advance. Today they use “the same as last week” as the plan. You are asked to build a 28-day forecast of the total units sold per day and to show, with honest numbers, whether a statistical model or a machine learning model beats the current rule.
Your deliverable is one script, units_forecast.py, that:
- builds a clean daily series from the raw order lines;
- compares four forecasters with an expanding-window backtest;
- chooses one model with the backtest only;
- reports the chosen model and its rivals once on a locked holdout of the last 28 days;
- prints the forecast for the 28 days after the data ends, for the ordering team.
The project uses every part of module 40: the datetime index, resampling and gap checks, decomposition, the ADF test, baselines, SARIMA, lag features, LightGBM, TimeSeriesSplit and the five forecast metrics.
Dataset
Section titled “Dataset”data/sales.csv has 20,228 order lines from 2023-01-01 to 2024-12-31 (see the data dictionary). Sum quantity per order_date to get the daily units. Facts from the dictionary that matter here:
- Every day of 2023–2024 has orders (731 days). Daily units have a mean of 40.4.
- Volume grows about 45% from the start to the end of the period.
- Saturday is the busiest day; there is a November–December peak and a January–February dip.
- Promo days add large spikes: Black Friday (2023-11-24, 2024-11-29), the weekend after it and Cyber Monday (2023-11-27, 2024-12-02), and summer sales in July.
The holdout is 2024-12-04 to 2024-12-31. Keep it locked until the last step.
Requirements
Section titled “Requirements”Your script must:
- Build the daily units series with a daily frequency and check that no day is missing.
- Split off the last 28 days as the holdout before any exploration. Do not use them for any choice.
- On the training data only, print the weekday effect from an STL decomposition (
period=7) and the ADF p-values of the level (with"c"and with"ct") and of the first difference. - Implement four forecasters for a 28-day horizon: seasonal naive, a 4-week seasonal mean, SARIMA on the log, and LightGBM on direct lag features (every lag at least 28 days old).
- Choose the SARIMA orders by AIC on the training data, among a few small candidates with the same differencing. No
ConvergenceWarningis allowed. - Backtest all four forecasters with
TimeSeriesSplit(n_splits=5, test_size=28)on the training data, and choose the model with the lowest mean MAE. - Report MAE, RMSE, MAPE, sMAPE and MASE of all four models on the holdout, once.
- Refit the chosen model on all 731 days and print the forecast for 2025-01-01 to 2025-01-28: the first week by day, and the 4-week total.
- End with
assertchecks: no missing day, no overlap between training and test in any fold, and a forecast of the right length with positive values.
Step plan
Section titled “Step plan”-
Load and aggregate.
groupby("order_date")["quantity"].sum(), thenasfreq("D"). Count theNaNvalues: there should be none. -
Lock the holdout.
train, test = units.iloc[:-28], units.iloc[-28:]. From here until step 7, onlytrainexists. -
Explore the training data. Fit
STL(train, period=7, robust=True)and average the seasonal part per weekday. Runadfullerwithresult_object=Trueon the level ("c"and"ct") and ontrain.diff().dropna(). -
Write the forecasters. One function
fit_and_forecast(history, target_index)that returns a dictionary of four arrays. Build the LightGBM features once for the whole log series withshift(28)and more; a feature that is at least 28 days old is known for every day of the horizon. -
Choose SARIMA orders. Fit two or three candidates such as and on
np.log(train), withfit(disp=False, maxiter=200). Keep the lowest AIC. Checkmle_retvals["converged"]. -
Backtest. Loop over the folds of
TimeSeriesSplit. Collect the MAE per fold and model in a DataFrame. Pivot it to see the folds side by side. Choose the lowest mean MAE. -
Score the holdout once. Call
fit_and_forecast(train, test.index)and compute the five metrics for every model. -
Forecast the future. Refit on all of
unitsand forecast 28 days after 2024-12-31. Print the first week and the total. -
Write a short conclusion as comments at the end of the script: which model you chose, by how much it beats “the same as last week”, and one risk the ordering team should know.
Rubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Clean series | 2 | Daily frequency, completeness checked with an assert |
| Exploration | 2 | Weekday effect and ADF results printed and interpreted in a comment |
| No leakage | 3 | Holdout locked until the end; every LightGBM feature is at least 28 days old; folds never overlap |
| Baselines | 2 | Seasonal naive and seasonal mean implemented and scored |
| SARIMA | 2 | Orders chosen by AIC on the training data; converged; no warnings |
| Machine learning | 2 | LightGBM with lag, rolling and calendar features; verbose=-1 |
| Backtest and choice | 3 | TimeSeriesSplit with 5 folds of 28 days; model chosen by the mean backtest score |
| Metrics | 2 | MAE, RMSE, MAPE, sMAPE and MASE on the holdout, computed once |
| Future forecast and conclusion | 2 | 28-day forecast for January 2025 and a written conclusion with one risk |
| Total | 20 | 16 or more: you are ready for module 41 |
Stretch goals
Section titled “Stretch goals”- Add an exogenous promo flag (Black Friday weekend, Cyber Monday, summer sale days) to SARIMAX, and to the LightGBM features. Promo dates are planned, so their future values are known.
- Add a recursive LightGBM model with lags 1 to 7 and compare it in the backtest.
- Forecast weekly totals instead of daily units and compare the error of the 4-week total.
- Forecast the units of each category separately and check whether the sum of the category forecasts beats the total forecast.
- Plot the backtest errors per fold as a bar chart and mark the folds that contain promo days.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names can differ; the numbers for the same models must match.
Reference solution
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom lightgbm import LGBMRegressorfrom sklearn.model_selection import TimeSeriesSplitfrom statsmodels.tsa.seasonal import STLfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom statsmodels.tsa.stattools import adfuller
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
HORIZON = 28
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])units = sales.groupby("order_date")["quantity"].sum().asfreq("D").astype(float)assert units.isna().sum() == 0, "a day is missing"print(f"{len(units)} days, {units.index[0].date()} to {units.index[-1].date()}")low, high = units.min(), units.max()print(f"mean {units.mean():.1f} units/day, min {low:.0f}, max {high:.0f}")
train, test = units.iloc[:-HORIZON], units.iloc[-HORIZON:] # test stays locked
stl = STL(train, period=7, robust=True).fit()effect = stl.seasonal.groupby(train.index.day_of_week).mean()effect.index = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]print(effect.round(1).to_frame("weekday effect").T)tests = [("level, c", train, "c"), ("level, ct", train, "ct"), ("first difference", train.diff().dropna(), "c")]for name, series, regression in tests: pvalue = adfuller(series, regression=regression, result_object=True).pvalue print(f"ADF {name}: p={pvalue:.3g}")731 days, 2023-01-01 to 2024-12-31mean 40.4 units/day, min 5, max 242 Mon Tue Wed Thu Fri Sat Sunweekday effect -4.3 -6.3 -3.0 -4.7 0.6 11.9 6.1ADF level, c: p=0.975ADF level, ct: p=0.964ADF first difference: p=1.25e-20The series is complete, so no fill is needed. The holdout is split off before any exploration. On the training data, Saturday is the busiest day and Tuesday the quietest. The ADF test finds no evidence that the level is stationary, even around a linear trend (unlike the visits of the lesson), and strong evidence that the first difference is. Here d = 1 is what the evidence supports.
log_units = np.log(units)
aic = {}for order in [(0, 1, 1), (1, 1, 1)]: res = SARIMAX(np.log(train), order=order, seasonal_order=(0, 1, 1, 7)).fit( disp=False, maxiter=200 ) assert res.mle_retvals["converged"], order aic[order] = res.aic print(order, "(0, 1, 1, 7)", "AIC", round(res.aic, 1))SARIMA_ORDER = min(aic, key=aic.get) # the lowest AIC winsprint("chosen order:", SARIMA_ORDER)
# Features for every known day plus the 28 future days (their lags are known).future_index = pd.date_range("2025-01-01", periods=HORIZON, freq="D")extended = log_units.reindex(units.index.append(future_index))features = pd.DataFrame(index=extended.index)for lag in [28, 35, 42]: features[f"lag_{lag}"] = extended.shift(lag)features["roll_mean_28"] = extended.shift(28).rolling(28).mean()features["day_of_week"] = extended.index.day_of_weekfeatures["month"] = extended.index.monthfeatures["day_of_year"] = extended.index.day_of_year
def fit_and_forecast(history: pd.Series, target_index: pd.DatetimeIndex) -> dict: """Fit four forecasters on `history`; forecast the dates in `target_index`.""" steps = len(target_index) last_4_weeks = history.iloc[-28:].to_numpy().reshape(4, 7) sarima = SARIMAX(np.log(history), order=SARIMA_ORDER, seasonal_order=(0, 1, 1, 7)) sarima_fc = np.exp(sarima.fit(disp=False, maxiter=200).forecast(steps)).to_numpy() rows = features.loc[history.index].dropna() lgbm = LGBMRegressor(n_estimators=200, learning_rate=0.05, n_jobs=1, random_state=42, verbose=-1) lgbm.fit(rows, log_units.loc[rows.index]) return { "seasonal naive": np.resize(history.iloc[-7:].to_numpy(), steps), "seasonal mean 4w": np.resize(last_4_weeks.mean(axis=0), steps), "SARIMA": sarima_fc, "LightGBM": np.exp(lgbm.predict(features.loc[target_index])), }(0, 1, 1) (0, 1, 1, 7) AIC 652.4(1, 1, 1) (0, 1, 1, 7) AIC 653.7chosen order: (0, 1, 1)The two candidates have the same differencing, so their AIC values are comparable. The AR term does not lower the AIC, so min keeps the simpler airline model . (The airline model is SARIMA : one regular and one seasonal difference, each with one MA term. It is named after a classic airline passenger series.) The feature table also covers the 28 days after the data ends: every LightGBM feature is at least 28 days old, so it is known for the whole future horizon.
def mae(actual, forecast) -> float: return float(np.mean(np.abs(np.asarray(actual) - np.asarray(forecast))))
results = []splitter = TimeSeriesSplit(n_splits=5, test_size=HORIZON)for k, (tr, te) in enumerate(splitter.split(train), start=1): assert tr.max() < te.min() # no overlap: training ends before testing starts fold_train, fold_test = train.iloc[tr], train.iloc[te] for name, fc in fit_and_forecast(fold_train, fold_test.index).items(): results.append({"fold": k, "test starts": fold_test.index[0].date(), "model": name, "MAE": mae(fold_test, fc)})backtest = pd.DataFrame(results).pivot( index=["fold", "test starts"], columns="model", values="MAE")print(backtest.round(1))mean_mae = backtest.mean().sort_values()print(mean_mae.round(2))chosen = mean_mae.index[0]print("chosen model:", chosen)model LightGBM SARIMA seasonal mean 4w seasonal naivefold test starts1 2024-07-17 12.1 9.1 8.9 14.02 2024-08-14 15.9 13.1 13.6 17.03 2024-09-11 9.8 9.1 12.5 13.24 2024-10-09 11.8 11.4 13.0 16.15 2024-11-06 25.1 29.3 32.9 26.2modelSARIMA 14.38LightGBM 14.93seasonal mean 4w 16.21seasonal naive 17.31dtype: float64chosen model: SARIMASARIMA has the lowest mean MAE, with LightGBM second. Fold 5 contains Black Friday and Cyber Monday, and every model has its largest error there. The choice uses only the training data.
def rmse(a, f) -> float: return float(np.sqrt(np.mean((np.asarray(a) - np.asarray(f)) ** 2)))
def mape(a, f) -> float: a, f = np.asarray(a), np.asarray(f) return float(100 * np.mean(np.abs(a - f) / np.abs(a)))
def smape(a, f) -> float: a, f = np.asarray(a), np.asarray(f) return float(100 * np.mean(2 * np.abs(a - f) / (np.abs(a) + np.abs(f))))
def mase(a, f, history, m: int = 7) -> float: h = np.asarray(history) return mae(a, f) / float(np.mean(np.abs(h[m:] - h[:-m])))
holdout = fit_and_forecast(train, test.index)report = pd.DataFrame( {name: {"MAE": mae(test, fc), "RMSE": rmse(test, fc), "MAPE %": mape(test, fc), "sMAPE %": smape(test, fc), "MASE": mase(test, fc, train)} for name, fc in holdout.items()}).T.sort_values("MAE")print(f"Holdout {test.index[0].date()} to {test.index[-1].date()}:")print(report.round(2))gain = 1 - report.loc[chosen, "MAE"] / report.loc["seasonal naive", "MAE"]print(f"chosen model ({chosen}) vs seasonal naive: {gain:.0%} lower MAE")Holdout 2024-12-04 to 2024-12-31: MAE RMSE MAPE % sMAPE % MASESARIMA 16.39 21.56 34.57 23.44 1.14seasonal mean 4w 17.86 21.73 29.98 25.91 1.24LightGBM 17.90 23.30 31.76 25.71 1.25seasonal naive 64.75 82.84 96.09 59.32 4.51chosen model (SARIMA) vs seasonal naive: 75% lower MAEThe chosen SARIMA model is also the best on the holdout, by a small margin over the 4-week seasonal mean and LightGBM. The current rule, “the same as last week”, is far behind: the last week before the holdout holds Black Friday and Cyber Monday, so it copies a promo week into December.
fig, ax = plt.subplots(figsize=(10, 4))ax.plot(train.loc["2024-10-15":], color="0.5", label="training data")ax.plot(test, color="black", linewidth=2, label="actual (holdout)")for name in ["seasonal naive", "SARIMA", "LightGBM"]: ax.plot(test.index, holdout[name], label=name)ax.set(title="Daily units: 28-day forecasts on the holdout", ylabel="units")ax.legend(loc="upper left")plt.show()
The picture explains the holdout table: one promo week, copied four times, ruins the seasonal naive forecast. SARIMA and LightGBM both stay close to the actual units.
final = fit_and_forecast(units, future_index)future = pd.Series(final[chosen], index=future_index)print("first week:")print(future.head(7).round(1).to_string())print(f"4-week total: {future.sum():,.0f} units")assert len(future) == HORIZON and (future > 0).all()
# Conclusion: SARIMA (0,1,1)(0,1,1)_7 on the log wins the backtest and the holdout.# It cuts the holdout MAE of "the same as last week" by about 75%, mostly because# the old rule copies promo weeks. Risks: no model knows about planned promotions,# and SARIMA has no yearly season, so it carries the December level into January,# a month with a known dip. Check the January plan against last January.first week:2025-01-01 61.92025-01-02 63.82025-01-03 77.02025-01-04 95.12025-01-05 81.02025-01-06 59.32025-01-07 58.8Freq: D4-week total: 2,015 unitsfit_and_forecast is called with the full series and the 28 future dates. Only the chosen model’s forecast is reported. The LightGBM features for January 2025 exist, because every lag is at least 28 days old: the newest value they need is 2024-12-31. The forecast keeps the weekly shape (Saturday is the peak) at about the level of late December. The data dictionary describes a January–February dip that a weekly SARIMA cannot know, so the conclusion names it as a risk.
How it works:
- Data. One
groupbyturns order lines into a daily series;asfreq("D")and an assert prove that no day is missing. - Exploration. The holdout is split off first, so STL and the ADF tests see only the training data. STL shows the weekly shape. The ADF tests find no unit-root rejection for the level, even with a trend, and a clearly stationary first difference, which supports
d = 1. - One function, every split.
fit_and_forecastis the only place where models are fitted. The backtest, the holdout and the future forecast all call it, so they test exactly the same code. - Choice before the holdout. AIC chooses the SARIMA orders and the backtest chooses the model. The holdout is touched once, after both choices.
- Metrics. MAE, RMSE and MASE rank SARIMA first. MAPE ranks the 4-week seasonal mean first: on low days, such as 2024-12-25 when the stores are closed, small absolute errors become large percentages. Every MASE is above 1: December, with its holidays and the days after the promos, is harder than an average week of the training data. Report MAE or MASE, and use MAPE as a second view.
Alternative: replace the 4-week seasonal mean with a seasonal median. A median of the last 4 same weekdays ignores one promo day completely, so it is a stronger baseline around Black Friday. Any forecaster that beats it is worth its complexity.