40. Time series — Exercises
These exercises practice every idea of the Time series lesson. They use the daily website visits (data/web_traffic.csv), daily units and revenue aggregated from data/sales.csv, and the 10-minute readings of data/sensors.csv. The data dictionary describes every column.
How to work:
- Read the task and the expected output.
- Copy the setup block and the starter code into a script and replace each to-do comment with your code.
- Run the script. Compare your output with the expected output.
- Stuck? Open one hint at a time. Open the solution only after a real attempt.
Each solution ends with assert checks. Add the same checks to your own code.
Every exercise starts from this block. It loads the daily visits with a daily frequency and fills the 5 blank days by time interpolation.
import numpy as npimport pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")traffic = traffic.asfreq("D")y = traffic["visits"].interpolate("time")Warm-up
Section titled “Warm-up”M40-W01 · Select a month by date string
Section titled “M40-W01 · Select a month by date string”From traffic, select February 2024 with a partial date string. Print the number of days, the total signups and the date with the most visits in that month.
days: 29signups: 2230busiest day: 2024-02-20 5629 visits# TODO: select February 2024 from traffic with .loc# TODO: print the number of days, the total signups and the busiest dateHint 1
traffic.loc["2024-02"] selects every row of February 2024.
Hint 2
idxmax() returns the index label of the largest value. .date() prints a timestamp without the time.
Solution
feb = traffic.loc["2024-02"]busiest = feb["visits"].idxmax()print("days:", len(feb))print("signups:", feb["signups"].sum())print("busiest day:", busiest.date(), int(feb.loc[busiest, "visits"]), "visits")assert len(feb) == 29 # 2024 is a leap yearassert feb.index.min() == pd.Timestamp("2024-02-01")days: 29signups: 2230busiest day: 2024-02-20 5629 visitsHow it works:
- A partial date string selects every row whose date starts with it.
"2024-02"gives the whole month. - 2024 is a leap year, so February has 29 days. The selection gets this right with no calendar code.
idxmax()returns the date (the index label) of the largest value, not its position.
Alternative: a boolean mask on the index: traffic[(traffic.index.year == 2024) & (traffic.index.month == 2)]. It gives the same rows, with more code.
M40-W02 · Fill the days with no sales
Section titled “M40-W02 · Fill the days with no sales”Sum the daily units of product P001 in data/sales.csv. Days without an order of P001 have no row at all. Count the days with sales, then reindex the series to every day of 2023–2024 with 0 for the missing days. Print the number of zero days and the mean daily units.
days with sales: 591zero days: 140 of 731mean units per day: 2.12 (without zeros: 2.62)sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])# TODO: daily units of P001 with groupby# TODO: reindex to every day of 2023-2024 with fill_value=0Hint 1
Filter sales[sales["product_id"] == "P001"], then groupby("order_date")["quantity"].sum().
Hint 2
pd.date_range("2023-01-01", "2024-12-31", freq="D") builds every day. series.reindex(days, fill_value=0) adds the missing days with 0.
Solution
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])p001 = sales[sales["product_id"] == "P001"].groupby("order_date")["quantity"].sum()days = pd.date_range("2023-01-01", "2024-12-31", freq="D")p001_daily = p001.reindex(days, fill_value=0)print("days with sales:", len(p001))print("zero days:", (p001_daily == 0).sum(), "of", len(p001_daily))print(f"mean units per day: {p001_daily.mean():.2f} (without zeros: {p001.mean():.2f})")assert len(p001_daily) == 731assert p001_daily.sum() == p001.sum()days with sales: 591zero days: 140 of 731mean units per day: 2.12 (without zeros: 2.62)How it works:
groupbygives one row per day with at least one order ofP001. Days with no order are absent, notNaN.reindexwith the full calendar adds the absent days. For a count, a missing row means “nothing sold”, so 0 is the right fill, not interpolation.- The mean over all days is lower than the mean over the days with sales. A forecast built on the series without zeros would be too high.
Alternative: p001.asfreq("D", fill_value=0) fills the inner gaps, but it starts at the first sale and ends at the last one. reindex with an explicit range also covers the edges.
M40-W03 · Fix the bug: monthly signups
Section titled “M40-W03 · Fix the bug: monthly signups”Fix the bug: this code should print the total signups of the first three months, labeled by the first day of each month. It raises a ValueError in pandas 3.
monthly = traffic["signups"].resample("M").sum()print(monthly.head(3))date2022-01-01 16202022-02-01 14442022-03-01 1977Freq: MS, Name: signups, dtype: int64monthly = traffic["signups"].resample("M").sum() # TODO: fix the aliasprint(monthly.head(3))Hint 1
Read the end of the error message: it names the new alias for month end.
Hint 2
The task asks for labels on the first day of the month. The alias for month start is "MS".
Solution
monthly = traffic["signups"].resample("MS").sum()print(monthly.head(3))assert monthly.index[0] == pd.Timestamp("2022-01-01")assert monthly.sum() == traffic["signups"].sum()date2022-01-01 16202022-02-01 14442022-03-01 1977Freq: MS, Name: signups, dtype: int64How it works:
- pandas 3 removed
"M". The message says to use"ME"(month end). "ME"and"MS"give the same totals with different labels. The task wants the first day, so"MS"is the fix.- Signups are a flow (a count per day), so
sumis correct, and the total over all months equals the total over all days.
Alternative: resample("ME").sum() with the labels 2022-01-31, 2022-02-28 and 2022-03-31. Use it when a report labels months by their closing date, as accounting does.
M40-W04 · Predict the output: shift, diff and rolling
Section titled “M40-W04 · Predict the output: shift, diff and rolling”Predict the output: write down the three columns of the table that this code prints, line by line. Then run it.
s = pd.Series([10.0, 12.0, 15.0, 11.0, 14.0], index=pd.date_range("2024-03-04", periods=5, freq="D"))table = pd.DataFrame({ "lag_1": s.shift(1), "diff_1": s.diff(), "past_mean_2": s.shift(1).rolling(2).mean(),})print(table)Acceptance criteria:
- Write your prediction for all 15 cells, including the
NaNcells. - Run the code. Your prediction matches the Output in the solution.
Hint 1
shift(1) moves every value one row down. The first row has no earlier value, so it is NaN.
Hint 2
diff() is s - s.shift(1). shift(1).rolling(2).mean() averages the two values before each row; it needs two values, so the first two rows are NaN.
Solution
s = pd.Series([10.0, 12.0, 15.0, 11.0, 14.0], index=pd.date_range("2024-03-04", periods=5, freq="D"))table = pd.DataFrame({ "lag_1": s.shift(1), "diff_1": s.diff(), "past_mean_2": s.shift(1).rolling(2).mean(),})print(table)assert table["diff_1"].iloc[3] == -4.0assert table["past_mean_2"].iloc[2] == 11.0 lag_1 diff_1 past_mean_22024-03-04 NaN NaN NaN2024-03-05 10.0 2.0 NaN2024-03-06 12.0 3.0 11.02024-03-07 15.0 -4.0 13.52024-03-08 11.0 3.0 13.0How it works:
lag_1on 2024-03-06 is the value of 2024-03-05: 12.diff_1is today minus yesterday: 12 − 10 = 2, 15 − 12 = 3, 11 − 15 = −4, 14 − 11 = 3.past_mean_2on 2024-03-06 is the mean of 10 and 12 (11.0). It never includes the value of its own row, so it is a safe feature.
Alternative: s.rolling(2).mean().shift(1) gives the same column. The order of shift and rolling does not matter for a trailing window; what matters is that a shift happens.
M40-W05 · Sum or mean: choose and justify
Section titled “M40-W05 · Sum or mean: choose and justify”Choose a method and justify it: resample traffic to weeks ("W") with one aggregation per column: visits, signups, bounce_rate and marketing_spend. Pick sum or mean for each. Print the number of days in the first weekly bin, then the first two full weeks.
days in the first bin: 2 visits signups bounce_rate marketing_spenddate2022-01-09 23640.0 361 0.428 2921.972022-01-16 23872.0 358 0.434 2986.88weekly = traffic.resample("W").agg({ # TODO: one aggregation per column})# TODO: count the days per week and keep full weeks onlyHint 1
A flow is an amount per period: add it up. A rate or a state is a level: average it.
Hint 2
Add the day count with traffic["visits"].resample("W").size(), then keep the rows where it equals 7.
Solution
weekly = traffic.resample("W").agg( {"visits": "sum", "signups": "sum", "bounce_rate": "mean", "marketing_spend": "sum"})days = traffic["visits"].resample("W").size()print("days in the first bin:", days.iloc[0])full = weekly[days == 7]print(full.head(2))assert (days.iloc[1:-1] == 7).all()assert full.index[0] == pd.Timestamp("2022-01-09")days in the first bin: 2 visits signups bounce_rate marketing_spenddate2022-01-09 23640.0 361 0.428 2921.972022-01-16 23872.0 358 0.434 2986.88How it works:
visits,signupsandmarketing_spendare flows: the week’s value is the sum of its days.bounce_rateis a rate, a level. The mean of seven daily rates is a fair weekly rate; their sum is meaningless. (A visit-weighted mean is even more exact.)- 2022-01-01 is a Saturday and 2022-01-02 a Sunday, so the first
"W"bin, which ends on Sunday 2022-01-02, holds 2 days. Its sums are not comparable with full weeks, so the solution keeps weeks with 7 days. - The weekly sum of visits has a blank day inside week 2022-08-14:
sumskipsNaN, so that week is a little low. Use the interpolatedywhen the exact total matters.
Alternative: named aggregation: traffic.resample("W").agg(visits=("visits", "sum"), bounce_rate=("bounce_rate", "mean")) lets you rename the columns too.
M40-W06 · Find the biggest shock with a rolling standard deviation
Section titled “M40-W06 · Find the biggest shock with a rolling standard deviation”Compute the trailing 7-day standard deviation of y. Print the date where it is highest, its value, and the date of the largest single-day visits inside that 7-day window.
highest 7-day std: 2024-04-09 6148busiest day in that window: 2024-04-08 18385rolling_std = ... # TODO: trailing 7-day standard deviation of y# TODO: date and value of the maximum; the busiest day in that windowHint 1
y.rolling(7).std() gives the standard deviation of each day and the 6 days before it.
Hint 2
The window that ends on peak starts 6 days earlier: y.loc[peak - pd.Timedelta(days=6):peak].
Solution
rolling_std = y.rolling(7).std()peak = rolling_std.idxmax()window = y.loc[peak - pd.Timedelta(days=6):peak]print("highest 7-day std:", peak.date(), round(rolling_std.max()))print("busiest day in that window:", window.idxmax().date(), int(window.max()))assert len(window) == 7assert window.idxmax() <= peakhighest 7-day std: 2024-04-09 6148busiest day in that window: 2024-04-08 18385How it works:
- The standard deviation is large when the window holds both normal days and a spike.
- It peaks one day after the campaign start of 2024-04-08: the window then holds the two huge days and five normal days.
- A threshold on the rolling standard deviation, for example 3 times its median, is a cheap event alarm in monitoring tools.
Alternative: a rolling z-score, (y - y.shift(1).rolling(28).mean()) / y.shift(1).rolling(28).std(), compares each day with the 28 days before it. It flags the first day of the campaign itself.
M40-W07 · Interpret an ADF result
Section titled “M40-W07 · Interpret an ADF result”Interpret a result: run the ADF test on the daily signups (default regression="c"). Print the p-value and a decision at the 5% level and at the 1% level. Then explain in one sentence what the decision means.
p-value: 0.0359alpha=0.05: reject H0: stationaryalpha=0.01: keep H0: no evidencefrom statsmodels.tsa.stattools import adfuller
# TODO: run adfuller with result_object=True# TODO: print the decision at alpha = 0.05 and alpha = 0.01Hint 1
H0 of the ADF test is “the series has a unit root”. You reject H0 when the p-value is below alpha.
Hint 2
Rejecting H0 means evidence of stationarity. Not rejecting means no evidence of stationarity.
Solution
from statsmodels.tsa.stattools import adfuller
res = adfuller(traffic["signups"], result_object=True)print(f"p-value: {res.pvalue:.4f}")for alpha in [0.05, 0.01]: decision = "reject H0: stationary" if res.pvalue < alpha else "keep H0: no evidence" print(f"alpha={alpha}: {decision}")assert 0.01 < res.pvalue < 0.05p-value: 0.0359alpha=0.05: reject H0: stationaryalpha=0.01: keep H0: no evidenceHow it works:
- The p-value is between 0.01 and 0.05. At the 5% level you reject the unit root; at the 1% level you do not.
- Interpretation: the signups give moderate evidence of stationarity around a constant mean. The evidence is weaker than for the first difference of the visits, which gives a p-value near 1e-19.
- A borderline p-value is a reason to look at the plot and test the trend version (
regression="ct"), not a reason to pick the alpha that gives the answer you want.
Alternative: the KPSS test (statsmodels.tsa.stattools.kpss, with result_object=True to avoid a FutureWarning) has the opposite null hypothesis: H0 is “stationary”. When ADF rejects and KPSS does not, both agree that the series is stationary.
M40-W08 · Seasonal naive forecast for next week
Section titled “M40-W08 · Seasonal naive forecast for next week”Make a seasonal naive forecast of y for the 7 days after the last date in the data (2025-01-01 to 2025-01-07). Store it as a Series with the new dates, then print it in a table next to the weekday names.
day forecast2025-01-01 Wednesday 5790.02025-01-02 Thursday 6123.02025-01-03 Friday 5751.02025-01-04 Saturday 6279.02025-01-05 Sunday 6200.02025-01-06 Monday 7283.02025-01-07 Tuesday 7218.0future = pd.date_range(...) # TODO: 7 days after the last date# TODO: repeat the last 7 values of y on the new datesHint 1
pd.date_range(y.index[-1] + pd.Timedelta(days=1), periods=7, freq="D") builds the future dates.
Hint 2
Each future date takes the value of the same weekday last week: y.iloc[-7:].to_numpy() is already in the right order.
Solution
future = pd.date_range(y.index[-1] + pd.Timedelta(days=1), periods=7, freq="D")forecast = pd.Series(y.iloc[-7:].to_numpy(), index=future, name="forecast")print(pd.DataFrame({"day": future.day_name(), "forecast": forecast}))assert (forecast.index - pd.Timedelta(days=7) == y.index[-7:]).all() day forecast2025-01-01 Wednesday 5790.02025-01-02 Thursday 6123.02025-01-03 Friday 5751.02025-01-04 Saturday 6279.02025-01-05 Sunday 6200.02025-01-06 Monday 7283.02025-01-07 Tuesday 7218.0How it works:
- The last date is 2024-12-31, so the forecast starts on 2025-01-01.
- The last 7 values run from Wednesday 2024-12-25 to Tuesday 2024-12-31. Seven days later is the same weekday, so the values line up with no reordering.
- The assert checks that every forecast date is exactly one week after the date it copies.
Alternative: y.shift(7, freq="D").iloc[-7:] moves the index forward by 7 days instead of the values, which gives the same Series in one line.
M40-W09 · Percentage errors by hand
Section titled “M40-W09 · Percentage errors by hand”For actual units [200, 50, 120] and forecasts [180, 60, 120], compute MAE and MAPE (in %) with NumPy. Then compare your MAPE with scikit-learn’s mean_absolute_percentage_error.
MAE 10.00, MAPE 10.00%scikit-learn: 0.1000from sklearn.metrics import mean_absolute_percentage_error
actual = np.array([200, 50, 120])forecast = np.array([180, 60, 120])# TODO: MAE and MAPE in %, then the scikit-learn valueHint 1
MAPE = 100 × mean(|actual − forecast| / |actual|).
Hint 2
Print the scikit-learn value as it is. Look at its scale.
Solution
from sklearn.metrics import mean_absolute_percentage_error
actual = np.array([200, 50, 120])forecast = np.array([180, 60, 120])mae = np.mean(np.abs(actual - forecast))mape = 100 * np.mean(np.abs(actual - forecast) / np.abs(actual))sk_mape = mean_absolute_percentage_error(actual, forecast)print(f"MAE {mae:.2f}, MAPE {mape:.2f}%")print(f"scikit-learn: {sk_mape:.4f}")assert np.isclose(mape, 100 * sk_mape)MAE 10.00, MAPE 10.00%scikit-learn: 0.1000How it works:
- The absolute errors are 20, 10 and 0, so the MAE is 10 units.
- The percentage errors are 10%, 20% and 0%: the small day (50 units) has the largest percentage error although its absolute error is the smallest.
- scikit-learn returns a fraction, not a percentage: 0.1 means 10%. Multiply by 100 before you compare it with a MAPE in a report.
Alternative: sklearn.metrics.mean_absolute_error(actual, forecast) gives the MAE. scikit-learn has no sMAPE or MASE; write them as one-line functions, as in the lesson.
M40-C01 · Weekly units by category
Section titled “M40-C01 · Weekly units by category”From data/sales.csv, build a table of daily units with one column per category. Resample it to weeks ("W"), keep only full weeks, and print the number of full weeks, the last full week and the category with the most units in that week.
full weeks: 104last full week ends: 2024-12-29categoryClothing 98Electronics 81Books 76Name: 2024-12-29 00:00:00, dtype: int64top category: Clothingsales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])daily = ... # TODO: pivot_table of quantity, index order_date, columns categoryweekly = ... # TODO: weekly sums# TODO: keep weeks with 7 days and report the last oneHint 1
sales.pivot_table(index="order_date", columns="category", values="quantity", aggfunc="sum", fill_value=0) gives one row per day.
Hint 2
daily.resample("W").size() counts the days per week. Use it as a mask.
Hint 3
row.idxmax() on one row returns the column with the largest value.
Solution
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])daily = sales.pivot_table( index="order_date", columns="category", values="quantity", aggfunc="sum", fill_value=0,).asfreq("D", fill_value=0)weekly = daily.resample("W").sum()days = daily.resample("W").size()full = weekly[days == 7]last = full.iloc[-1]print("full weeks:", len(full))print("last full week ends:", full.index[-1].date())print(last.sort_values(ascending=False).head(3))print("top category:", last.idxmax())assert len(full) == len(weekly) - 2assert full.sum().sum() <= sales["quantity"].sum()full weeks: 104last full week ends: 2024-12-29categoryClothing 98Electronics 81Books 76Name: 2024-12-29 00:00:00, dtype: int64top category: ClothingHow it works:
pivot_tablesums the units per day and category;fill_value=0writes 0 where a category sold nothing that day.asfreq("D", fill_value=0)guarantees a row for every day, even if a whole day had no sale.- The first bin (one day) and the last bin (two days) are partial, so 2 of the weekly rows drop out.
- In the last full week of December, Clothing leads in units. Units count items: electronics bring half of the revenue, but each item is expensive, so they sell fewer units.
Alternative: sales.groupby([pd.Grouper(key="order_date", freq="W"), "category"])["quantity"].sum().unstack() does the grouping and the weekly binning in one step.
M40-C02 · The daily cycle of a sensor
Section titled “M40-C02 · The daily cycle of a sensor”From data/sensors.csv, take the temperature of sensor S1, resample it to hourly medians (a median resists the temperature spikes) and average each hour of the day over the 14 days. Print the hours with the lowest and the highest mean temperature, and the size of the daily swing.
coldest hour: 2 19.47warmest hour: 15 24.42daily swing: 4.95 °Csensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])s1 = ... # TODO: S1 temperature with a timestamp indexhourly = ... # TODO: hourly mediansprofile = ... # TODO: mean by hour of dayHint 1
Filter sensors["sensor_id"] == "S1", then set_index("timestamp")["temperature_c"].
Hint 2
hourly.groupby(hourly.index.hour).mean() gives 24 values, one per hour of the day.
Solution
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])s1 = sensors[sensors["sensor_id"] == "S1"].set_index("timestamp")["temperature_c"]hourly = s1.resample("h").median()profile = hourly.groupby(hourly.index.hour).mean()print("coldest hour:", profile.idxmin(), round(profile.min(), 2))print("warmest hour:", profile.idxmax(), round(profile.max(), 2))print("daily swing:", round(profile.max() - profile.min(), 2), "°C")assert len(hourly) == 14 * 24assert profile.idxmin() < profile.idxmax()coldest hour: 2 19.47warmest hour: 15 24.42daily swing: 4.95 °CHow it works:
- Six 10-minute readings fall into each hour. The solution uses the hourly median instead of the mean, so one temperature spike of +9 to +18 °C does not distort a whole hour.
- Grouping by
index.houraverages each clock hour over the 14 days: this is the seasonal profile with a period of 24 hours. - The coldest hour is early in the morning and the warmest in the afternoon, as the data dictionary describes.
Alternative: STL with period=24 on the hourly series gives the same profile in its seasonal component, and it also separates the trend.
M40-C03 · Upsample a weekly budget to days
Section titled “M40-C03 · Upsample a weekly budget to days”A planning tool stores the marketing budget per week. Build the weekly totals of marketing_spend for the full weeks of January 2024 (weeks ending 2024-01-07 to 2024-01-28). Then upsample them to days in two ways: copy each week’s total to its 7 days, and an even split (weekly total ÷ 7). Print the first 3 days of each and check which one keeps the monthly total.
copied split2024-01-01 3461.65 494.522024-01-02 3461.65 494.522024-01-03 3461.65 494.52weekly total 15,396.91copied total 107,778.37 | split total 15,396.91weekly = traffic["marketing_spend"].resample("W").sum().loc["2024-01-07":"2024-01-28"]# TODO: give each day of 2024-01-01..2024-01-28 its own week's total (copy)# TODO: then an even split: the week's total / 7# TODO: compare the totals with weekly.sum()Hint 1
resample("W") labels each week by the Sunday that ends it. A plain ffill from those labels would give each day the previous week’s total. Make the daily index from the Monday of the first week and fill each day from the label that comes after it.
Hint 2
weekly.reindex(days, method="bfill") gives every day the value of the next week label at or after it: the Sunday that ends its own week. Divide by 7 for an even split.
Solution
weekly = traffic["marketing_spend"].resample("W").sum().loc["2024-01-07":"2024-01-28"]days = pd.date_range("2024-01-01", "2024-01-28", freq="D")week_of_day = weekly.reindex(days, method="bfill") # each day gets its week's totalcopied = week_of_day # the weekly total copied to each of its 7 dayssplit = week_of_day / 7print(pd.DataFrame({"copied": copied, "split": split}).head(3).round(2))print(f"weekly total {weekly.sum():,.2f}")print(f"copied total {copied.sum():,.2f} | split total {split.sum():,.2f}")assert np.isclose(split.sum(), weekly.sum()) copied split2024-01-01 3461.65 494.522024-01-02 3461.65 494.522024-01-03 3461.65 494.52weekly total 15,396.91copied total 107,778.37 | split total 15,396.91How it works:
reindex(days, method="bfill")gives each day the value of the next label at or after it: the Sunday that closes its week. That is the weekly total of the day’s own week. With end-of-week labels, filling backward is what copies a week to its own days;ffillwould copy the previous week.- Copying the weekly total to every day multiplies the budget by 7. Spend is a flow: when you upsample a flow, split it, do not copy it.
- The even split keeps the total exactly. Copying is right for a level, such as a price that holds for the whole week.
Alternative: if you know the real daily pattern (for example more spend on weekdays), split by weights that sum to 1 instead of 1/7 each.
M40-C04 · Decompose daily units with STL
Section titled “M40-C04 · Decompose daily units with STL”Aggregate data/sales.csv to daily units. Decompose the series with STL (period=7, robust=True). Print the weekday effect (mean seasonal component per weekday, Monday first), the peak day, and the strength of the seasonality and of the trend.
Mon -4.1Tue -6.8Wed -4.3Thu -3.7Fri 0.9Sat 11.3Sun 6.8Name: season, dtype: float64peak day: Satseasonal strength 0.26, trend strength 0.45from statsmodels.tsa.seasonal import STL
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])units = ... # TODO: daily units as float with a daily frequency# TODO: STL, weekday effect and strengthsHint 1
sales.groupby("order_date")["quantity"].sum().asfreq("D").astype(float) gives the series.
Hint 2
Strength of seasonality: max(0, 1 - resid.var() / (seasonal + resid).var()). Use trend instead of seasonal for the trend strength.
Solution
from statsmodels.tsa.seasonal import STL
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])units = sales.groupby("order_date")["quantity"].sum().asfreq("D").astype(float)stl = STL(units, period=7, robust=True).fit()effect = stl.seasonal.groupby(units.index.day_of_week).mean()effect.index = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]f_s = max(0, 1 - stl.resid.var() / (stl.seasonal + stl.resid).var())f_t = max(0, 1 - stl.resid.var() / (stl.trend + stl.resid).var())print(effect.round(1))print("peak day:", effect.idxmax())print(f"seasonal strength {f_s:.2f}, trend strength {f_t:.2f}")assert effect.idxmax() == "Sat"assert abs(effect.sum()) < 1Mon -4.1Tue -6.8Wed -4.3Thu -3.7Fri 0.9Sat 11.3Sun 6.8Name: season, dtype: float64peak day: Satseasonal strength 0.26, trend strength 0.45How it works:
- The seasonal component of an additive decomposition sums to about 0 over a week, so the weekday effects are “units above or below the trend”.
- Saturday is the peak, as the data dictionary says for revenue; units follow the same weekly shape.
- The seasonal strength of daily units (0.26) is higher than for the visits in the lesson (0.18): the weekly pattern explains a larger part of the day-to-day movement of sales. The trend is still the stronger part.
Alternative: seasonal_decompose(units, period=7) gives similar weekday effects, but its trend has 3 NaN values at each end and the spikes of Black Friday leak into the seasonal pattern.
M40-C05 · Multiplicative seasonal factors
Section titled “M40-C05 · Multiplicative seasonal factors”Interpret a result: decompose y with seasonal_decompose(y, model="multiplicative", period=7). Print the seasonal factor of each weekday (Monday first) and a sentence that says by how many percent Saturday is below the trend.
Mon 1.089Tue 1.106Wed 1.067Thu 1.024Fri 0.946Sat 0.849Sun 0.917Name: seasonal, dtype: float64Saturday is 15.1% below the trendtrend NaN at each end: 3from statsmodels.tsa.seasonal import seasonal_decompose
result = ... # TODO: multiplicative decomposition with period 7# TODO: seasonal factor per weekday; Saturday in percentHint 1
In a multiplicative decomposition, the seasonal part is a factor around 1. A factor of 0.9 means 10% below the trend.
Hint 2
The factor is the same every week, so result.seasonal.groupby(y.index.day_of_week).first() reads it.
Solution
from statsmodels.tsa.seasonal import seasonal_decompose
result = seasonal_decompose(y, model="multiplicative", period=7)factors = result.seasonal.groupby(y.index.day_of_week).first()factors.index = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]print(factors.round(3))print(f"Saturday is {100 * (1 - factors['Sat']):.1f}% below the trend")print("trend NaN at each end:", result.trend.isna().sum() // 2)assert np.isclose(factors.mean(), 1, atol=1e-6)Mon 1.089Tue 1.106Wed 1.067Thu 1.024Fri 0.946Sat 0.849Sun 0.917Name: seasonal, dtype: float64Saturday is 15.1% below the trendtrend NaN at each end: 3How it works:
- The factors average 1 over a week. Tuesday is the busiest day and Saturday the quietest.
- A multiplicative factor reads as a percentage of the trend, so it stays valid as the traffic grows. An additive effect of “−700 visits” would be too small in 2024 and too large in 2022.
- The centered moving average of the trend needs 3 days on each side, so the trend is
NaNfor 3 days at each end. STL has no such gap.
Alternative: STL on np.log(y) gives a log-scale seasonal component; np.exp of it gives factors close to these.
M40-C06 · Fix the bug: a leaky rolling feature
Section titled “M40-C06 · Fix the bug: a leaky rolling feature”Fix the bug: this one-step model of the visits has a near-perfect error on the validation window 2024-11-06 to 2024-12-03. Find the leak, fix it, and print the MAE before and after.
from sklearn.linear_model import LinearRegression
X = pd.DataFrame({f"lag_{k}": y.shift(k) for k in range(1, 7)})X["mean_7"] = y.rolling(7).mean()X = X.dropna()fit = X.index <= "2024-11-05"valid = (X.index >= "2024-11-06") & (X.index <= "2024-12-03")model = LinearRegression().fit(X[fit], y[X.index][fit])print(np.mean(np.abs(y[X.index][valid] - model.predict(X[valid]))))leaky MAE 0.00fixed MAE 545.33from sklearn.linear_model import LinearRegression
def one_step_mae(mean_7: pd.Series) -> float: X = pd.DataFrame({f"lag_{k}": y.shift(k) for k in range(1, 7)}) X["mean_7"] = mean_7 # TODO: drop NaN rows, fit on days up to 2024-11-05, score 2024-11-06 to 2024-12-03 ...
# TODO: print the MAE with y.rolling(7).mean() and with the fixed featureHint 1
Which days does y.rolling(7).mean() average on day t? Is day t among them?
Hint 2
7 × mean_7 − (lag_1 + … + lag_6) is exactly y on day t. A linear model finds that formula.
Solution
from sklearn.linear_model import LinearRegression
def one_step_mae(mean_7: pd.Series) -> float: X = pd.DataFrame({f"lag_{k}": y.shift(k) for k in range(1, 7)}) X["mean_7"] = mean_7 X = X.dropna() target = y.loc[X.index] fit = X.index <= "2024-11-05" valid = (X.index >= "2024-11-06") & (X.index <= "2024-12-03") model = LinearRegression().fit(X[fit], target[fit]) return float(np.mean(np.abs(target[valid] - model.predict(X[valid]))))
leaky = one_step_mae(y.rolling(7).mean())fixed = one_step_mae(y.shift(1).rolling(7).mean())print(f"leaky MAE {leaky:.2f}")print(f"fixed MAE {fixed:.2f}")assert leaky < 1 < fixedleaky MAE 0.00fixed MAE 545.33How it works:
y.rolling(7).mean()on daytaverages dayst − 6tot, so it contains the target.- With the six lags in the table, the model can rebuild the target exactly:
y_t = 7 × mean_7 − (lag_1 + … + lag_6). The “error” is only floating-point noise. y.shift(1).rolling(7).mean()averages dayst − 7tot − 1. The MAE becomes a real one-step error of a few hundred visits.
Alternative: check every feature with a “future test”: change the target of one day and recompute the features. If a feature of that same day changes, it leaks.
M40-C07 · A reusable lag feature builder
Section titled “M40-C07 · A reusable lag feature builder”Write a function make_lag_features(series, lags, windows, min_shift) that returns a DataFrame with one column lag_k per lag, one column roll_mean_w per window (the mean of w days, shifted by min_shift), and day_of_week. It must raise a ValueError if a lag is smaller than min_shift. Build features for y with lags 7 and 14, window 7 and min_shift=7. Print the row for 2024-01-15 and the number of complete rows.
lag_7 5638.0lag_14 4830.0roll_mean_7 4789.9day_of_week 0.0Name: 2024-01-15 00:00:00, dtype: float64complete rows: 1082 of 1096error: lag 1 is smaller than min_shift=7def make_lag_features(series: pd.Series, lags: list[int], windows: list[int], min_shift: int) -> pd.DataFrame: # TODO: validate lags, build lag, rolling and calendar columns ...Hint 1
series.shift(min_shift).rolling(w).mean() is a rolling mean that ends min_shift days before each row.
Hint 2
Check min(lags) < min_shift before you build anything, and raise with a clear message.
Solution
def make_lag_features(series: pd.Series, lags: list[int], windows: list[int], min_shift: int) -> pd.DataFrame: """Lag, rolling-mean and weekday features that use only values >= min_shift old.""" if min(lags) < min_shift: raise ValueError(f"lag {min(lags)} is smaller than min_shift={min_shift}") X = pd.DataFrame(index=series.index) for k in lags: X[f"lag_{k}"] = series.shift(k) for w in windows: X[f"roll_mean_{w}"] = series.shift(min_shift).rolling(w).mean() X["day_of_week"] = series.index.day_of_week return X
X = make_lag_features(y, lags=[7, 14], windows=[7], min_shift=7)print(X.loc["2024-01-15"].round(1))print("complete rows:", len(X.dropna()), "of", len(X))assert X.loc["2024-01-15", "lag_7"] == y.loc["2024-01-08"]try: make_lag_features(y, lags=[1, 7], windows=[7], min_shift=7)except ValueError as err: print("error:", err)lag_7 5638.0lag_14 4830.0roll_mean_7 4789.9day_of_week 0.0Name: 2024-01-15 00:00:00, dtype: float64complete rows: 1082 of 1096error: lag 1 is smaller than min_shift=7How it works:
- Each lag is a
shiftbykdays; the assert checks one value by hand. - The rolling mean is shifted by
min_shiftfirst, so the newest day it uses ismin_shiftdays old, like the lags. lag_14needs 14 earlier days and the rolling mean 7 + 6 = 13, so the first 14 rows are incomplete.- The
ValueErrorturns a silent leak (a lag shorter than the horizon) into a loud error.
Alternative: scikit-learn has no lag transformer, but skforecast and sktime are libraries built around this pattern. Writing the function yourself first shows exactly what they do.
M40-C08 · Is daily demand stationary?
Section titled “M40-C08 · Is daily demand stationary?”Interpret a result: aggregate data/sales.csv to daily units. Run the ADF test with regression="c", with regression="ct" and on the first difference. Print one line per test and write down what you conclude. Compare with the visits of the lesson.
level, c p=0.346level, ct p=0.175first diff, c p=1.03e-25from statsmodels.tsa.stattools import adfuller
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])units = ... # TODO: daily units, float, daily frequency# TODO: three ADF tests, one line eachHint 1
Loop over [("level, c", units, "c"), ("level, ct", units, "ct"), ("diff, c", units.diff().dropna(), "c")].
Hint 2
A p-value below 0.05 rejects the unit root.
Solution
from statsmodels.tsa.stattools import adfuller
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])units = sales.groupby("order_date")["quantity"].sum().asfreq("D").astype(float)tests = [("level, c", units, "c"), ("level, ct", units, "ct"), ("first diff, c", units.diff().dropna(), "c")]pvalues = {}for name, series, regression in tests: res = adfuller(series, regression=regression, result_object=True) pvalues[name] = res.pvalue print(f"{name:<14} p={res.pvalue:.3g}")assert pvalues["level, ct"] > 0.05 > pvalues["first diff, c"]level, c p=0.346level, ct p=0.175first diff, c p=1.03e-25How it works:
- Level with a constant: p is well above 0.05, so no evidence of stationarity.
- Level with a trend: still above 0.05. Unlike the visits, daily units are not stationary around a straight trend: the November–December peaks and the promo days move the mean in a way a line does not capture.
- The first difference is clearly stationary. So
d = 1is the natural choice for an ARIMA model of daily units.
Alternative: the yearly peak suggests a seasonal effect with period 365, which daily SARIMA handles badly (the seasonal lag is too long). Calendar features in a gradient boosting model, or a log plus a yearly Fourier term as exogenous input, handle it better.
M40-C09 · Identify the AR order from the PACF
Section titled “M40-C09 · Identify the AR order from the PACF”Choose a method and justify it: simulate 1,000 values of an AR(2) process with ArmaProcess and rng = np.random.default_rng(42). Print the ACF and PACF at lags 1 to 5 and the 95% band. Which plot tells you the order, and what is it?
acf pacf1 0.807 0.8082 0.703 0.1493 0.602 -0.0054 0.512 -0.0165 0.433 -0.009band: +/-0.062PACF lags outside the band before the first one inside: 2from statsmodels.tsa.arima_process import ArmaProcessfrom statsmodels.tsa.stattools import acf, pacf
rng = np.random.default_rng(42)process = ArmaProcess(ar=[1, -0.6, -0.25]) # note the signs# TODO: generate 1,000 values, print ACF and PACF for lags 1-5 and the bandHint 1
process.generate_sample(nsample=1000, distrvs=rng.standard_normal) draws the sample with your generator.
Hint 2
The band is about 1.96 / np.sqrt(n). Count the PACF lags outside it.
Solution
from statsmodels.tsa.arima_process import ArmaProcessfrom statsmodels.tsa.stattools import acf, pacf
rng = np.random.default_rng(42)process = ArmaProcess(ar=[1, -0.6, -0.25]) # 1 - 0.6 L - 0.25 L^2sample = process.generate_sample(nsample=1000, distrvs=rng.standard_normal)band = 1.96 / np.sqrt(len(sample))table = pd.DataFrame( {"acf": acf(sample, nlags=5)[1:], "pacf": pacf(sample, nlags=5)[1:]}, index=range(1, 6),)print(table.round(3))print(f"band: +/-{band:.3f}")order = int((np.abs(table["pacf"]) > band).to_numpy().argmin())print("PACF lags outside the band before the first one inside:", order)assert order == 2 acf pacf1 0.807 0.8082 0.703 0.1493 0.602 -0.0054 0.512 -0.0165 0.433 -0.009band: +/-0.062PACF lags outside the band before the first one inside: 2How it works:
ArmaProcesstakes the coefficients of the lag polynomial, so an AR coefficient of +0.6 is written −0.6.- The ACF decays slowly (0.81, 0.70, 0.60…): every AR process has a decaying ACF, so it cannot tell you the order.
- The PACF is outside the band at lags 1 and 2 and inside from lag 3 on. A PACF that cuts off after lag
pis the signature of AR(p). The order is 2.
Alternative: fit AR models of order 1, 2 and 3 and compare the AIC:
from statsmodels.tsa.statespace.sarimax import SARIMAX
for p in [1, 2, 3]: res = SARIMAX(sample, order=(p, 0, 0)).fit(disp=False) print(f"AR({p}) AIC {res.aic:.1f}")AR(1) AIC 2833.8AR(2) AIC 2812.9AR(3) AIC 2814.9AR(2) has the lowest AIC on this sample, which confirms the PACF reading.
M40-C10 · SARIMA for hourly sensor data
Section titled “M40-C10 · SARIMA for hourly sensor data”Forecast the last day (24 hours) of the hourly mean temperature of sensor S1 from the 13 days before it. Compare a seasonal naive forecast (period 24) with SARIMAX(order=(1, 0, 0), seasonal_order=(0, 1, 1, 24)). Print the MAE of both and the fitted parameters.
seasonal naive MAE 0.425 °CSARIMA MAE 0.217 °C{'ar.L1': 0.173, 'ma.S.L24': -0.988, 'sigma2': 0.211}from statsmodels.tsa.statespace.sarimax import SARIMAX
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])hourly = ... # TODO: hourly mean temperature of S1train, last_day = hourly.iloc[:-24], hourly.iloc[-24:]# TODO: seasonal naive (24) and SARIMA, MAE of bothHint 1
The seasonal naive forecast of the last day is train.iloc[-24:]: the day before.
Hint 2
SARIMAX(...).fit(disp=False, maxiter=200) fits silently; forecast(24) predicts the next 24 hours.
Solution
from statsmodels.tsa.statespace.sarimax import SARIMAX
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])s1 = sensors[sensors["sensor_id"] == "S1"].set_index("timestamp")["temperature_c"]hourly = s1.resample("h").mean()train, last_day = hourly.iloc[:-24], hourly.iloc[-24:]snaive = train.iloc[-24:].to_numpy()res = SARIMAX(train, order=(1, 0, 0), seasonal_order=(0, 1, 1, 24)).fit( disp=False, maxiter=200)sarima = res.forecast(24)print(f"seasonal naive MAE {np.mean(np.abs(last_day - snaive)):.3f} °C")print(f"SARIMA MAE {np.mean(np.abs(last_day - sarima)):.3f} °C")print(res.params.round(3).to_dict())assert res.mle_retvals["converged"]assert len(train) == 13 * 24seasonal naive MAE 0.425 °CSARIMA MAE 0.217 °C{'ar.L1': 0.173, 'ma.S.L24': -0.988, 'sigma2': 0.211}How it works:
resample("h").mean()turns 6 readings into one hourly value; the series has a daily cycle, so the seasonal period is 24.- The seasonal naive forecast copies yesterday hour by hour. It also copies yesterday’s random noise.
- SARIMA with a seasonal difference and a seasonal MA term learns an average daily shape, which is smoother. It halves the error.
ma.S.L24close to −1 says the daily shape is almost fixed, as for the weekly shape of the visits.
Alternative: a seasonal mean baseline, the mean of the same hour over the last 7 days, is also smoother than the plain seasonal naive forecast and often close to SARIMA.
M40-C11 · TimeSeriesSplit with a gap and a sliding window
Section titled “M40-C11 · TimeSeriesSplit with a gap and a sliding window”The daily visits arrive with a delay of 7 days, so a model trained today cannot use the last week. Build TimeSeriesSplit(n_splits=4, test_size=28, gap=7, max_train_size=365) on the days of 2024 before the holdout (2024-01-01 to 2024-12-03). Print the train and test dates of each fold and check the gap.
fold 1: train 2024-01-01..2024-08-06 (219) | test 2024-08-14..2024-09-10 | gap 7fold 2: train 2024-01-01..2024-09-03 (247) | test 2024-09-11..2024-10-08 | gap 7fold 3: train 2024-01-01..2024-10-01 (275) | test 2024-10-09..2024-11-05 | gap 7fold 4: train 2024-01-01..2024-10-29 (303) | test 2024-11-06..2024-12-03 | gap 7from sklearn.model_selection import TimeSeriesSplit
days = y.loc["2024-01-01":"2024-12-03"]tscv = ... # TODO# TODO: print train start/end and test start/end per foldHint 1
tscv.split(days) yields integer positions. Use days.index[positions] to read the dates.
Hint 2
The gap is the number of days between the last training day and the first test day, minus 1.
Solution
from sklearn.model_selection import TimeSeriesSplit
days = y.loc["2024-01-01":"2024-12-03"]tscv = TimeSeriesSplit(n_splits=4, test_size=28, gap=7, max_train_size=365)for k, (tr, te) in enumerate(tscv.split(days), start=1): tr_dates, te_dates = days.index[tr], days.index[te] gap_days = (te_dates[0] - tr_dates[-1]).days - 1 print(f"fold {k}: train {tr_dates[0].date()}..{tr_dates[-1].date()} ({len(tr)})" f" | test {te_dates[0].date()}..{te_dates[-1].date()} | gap {gap_days}") assert gap_days == 7 and len(te) == 28 and len(tr) <= 365fold 1: train 2024-01-01..2024-08-06 (219) | test 2024-08-14..2024-09-10 | gap 7fold 2: train 2024-01-01..2024-09-03 (247) | test 2024-09-11..2024-10-08 | gap 7fold 3: train 2024-01-01..2024-10-01 (275) | test 2024-10-09..2024-11-05 | gap 7fold 4: train 2024-01-01..2024-10-29 (303) | test 2024-11-06..2024-12-03 | gap 7How it works:
test_size=28makes 4 test windows of 28 days at the end of the range.gap=7drops the 7 days before each test window from the training set, as in real use with a one-week delay.max_train_size=365would cap the training set at one year (a sliding window). The 2024 data before the holdout is shorter than that, so here every training set still starts on 2024-01-01 and the window expands.
Alternative: run the same splitter on all of y before the holdout. Then the cap matters: from the fold where more than 365 days are available, the training start moves forward with every fold.
M40-C12 · When MAPE breaks, use MASE
Section titled “M40-C12 · When MAPE breaks, use MASE”Daily units of product P001 have many zero days. Split the 2023–2024 series (zeros filled) into a fit part and the last 28 days. Forecast the 28 days with the seasonal naive method. Print the number of zero days in the window, MAPE over the non-zero days only, sMAPE over all days, and MASE (period 7).
zero days in the window: 1MAPE on non-zero days 182.2% | sMAPE 76.0%MAE 5.71 | MASE 3.38sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])days = pd.date_range("2023-01-01", "2024-12-31", freq="D")units = ... # TODO: daily units of P001, zeros filled# TODO: seasonal naive forecast of the last 28 days; MAPE (non-zero days), sMAPE, MASEHint 1
MAPE divides by the actual value. Mask the days where the actual value is 0 before you divide.
Hint 2
In sMAPE, a day where actual and forecast are both 0 divides 0 by 0. Count such a day as 0 error.
Solution
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])days = pd.date_range("2023-01-01", "2024-12-31", freq="D")units = (sales[sales["product_id"] == "P001"].groupby("order_date")["quantity"].sum() .reindex(days, fill_value=0).astype(float))fit, actual = units.iloc[:-28], units.iloc[-28:].to_numpy()forecast = np.resize(fit.iloc[-7:].to_numpy(), 28)errors = np.abs(actual - forecast)nonzero = actual != 0mape_nz = 100 * np.mean(errors[nonzero] / actual[nonzero])denominator = np.abs(actual) + np.abs(forecast)smape_terms = np.divide( 2 * errors, denominator, out=np.zeros(28), where=denominator > 0)scale = np.mean(np.abs(fit.to_numpy()[7:] - fit.to_numpy()[:-7]))print("zero days in the window:", int((~nonzero).sum()))print(f"MAPE on non-zero days {mape_nz:.1f}% | sMAPE {100 * smape_terms.mean():.1f}%")print(f"MAE {errors.mean():.2f} | MASE {errors.mean() / scale:.2f}")assert (~nonzero).sum() > 0zero days in the window: 1MAPE on non-zero days 182.2% | sMAPE 76.0%MAE 5.71 | MASE 3.38How it works:
- MAPE is undefined on zero days, so it must skip them. It silently ignores the days where the forecast is wrong because nothing sold.
- MAPE is 182%: on a day with 1 unit sold, an error of 3 units counts as 300%. Small actual values dominate it.
np.divide(..., where=denominator > 0)computes sMAPE without a division by zero; a day with 0 actual and 0 forecast counts as a perfect forecast. sMAPE divides by the mean of actual and forecast, so it is lower, but a day where one side is 0 still scores the maximum of 200%.- MASE stays well defined. A MASE of 3.38 is a clear warning: the last week before the window holds Black Friday and Cyber Monday, so the seasonal naive forecast copies a promo week into December.
Alternative: for intermittent demand, report the MAE in units next to MASE, and consider a forecast of the weekly total instead of daily values.
M40-C13 · Refactor a loop into shift and rolling
Section titled “M40-C13 · Refactor a loop into shift and rolling”Refactor: this loop computes, for every day of 2024, the seasonal naive error (today minus the same weekday last week) and the trailing 28-day mean of the absolute error. Rewrite it with shift, abs and rolling in three lines, and check that both versions agree.
errors, smooth = {}, {}dates = list(y.index)for i, day in enumerate(dates): if i >= 7: errors[day] = abs(y.iloc[i] - y.iloc[i - 7]) if i >= 7 + 27: window = [errors[dates[j]] for j in range(i - 27, i + 1)] smooth[day] = sum(window) / 28loop_result = pd.Series(smooth).loc["2024"]count 366.0mean 675.4std 720.4min 217.825% 286.150% 363.775% 508.5max 2872.9Name: visits, dtype: float64# TODO: abs_error = ...# TODO: rolling_mae = ...# TODO: compare with the loop result for 2024Hint 1
y - y.shift(7) is the seasonal naive error of every day in one expression.
Hint 2
.rolling(28).mean() averages the last 28 values, including the current one, like the loop.
Solution
errors, smooth = {}, {}dates = list(y.index)for i, day in enumerate(dates): if i >= 7: errors[day] = abs(y.iloc[i] - y.iloc[i - 7]) if i >= 7 + 27: window = [errors[dates[j]] for j in range(i - 27, i + 1)] smooth[day] = sum(window) / 28loop_result = pd.Series(smooth).loc["2024"]
abs_error = (y - y.shift(7)).abs()rolling_mae = abs_error.rolling(28).mean()vector_result = rolling_mae.loc["2024"]print(vector_result.describe().round(1))assert np.allclose(loop_result, vector_result)count 366.0mean 675.4std 720.4min 217.825% 286.150% 363.775% 508.5max 2872.9Name: visits, dtype: float64How it works:
y.shift(7)aligns every day with the same weekday a week earlier, soy - y.shift(7)is the full error series. The first 7 days areNaN, like the skipped indexes of the loop.rolling(28).mean()replaces the inner list comprehension. It needs 28 errors, so the first value appears at position 34, as in the loop.- The vectorized version is shorter, uses the dates directly and runs in compiled code.
np.allcloseproves that both give the same 366 values.
Alternative: y.diff(7).abs().rolling(28).mean() is the same computation in one line. A rolling MAE like this is a good monitoring metric for a deployed forecast.
Challenge
Section titled “Challenge”M40-X01 · Recursive vs direct forecasting
Section titled “M40-X01 · Recursive vs direct forecasting”On the validation window of the lesson (origin 2024-11-05, forecast 2024-11-06 to 2024-12-03), compare two LightGBM strategies on np.log(y):
- Direct: features
lag_28,lag_35,lag_42,day_of_week. - Recursive: a one-step model with
lag_1tolag_7andday_of_week, applied 28 times, each prediction fed back as the next lag.
Use LGBMRegressor(n_estimators=200, learning_rate=0.05, n_jobs=1, random_state=42, verbose=-1) for both. Print the MAE of each strategy in visits.
direct MAE 1173.2recursive MAE 1486.7from lightgbm import LGBMRegressor
log_y = np.log(y)origin = pd.Timestamp("2024-11-05")window = pd.date_range(origin + pd.Timedelta(days=1), periods=28, freq="D")
def features(series: pd.Series, lags: list[int]) -> pd.DataFrame: # TODO: lag columns and day_of_week ...
# TODO: direct model: fit on rows up to the origin, predict the window# TODO: recursive model: fit on lags 1-7, then loop over the windowHint 1
For the recursive loop, keep a copy of the log series up to the origin. For each new day, build its feature row from the copy, predict, and append the prediction to the copy.
Hint 2
history.loc[day] = prediction adds a new date to a Series with a DatetimeIndex. Build the next feature row from history again.
Hint 3
Score both strategies on np.exp of the predictions against y.loc[window].
Solution
from lightgbm import LGBMRegressor
log_y = np.log(y)origin = pd.Timestamp("2024-11-05")window = pd.date_range(origin + pd.Timedelta(days=1), periods=28, freq="D")params = dict( n_estimators=200, learning_rate=0.05, n_jobs=1, random_state=42, verbose=-1)
def features(series: pd.Series, lags: list[int]) -> pd.DataFrame: X = pd.DataFrame({f"lag_{k}": series.shift(k) for k in lags}, index=series.index) X["day_of_week"] = series.index.day_of_week return X
# Direct: every lag >= 28, one prediction for the whole windowdirect_X = features(log_y, [28, 35, 42])fit_rows = direct_X.loc[:origin].dropna()direct = LGBMRegressor(**params).fit(fit_rows, log_y.loc[fit_rows.index])direct_fc = np.exp(direct.predict(direct_X.loc[window]))
# Recursive: one-step model, predictions fed back as lagsstep_X = features(log_y.loc[:origin], list(range(1, 8))).dropna()one_step = LGBMRegressor(**params).fit(step_X, log_y.loc[step_X.index])history = log_y.loc[:origin].copy()for day in window: history.loc[day] = np.nan row = features(history, list(range(1, 8))).loc[[day]] history.loc[day] = one_step.predict(row)[0]recursive_fc = np.exp(history.loc[window])
actual = y.loc[window]print(f"direct MAE {np.mean(np.abs(actual - direct_fc)):.1f}")print(f"recursive MAE {np.mean(np.abs(actual - recursive_fc)):.1f}")assert history.index[-1] == window[-1]assert log_y.loc[window].index.equals(window) # actual values used only for scoringdirect MAE 1173.2recursive MAE 1486.7How it works:
- The direct model sees values from 28 or more days back, so it can predict all 28 days at once with no loop.
- The recursive model is trained to predict one day ahead from the last 7 days. To go further, the loop writes each prediction into
historyand builds the next row from it, so from day 2 on, the lags are predictions, not data. - The actual values of the window are used only in the last two lines, to score. A recursive loop that reads
log_yinstead ofhistoryinside the window would leak. - On this window the direct model wins. Neither strategy is better in general: the recursive model reacts to the latest level, but its errors pile up over 28 steps.
Alternative: a third strategy trains one direct model per horizon step (h = 1, …, 28), each with lags of at least h. It uses the freshest data for every step, at the cost of 28 models.
M40-X02 · Add the marketing budget as an exogenous variable
Section titled “M40-X02 · Add the marketing budget as an exogenous variable”The campaign of 2024-09-16 ruins every forecast that does not know about it. The marketing team plans the budget in advance, so the daily marketing_spend is known for the next 28 days. Forecast 2024-09-11 to 2024-10-08 (origin 2024-09-10) with SARIMA (1, 1, 1)(0, 1, 1, 7) on np.log(y), without and with np.log(marketing_spend) as exog. Print the MAE of both and the coefficient of the spend.
SARIMA MAE 1513.9SARIMAX + spend MAE 862.2spend coefficient 0.224from statsmodels.tsa.statespace.sarimax import SARIMAX
origin = pd.Timestamp("2024-09-10")window = pd.date_range(origin + pd.Timedelta(days=1), periods=28, freq="D")log_spend = np.log(traffic["marketing_spend"])# TODO: fit without exog, forecast 28 days# TODO: fit with exog=log_spend up to the origin, forecast with the planned spendHint 1
Pass exog=log_spend.loc[:origin] to SARIMAX, and exog=log_spend.loc[window] to forecast.
Hint 2
Both series in the model must cover the same dates: slice np.log(y).loc[:origin] and log_spend.loc[:origin].
Solution
from statsmodels.tsa.statespace.sarimax import SARIMAX
origin = pd.Timestamp("2024-09-10")window = pd.date_range(origin + pd.Timedelta(days=1), periods=28, freq="D")log_spend = np.log(traffic["marketing_spend"])history = np.log(y.loc[:origin])spec = dict(order=(1, 1, 1), seasonal_order=(0, 1, 1, 7))
plain = SARIMAX(history, **spec).fit(disp=False, maxiter=200)with_spend = SARIMAX(history, exog=log_spend.loc[:origin], **spec).fit( disp=False, maxiter=200)plain_fc = np.exp(plain.forecast(28))spend_fc = np.exp(with_spend.forecast(28, exog=log_spend.loc[window]))actual = y.loc[window]print(f"SARIMA MAE {np.mean(np.abs(actual - plain_fc)):7.1f}")print(f"SARIMAX + spend MAE {np.mean(np.abs(actual - spend_fc)):7.1f}")print(f"spend coefficient {with_spend.params['marketing_spend']:.3f}")assert plain.mle_retvals["converged"] and with_spend.mle_retvals["converged"]SARIMA MAE 1513.9SARIMAX + spend MAE 862.2spend coefficient 0.224How it works:
exogadds a regression on the spend to the SARIMA model: on log scales, the coefficient is an elasticity. A coefficient of about 0.22 means that 10% more spend goes with about 2.2% more visits on the same day.- The forecast needs the future values of
exog. That is legitimate only because the budget is planned. A variable that you only learn after the fact (for example the bounce rate) cannot be an exogenous input for a forecast. - The spend explains most of the campaign jump, so the error falls by about 40%. The decay over the following days is only partly captured, because the model links visits to same-day spend only.
Alternative: add log_spend.shift(1) and shift(2) as extra exogenous columns to model the decay, or give the same features to the gradient boosting model of the lesson.
M40-X03 · Choose a feature set by backtest
Section titled “M40-X03 · Choose a feature set by backtest”The lesson’s gradient boosting model uses lag_28, lag_35, lag_42, roll_mean_28, day_of_week and month on np.log(y). A colleague proposes to add lag_364 (same weekday last year) and day_of_year. Decide with a backtest, not with the holdout: use TimeSeriesSplit(n_splits=5, test_size=28) on the days before the holdout. Print the MAE per fold of both feature sets, their means, and your choice.
base base + yearlyfold1 275.0 341.02 271.0 306.03 1538.0 1605.04 332.0 350.05 1087.0 905.0base 700.4base + yearly 701.5dtype: float64choice: basefrom lightgbm import LGBMRegressorfrom sklearn.model_selection import TimeSeriesSplit
log_y = np.log(y)train = y.iloc[:-28] # the last 28 days stay locked# TODO: build both feature tables# TODO: for each fold, fit both models on the fold's training rows, score the test rowsHint 1
Build one table with all columns, then select base_cols or base_cols + extra_cols inside the loop.
Hint 2
dropna() on the training rows of each feature set separately: lag_364 removes the first year, so the extended set has fewer training rows.
Solution
from lightgbm import LGBMRegressorfrom sklearn.model_selection import TimeSeriesSplit
log_y = np.log(y)train = y.iloc[:-28] # the last 28 days stay lockedX = pd.DataFrame(index=y.index)for lag in [28, 35, 42, 364]: X[f"lag_{lag}"] = log_y.shift(lag)X["roll_mean_28"] = log_y.shift(28).rolling(28).mean()X["day_of_week"] = y.index.day_of_weekX["month"] = y.index.monthX["day_of_year"] = y.index.day_of_yearsets = { "base": ["lag_28", "lag_35", "lag_42", "roll_mean_28", "day_of_week", "month"],}sets["base + yearly"] = sets["base"] + ["lag_364", "day_of_year"]
scores = {name: [] for name in sets}for tr, te in TimeSeriesSplit(n_splits=5, test_size=28).split(train): fold_train, fold_test = train.index[tr], train.index[te] for name, cols in sets.items(): rows = X.loc[fold_train, cols].dropna() model = LGBMRegressor(n_estimators=200, learning_rate=0.05, n_jobs=1, random_state=42, verbose=-1) model.fit(rows, log_y.loc[rows.index]) pred = np.exp(model.predict(X.loc[fold_test, cols])) scores[name].append(np.mean(np.abs(y.loc[fold_test] - pred)))table = pd.DataFrame(scores, index=range(1, 6)).rename_axis("fold")print(table.round(0))print(table.mean().round(1))print("choice:", table.mean().idxmin())assert set(table.columns) == set(sets) base base + yearlyfold1 275.0 341.02 271.0 306.03 1538.0 1605.04 332.0 350.05 1087.0 905.0base 700.4base + yearly 701.5dtype: float64choice: baseHow it works:
- Both feature sets are scored on the same five 28-day windows, all before the holdout. The holdout plays no part in the choice.
- The yearly features cost the first 364 days of training rows, because
lag_364isNaNthere. - The means differ by about 1 visit, and the folds disagree: the yearly features help in fold 5 and hurt in the other four. When the difference is this small, prefer the simpler set: the base set wins the mean and has fewer features.
Alternative: compare the sets on MASE as well, or on the median fold error, which the campaign fold does not dominate.
M40-X04 · Hourly forecasts for every sensor
Section titled “M40-X04 · Hourly forecasts for every sensor”Repeat the hourly forecast of M40-C10 for all four sensors: hourly mean temperature, the last 24 hours as the test day, seasonal naive (period 24) vs SARIMA (1, 0, 0)(0, 1, 1, 24). Print a table of MAE per sensor and model, and the sensor with the largest SARIMA error.
seasonal naive SARIMAsensorS1 0.425 0.217S2 0.424 0.325S3 0.597 1.614S4 0.245 0.191hardest sensor for SARIMA: S3from statsmodels.tsa.statespace.sarimax import SARIMAX
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])hourly = ... # TODO: pivot to one column per sensor, then hourly means# TODO: loop over the sensors, fit, forecast, scoreHint 1
sensors.pivot(index="timestamp", columns="sensor_id", values="temperature_c").resample("h").mean() gives a 336 × 4 table.
Hint 2
Collect one dictionary per sensor in a list, then build a DataFrame from the list.
Solution
from statsmodels.tsa.statespace.sarimax import SARIMAX
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])hourly = sensors.pivot( index="timestamp", columns="sensor_id", values="temperature_c").resample("h").mean()rows = []for sensor in hourly.columns: series = hourly[sensor] train, test = series.iloc[:-24], series.iloc[-24:] res = SARIMAX(train, order=(1, 0, 0), seasonal_order=(0, 1, 1, 24)).fit( disp=False, maxiter=200 ) assert res.mle_retvals["converged"], sensor snaive = train.iloc[-24:].to_numpy() rows.append({ "sensor": sensor, "seasonal naive": np.mean(np.abs(test.to_numpy() - snaive)), "SARIMA": np.mean(np.abs(test - res.forecast(24))), })table = pd.DataFrame(rows).set_index("sensor")print(table.round(3))print("hardest sensor for SARIMA:", table["SARIMA"].idxmax())assert hourly.isna().sum().sum() == 0 seasonal naive SARIMAsensorS1 0.425 0.217S2 0.424 0.325S3 0.597 1.614S4 0.245 0.191hardest sensor for SARIMA: S3How it works:
- The pivot and the hourly resample give one clean series per sensor; every hour has at least one valid reading, so there are no gaps.
- The same model specification runs for every sensor in a loop, and the assert stops the loop if one fit does not converge.
- SARIMA beats the seasonal naive forecast for S1, S2 and S4, but it is far worse for S3. The data dictionary explains why: S3 drifts up about 0.35 °C a day. A seasonal MA close to −1 makes the forecast an average daily shape at a level from the past, so it is too low. The seasonal naive forecast copies yesterday, which already includes the drift.
- A table like this is how a monitoring team spots the sensor that needs attention.
Alternative: add a constant to the seasonally differenced model with trend="c". The constant is the average change from one day to the next, so it models the drift:
from statsmodels.tsa.statespace.sarimax import SARIMAX
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])s3 = sensors[sensors["sensor_id"] == "S3"].set_index("timestamp")["temperature_c"]hourly = s3.resample("h").mean()train, test = hourly.iloc[:-24], hourly.iloc[-24:]res = SARIMAX(train, order=(1, 0, 0), seasonal_order=(0, 1, 1, 24), trend="c").fit( disp=False, maxiter=200)daily_drift = res.params["intercept"] / (1 - res.params["ar.L1"])print(f"S3 SARIMA with drift MAE {np.mean(np.abs(test - res.forecast(24))):.3f} °C")print(f"estimated drift {daily_drift:.2f} °C per day")S3 SARIMA with drift MAE 0.306 °Cestimated drift 0.35 °C per dayThe error falls from about 1.6 °C to about 0.3 °C. The intercept divided by (1 − ar.L1) is the mean daily change, and it matches the drift that the data dictionary reports.
M40-X05 · Refactor into forecaster classes
Section titled “M40-X05 · Refactor into forecaster classes”Refactor procedural code into classes. This script compares two seasonal forecasters in a backtest. Each method is an if branch inside the loop, so a third method means editing the loop again:
from sklearn.model_selection import TimeSeriesSplit
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])units = sales.groupby("order_date")["quantity"].sum().asfreq("D").astype(float)history = units.iloc[:-28]for method in ["naive", "mean of 4 weeks"]: errors = [] for tr, te in TimeSeriesSplit(n_splits=6, test_size=28).split(history): past = history.iloc[tr] if method == "naive": season = past.iloc[-7:].to_numpy() else: season = past.iloc[-28:].to_numpy().reshape(4, 7).mean(axis=0) pred = np.resize(season, len(te)) errors.append(np.mean(np.abs(history.iloc[te].to_numpy() - pred))) print(method, round(np.mean(errors), 2))Rewrite it as two forecasters with the same interface, fit(history) and predict(steps):
SeasonalNaive(m): repeats the lastmvalues.SeasonalMean(m, k): repeats, for each position in the season, the mean of the lastkseasons.
Write a function backtest(forecaster, series, splitter) that returns the mean MAE. Compare SeasonalNaive(7) with SeasonalMean(7, 4) on the daily units of data/sales.csv, with TimeSeriesSplit(n_splits=6, test_size=28) on the days before the last 28.
SeasonalNaive mean MAE 16.70SeasonalMean mean MAE 15.47from sklearn.model_selection import TimeSeriesSplit
class SeasonalNaive: def __init__(self, m: int) -> None: self.m = m
def fit(self, history: pd.Series) -> "SeasonalNaive": # TODO: store what predict needs return self
def predict(self, steps: int) -> np.ndarray: # TODO ...
# TODO: SeasonalMean, backtest(), and the comparisonHint 1
np.resize(values, steps) repeats a season until it has steps values.
Hint 2
For SeasonalMean, reshape the last m * k values to (k, m) and take the mean over axis 0.
Hint 3
fit returns self, so forecaster.fit(train).predict(28) reads well, like scikit-learn.
Solution
from sklearn.model_selection import TimeSeriesSplit
class SeasonalNaive: """Repeat the last full season."""
def __init__(self, m: int) -> None: self.m = m
def fit(self, history: pd.Series) -> "SeasonalNaive": self.season_ = history.iloc[-self.m:].to_numpy() return self
def predict(self, steps: int) -> np.ndarray: return np.resize(self.season_, steps)
class SeasonalMean(SeasonalNaive): """Repeat the mean of the last k seasons, position by position."""
def __init__(self, m: int, k: int) -> None: super().__init__(m) self.k = k
def fit(self, history: pd.Series) -> "SeasonalMean": last = history.iloc[-self.m * self.k:].to_numpy() self.season_ = last.reshape(self.k, self.m).mean(axis=0) return self
def backtest(forecaster, series: pd.Series, splitter) -> float: """Mean MAE of `forecaster` over the folds of `splitter`.""" errors = [] for tr, te in splitter.split(series): pred = forecaster.fit(series.iloc[tr]).predict(len(te)) errors.append(np.mean(np.abs(series.iloc[te].to_numpy() - pred))) return float(np.mean(errors))
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])units = sales.groupby("order_date")["quantity"].sum().asfreq("D").astype(float)history = units.iloc[:-28] # the last 28 days stay lockedsplitter = TimeSeriesSplit(n_splits=6, test_size=28)for model in [SeasonalNaive(7), SeasonalMean(7, 4)]: score = backtest(model, history, splitter) print(f"{type(model).__name__:<13} mean MAE {score:.2f}")assert np.allclose(SeasonalMean(7, 1).fit(history).predict(7), SeasonalNaive(7).fit(history).predict(7))SeasonalNaive mean MAE 16.70SeasonalMean mean MAE 15.47How it works:
- Both classes share one
predict:SeasonalMeaninherits it and only overridesfit. The trailing underscore inseason_follows the scikit-learn convention for attributes learned infit. backtestaccepts any object withfitandpredict: this is duck typing. A SARIMA or LightGBM wrapper with the same two methods plugs in without changes.- Averaging 4 weeks smooths out one unusual week, such as a promo week, so
SeasonalMeanhas the lower error. - The last assert checks a property: with
k = 1, the seasonal mean must equal the seasonal naive forecast.
Alternative: make the classes inherit from scikit-learn’s BaseEstimator to get get_params and clone for free, as module 34 does for minilearn.