Time-Series Forecasting

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.

Race four forecasters

4

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

Why Forecast, and Why One Number Is Not Enough

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

Push the forecast further out

Teal is the history. Warm is the forecast and its 80% band. Drag the horizon and watch the band open.

4

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.

Failure: the confident point forecast. Symptom: plans that work on average and fail badly on some days. Measure: count how often the truth falls outside your stated band; for an 80% band it should be about 1 time in 5. Fix: forecast a range, then pick the point inside it that matches your costs (Chapter 6).

The road

The hero above uses every idea below. Each chapter builds one part.

  1. The setup: lookback, horizon, a time-ordered split and the baselines.
  2. Scoring a forecast: MAE, MAPE, sMAPE and MASE, the hero's score.
  3. Smoothing: the moving average and exponential smoothing.
  4. Decomposition: trend plus season plus residual, and Holt-Winters.
  5. ARIMA: a value that leans on the last value, and differencing.
  6. Quantile forecasts: the band, trained with the pinball loss.
  7. Global models and N-BEATS: one network for many series.
  8. Transformers and foundation models: patches, PatchTST, TimesFM, Chronos.
  9. Covariates and what breaks: holidays, leakage and shifts.
  10. The field guide: terms, numbers, code and links.
A random walk has a typical step surprise of 5 units. How wide is its 80% band 9 steps ahead, compared with 1 step ahead?

Chapter 1

The Setup: Lookback, Horizon and Baselines

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.

The baselines

A baseline is a forecaster so simple that any real model must beat it. Three are standard.

  1. Mean: every future value is the average of the past.
  2. Naive: every future value equals the last value.
  3. Seasonal naive: each future value equals the value one season earlier, here the same quarter last year.

Pick a baseline

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.

Failure: a model that loses to seasonal naive. Symptom: a complex model with a good-looking loss. Measure: score seasonal naive on the same backtest. Fix: if the model does not beat it, ship the baseline and look for the bug.
You have three years of monthly data. Why must the test months come after the training months, never mixed in at random?

Chapter 2

Scoring a Forecast: MAE, MAPE, sMAPE and MASE

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.

Say it aloud

M-A-E equals one over n, times the sum over t of the absolute value of y-t minus y-hat-t.

MAE
M-A-E the mean absolute error, in the units of the series.
1/n
one over n divide by the number of scored steps n, to get an average.
Σt
the sum over t add one term for each scored step.
yt
y-t the true value at step t.
ŷt
y-hat-t the forecast for step t. The bars | | mean "drop the sign".
In plain words

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.

With numbers

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.

Say it aloud

MAPE equals one hundred over n, times the sum over t of the absolute miss, divided by the absolute value of y-t.

MAPE
MAPE the mean absolute percentage error, in percent.
100/n
one hundred over n average over n steps and turn the fraction into a percent.
Σt
the sum over t add one term for each scored step.
yt − ŷt
y-t minus y-hat-t the miss at step t.
ŷt
y-hat-t the forecast for step t.
|yt|
the absolute value of y-t the true value, used as the yardstick for that step.
In plain words

Divide each miss by its true value y-t. Average those fractions over the n steps. Multiply by 100.

With numbers

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.

Say it aloud

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.

MASE
MASE the mean absolute scaled error. No units. Below 1 beats the in-sample seasonal naive.
MAE
M-A-E your forecast's mean absolute error on the test steps.
q
q the scale: how much the series moves from one season to the next.
q =
q equals its definition follows.
mean
the mean over the training data average over every training step t that has a value m steps earlier.
yt
y-t a training value.
yt−m
y-t-minus-m the value one season earlier; m = 4 for quarters, 12 for months.
In plain words

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.

With numbers

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.

Sink the series toward zero

The forecast misses by the same amounts at every level. Drag the level down. Watch the red bars, one percentage error per month.

60

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.

Failure: MAPE on low-volume series. Symptom: a few slow-selling products dominate the average score. Measure: sort series by MAPE and look at their sales level. Fix: report MASE, or weight MAPE by volume.
One store sells about 3 units a day, another about 3,000. Your forecaster misses each by 2 units. Which score treats them on equal terms of how predictable each series is?

Chapter 3

Smoothing: Moving Average and Exponential Smoothing

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.

Say it aloud

L-t equals alpha times y-t, plus one minus alpha times L-t-minus-one.

ℓt
L-t the new level after seeing step t. It is also the forecast for every future step.
α
alpha the smoothing weight, from 0 to 1: how much the newest value counts.
yt
y-t the value just observed.
1 − α
one minus alpha how much the old level keeps.
ℓt−1
L-t-minus-one the level before step t.
In plain words

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.

With numbers

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.

Set how fast it forgets

The level jumps from 50 to 70 at week 30. Warm is the smoothed level. Drag alpha. Turn on the moving average to compare.

0.30

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.

Failure: smoothing a trending series. Symptom: the forecast sits below the truth and the gap grows each step. Measure: plot the forecast errors over the horizon; they all share one sign. Fix: add a trend term (Holt) or difference the series (Chapter 5).
The level is 40 and alpha is 0.5. The new value is 50. What is the new level, and what does smoothing forecast for 3 steps ahead?

Chapter 4

Decomposition: Trend, Season and Residual

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.

Say it aloud

y-t equals T-t plus S-t plus R-t.

yt
y-t the observed value at step t.
Tt
T-t the trend at step t, the slow part.
St
S-t the seasonal offset for step t's position in the cycle. The offsets of one cycle add up to zero.
Rt
R-t the residual, what is left over.
In plain words

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.

With numbers

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.

  1. Trend: a centred moving average over one full season. For quarters, average 5 values with weights 1/2, 1, 1, 1, 1/2, then divide by 4. At the third quarter: (10 + 31 + 45 + 27 + 12.5) / 4 = 31.375.
  2. Season: subtract the trend. Average what is left for each quarter. Shift the offsets so they sum to zero. Here they are −8.56, +0.56, +13.56 and −5.56.
  3. Residual: subtract both. Here every residual is 0.06.

Take a series apart

Top: the series. Below: the trend, season and residual that classical decomposition recovers. Drag the noise and see which strip absorbs it.

3

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.

Failure: additive season on a growing series. Symptom: the summer peaks grow with the level, and residuals swell in summer. Measure: plot residuals by season. Fix: use a multiplicative season (y = T × S × R), or take the logarithm first.
After you subtract the trend, the four quarterly averages are −8, +1, +14 and −5. Before you use them as seasonal offsets, what do you do, and why?

Chapter 5

ARIMA: Lean on the Last Value

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.

Say it aloud

y-hat at T-plus-h equals mu, plus phi to the h times the quantity y-T minus mu.

ŷT+h
y-hat at T-plus-h the forecast h steps after the last observation.
μ
mu the long-run mean the series returns to.
φh
phi to the h the pull-back factor phi, multiplied by itself h times.
yT
y-T the last observed value.
yT − μ
y-T minus mu today's gap from the mean.
In plain words

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 numbers

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.

Set the pull-back factor

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.

0.80

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.

Failure: ARIMA on a series with a trend. Symptom: the fitted φ sits near 1 and forecasts drift back to an old mean. Measure: plot the series and its differences; check if the mean moves. Fix: set d = 1, or remove the trend first.
An AR(1) has mean 100, phi 0.5, and the last value is 120. What is the forecast 2 steps ahead?

Chapter 6

Quantile Forecasts and the Pinball Loss

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.

Say it aloud

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.

Lτ(y, q)
L-tau of y and q the pinball loss for one forecast at quantile level tau.
τ
tau the quantile level, from 0 to 1: the price per unit when the forecast is too low.
y
y the true value.
q
q the forecast of the tau quantile.
1 − τ
one minus tau the price per unit when the forecast is too high.
In plain words

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 numbers

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.

Find the forecast with the lowest loss

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.

0.90

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.

Failure: a band that is too narrow. Symptom: the truth leaves the 80% band on 40% of days. Measure: coverage, the share of test points inside the band, per horizon step. Fix: retrain the quantiles on recent data, or widen the band until backtest coverage matches.
A stock-out costs 4 euros per unit and a leftover unit costs 1 euro. Which quantile should you stock to?

Chapter 7

Global Models and N-BEATS

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.

ApproachOne model perA new series
Local (ETS, ARIMA)seriesneeds its own history
Global (DeepAR, N-BEATS)whole collectionborrows 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.

Say it aloud

x-l-plus-one equals x-l minus x-hat-l; and y-hat equals the sum over l of y-hat-l.

xl+1
x-l-plus-one the input to the next block: what block l could not explain.
xl
x-l the input window of block l. Block 1 reads the raw lookback.
x̂l
x-hat-l the backcast: block l's fit of its own input.
ŷ
y-hat the final forecast for the horizon.
Σl
the sum over l add one term per block.
ŷl
y-hat-l block l's forecast, its share of the future.
In plain words

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 numbers

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.

Stack the blocks

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.

1

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.

Failure: a global model that ignores scale. Symptom: forecasts for small series look like the big series. Measure: MASE per series, grouped by volume. Fix: divide each window by its own mean or last value before training, and multiply back after.
In N-BEATS, what does block 2 receive as its input?

Chapter 8

Transformers and Foundation Models

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.

Cut the series into patches

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.

16
8

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.

ModelFromHow it reads a series
TimesFM (Das et al., 2023)Googlea decoder-only transformer over patches
Chronos (Ansari et al., 2024)Amazonscales and rounds values into a fixed vocabulary of tokens, then trains T5 language models, 20M to 710M parameters
Moirai (Woo et al., 2024)Salesforcea 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.

Failure: trusting zero-shot on your data. Symptom: a foundation model looks strong on public benchmarks and weak on your series. Measure: backtest it against seasonal naive and a tuned ETS on your own history. Fix: fine-tune, add your covariates, or keep the simpler model.
With L = 336, patch length 16 and stride 16 (no overlap), how many tokens does the PatchTST formula give?

Chapter 9

Covariates and What Breaks

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.

KindKnown when?Example
Known-futurefor the whole horizon, in advanceholidays, planned promotions, day of week
Past-observedonly up to todaya related product's sales, the weather so far
Staticfixed for the seriesstore location, product category

Move the holiday

The yellow marker is a holiday inside the forecast window. Drag it. Turn the covariate on and off and compare the misses.

12

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.

Three ways forecasts fail

Leakage. Symptom: the backtest is great and live accuracy is poor. Measure: check every input; was it known at the forecast origin? A "past-observed" input used as known-future is the usual leak. Fix: build each training row only from data available at its origin.
A regime shift. Symptom: errors jump and stay high after a date, such as a new competitor or a pandemic. Measure: plot the error per week; look for a step. Fix: weight recent data more, refit often, and widen the band after a shift.
A band nobody checks. Symptom: plans built on the 0.9 quantile run short every month. Measure: coverage per horizon step on a rolling backtest. Fix: recalibrate the quantiles and report coverage next to accuracy.
Which input is a known-future covariate for a 14-day sales forecast?

Chapter 10

The Field Guide

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.

TermWhat it isNumber from this lesson
Seasonal naivecopy the value one season backMAE 4 on the ice cream year
MAEaverage absolute miss, in units16 / 4 = 4
MAPEaverage miss as a percent of truth10.5%; a miss of 2 on a truth of 2 is 100%
sMAPEmiss over the mean of truth and forecast40% for 150, 66.7% for 50, truth 100
MASEMAE over the in-sample seasonal naive MAEnaive 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 step58, 56.4, 55.12 from 60
Pinball losstrains a quantileτ = 0.9: low miss costs 9, high miss 1
PatchTST tokensfloor((L − P) / S) + 242 for 336, 16, 8

Checklist

  1. Split by time. Backtest from several origins.
  2. Score seasonal naive first. Report MASE next to MAE.
  3. Plot the decomposition before you choose a model.
  4. Forecast quantiles and report coverage per horizon step.
  5. For every covariate, ask: will I know it at forecast time?
  6. Refit on a schedule and watch the error for a step change.

The core in code

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))

Which tool

SituationStart with
A few series with clear seasonseasonal naive, then ETS or ARIMA
Many related seriesa global model: boosted trees, DeepAR, N-BEATS, PatchTST
Known-future events mattera model with covariates, such as TFT or boosted trees with date features
Little or no historya foundation model zero-shot, checked against seasonal naive

Sources

Keep going

The takeaway. Predict the structure, price the rest. Beat seasonal naive on a time-ordered backtest, score with MASE, and ship a band whose coverage you have checked.

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.

Your new model has MAE 8.0 on the test year. Seasonal naive has an in-sample MAE of 10.0 on the training years. What is the model's MASE, and what does it tell you?
TIME-SERIES FORECASTING
Back to Gleams