Skip to content

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.

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.

Your script must:

  1. Build the daily units series with a daily frequency and check that no day is missing.
  2. Split off the last 28 days as the holdout before any exploration. Do not use them for any choice.
  3. 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.
  4. 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).
  5. Choose the SARIMA orders by AIC on the training data, among a few small candidates with the same differencing. No ConvergenceWarning is allowed.
  6. 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.
  7. Report MAE, RMSE, MAPE, sMAPE and MASE of all four models on the holdout, once.
  8. 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.
  9. End with assert checks: no missing day, no overlap between training and test in any fold, and a forecast of the right length with positive values.
  1. Load and aggregate. groupby("order_date")["quantity"].sum(), then asfreq("D"). Count the NaN values: there should be none.

  2. Lock the holdout. train, test = units.iloc[:-28], units.iloc[-28:]. From here until step 7, only train exists.

  3. Explore the training data. Fit STL(train, period=7, robust=True) and average the seasonal part per weekday. Run adfuller with result_object=True on the level ("c" and "ct") and on train.diff().dropna().

  4. 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 with shift(28) and more; a feature that is at least 28 days old is known for every day of the horizon.

  5. Choose SARIMA orders. Fit two or three candidates such as (0,1,1)(0,1,1)7(0,1,1)(0,1,1)_7 and (1,1,1)(0,1,1)7(1,1,1)(0,1,1)_7 on np.log(train), with fit(disp=False, maxiter=200). Keep the lowest AIC. Check mle_retvals["converged"].

  6. 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.

  7. Score the holdout once. Call fit_and_forecast(train, test.index) and compute the five metrics for every model.

  8. Forecast the future. Refit on all of units and forecast 28 days after 2024-12-31. Print the first week and the total.

  9. 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.

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
  1. 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.
  2. Add a recursive LightGBM model with lags 1 to 7 and compare it in the backtest.
  3. Forecast weekly totals instead of daily units and compare the error of the 4-week total.
  4. Forecast the units of each category separately and check whether the sum of the category forecasts beats the total forecast.
  5. Plot the backtest errors per fold as a bar chart and mark the folds that contain promo days.

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
units_forecast.py (part 1: data and exploration)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from lightgbm import LGBMRegressor
from sklearn.model_selection import TimeSeriesSplit
from statsmodels.tsa.seasonal import STL
from statsmodels.tsa.statespace.sarimax import SARIMAX
from 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}")
Output
731 days, 2023-01-01 to 2024-12-31
mean 40.4 units/day, min 5, max 242
Mon Tue Wed Thu Fri Sat Sun
weekday effect -4.3 -6.3 -3.0 -4.7 0.6 11.9 6.1
ADF level, c: p=0.975
ADF level, ct: p=0.964
ADF first difference: p=1.25e-20

The 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.

units_forecast.py (part 2: forecasters and SARIMA orders)
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 wins
print("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_week
features["month"] = extended.index.month
features["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])),
}
Output
(0, 1, 1) (0, 1, 1, 7) AIC 652.4
(1, 1, 1) (0, 1, 1, 7) AIC 653.7
chosen 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 (0,1,1)(0,1,1)7(0,1,1)(0,1,1)_7. (The airline model is SARIMA (0,1,1)(0,1,1)s(0,1,1)(0,1,1)_s: 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.

units_forecast.py (part 3: backtest and choice)
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)
Output
model LightGBM SARIMA seasonal mean 4w seasonal naive
fold test starts
1 2024-07-17 12.1 9.1 8.9 14.0
2 2024-08-14 15.9 13.1 13.6 17.0
3 2024-09-11 9.8 9.1 12.5 13.2
4 2024-10-09 11.8 11.4 13.0 16.1
5 2024-11-06 25.1 29.3 32.9 26.2
model
SARIMA 14.38
LightGBM 14.93
seasonal mean 4w 16.21
seasonal naive 17.31
dtype: float64
chosen model: SARIMA

SARIMA 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.

units_forecast.py (part 4: holdout, once)
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")
Output
Holdout 2024-12-04 to 2024-12-31:
MAE RMSE MAPE % sMAPE % MASE
SARIMA 16.39 21.56 34.57 23.44 1.14
seasonal mean 4w 17.86 21.73 29.98 25.91 1.24
LightGBM 17.90 23.30 31.76 25.71 1.25
seasonal naive 64.75 82.84 96.09 59.32 4.51
chosen model (SARIMA) vs seasonal naive: 75% lower MAE

The 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.

units_forecast.py (part 5: plot the holdout)
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()
Daily units from mid-October to the end of December 2024: a spike to about 240 units on Black Friday and high values during the following weekend and Cyber Monday. In the December holdout the seasonal naive line repeats that promo week with values far above the actual units, while the SARIMA and LightGBM lines stay close to the actual values, which move between about 15 units (Christmas Day) and 130 units.
The seasonal naive forecast copies the Black Friday week into December.

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.

units_forecast.py (part 6: forecast January 2025)
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.
Output
first week:
2025-01-01 61.9
2025-01-02 63.8
2025-01-03 77.0
2025-01-04 95.1
2025-01-05 81.0
2025-01-06 59.3
2025-01-07 58.8
Freq: D
4-week total: 2,015 units

fit_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:

  1. Data. One groupby turns order lines into a daily series; asfreq("D") and an assert prove that no day is missing.
  2. 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.
  3. One function, every split. fit_and_forecast is 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.
  4. Choice before the holdout. AIC chooses the SARIMA orders and the backtest chooses the model. The holdout is touched once, after both choices.
  5. 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.