Forecasting demand in Python: autocorrelation, seasonality and an honest error band
TL;DR
Difficulty: Advanced
- A forecast earns trust in three ways: it beats seasonal naive with growth on weeks it never saw, it is scored at the lead time of the decision, and its 80% band catches about 80% of the weeks.
- Build the weeks in the shop's own time zone and the calendar from real dates, in one function used for the past and the future.
- A seasonal dummy regression with AR(1) errors in SARIMAX wins the holdout here, 26 orders a week against 37 for the baseline.
- The AR term's help fades as rho to the power h: at a six week lead time it is gone. It still makes standard errors and the bands of totals honest.
- SARIMAX bands ignore coefficient uncertainty. Add it back, check coverage, and simulate quarter totals.
The Marketing Analytics chapter on forecasting explains the ideas. This one builds them in Python, line by line, on the same invented hamper shop: a weekly series cut in the right time zone, a calendar of seasons and moving holidays, five models raced against a seasonal naive baseline, a score at the lead time the decision needs, and an 80% band that is checked before anyone plans against it.
A demand forecast earns trust in three ways, and the choice of model is not one of them. It beats a dumb seasonal baseline on weeks it has never seen. It is scored at the horizon where the decision is actually made, not the week after the data ends. And its 80% band really does contain about 80% of the weeks. This chapter builds all three in Python, line by line, on the same invented hamper shop as the Marketing Analytics chapter it mirrors, so you can run every block and check every number.
The concepts (autocorrelation, seasonal dummies, the error band, the difference between a forecast and a target) are explained in Forecasting demand: autocorrelation, seasonality and honest error bands. Here I build it in Python. If a term below feels quick, that chapter takes it slowly.
If you only read one section
This part is for the person who commissions a forecast and will never run the code.
- Ask what it beat. Every forecast should be compared with "the same week last year, times growth". If the clever model cannot beat that on weeks it never saw, it has not earned its keep. In this chapter the best model beats it by about 10 orders a week, and a seasonal ARIMA does not beat it at all.
- Ask at which horizon it was scored. If ribbon and boxes have to be ordered six weeks ahead, the only accuracy that matters is the accuracy six weeks ahead. Models that look brilliant one week ahead often lose their edge by then. I show how to measure this, and why the arithmetic says it must happen.
- Ask how often the actuals landed inside the band. An 80% band that catches 50% of the weeks is a confident lie. Here the band caught 19 of 26 weeks, 73%, slightly too narrow, and I show where the missing width comes from and how to add it back.
- Keep the target in a different column. The forecast is what happens if nothing changes. The target is what you want. The gap between them is the job marketing has to do.
If those four answers come back clear, you can plan stock and staff against the band with a calm mind. If they do not, no amount of model sophistication will save the Friday before Christmas.
Where this sits in the programme
This is the eighth chapter of Marketing analytics in Python, and it rebuilds the forecasting chapter of the Marketing Analytics series in code. It leans on two foundation chapters: time series in pandas, which covers weekly periods, ISO weeks, time zones and shifting (read that first), and statistical models in Python with statsmodels and scikit learn, which explains why I use statsmodels when I want standard errors. The charts follow charts in Python for business and the data storytelling chapter on showing time, trends and seasonality.
Two earlier chapters in this series are close relatives. Distributed lags in Python also lets the past leak into the present, through advertising rather than through errors. Panel regression in Python followed many shops through time, and this chapter follows one. The next chapter, on simultaneous equations in Python, deals with marketing and sales that cause each other.
The example is the one from the Marketing Analytics chapter: Northgate Hampers, an invented online hamper shop in Cork run by Priya, with three years of weekly orders and a Christmas peak that once ran the packing room out of ribbon. Every number here is made up so each step can be shown.
What you need, and what changed since the book
I wrote and ran every block with the versions that are current in May 2026: Python 3.14 (released 7 October 2025),1 pandas 3.0.3, NumPy 2.4.4, statsmodels 0.14.6 and matplotlib 3.10.9.
python -m pip install "pandas==3.0.*" "numpy==2.4.*" "statsmodels==0.14.6" "matplotlib==3.10.*"
Two changes matter for this chapter.
pandas 3.0 copies on write. Since 21 January 2026, every indexing step in pandas behaves like a copy, so "chained assignment" such as df["orders"][mask] = values no longer changes df at all.2 The old SettingWithCopyWarning is gone, because the chained form now consistently does nothing. Write df.loc[mask, "orders"] = values instead, which is what the code below does. pandas 3.0 also gives text columns a dedicated string type by default, which you will see in the order export block.
The book's AR class is gone. Wes McKinney's Python for Data Analysis, the reference for this programme, closes its modelling chapter with a quick autoregressive model using sm.tsa.AR.3 That class no longer exists in statsmodels 0.14. Its replacement, AutoReg, arrived in statsmodels 0.11, alongside a new ARIMA class and the STL decomposition I use below.4 For forecasting with calendar regressors I use SARIMAX throughout, because it fits regression and autocorrelated errors in one model and returns prediction intervals.
Build the calendar first, then the data
A forecast of weekly demand is a regression whose drivers are made from the calendar: a trend counter, a column per season, a column per moving holiday, a column per planned event. So the first block builds the weeks, and the second builds the calendar columns. Only then does any data appear.
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from statsmodels.tsa.seasonal import STL
from statsmodels.tsa.stattools import acf, pacf
from statsmodels.stats.stattools import durbin_watson
# 156 weeks, each starting on a Monday: ISO week 1 of 2023 to ISO week 52 of 2025
weeks = pd.date_range("2023-01-02", periods=156, freq="W-MON", name="week_start")
df = pd.DataFrame(index=weeks)
iso = df.index.isocalendar()
df["iso_year"] = iso["year"].to_numpy()
df["iso_week"] = iso["week"].to_numpy()
df["t"] = np.arange(1, len(df) + 1) # the trend counter: 1, 2, 3, ...
freq="W-MON" makes every date a Monday, which matches the ISO week (Monday to Sunday). ISO week 1 of 2023 began on Monday 2 January, and 156 weeks later the data reaches ISO week 52 of 2025, which began on 22 December. The next Monday, 29 December 2025, is already ISO week 1 of 2026, because 1 January 2026 is a Thursday.5
Seasons as dummy columns, holidays from real dates
A dummy variable is a column of zeros with ones in the weeks it describes. Fixed seasons come from the ISO week number. Moving holidays must come from their actual dates, because a holiday that wanders across the calendar smears its effect over two weeks if you tie it to a week number.
MOTHERING = pd.to_datetime(["2023-03-19", "2024-03-10", "2025-03-30", "2026-03-15"])
FATHERS = pd.to_datetime(["2023-06-18", "2024-06-16", "2025-06-15", "2026-06-21"])
def weeks_before(index, holidays, n=2):
"""1 in the n weeks up to and including the week of each holiday, else 0."""
flag = pd.Series(0, index=index)
for day in holidays:
monday = day - pd.Timedelta(days=day.weekday()) # Monday of the holiday's week
start = monday - pd.Timedelta(weeks=n - 1)
flag[(index >= start) & (index <= monday)] = 1
return flag
def calendar(index):
"""The seasons of a hamper shop, as dummy columns (0 or 1)."""
w = pd.Series(index.isocalendar()["week"].to_numpy(), index=index)
cal = pd.DataFrame(index=index)
cal["nov"] = w.between(45, 48).astype(int) # gift buyers start early
cal["early_dec"] = w.between(49, 50).astype(int) # the ramp
cal["w51"] = (w == 51).astype(int) # last order week before Christmas
cal["xmas_ny"] = w.isin([52, 53, 1]).astype(int) # the dead stretch
cal["jan"] = w.between(2, 5).astype(int)
cal["mothering"] = weeks_before(index, MOTHERING)
cal["fathers"] = weeks_before(index, FATHERS)
cal["corporate"] = w.between(36, 39).astype(int) # the September corporate mailing
return cal
cal = calendar(df.index)
print(cal.sum().to_dict())
# {'nov': 12, 'early_dec': 6, 'w51': 3, 'xmas_ny': 6, 'jan': 12,
# 'mothering': 6, 'fathers': 6, 'corporate': 12}
Example: the calendar for Northgate. Mother's Day in Ireland falls on Mothering Sunday, the fourth Sunday in Lent, three weeks before Easter Sunday, so it moves: 19 March 2023, 10 March 2024, 30 March 2025, 15 March 2026.6 Father's Day in Ireland is the third Sunday in June.7 St Patrick's Day, on the other hand, is always 17 March and a public holiday,8 so its week can come straight from the date without any of this machinery, and in some years it sits right next to Mother's Day, which is worth a look in the residuals. The function marks the week of the holiday and the week before, so each holiday contributes two weeks a year, six in three years, which is what the count shows. Week 51 appears three times, once a year. Three observations is all the data the model will ever have about its most important week, which is worth remembering when the error band comes up.
The corporate column is a planned event, not a season: the weeks in which Northgate's September mailing to companies was live. Planned events belong in the calendar because you know them in advance, which means you can put them into a forecast. An event you only learn about afterwards (a press mention, a competitor's stockout) cannot be a forecast input, however well it explains the past.
The function takes any index of Mondays, so the same calendar() will build the future weeks of 2026 later. That matters more than it looks: the most common forecasting bug I see is a future calendar built by different code from the past one.
Three years of Northgate, generated to match the original
The next block simulates the orders. It uses the coefficients from the Marketing Analytics chapter: a plain week of 212 orders at the start of 2023, 0.62 extra orders per week of trend, and the season effects from that chapter's table. The errors are AR(1), which means each week carries part of the previous week's surprise.
rng = np.random.default_rng(7)
effects = {"nov": 148, "early_dec": 391, "w51": 523, "xmas_ny": -96, "jan": -61,
"mothering": 117, "fathers": 64, "corporate": 88}
expected = 212 + 0.62 * df["t"] + sum(cal[k] * v for k, v in effects.items())
# AR(1) errors: about a third of last week's surprise carries into this week
shocks = rng.normal(0, 36, len(df))
errors = np.zeros(len(df))
for i in range(len(df)):
errors[i] = (0.34 * errors[i - 1] if i > 0 else 0) + shocks[i]
df["orders"] = np.round(expected + errors).astype(int)
# pin Q4 2025 and week 51 of 2024 to the Marketing Analytics chapter's figures
q4_2025 = [281, 334, 296, 342, 309, 431, 498, 452, 512, 668, 741, 845, 236]
df.loc[(df.iso_year == 2025) & df.iso_week.between(40, 52), "orders"] = q4_2025
df.loc[(df.iso_year == 2024) & (df.iso_week == 51), "orders"] = 780
print(df.groupby("iso_year")["orders"].sum())
# 2023 13246
# 2024 15612
# 2025 17251
Example: what the two pinned lines do. The Marketing Analytics chapter quotes real looking actuals for the last quarter of 2025, ending with 845 orders in week 51 and 236 in week 52, and 780 orders in week 51 of 2024, the week the ribbon ran out. I overwrite those 14 weeks with exactly those figures, so the two chapters read as a pair, and leave the rest to the simulation. The data is therefore generated to resemble the example in the Marketing Analytics chapter, not copied from it: the fitted coefficients below land close to the original ones, but not on them, because a random draw of 156 weeks never returns exactly the numbers it was built from. That gap is itself the lesson of this chapter in miniature.
Note the .loc on both lines. Under pandas 3.0 the chained version would silently leave df untouched.
Before the model: turning an order export into honest weeks
On real data, the weekly series is where most forecasts go wrong, long before any model. A shop's order export has one row per event, timestamps in UTC, test orders, and refunds as rows of their own. Here is a six row export that contains every one of those traps.
raw = pd.DataFrame({
"order_id": ["1001", "1002", "1003", "1004", "1005", "1006"],
"created_at_utc": ["2025-06-29 22:40", "2025-06-29 23:15", "2025-06-30 08:05",
"2025-06-30 09:12", "2025-07-01 14:30", "2025-07-02 10:00"],
"email": ["ann@mail.example", "ben@mail.example", "test@northgatehampers.example",
"cat@mail.example", "ann@mail.example", "dan@mail.example"],
"type": ["order", "order", "order", "order", "refund", "order"],
})
raw["created_at"] = pd.to_datetime(raw["created_at_utc"], utc=True).dt.tz_convert("Europe/Dublin")
raw = raw[~raw["email"].str.endswith("@northgatehampers.example")] # drop test and staff orders
raw["count"] = np.where(raw["type"] == "refund", 0, 1) # a refund row is not an extra order
raw["week_utc"] = pd.to_datetime(raw["created_at_utc"]).dt.to_period("W-SUN").dt.start_time
raw["week_local"] = raw["created_at"].dt.tz_localize(None).dt.to_period("W-SUN").dt.start_time
print(raw[["order_id", "created_at", "week_utc", "week_local"]])
# order_id created_at week_utc week_local
# 0 1001 2025-06-29 23:40:00+01:00 2025-06-23 2025-06-23
# 1 1002 2025-06-30 00:15:00+01:00 2025-06-23 2025-06-30
# 3 1004 2025-06-30 10:12:00+01:00 2025-06-30 2025-06-30
# 4 1005 2025-07-01 15:30:00+01:00 2025-06-30 2025-06-30
# 5 1006 2025-07-02 11:00:00+01:00 2025-06-30 2025-06-30
print(raw.groupby("week_local")["count"].sum())
# 2025-06-23 1
# 2025-06-30 3
Example: order 1002. It was placed at a quarter past midnight on Monday 30 June, Irish summer time, which is 23:15 on Sunday in UTC. Bucket by the UTC timestamp and it lands in the previous week. Every order in the first hour of a Monday between late March and late October moves a week back. That blurs the seasonal peaks and creates a lag 1 pattern in the errors that has nothing to do with customers. In winter Irish time equals UTC and the problem disappears, which makes it harder to spot, not easier. Convert to the shop's own time zone first, then cut the weeks, as the pandas time zone guide describes.9
Order 1003 is the shop's own test order and goes. Order 1005 is a refund: it is a row in the export, but not a second order, so it counts zero. For ribbon and boxes the refunded hamper still counts as demand, because it was packed. For revenue it does not.
Two more traps do not fit in six rows. A week in which a product sold out records what you could ship, not what people wanted, so it understates demand. Mark such weeks and either leave them out of the fit or add an event dummy for them. And a week with a site outage, a payment provider failure or a tracking change is not a season. Write these down while you still remember them. The chapter on cleaning data in pandas covers the general tools, and loading business data into pandas covers reading the export in the first place.
Look at the autocorrelation before you model anything
Autocorrelation is the correlation of a series with a shifted copy of itself. If this week's orders tell you something about next week's, the series is autocorrelated. The autocorrelation function, the ACF, lists that correlation for every lag :
Here is the autocorrelation at lag (the number of weeks of shift), is orders in week , is orders weeks earlier, is the mean of the whole series and is the number of weeks.10 The top of the fraction asks whether weeks above the average tend to be followed, weeks later, by weeks above the average. The bottom scales it so that lies between minus 1 and 1. It is built from means and squared deviations, see Foundations: the mean and Foundations: spread.
The partial autocorrelation function, the PACF, answers a narrower question: how much does the week weeks back still add once the weeks in between are known? An AR(1) process, where only last week matters directly, shows one tall PACF bar at lag 1 and nothing after it, while its ACF fades away gradually.
y = df["orders"]
r = acf(y, nlags=52)
print("ACF of orders at lags 1, 2, 3, 52:", r[[1, 2, 3, 52]].round(2))
# ACF of orders at lags 1, 2, 3, 52: [0.65 0.41 0.21 0.53]
# for the picture: sm.graphics.tsa.plot_acf(y, lags=60) and plot_pacf(y, lags=30)
Example: reading Northgate's raw ACF. Lag 1 is 0.65: a busy week is usually followed by another busy week. That is mostly the seasons, not the errors. November weeks follow November weeks, and the Christmas ramp is four weeks of rising numbers. Lag 52 is 0.53: this week looks like the same week last year. Both say the calendar drives the series. The raw ACF cannot tell you whether anything is left once the calendar is modelled. For that you look at the ACF of the residuals, after the regression, further down. The functions are acf and pacf in statsmodels.tsa.stattools, and plot_acf and plot_pacf draw the familiar bar charts with a shaded band around zero.11
Trend, season and remainder with STL
Before fitting a forecast model, it helps to see the three parts the model is trying to separate. The additive decomposition writes each week as
where is orders in week , is the trend (where the business has got to), is the seasonal component (what this time of year adds or takes away) and is the remainder, everything else.12 The seasonal part is an index of how each week compares with the trend, the idea behind Foundations: indexing and base rates.
STL, short for Seasonal and Trend decomposition using Loess, estimates the three parts with local smoothing, so the seasonal pattern can drift slowly from year to year.13 It was published by Cleveland and colleagues in 1990, and statsmodels implements it as STL.14
stl = STL(y, period=52).fit()
parts = pd.DataFrame({"orders": y, "trend": stl.trend, "season": stl.seasonal,
"remainder": stl.resid}).round(0)
print(parts[(df.iso_year == 2025) & (df.iso_week == 51)])
# orders trend season remainder
# week_start
# 2025-12-15 845 349.0 482.0 14.0
Example: week 51 of 2025. STL puts the trend at 349 orders, the season adds 482, and the remainder is 14: , the actual. The Marketing Analytics chapter, from its regression, got a trend of about 308 and a season of 523 for the same week, with the same remainder of 14. The split differs because STL's trend is a smooth local average, which absorbs part of the busy fourth quarter, while the regression's trend is a straight line through all three years. The decomposition is a picture for understanding the series, not a forecast. Note period=52: STL needs to be told the length of the seasonal cycle, and for weekly retail data that is 52.
The baseline every model has to beat
Before you fit anything clever, write down the forecast that knows nothing. For seasonal weekly data that is the seasonal naive forecast: next year's week 51 will be like this year's week 51.15 Add a growth factor and you have a benchmark that is embarrassingly hard to beat:
Here is the forecast for week , is the actual orders in the same week a year earlier, and is the growth factor: the orders of the most recent 52 weeks divided by the orders of the 52 weeks before them. A growth factor of 1.107 is growth of 10.7% written as a multiplier, see Foundations: percentages and Foundations: ratios and rates.
The holdout comes first. I fit every model on the first 130 weeks and keep the last 26, the second half of 2025 with the whole Christmas run, hidden. Nothing about those weeks may touch the fit, the growth factor or the choice of seasons.
train = df.index[:130] # ISO week 1 of 2023 to ISO week 26 of 2025
test = df.index[130:] # the last 26 weeks, with the whole Christmas run
actual = y[test]
forecasts = {}
forecasts["Seasonal naive"] = y.shift(52)[test]
growth = y[train][-52:].sum() / y[train][-104:-52].sum()
print("growth factor:", round(growth, 3))
# growth factor: 1.107
forecasts["Seasonal naive x growth"] = growth * y.shift(52)[test]
Example: week 51 of 2025 from the baseline. Week 51 of 2024 brought 780 orders. The growth factor from the training weeks is 1.107, so the forecast is , about 864. The actual was 845, a miss of about 19 orders, or . Two lines of code, within 2.2% on the most important week of the year.
Seasons as dummy variables in a regression
The workhorse is the seasonal dummy regression from the Marketing Analytics chapter:
Here is orders in week . is the level of a plain week at the start of the data and the trend, the extra orders per week, with counting the weeks. is 1 if week belongs to season or event and 0 otherwise, with such columns, and is how many orders season adds to a plain week. is the error. The fitted value for any week is the expected number of orders given its calendar, see Foundations: expected value.
X = sm.add_constant(pd.concat([df[["t"]], cal], axis=1)).astype(float)
ols = sm.OLS(y[train], X.loc[train]).fit()
print(ols.params.round(2))
# const 194.48
# t 0.69
# nov 140.42
# early_dec 392.49
# w51 550.71
# xmas_ny -74.29
# jan -48.55
# mothering 119.76
# fathers 65.24
# corporate 107.59
forecasts["Dummy regression, OLS"] = ols.predict(X.loc[test])
sm.add_constant adds the column of ones that carries . The .astype(float) matters: statsmodels wants numbers, and the integer dummies plus the trend become one float matrix.
Example: reading the coefficients. A plain week at the start of 2023 is worth about 194 orders and each week adds 0.69, so a plain week at the end of the training data, week 130, sits at . Week 51 adds 551 on top, so a week 51 in the middle of 2025 would come out near 835. Mothering Sunday is worth 120 orders in each of its two weeks, Father's Day 65. These are close to the values the data was built from (523 for week 51, 117 for Mothering Sunday, 64 for Father's Day) and land within a standard error or two of each.
Testing the residuals for autocorrelation
Ordinary least squares, OLS, assumes that each week's error is independent of the last. In a time series it rarely is. The first check is the Durbin Watson statistic:
where is the residual in week , the residual a week earlier, the number of weeks and the lag 1 autocorrelation of the residuals.16 It runs from 0 to 4 and sits at 2 when there is no autocorrelation. Below about 1.5 means positive autocorrelation, the usual case for sales. The approximation on the right ties it to the ACF, and the sums are the squared deviations of Foundations: spread.
print("Durbin Watson:", round(durbin_watson(ols.resid), 2))
print("residual ACF lags 1 to 3:", acf(ols.resid, nlags=3)[1:].round(2))
print("residual PACF lags 1 to 3:", pacf(ols.resid, nlags=3)[1:].round(2))
# Durbin Watson: 1.5
# residual ACF lags 1 to 3: [0.25 0.14 0.13]
# residual PACF lags 1 to 3: [0.25 0.08 0.08]
Example: Northgate's residuals. The residual autocorrelation at lag 1 is 0.25, so the approximation gives , and statsmodels reports 1.5. Borderline by the rule of thumb, and clearly not 2. The PACF has one bar of 0.25 at lag 1 and small bars after it, the signature of AR(1). The raw series had an ACF of 0.65 at lag 1. The calendar explained most of that, and 0.25 is what remains: a real but modest carry over of surprises from one week to the next.
Regression with AR(1) errors in SARIMAX
The fix is to let the errors follow their own small model, the first order autoregressive process:
Here is the model's error in week , is the autocorrelation coefficient between minus 1 and 1, is last week's error and is a fresh, independent shock. With you are back at plain OLS. The expected error next week, given this week's, is times this week's error, the idea of Foundations: expected value.
The textbooks call this regression with ARIMA errors.17 In statsmodels it is SARIMAX with the calendar as exog (the exogenous regressors) and order=(1, 0, 0), which means one autoregressive term, no differencing and no moving average term.18 The Marketing Analytics chapter used GLSAR, which estimates the same idea by iterated least squares. SARIMAX fits it by maximum likelihood and, more usefully here, produces forecasts with prediction intervals directly.
reg_ar = SARIMAX(y[train], exog=X.loc[train], order=(1, 0, 0)).fit(disp=False, maxiter=500)
print(reg_ar.params.round(2))
# const 195.31
# t 0.69
# nov 140.13
# early_dec 393.83
# w51 540.67
# xmas_ny -77.21
# jan -49.27
# mothering 116.19
# fathers 67.27
# corporate 99.60
# ar.L1 0.27
# sigma2 999.33
compare = pd.DataFrame({"OLS se": ols.bse, "AR(1) se": reg_ar.bse[ols.bse.index]}).round(1)
print(compare)
# OLS se AR(1) se
# const 6.5 8.2
# t 0.1 0.1
# nov 12.7 10.5
# early_dec 17.5 17.2
# w51 24.4 34.1
# xmas_ny 15.7 15.4
# jan 10.6 20.3
# mothering 14.4 22.5
# fathers 14.4 10.3
# corporate 12.6 18.0
fc = reg_ar.get_forecast(steps=len(test), exog=X.loc[test])
forecasts["Dummy regression, AR(1) errors"] = fc.predicted_mean.set_axis(test)
maxiter=500 gives the optimiser room. With the default limit, some of the refits later in this chapter stop early and statsmodels warns that the optimisation failed to converge. Raise the limit rather than silence the warning: a warning you hide today is a wrong number you defend next quarter.
Example: what the AR(1) term changes. The estimated is 0.27, close to the residual ACF of 0.25. If the model was 50 orders short this week, it expects to be short next week, the week after, and about 1 by the third week. The coefficients barely move compared with OLS, which is what theory says: autocorrelated errors leave OLS coefficients unbiased. The standard errors move a lot. The week 51 effect had a standard error of 24.4 under OLS and 34.1 with AR(1) errors, so the naive figure was about 28% too small. January's doubles, from 10.6 to 20.3. A few go the other way: Father's Day falls from 14.4 to 10.3. The direction depends on how each dummy's weeks line up with the error pattern. What matters is that these are now computed under an assumption the data supports, which is the only kind of standard error worth putting in front of a decision.
Holt Winters: let the pattern adapt
Exponential smoothing keeps running estimates of a level, a trend and a seasonal pattern, and nudges each towards what has just happened. With an additive trend and additive seasons it is the Holt Winters method.19 It needs no calendar at all, which is both its charm and its weakness: it cannot know that Mothering Sunday moved, and it learns a week 51 from only the week 51s it has seen. In statsmodels it is ExponentialSmoothing.20
hw = ExponentialSmoothing(y[train], trend="add", seasonal="add",
seasonal_periods=52).fit()
forecasts["Holt Winters"] = hw.forecast(len(test)).set_axis(test)
print(hw.params["smoothing_level"].round(2), hw.params["smoothing_trend"].round(2),
hw.params["smoothing_seasonal"].round(2))
# 0.06 0.0 0.0
Example: reading the smoothing parameters. Each parameter between 0 and 1 says how strongly the method reacts to the latest week. The level reacts a little (0.06), and the trend and the seasonal pattern not at all (0.0). With two and a half years of training data, the method treats the seasonal pattern as fixed and lets the level move slowly, which makes it close to a smoothed seasonal naive forecast. I use it for the point forecast only. statsmodels can produce intervals for it by simulation, but the dummy model is the one I would put in front of the warehouse.
SARIMA: seasonal differencing with a memory
The seasonal ARIMA family models the series through its own past.21 The variant I fit here is small enough to read: take each week minus the same week a year earlier, and let that year on year change follow an AR(1) with a constant.
Here is this week's change on the same week last year, is the average year on year change, (phi) is how much of last week's year on year change repeats this week, is last week's year on year change and a fresh shock. In the usual notation this is SARIMA(1,0,0)(0,1,0) with period 52. A year on year change is a rate of growth in orders, see Foundations: ratios and rates.
sarima = SARIMAX(y[train], order=(1, 0, 0), seasonal_order=(0, 1, 0, 52),
trend="c").fit(disp=False, maxiter=500)
print(sarima.params.round(2))
# intercept 27.19
# ar.L1 0.26
# sigma2 3220.12
forecasts["SARIMA (1,0,0)(0,1,0)52"] = sarima.get_forecast(len(test)).predicted_mean.set_axis(test)
Example: one step of the SARIMA forecast. Say last week's orders were 40 above the same week a year earlier. The forecast for this week's year on year change is , so this week is forecast at the same week last year plus about 38. Read that way, this SARIMA is the seasonal naive forecast with growth, except that the growth is a fixed number of orders that adapts to recent weeks. You should expect it to score close to the naive baseline, and it does.
Scoring on weeks the model never saw: MAE and MAPE
Fit statistics describe the past. The holdout says whether the model knows anything about the future. Two measures do most of the work:
Here is the actual orders in holdout week , the forecast for it, the number of holdout weeks, and the vertical bars take the size of the miss without its sign.22 MAE, the mean absolute error, is in orders, the unit the warehouse understands. MAPE, the mean absolute percentage error, is a percentage and compares across products and shops. Both are averages, see Foundations: the mean and Foundations: percentages.
q4 = (df.loc[test, "iso_year"] == 2025) & df.loc[test, "iso_week"].between(40, 52)
def score(fcst):
err = actual - fcst
return pd.Series({
"MAE": err.abs().mean(),
"MAPE %": (err.abs() / actual).mean() * 100,
"Q4 total %": (fcst[q4].sum() / actual[q4].sum() - 1) * 100,
})
board = pd.DataFrame({name: score(f) for name, f in forecasts.items()}).T.round(1)
print(board.sort_values("MAE"))
| Model | MAE (orders per week) | MAPE | Q4 2025 total, forecast against actual |
|---|---|---|---|
| Dummy regression, AR(1) errors | 26.2 | 7.1% | minus 4.3% |
| Dummy regression, OLS | 27.1 | 7.3% | minus 4.3% |
| Holt Winters | 31.6 | 8.8% | minus 4.2% |
| Seasonal naive times growth | 36.7 | 10.0% | minus 2.8% |
| SARIMA (1,0,0)(0,1,0)52 | 37.0 | 10.0% | minus 4.1% |
| Seasonal naive | 48.8 | 12.1% | minus 12.2% |
Example: reading the scoreboard. The dummy regression with AR(1) errors wins with an MAE of 26.2 orders a week, the same 26 the Marketing Analytics chapter reports, which is a pleasant coincidence of the simulation rather than a law. It beats seasonal naive with growth by orders a week, about 29% less error. That margin is large enough to change how much ribbon you order, so the regression has earned its place. The AR(1) term itself is worth less than one order a week over plain OLS, 26.2 against 27.1. Plain seasonal naive underestimates the quarter by 12% because it does not know the shop is growing. With the growth factor, it is the closest of all on the quarterly total, minus 2.8%, while being the worst serious model week by week. A model can be right about the quarter and wrong about every week in it, and it is the weeks that decide whether the packing room has ribbon.
Here is the holdout quarter week by week for the winning model.
The forecast is a staircase: within a season the dummies are flat and only the trend creeps up, and between seasons there is a step. The actuals wobble around the stairs.
Worked example: scoring the holdout quarter by hand
Example: the 13 weeks of the fourth quarter. The absolute misses of the AR(1) model, with the forecasts rounded to whole orders, are 13, 39, 0, 46, 12, 7, 60, 13, 72, 26, 46, 3 and 11. They add up to 348, so the MAE over the quarter is orders a week. The forecast for the quarter adds up to 5,689 orders against 5,945 actual, so , the figure in the table. Week 51 was forecast at 842 against 845 actual: three orders, the best week of the quarter. The worst was week 48, 440 against 512, 72 orders short, at the end of November, when the November season ran hotter than in the years the model learned from.
The traps in MAE and MAPE
Both measures are simple, and both can mislead in ways the tutorials skip.
MAPE punishes quiet weeks. The same miss counts for far more in a small week. MAPE is undefined when a week has zero sales and explodes when it has very few, and it penalises forecasts that are too high more heavily than forecasts that are too low, which quietly rewards a model that under forecasts.22
Example: an 11 order miss. In week 52, with 236 actual orders, it is . The same 11 orders in week 51, with 845 actual orders, is . The warehouse feels the same 11 hampers either way. So I plan with MAE and use MAPE only to compare shops or products of different sizes.
MAE treats all weeks as equal. A 40 order miss in a plain July week costs a little overtime. A 40 order miss in week 51 costs an emergency courier. If some weeks matter more, score those weeks separately, as the Q4 column does, or weight the errors by what a miss costs in that week.
Scale free comparisons need a scaled error. If you compare forecasts across products with very different volumes, the mean absolute scaled error, MASE, divides each error by the average error of the seasonal naive forecast on the training data. A MASE below 1 means "better than seasonal naive" in one number, which is the question this chapter keeps asking.23
Score the forecast at the decision's lead time
This is the idea I would most like you to take from this chapter. A single holdout is one forecast made at one point in time, and it mixes horizons: the first holdout week was one week ahead, the last was 26 weeks ahead. But decisions are made at a fixed distance. In this example, Northgate's packaging supplier needs six weeks: the boxes and ribbon for week 51 are ordered in week 45. The forecast that matters for that decision is the forecast made six weeks before the week, so that is the one to score.
Time series cross validation, also called evaluation on a rolling forecasting origin, does exactly this.24 Pick an origin, fit on everything before it, forecast weeks ahead, record the error, move the origin one week, repeat. Unlike ordinary cross validation, the training data always lies before the test week, so no future information leaks in.
def rolling_origin(fit_and_forecast, h, first=104, last=None):
"""Refit at every origin and keep only the forecast h weeks ahead."""
last = last or len(y) - h
rows = []
for origin in range(first, last + 1):
past = df.index[:origin]
target = df.index[origin + h - 1]
rows.append((target, fit_and_forecast(past, h)))
pred = pd.Series(dict(rows))
return (y[pred.index] - pred).abs().mean()
def naive_growth(past, h):
g = y[past][-52:].sum() / y[past][-104:-52].sum()
target = df.index[len(past) + h - 1]
return g * y[target - pd.Timedelta(weeks=52)]
def dummy_ols(past, h):
m = sm.OLS(y[past], X.loc[past]).fit()
return m.predict(X.iloc[[len(past) + h - 1]]).iloc[0]
def dummy_ar1(past, h):
m = SARIMAX(y[past], exog=X.loc[past], order=(1, 0, 0)).fit(disp=False, maxiter=500)
future = X.iloc[len(past):len(past) + h]
return m.forecast(steps=h, exog=future).iloc[-1]
for h in (1, 6):
print(f"h={h}:", {name: round(rolling_origin(f, h), 1) for name, f in
[("naive x growth", naive_growth), ("OLS", dummy_ols), ("AR(1)", dummy_ar1)]})
# h=1: {'naive x growth': 43.1, 'OLS': 26.2, 'AR(1)': 27.4}
# h=6: {'naive x growth': 46.6, 'OLS': 27.5, 'AR(1)': 26.9}
The first origin is week 104, so every fit has at least two full years of history, which the growth factor needs. For there are 52 origins, for there are 47. The loop refits the SARIMAX model each time, about a minute on a laptop. NumPy 2 prints these values as np.float64(43.1), trimmed in the comment.
Why the AR(1) term fades with the horizon
The AR(1) term uses this week's surprise to adjust next week. How much of it survives weeks ahead follows from the AR(1) equation applied times:
Here is the error in the last observed week , the error weeks later, the autocorrelation and the expected value given what you know, see Foundations: expected value.
Example: Northgate at a six week lead time. With , the share of a surprise that survives one week is 0.27. After six weeks it is , which is nothing. So at the lead time where the ribbon is ordered, the AR(1) model and the OLS model must forecast almost the same number, and the output agrees: 26.9 against 27.5. One week ahead the AR(1) term should help a little, but with the error it can remove is small. The share of the error variance it removes is , and here even that is lost in the noise: 27.4 against 26.2.
This is the practical rule I use: compute at your lead time before you celebrate an AR term's accuracy. If it is below about 0.05, the AR term will not improve the forecast you act on. It still matters, for two reasons that have nothing to do with the point forecast: it makes the standard errors honest, and it makes the band for a total of several weeks honest. Both come next.
The other lesson from the table: both regressions beat the baseline by about 16 to 20 orders a week at both horizons. That is the margin that survives the honest test, and it is the margin I would quote.
Prediction intervals, and checking that they are honest
A point forecast without a band is a target in disguise. The 80% prediction interval is
where is the point forecast weeks after the last observed week , is the normal quantile that leaves 10% in each tail so that 80% lies between,25 and is the forecast standard error at horizon . The normal curve and how intervals are built from it are in Foundations: confidence intervals. A confidence interval says where the average would land, a prediction interval says where the actual week will land, and planning needs the second.
get_forecast returns the band directly. Then comes the step almost everybody skips: count how many holdout weeks fell inside it.
band = fc.conf_int(alpha=0.20).set_axis(test)
band.columns = ["low", "high"]
inside = actual.between(band["low"], band["high"])
print(f"inside the 80% band: {inside.sum()} of {len(inside)} weeks ({inside.mean():.0%})")
# inside the 80% band: 19 of 26 weeks (73%)
Example: the coverage check. An honest 80% band should catch about 80% of the weeks, so about 21 of 26. Northgate's catches 19, which is 73%. With only 26 weeks that is within the range of chance, but it leans the way the textbook predicts. Intervals from ARIMA type models tend to be too narrow, because they account for the randomness of the errors but treat the estimated coefficients as if they were known exactly.26 The band for the holdout weeks is about plus or minus 42 orders throughout, and it is the same width in week 51, built on three Christmases, as in a plain October week built on dozens. That cannot be right, and the next step fixes it.
The 2026 forecast, with the band the warehouse needs
For the real forecast, refit on all 156 weeks and build the 2026 calendar with the same calendar() function. 2026 is a long ISO year with a week 53, from 28 December 2026 to 3 January 2027, so the future frame has 53 weeks.5
full = SARIMAX(y, exog=X, order=(1, 0, 0)).fit(disp=False, maxiter=500)
future_idx = pd.date_range("2025-12-29", periods=53, freq="W-MON", name="week_start")
fut = pd.DataFrame(index=future_idx)
fut["t"] = np.arange(157, 157 + len(fut))
X_future = sm.add_constant(pd.concat([fut[["t"]], calendar(future_idx)], axis=1),
has_constant="add").astype(float)
f26 = full.get_forecast(steps=len(fut), exog=X_future)
table = f26.summary_frame(alpha=0.20)[["mean", "mean_ci_lower", "mean_ci_upper"]].round(0)
table["iso_week"] = future_idx.isocalendar()["week"].to_numpy()
print(table[table.iso_week.between(40, 53)].to_string())
has_constant="add" matters: without it, add_constant skips the column of ones whenever some column of the future frame happens to be constant, and the future matrix no longer matches the past one.
The refitted model has and a shock standard deviation of 31.9 orders. The fourth quarter of 2026:
| Week of 2026 | Point forecast | 80% low (errors only) | 80% high (errors only) | Season |
|---|---|---|---|---|
| 40 to 44 (each week) | 340 to 343 | about 299 | about 384 | plain |
| 45 to 48 (each week) | 492 to 494 | about 451 | about 535 | November |
| 49 and 50 (each week) | 739 | 697 | 781 | early December |
| 51 | 885 | 843 | 926 | last order week |
| 52 | 272 | 230 | 314 | Christmas to New Year |
Adding the coefficient uncertainty back
The band above treats the week 51 coefficient as known, when it rests on three observations. The fix, which the Marketing Analytics chapter writes as a formula, is to add the variance of the estimated calendar part to the variance of the errors:
Here is the standard error SARIMAX reports, is the row of calendar values for the forecast week (the constant, the trend value and which dummies are on), turns it on its side, and is the covariance matrix of the estimated calendar coefficients, their squared standard errors plus how they move together. Adding variances is the arithmetic of Foundations: spread.
V = full.cov_params().loc[X.columns, X.columns] # covariance of the calendar coefficients
x51 = X_future[X_future.index.isocalendar()["week"].to_numpy() == 51].iloc[0]
var_coef = float(x51 @ V @ x51)
se_err = float(f26.se_mean[x51.name == X_future.index].iloc[0])
se_total = np.sqrt(se_err**2 + var_coef)
point = float(f26.predicted_mean[x51.name == X_future.index].iloc[0])
print(f"week 51: se from errors {se_err:.1f}, from coefficients {np.sqrt(var_coef):.1f}, total {se_total:.1f}")
print(f"week 51 band: {point - 1.2816 * se_total:.0f} to {point + 1.2816 * se_total:.0f}")
# week 51: se from errors 32.6, from coefficients 28.7, total 43.4
# week 51 band: 829 to 940
Example: the band for week 51 of 2026. The error part has a standard error of 32.6 orders, the coefficient part 28.7. Variances add, standard errors do not, so the total is . The band is , so 829 to 940. That is a third wider than the band from get_forecast alone (843 to 926), and almost all of the extra width comes from the week 51 dummy resting on three Christmases. The Marketing Analytics chapter's band for the same week was 790 to 936. Mine is a little narrower and a little higher because the simulated history came out slightly calmer and slightly busier than the original. The method is the same.
This is the band I would hand to the warehouse. In this example, packaging costs little to hold and keeps for years, so Priya orders it to the upper end: 940 boxes and ribbon lengths for week 51, ordered in week 45, six weeks ahead, which is exactly the horizon scored above. Perishables are ordered to the point forecast.
Quarter totals: where autocorrelation bites
The finance question is usually not week 51 but the quarter. A quarterly band cannot be built by adding the weekly bands, and it cannot be built by treating the weeks as independent either, because with a good week tends to be followed by a good week and the errors pile up. The cleanest way in Python is to simulate many possible futures from the fitted model and read the band off the simulated totals.27
sims = full.simulate(nsimulations=len(fut), anchor="end", repetitions=5000,
exog=X_future, random_state=7)
sims = np.asarray(sims).reshape(len(fut), -1) # one column per simulated year
q4_rows = (table.iso_week.between(40, 52)).to_numpy()
q4_total = sims[q4_rows].sum(axis=0)
print("Q4 2026 total, point:", table.loc[q4_rows, "mean"].sum())
print("80% band:", np.percentile(q4_total, [10, 90]).round(0))
var_ind = (f26.se_mean[q4_rows] ** 2).sum()
print("band if errors were independent: +/-", round(1.2816 * np.sqrt(var_ind)))
# Q4 2026 total, point: 6314.0
# 80% band: [6132. 6497.]
# band if errors were independent: +/- 151
anchor="end" starts each simulation from the last observed week, so the simulated futures carry the last known error forward with the AR(1) term, exactly as the forecast does.
Example: the fourth quarter of 2026. The point forecast for weeks 40 to 52 is 6,314 orders. The simulated 80% band runs from 6,132 to 6,497, about plus or minus 183. Treating the weeks as independent gives plus or minus 151, so ignoring the autocorrelation would make the quarterly band about too narrow. The simulation also treats the coefficients as known, so the honest band is wider still. Here is the AR(1) term earning its place: not in the point forecast six weeks ahead, where it has faded to nothing, but in the uncertainty of a total, where every week's surprise is still in the sum.
Forecast, target, decision
The Marketing Analytics chapter has Northgate's marketing plan asking for 7,000 orders in the fourth quarter of 2026. The forecast says 6,314, and even the top of the band, 6,497, is about 500 short. That is not a conflict. The forecast is what happens if the shop keeps doing what it has been doing. The target is what Priya wants. The gap of about 690 orders is what marketing has to earn above trend, and now it has a size, so it can have a budget and a test plan. The chapter on distributed lags in Python shows how to measure what a campaign adds once it runs.
Keep the forecast and the target in separate columns of the same table, and never let the target quietly become the forecast.
The whole workflow, from export to decision, fits on one page:
My view
My view: for a single shop with two to five years of weekly data, the seasonal dummy regression with AR(1) errors is the right default, and the seasonal naive forecast with growth is the right opponent. The regression wins because it knows the calendar: it knows that Mothering Sunday moved, that 2026 has a week 53, and that the corporate mailing is planned for September. Holt Winters and SARIMA have to learn all of that from the series itself, and three Christmases are not enough to learn from.
I would not spend time on larger ARIMA searches or on machine learning for one weekly series of this length. The gains, if any, are smaller than the error in the history itself, and the cost is a model nobody in the business can read. Where I would spend the time is on the three things this chapter keeps returning to: the weekly series built in the right time zone with the stockouts marked, the score at the lead time the decision needs, and a band whose coverage has been checked. The AR(1) term belongs in the model, but for the honesty of the band and the standard errors, not for a better point forecast six weeks ahead. Anyone who sells you the AR term as an accuracy gain at a long horizon has not computed .
Forecasting from weekly data, with bands the business can plan against, is a core part of the Data Science work I do for clients. The code lives in a repository the client owns, together with the holdout scoreboard that shows what the model beat.
For the person who commissions this
Questions to ask whoever hands you a demand forecast, with what a good answer sounds like:
| Question | A good answer |
|---|---|
| What did the model beat, on which weeks? | "Seasonal naive with growth, on the last 26 weeks, by about 10 orders a week." |
| At which horizon was it scored? | "Six weeks ahead, because that is the packaging lead time." |
| How often did the actuals land inside the 80% band? | "19 of 26 weeks, so the band is slightly narrow, and I widened it for coefficient uncertainty." |
| How were the weekly numbers built? | "In the shop's time zone, test orders removed, refunds not double counted, stockout weeks marked." |
| How are moving holidays and week 53 handled? | "From real dates, in one calendar function used for the past and the future." |
| Where is the target? | "In its own column, with the gap to the forecast named." |
If you would like help building this on your own shop's data, the free workshop is where we agree the seasons, the events and the decisions the forecast has to support, and the first two weeks of work are on me.
Conclusion
Forecasting weekly demand in Python is less about the model than about the honesty around it. Build the weeks in the shop's own time zone. Build the calendar once, from real dates, and use it for the past and the future. Fit a seasonal dummy regression with AR(1) errors in SARIMAX, and race it against seasonal naive with growth on weeks it has never seen. Score it at the lead time where the decision is made, and remember that an AR term's help fades as . Check that the 80% band catches about 80% of the weeks, add back the uncertainty in the coefficients, and simulate the totals rather than adding up weekly bands. Then hand the warehouse a band, not a number, and keep the target in a different column.
