Four forecasters predict the same 12 months. On a clean series, Holt-Winters misses by about half as much as a copy of last year. Turn up the noise and the plain naive forecast catches up.
Pick a forecaster and read its score on the held-out year. Then drag the noise. Then we build, piece by piece, the baselines, the scores, smoothing, decomposition, ARIMA, quantiles and the deep models.
You need a little Python and what an average is. We build the rest from zero.
Illustrative series: 120 + 0.9 per month of trend + an 18-unit yearly wave + noise, 48 months to fit and 12 held out. Your browser fits each forecaster by least squares on the 48 months. The score is MASE (Chapter 2): below 1 beats a copy of last year.
Chapter 0
See that a forecast is a range that widens with distance, not a single number
You run a bakery. Tomorrow you must decide how many loaves to bake. Bake too few and customers leave empty-handed. Bake too many and you throw bread away. The decision needs a guess about tomorrow's sales.
A time series is a list of values in time order: daily sales, hourly power demand, monthly rainfall. Forecasting is predicting the next values of a time series from its past. Every plan for stock, staff or power depends on one.
"Sell 100 loaves" is not enough. If the truth is somewhere from 95 to 105, bake 100. If it is somewhere from 40 to 160, the choice depends on what a lost sale costs against a wasted loaf. A useful forecast gives a prediction interval: a range that holds the true value with a stated chance, such as 80%.
Teal is the history. Warm is the forecast and its 80% band. Drag the horizon and watch the band open.
Illustrative random walk: each step adds a surprise with a typical size of 5 units. The band is ±1.28 × 5 × √h, the 80% range for that model.
Why does the band widen? Each new step adds its own surprise, and surprises pile up. With a typical step surprise of 5 units, the 80% band one step ahead is ±6.4. Four steps ahead it is ±1.28 × 5 × 2 = ±12.8. The band doubles when the horizon grows four times.
The hero above uses every idea below. Each chapter builds one part.
Chapter 1
Split time the right way and set the bar every model must clear
A shop sells ice cream. You have two years of quarterly sales: 20, 31, 45, 27, then 25, 35, 49, 30. Summer is the third quarter. What will next year bring?
The model sees a lookback window: the recent past it reads. It predicts a horizon: the number of future steps it must fill. Here the lookback is 8 quarters and the horizon is 4.
To test a forecaster, hide the end of the series. Fit on the past and score on the hidden future. Never shuffle the points first. A shuffled split lets the model peek at the future it must predict, and the score looks better than it will be. Repeat the test from several cut points, called forecast origins, and average the scores. This is a backtest.
A baseline is a forecaster so simple that any real model must beat it. Three are standard.
Teal is the 8 quarters you fit on. Purple dots are the hidden year. Pick a baseline and read its average miss.
Illustrative sales in hundreds of cones. The hidden year is 27, 41, 52, 35.
Work the seasonal naive by hand. It forecasts 25, 35, 49, 30. The truth is 27, 41, 52, 35. The misses are 2, 6, 3 and 5, so the average miss is 16 / 4 = 4. The naive forecast says 30 four times and misses by 3, 11, 22 and 5, an average of 10.25. Copying last year cuts the miss by more than half.
Chapter 2
Turn misses into one number, and see which numbers lie near zero
Two forecasters, one hidden year. Which is better? You need one number. Four scores are common, and they disagree.
Call the true value at future step t yt and the forecast for that step ŷt. The error is their difference. Call the number of scored steps n.
M-A-E equals one over n, times the sum over t of the absolute value of y-t minus y-hat-t.
For each step, subtract the forecast y-hat-t from the truth y-t and drop the sign. Add the n misses. Divide by n.
Seasonal naive from Chapter 1: the misses are 2, 6, 3, 5 and n = 4, so MAE = 16 / 4 = 4 hundred cones.
MAE has units, so it cannot compare a bakery with a power grid. A percentage can: divide each miss by the true value.
MAPE equals one hundred over n, times the sum over t of the absolute miss, divided by the absolute value of y-t.
Divide each miss by its true value y-t. Average those fractions over the n steps. Multiply by 100.
Seasonal naive: 2/27 + 6/41 + 3/52 + 5/35 = 0.074 + 0.146 + 0.058 + 0.143 = 0.421. Times 100/4 gives MAPE = 10.5%.
MAPE breaks near zero. A miss of 2 on a true value of 200 is 1%. The same miss on a true value of 2 is 100%. At a true value of 0 it is infinite. sMAPE, used in the M4 competition, divides by the mean of truth and forecast:
sMAPE = 100/n · Σt 2 |yt − ŷt| / (|yt| + |ŷt|)
Despite its name, it is not symmetric. With truth 100, a forecast of 150 scores 40% and one of 50 scores 66.7%.
MASE compares your miss with a baseline's. Call q the scale: the training-data MAE of seasonal naive, with season length m.
MASE equals M-A-E over q, where q is the mean, over the training data, of the absolute value of y-t minus y-t-minus-m.
On the training data, measure how far each value y-t sits from the value one season back. Average those gaps to get q. Divide your test MAE by q.
Ice cream training gaps: |25 − 20| = 5, |35 − 31| = 4, |49 − 45| = 4, |30 − 27| = 3, so q = 4. Seasonal naive has MAE 4, so MASE = 1.0. Naive has MAE 10.25, so MASE = 2.56.
The forecast misses by the same amounts at every level. Drag the level down. Watch the red bars, one percentage error per month.
Illustrative: 12 months of truth = level + a 6-unit wave, and a forecast that misses by 2 to 4 units each month. The scale q comes from 24 earlier months of the same series.
Chapter 3
Average away the noise, and choose how fast the forecast forgets the past
Weekly orders at a warehouse: 50, 54, 48, 60, 58. The naive forecast says 58. But 58 holds one week's noise. An average of several weeks holds less.
A moving average forecasts the mean of the last k values. With k = 3 it says (48 + 60 + 58) / 3 = 55.3. Each of the last 3 weeks counts equally. Week 4 back counts zero. That cliff is odd: why should a week count fully, then not at all?
Exponential smoothing gives every past week a weight that shrinks smoothly. It keeps one number, the level: its current estimate of the series. Call the level after step t ℓt, the new value yt, and the smoothing weight α, a number from 0 to 1.
L-t equals alpha times y-t, plus one minus alpha times L-t-minus-one.
Mix the new value y-t and the old level L-t-minus-one. The new value gets the share alpha. The old level gets the rest.
Start the level at 50 and set alpha = 0.3. After 54: 0.3 × 54 + 0.7 × 50 = 51.2. After 48: 50.24. After 60: 53.17. After 58: 54.62. The forecast for next week is 54.6.
Unroll the rule and each past value gets weight α(1 − α)k, k steps back: 0.30, 0.21, 0.15, 0.10, 0.07 for α = 0.3. The weights fall smoothly. With α = 1 the level is the last value, so smoothing becomes the naive forecast. The hero shows this: at low noise its fitted α is 1.
The level jumps from 50 to 70 at week 30. Warm is the smoothed level. Drag alpha. Turn on the moving average to compare.
Illustrative series: level 50, then 70 from week 30, plus noise with a typical size of 3. The steps-to-catch-up count is the smallest n with (1 − α)n ≤ 0.1.
Small α gives a calm line that lags a real change. Large α reacts fast but chases noise. After a jump, the level closes 90% of the gap in n steps, where (1 − α)n first drops to 0.1. For α = 0.3 that is 7 steps. Fitting picks the α with the smallest one-step squared error on the past.
Smoothing forecasts a flat line. Holt's method adds a second smoothed number, the slope, so the forecast can rise. Holt-Winters adds a third, one seasonal offset per position in the season. Chapter 4 explains those offsets. All three belong to the ETS family: error, trend, season.
Chapter 4
Split a series into parts you can forecast and a part you cannot
Look at the ice cream sales again. They rise from year to year. They also peak every summer. What is left after those two is small and irregular.
Name the three parts. The trend is the slow direction. The season is the cycle that repeats with a fixed period, such as 4 quarters or 7 days. The residual is the rest. Call them Tt, St and Rt.
y-t equals T-t plus S-t plus R-t.
Each value y-t is a trend T-t, plus the offset S-t for its place in the cycle, plus a leftover R-t. To forecast, extend T-t, repeat S-t, and treat R-t as the uncertainty.
Ice cream, third quarter of year 1: the trend is 31.375, the summer offset is +13.5625, and the true value is 45. So R-t = 45 − 31.375 − 13.5625 = 0.06.
Classical decomposition finds the parts in three steps.
Top: the series. Below: the trend, season and residual that classical decomposition recovers. Drag the noise and see which strip absorbs it.
Illustrative monthly series: trend 100 + 0.8 per month, a yearly wave of size 18 (36 from trough to peak), and noise. Recovery uses a 2 × 12 centred moving average, as in classical decomposition.
Holt-Winters runs the same split online. It smooths a level, a slope and 12 seasonal offsets, one update per month. That is why it won the hero at low noise: the series there is a trend plus a yearly wave, the exact shape it assumes.
Chapter 5
Forecast a value from its own recent past, and difference away a trend
A room's temperature is 60 now. Its usual level is 50. A good guess for the next minute is a bit below 60, because the room drifts back toward its usual level. How fast it drifts is the whole model.
An autoregressive model predicts a value from its own past values. The simplest one, AR(1), uses one past value. Call the long-run mean μ, the last observed value yT, and the pull-back factor φ, from 0 to 1. Each step keeps the share φ of the gap from the mean, then adds a surprise. The forecast h steps ahead drops the surprises, which average zero.
y-hat at T-plus-h equals mu, plus phi to the h times the quantity y-T minus mu.
Take today's gap from the mean, y-T minus mu. Shrink it by phi once for each step ahead. Add the result back to mu.
With made-up numbers mu = 50, phi = 0.8, y-T = 60: the gap is 10. One step: 50 + 8 = 58. Two steps: 50 + 6.4 = 56.4. Three: 55.12. Ten steps: 51.07, almost back to the mean.
The band grows too, but it stops growing. Each step adds a surprise of typical size σ, and older surprises shrink by φ. With σ = 4 and φ = 0.8, the forecast's typical error is 4.0 at one step, 5.12 at two and 5.73 at three. It never exceeds 4 / √(1 − 0.64) = 6.67.
Teal is a simulated AR(1) series around a mean of 50. Warm is its forecast and 80% band. Drag phi toward 1 and watch the band stop levelling off.
Illustrative: mean 50, surprise size 4, the same random surprises for every phi. At phi = 1 the series is a random walk with no mean to return to.
At φ = 1 there is no pull-back: the series is a random walk, and the band grows forever. A series whose mean and spread stay fixed over time is stationary. A trend breaks that. The cure is differencing: model the changes yt − yt−1 instead of the values. A steady trend becomes a constant.
ARIMA(p, d, q) names three parts. p is the number of past values (AR). d is the rounds of differencing (I, integrated). q is the number of past surprises (MA). We checked the formula with statsmodels. An ARIMA(1, 0, 0) fitted to 300 simulated points found φ = 0.81. Its forecasts matched μ + φh(yT − μ) to machine precision.
Chapter 6
Train a model to say "90% of the time demand stays below this"
A lost sale costs you 9 euros of profit. An unsold loaf costs 1 euro. You should bake more than the average demand, because running out hurts 9 times more. How many more?
The answer is a quantile. The 0.9 quantile of demand is the amount that demand stays below 90% of the time. Stock that much and you run out on 1 day in 10. With costs of 9 and 1, the best stock is the quantile at 9 / (9 + 1) = 0.9.
A model can learn a quantile directly. Call the target quantile level τ (tau), the true value y and the model's forecast q. The pinball loss charges a different price per unit for a forecast that is too low and one that is too high.
L-tau of y and q equals tau times y minus q if y is at least q; otherwise one minus tau, times q minus y.
If the truth y lands above the forecast q, pay tau for each unit of shortfall. If it lands below, pay one minus tau for each unit of excess. Average the loss over many days.
With tau = 0.9 and truth y = 100: a forecast q = 90 is 10 too low and costs 0.9 × 10 = 9. A forecast q = 110 is 10 too high and costs 0.1 × 10 = 1. Low forecasts cost 9 times more, so the best q moves up.
Bars: 2,000 days of demand. The warm curve is the average pinball loss for each forecast q. Drag tau and watch the curve's lowest point move.
Illustrative demand: 2,000 seeded draws from a bell curve with mean 100 and spread 15. Your browser computes the loss curve over those draws.
The lowest point of the curve lands on the τ quantile of the data. That is the reason the pinball loss works: minimising it makes q the τ quantile. A model trained with τ = 0.1, 0.5 and 0.9 gives three lines, and the band between 0.1 and 0.9 is an 80% interval.
The other route is to predict the parameters of a distribution, such as a mean and a spread, and train by likelihood. DeepAR (Salinas et al., Amazon, 2017) does this, then samples many futures to read off any quantile.
Chapter 7
Train one network on many series, and stack blocks that each explain what is left
A retailer sells 50,000 products. Fitting 50,000 separate Holt-Winters models works, but a new product has no history to fit. A product launched last week has 7 days of data.
A global model is one model trained on many series at once. It learns patterns they share, such as a weekend dip or a December rise, and applies them to a short series. Series must first be put on one scale, for example by dividing each by its own mean. DeepAR was an early global model. The M5 competition on Walmart sales, about 42,000 series, was won by global machine-learning entries, many built on gradient-boosted trees.
| Approach | One model per | A new series |
|---|---|---|
| Local (ETS, ARIMA) | series | needs its own history |
| Global (DeepAR, N-BEATS) | whole collection | borrows patterns from the others |
N-BEATS (Oreshkin et al., 2019) is a deep stack of fully connected blocks. It reported about 3% better accuracy than the M4 winner. Each block reads its input window and makes two outputs: a backcast, its fit of the window, and a forecast, its share of the future. Call the input of block l xl, its backcast x̂l and its forecast ŷl.
x-l-plus-one equals x-l minus x-hat-l; and y-hat equals the sum over l of y-hat-l.
Each block fits what it can of its input x-l. Subtract that backcast and pass the remainder to the next block. Add up every block's forecast y-hat-l.
With a made-up lookback 12, 15, 14, 19: a trend block fits the line 12 + 2t. Its backcast is 12, 14, 16, 18 and its forecast is 20, 22. The next block gets 0, 1, −2, 1, a wiggle for a season block to fit.
Top: the lookback (teal), the summed forecast (warm) and the true future (purple dots). Bottom: what is still unexplained. Add blocks one at a time.
Illustrative series: trend + a 6-step cycle + a 3-step cycle + noise. Each block here is a least-squares fit on a fixed basis: a line, then the 6-step wave, then the 3-step wave. Real N-BEATS learns its blocks with neural networks; its interpretable version uses polynomial and Fourier bases like these.
This is the same residual idea as boosting: each block works only on what the blocks before it left. In the interpretable version, one stack is limited to smooth polynomial shapes and another to waves. You can then plot the trend and season it learned, as in Chapter 4.
Chapter 8
Cut a series into patches, and forecast a series the model never trained on
A transformer compares every token with every other token. Feed it 336 hourly values as 336 tokens, and it scores 336 × 336 = 112,896 pairs. Most of those pairs compare two neighbouring hours that say nearly the same thing.
There was a warning first. Zeng et al. (2022) showed that a one-layer linear model beat the transformer forecasters of the time on nine long-horizon datasets. Attention over single time steps did not pay.
PatchTST (Nie et al., 2022) cuts the series into patches: short runs of P values, started every S steps. Each patch becomes one token. Call the lookback length L, the patch length P and the stride S. The paper pads the end with S copies of the last value, so the patch count is:
N = floor((L − P) / S) + 2
With the paper's L = 336, P = 16 and S = 8: N = floor(320 / 8) + 2 = 42 tokens. Attention then scores 42 × 42 = 1,764 pairs, 64 times fewer. PatchTST also forecasts each variable on its own with shared weights, which it calls channel independence.
Each bar under the series is one patch, one token. Drag the patch length and the stride and watch the token count and the attention grid.
L = 336 and the count N = floor((L − P) / S) + 2 come from the PatchTST paper; its default is P = 16, S = 8. The device caps the stride at P so that every value lands in a patch. The series is illustrative.
The Temporal Fusion Transformer (TFT, Lim et al., Google, 2019) mixes recurrent layers with attention. It takes known-future inputs, such as holidays, and outputs quantiles. Chapter 9 shows why those inputs matter.
A foundation model learns from a huge mix of series first. Then it forecasts a new series with no training on it. That is zero-shot forecasting.
| Model | From | How it reads a series |
|---|---|---|
| TimesFM (Das et al., 2023) | a decoder-only transformer over patches | |
| Chronos (Ansari et al., 2024) | Amazon | scales and rounds values into a fixed vocabulary of tokens, then trains T5 language models, 20M to 710M parameters |
| Moirai (Woo et al., 2024) | Salesforce | a masked-encoder transformer trained on about 27 billion observations of many frequencies |
The TimesFM paper reports zero-shot accuracy close to supervised models trained on each dataset. Chronos reports zero-shot results comparable to, and sometimes better than, models trained on the target data.
Chapter 9
Tell the model about the holiday, and know the three ways forecasts fail in production
Next month has a public holiday. Sales triple that day. The series alone cannot know the date moved this year. You know it in advance, so tell the model.
A covariate is an extra input besides the series' own past. There are three kinds.
| Kind | Known when? | Example |
|---|---|---|
| Known-future | for the whole horizon, in advance | holidays, planned promotions, day of week |
| Past-observed | only up to today | a related product's sales, the weather so far |
| Static | fixed for the series | store location, product category |
The yellow marker is a holiday inside the forecast window. Drag it. Turn the covariate on and off and compare the misses.
Illustrative daily sales: a weekly pattern, noise, and a holiday that adds 60 units. The forecast with the covariate adds the uplift it measured on past holidays, 55 units, on the holiday date.
Without the covariate, the forecast repeats last week and misses the holiday by about 60 units. One miss of 60 on a 21-day horizon adds almost 3 units to the MAE. With the covariate, the forecast adds the uplift measured on past holidays, here 55, so at the default day 12 the miss drops to 6.
Chapter 10
Keep the terms, numbers, code and checklist in one place
A forecast is a range over a horizon, scored against a baseline on a time-ordered backtest. Start with seasonal naive, then smoothing and ARIMA, then quantiles, then global and pretrained models when you have many series.
| Term | What it is | Number from this lesson |
|---|---|---|
| Seasonal naive | copy the value one season back | MAE 4 on the ice cream year |
| MAE | average absolute miss, in units | 16 / 4 = 4 |
| MAPE | average miss as a percent of truth | 10.5%; a miss of 2 on a truth of 2 is 100% |
| sMAPE | miss over the mean of truth and forecast | 40% for 150, 66.7% for 50, truth 100 |
| MASE | MAE over the in-sample seasonal naive MAE | naive 2.56, seasonal naive 1.0 |
| Smoothing α | weight on the newest value | α = 0.3: 7 steps to close 90% of a jump |
| AR(1) | gap from the mean shrinks by φ per step | 58, 56.4, 55.12 from 60 |
| Pinball loss | trains a quantile | τ = 0.9: low miss costs 9, high miss 1 |
| PatchTST tokens | floor((L − P) / S) + 2 | 42 for 336, 16, 8 |
pythonimport numpy as np def seasonal_naive(y, m, h): # y: 1-D array, m: season length return np.array([y[len(y) - m + (i % m)] for i in range(h)]) def mase(y_train, y_test, y_hat, m): q = np.mean(np.abs(y_train[m:] - y_train[:-m])) # in-sample seasonal naive MAE return np.mean(np.abs(y_test - y_hat)) / q def ses(y, alpha): # returns the final level = flat forecast level = y[0] for v in y[1:]: level = alpha * v + (1 - alpha) * level return level def pinball(y, q, tau): d = y - q return np.mean(np.maximum(tau * d, (tau - 1) * d)) y_tr = np.array([20, 31, 45, 27, 25, 35, 49, 30]); y_te = np.array([27, 41, 52, 35]) print(mase(y_tr, y_te, seasonal_naive(y_tr, 4, 4), 4)) # 1.0 # the library versions from statsmodels.tsa.holtwinters import ExponentialSmoothing from statsmodels.tsa.arima.model import ARIMA hw = ExponentialSmoothing(y, trend="add", seasonal="add", seasonal_periods=12).fit() ar1 = ARIMA(y, order=(1, 0, 0)).fit() print(hw.forecast(12), ar1.get_forecast(3).conf_int(alpha=0.2))
| Situation | Start with |
|---|---|
| A few series with clear season | seasonal naive, then ETS or ARIMA |
| Many related series | a global model: boosted trees, DeepAR, N-BEATS, PatchTST |
| Known-future events matter | a model with covariates, such as TFT or boosted trees with date features |
| Little or no history | a foundation model zero-shot, checked against seasonal naive |
Now teach it back: open Teach or Present and explain MASE and the pinball loss out loud. Then go back to the hero and find the noise level where Holt-Winters stops beating the naive forecast.