ARIMA and SARIMA: differencing, forecasting and prediction intervals
Before this lesson: lesson 02 (stationarity, differencing, unit roots), lesson 04 (simple exponential smoothing) and lesson 05 (AR, MA, ARMA, -weights, AIC). Lesson 03 gives the benchmarks and backtests we compare against. Time: about 90 minutes, plus the notebook.
Why this matters #
- The standard statistical forecaster. ARIMA, with automatic order selection (
auto.arimain R,AutoARIMAin statsforecast,pmdarima), is a benchmark in almost every forecasting paper and in competitions such as M4 and M5. A new ML model that cannot beat it, or a seasonal naive forecast, is not useful. - Honest uncertainty. The ARIMA fan shows how uncertainty grows with the horizon, and it is exact under the model's assumptions. It is the reference for the probabilistic forecasts of lesson 10.
- Links to the rest of the track. Simple exponential smoothing (lesson 04) is an ARIMA(0,1,1); every ARIMA is a state-space model whose likelihood the Kalman filter computes (lesson 07); residuals of a seasonal ARIMA are a common anomaly score (lesson 11).
- Science. The CO₂ record of Mauna Loa, river flows, electricity load and epidemic counts are all modelled with seasonal ARIMA or regression with ARIMA errors.
1. Predict first #
2. The picture #
Differencing removes a unit root. A random walk is not stationary, but its difference is white noise (lesson 02). A linear trend disappears after one difference; a stable seasonal pattern with period disappears after a seasonal difference . ARIMA models the differences as ARMA and then "integrates" (sums) them back.
The forecast fan. Forecasts start at the forecast origin (yellow line) and go into the future. Around the point forecast (orange line) we draw the 80 % and 95 % prediction intervals (orange bands). The figure lets you compare model families.
Pick a model and move the sliders. Blue: the history (simulated from the chosen model, except for the CO₂ case). Orange line: the point forecast from the yellow origin; dark and light orange bands: 80 % and 95 % intervals. Notice: for AR(1) the forecast returns to the mean and the bands stop growing; for the random walk the bands grow like ; drift tilts the whole fan; ARIMA(0,1,1) gives a flat forecast with growing bands. The readout lists and the 95 % half-width at .
Why do the bands grow? Write the future value as a sum of shocks: . The future shocks are unknown, so they make up the forecast error. Each one adds to the variance. If the shrink quickly (a stationary model), the sum converges and the bands reach a fixed width. If the do not shrink (a differenced model, where every shock acts forever), the sum grows without limit.
Choose a model and move or . Top: the -weights (orange bars), the effect of a shock steps later. Bottom: the forecast variance (aqua line). Notice: for AR(1) the bars shrink like and the line flattens at ; for ARIMA(0,1,1) all bars after the first equal and the line keeps rising.
A random walk with is forecast from . What is the 95 % prediction interval at ?
For a random walk all , so and the standard deviation is . The half-width is . The variance grows like , so the width grows like , not like .
3. Definitions and main results #
ARIMA() #
Let be the difference operator, so and . An ARIMA() model says that the -times differenced series is a stationary, invertible ARMA():
with and (plus-sign convention, as in lesson 05). The AR part of the whole model, , has roots exactly on the unit circle at : the unit roots. In practice .
Special cases.
| Model | Equation | Name |
|---|---|---|
| ARIMA(0,0,0) | white noise with mean | |
| ARIMA(0,1,0) | random walk (the naive forecast of lesson 03) | |
| ARIMA(0,1,0) with | random walk with drift (the drift method) | |
| ARIMA(,0,0) | AR() | |
| ARIMA(0,1,1) | simple exponential smoothing |
Theorem (SES is ARIMA(0,1,1)). Simple exponential smoothing with parameter gives the same one-step forecasts as ARIMA(0,1,1) with , when both start from the same first forecast.
Proof.
- SES in error-correction form (lesson 04): , where and .
- Replace by : .
- For ARIMA(0,1,1), write the model at time : . The future shock is replaced by 0 and the past shock by the residual : .
- Steps 2 and 3 are the same recursion when . With the same start, all forecasts and residuals agree.
So corresponds to , an invertible MA part. SES assumes that the data are a random walk plus noise; this explains its flat forecast with growing intervals.
A fitted ARIMA(0,1,1) has (plus-sign convention). Which simple exponential smoothing gives the same one-step forecasts?
, so . The tempting answer comes from Box–Jenkins software, which writes the MA term with a minus sign: there and , the same model.
Forecasting step by step #
Let be the forecast made at origin for horizon . The rules (FPP3 §9.8):
- Write the model with alone on the left, everything else on the right.
- Replace by .
- On the right, replace future observations ( with ) by their forecasts, future shocks (, ) by 0, and past shocks (, ) by the residuals .
Why 0 for future shocks? The best forecast in mean squared error is the conditional mean , and a future shock has mean 0 and is independent of the data. Past shocks are not random any more once we have seen the data: for an invertible model they are functions of the observations, and the residuals estimate them (lesson 05).
Example: AR(1) with mean . . Then , and each further step multiplies by again:
The forecast decays geometrically from the last value to the mean. For any stationary ARMA the forecast tends to the mean as .
Press Step to compute the next forecast of the ARMA(1,1) from the origin with and residual . In each formula, blue terms are known data, magenta terms are residuals (past shocks), orange terms are earlier forecasts and grey terms are future shocks set to 0. Notice: the residual is used only at ; after that the forecast is times the previous forecast.
Forecast variance and prediction intervals #
Theorem (forecast error of an ARIMA model). Let the model have the -weights , defined by . Assume the parameters are known and the shocks are white noise with variance . Then the -step forecast error is
Proof idea.
- For a stationary ARMA, the MA() form gives .
- The terms with contain shocks up to time : they are known from the data, and they form the forecast. The terms with contain the future shocks: they have mean 0 and are independent of the data, so they form the error.
- The shocks are uncorrelated, so the variances add: .
- For there is no stationary MA() form, but the argument still works for a finite horizon. Unroll the model recursion from the origin : equals a function of the data up to plus , where the are the first coefficients of the power series .
The -weights come from the recursion of lesson 05, applied to the full AR polynomial : , .
| Model | () | as | |
|---|---|---|---|
| AR(1) | , the variance of | ||
| MA(1) | for , then 0 | for , then | constant from |
| random walk | grows like | ||
| ARIMA(0,1,1) | () | grows like |
A prediction interval under Gaussian shocks is
At every model gives . For a stationary model the half-width tends to times the standard deviation of ; for it grows like ; for like .
An AR(1) has mean and . The last observation is . What is the forecast ?
. After one step the distance to the mean halves to 2 (forecast 12); after two steps it halves again to 1. The forecast reaches the mean only as .
What and the constant do to the long run #
The constant and the number of differences fix the shape of the long-run forecast (FPP3 §9.5):
| goes to 0 | goes to a constant | follows a straight line | |
| goes to the mean | follows a straight line | follows a quadratic |
With , is the average change per step: the drift. The random walk with drift forecasts
, a straight line from the last value. With a nonzero constant
gives a quadratic trend, which is almost never sensible; software such as fable does not allow it.
Higher also makes the intervals grow faster. So is a modelling decision about the long run,
not only a way to pass a test.
Seasonal ARIMA #
For data with a seasonal period (12 for monthly data), the seasonal difference is . A seasonal ARIMA multiplies non-seasonal and seasonal polynomials:
with and . The capital letters act at multiples of .
Seasonal patterns in the ACF/PACF. The seasonal part shows up at lags :
- a seasonal MA(1), : one ACF spike at lag 12; the PACF decays over lags 12, 24, …;
- a seasonal AR(1), : the ACF decays over lags 12, 24, …; one PACF spike at lag 12.
The airline model (Box and Jenkins, first used for monthly airline passenger numbers):
Expand both sides. The left side is . The right side is . So
It has MA terms at lags 1, 12 and 13, but only two free coefficients (plus ). The lag-13 coefficient is the product : the multiplicative form ties it to the other two. The model says: "this month's change from last year is last month's change from last year, corrected by recent errors at both time scales".
Choose a transformation of the monthly Mauna Loa CO₂ series (1958–2001, Scripps; data from statsmodels). Top: the transformed series. Below: sample ACF (blue) and PACF (violet) up to lag 36 with the grey band ; dashed yellow lines mark the seasonal lags 12, 24, 36. Notice: the raw series and have a huge, slowly decaying ACF; still decays slowly; only looks stationary, with negative spikes at lags 1 and 12. Those two spikes ask for an MA(1) and a seasonal MA(1): the airline model.
Expand the airline model . Which lags of appear on the right side?
. The seasonal and non-seasonal polynomials multiply, so a cross term appears at lag . Its coefficient is not free: it is the product . That is why the model has only 2 MA parameters.
The Box–Jenkins workflow #
Box and Jenkins proposed an iterative cycle: identify, estimate, check, forecast. In the modern form of FPP3 §9.7:
- Plot the series. Look for outliers, level shifts and changes of variance.
- Transform if the variance grows with the level: a log or a Box–Cox transform (lesson 01).
- Difference until the series is stationary. Choose first (seasonal strength, or a clear seasonal pattern), then (a unit-root test such as KPSS, lesson 02). Rarely use .
- Identify candidate orders from the ACF/PACF of the differenced series (lesson 05 table, plus the seasonal patterns above).
- Estimate candidates by maximum likelihood and compare them by AICc. Remember: only models with the same and are comparable by AICc.
- Check the residuals: ACF inside the band, Ljung–Box test with degrees of freedom. If they fail, go back to step 4.
- Forecast, and back-transform if you transformed in step 2.
Back-transformation. If you model and forecast with forecast variance , then is the forecast median of , not its mean. For a Gaussian the mean is (FPP3 §5.6 calls this the bias adjustment). Intervals back-transform directly: .
Automatic ARIMA. The Hyndman–Khandakar algorithm (auto.arima) automates steps 3–5: it picks
by repeated KPSS tests and by a seasonal-strength measure, then searches (and )
stepwise. It starts from four models, for example ARIMA(2,,2) and ARIMA(0,,0), and moves and
by , with and without the constant, as long as AICc improves. It is a strong default, but it
still needs the residual check and a backtest.
Step through the workflow on the CO₂ series. Each box shows the check made at that step: the plot, the ACF after differencing, an AICc table of candidate models (fitted with statsmodels), the residual ACF and Ljung–Box test of the chosen model, and the 3-year forecast with 80 % and 95 % intervals. Notice: AICc slightly prefers a model with one more parameter, while BIC prefers the airline model; both pass the residual check.
Regression with ARIMA errors #
Often other variables help: temperature for electricity load, prices for sales, holidays. A regression with ARIMA errors (also called dynamic regression or ARIMAX) is
The regression explains the effect of the covariates, and the ARIMA error models the autocorrelation that is left. Three points matter:
- Fit both parts together by maximum likelihood. Ordinary least squares with autocorrelated errors gives wrong standard errors and can find spurious relations between unrelated trending series (lesson 02). If , the software differences and all together.
- To forecast, you need the future covariates. Calendar effects are known in advance; weather must itself be forecast, and its forecast error adds to yours.
- Fourier terms for long or non-integer seasons. For daily data with a yearly season () or several seasons, a seasonal ARIMA with is impractical. Use covariates and for (a dynamic harmonic regression), choose by AICc, and let a short ARIMA model the rest.
Changing variance: ARCH and GARCH
ARIMA assumes a constant shock variance . Financial returns violate this: calm periods and turbulent periods alternate (volatility clustering). The returns themselves are nearly uncorrelated, but their squares are strongly autocorrelated. Engle's ARCH model (1982) and Bollerslev's GARCH(1,1) (1986) model the conditional variance:
with , and , so the unconditional variance is finite. A large shock raises the next variance; makes the effect persist. ARIMA can model the mean and GARCH the variance of the same series. The point forecast does not change, but the intervals widen after turbulent days and narrow after calm ones.
Answers to section 1. (1) The random walk. The AR(1) interval tends to and stops growing; the random-walk interval is and grows without limit ( at ). (2) A straight line: . (3) At lags 1, 12 and 13 (the last one with coefficient ).
4. Worked example #
(a) ARMA(1,1) forecasts and intervals by hand. Model: with and mean 0. At the origin, and the last residual is .
- : . Replace by 0 and by : .
- : . Both shocks are in the future: .
- : . From now on each forecast is times the previous one.
- -weights: , , , .
- Variances: : ; : ; : .
- 95 % intervals: ; ; . As the half-width tends to .
For the ARMA(1,1) of example (a), with , and , a new value of is tried. What happens to the 95 % interval at ?
, so and the half-width is . In fact and cancel: the model is white noise (parameter redundancy, lesson 05). The model is still invertible: the root of is .
(b) SES as ARIMA(0,1,1). SES with is ARIMA(0,1,1) with . All for , so . With : the 95 % half-width is at and at . The point forecast is flat.
(c) The airline model on CO₂. Monthly mean CO₂ at Mauna Loa, March 1958 to December 2001
(; the 5 months without data are filled by linear interpolation). The variance does not grow
with the level, so no log is needed. The ACF of has spikes at lag 1 () and
lag 12 (). Maximum likelihood (statsmodels SARIMAX) gives
| Model | AICc | BIC |
|---|---|---|
| airline | 259.2 | 271.9 |
| 256.9 | 273.8 | |
| 258.3 | 275.2 | |
| 260.9 | 277.8 | |
| 265.6 | 282.5 | |
| 404.0 | 416.7 |
AICc prefers by 2.3 units; BIC prefers the airline model. A difference of about 2 is small, so we keep the simpler airline model. Its residuals pass the Ljung–Box test with (, 22 degrees of freedom, p-value 0.58). Forecasts from December 2001, with 95 % intervals:
| Horizon | Month | Forecast (ppm) | 95 % interval | |
|---|---|---|---|---|
| 1 | Jan 2002 | 371.98 | 0.30 | 371.38 – 372.57 |
| 12 | Dec 2002 | 372.54 | 0.72 | 371.12 – 373.95 |
| 24 | Dec 2003 | 374.13 | 1.07 | 372.03 – 376.22 |
| 36 | Dec 2004 | 375.72 | 1.39 | 372.99 – 378.44 |
The forecast continues the trend and the season. The interval widens like that of a model with two differences.
5. In code #
NumPy checks the worked example (a) and the -weight variance; the airline fit uses statsmodels.
import numpy as np
def psi_weights(phi_star, theta, m):
"""psi-weights for the full AR polynomial phi*(z) = 1 - sum phi*_i z^i (plus-sign MA)."""
psi = np.zeros(m); psi[0] = 1.0
for j in range(1, m):
psi[j] = (theta[j - 1] if j <= len(theta) else 0.0) + sum(
phi_star[i - 1] * psi[j - i] for i in range(1, min(j, len(phi_star)) + 1))
return psi
# (a) ARMA(1,1): phi = 0.6, theta = 0.3, y_n = 2.0, e_n = 0.5
f = [0.6 * 2.0 + 0.3 * 0.5]
for h in range(2, 4):
f.append(0.6 * f[-1])
psi = psi_weights([0.6], [0.3], 3)
half = 1.96 * np.sqrt(np.cumsum(psi**2))
print(np.round(f, 3), psi, np.round(half, 2)) # [1.35 0.81 0.486] [1. 0.9 0.54] [1.96 2.64 2.84]
# (b) ARIMA(0,1,1) with theta = -0.7: phi*(z) = 1 - z, so phi* = [1]
psi = psi_weights([1.0], [-0.7], 12)
print(psi[:4], round(1.96 * 2 * np.sqrt(np.sum(psi**2)), 2)) # [1. 0.3 0.3 0.3] 5.53
# (c) airline model on monthly CO2 (the data ship with statsmodels)
import statsmodels.api as sm
from statsmodels.tsa.statespace.sarimax import SARIMAX
co2 = sm.datasets.co2.load_pandas().data["co2"].resample("MS").mean().interpolate().to_numpy()
res = SARIMAX(co2, order=(0, 1, 1), seasonal_order=(0, 1, 1, 12)).fit(disp=False)
print(np.round(res.params, 3)) # [-0.353 -0.855 0.093]
fc = res.get_forecast(36)
print(np.round(fc.predicted_mean[[0, 11, 23, 35]], 2)) # [371.98 372.54 374.13 375.72]
6. Where it shows up #
- Forecasting practice. Retail demand, call-centre volumes, energy load, tourism and macroeconomic series are forecast with (seasonal) ARIMA or with its automatic versions; statistical agencies use X-13ARIMA-SEATS, a seasonal ARIMA, to remove the season from official statistics.
- Benchmarks for ML. The M4 and M5 competitions and most deep-learning forecasting papers report AutoARIMA and ETS as baselines. Lesson 08 and 09 compare against them with the backtests of lesson 03.
- Hybrid models. Gradient boosting on the residuals of an ARIMA, or ARIMA errors in a regression on weather covariates, combine the strengths of both worlds.
- Science. Seasonal ARIMA describes CO₂ and temperature records, river discharge and epidemic surveillance counts; residuals above the upper interval flag outbreaks or sensor faults (lesson 11).
7. Common mistakes #
- Over-differencing. Differencing a stationary series introduces an MA unit root: the differenced series has near and a non-invertible MA part, and the intervals become too wide. If the ACF of the differenced series starts with a large negative spike, you may have differenced once too often.
- Comparing AICc across different or . Differencing changes the data that the likelihood is computed on. Choose and first, then compare orders.
- Reading intervals as guaranteed. They ignore parameter uncertainty and model error. Check their coverage in a backtest.
- Forgetting the back-transform bias. is a median. Sums of such forecasts (for example monthly forecasts added up to a yearly total) are then biased low.
- Adding a constant with , or by habit with . With the constant is a drift that continues forever; include it only if the trend is real.
- Using future covariates you will not have. A regression with ARIMA errors evaluated with the observed future temperature looks better than it will be in production (leakage, lesson 03).
8. Check yourself #
- Write ARIMA(1,1,0) with as an equation for in terms of past .
Answer
. The left side is , so . It is an AR(2) with a unit root (). - For that model, compute the forecasts at from , .
Answer
. . The forecast changes are and , where is the last observed change . They decay geometrically, so the forecast levels off at . - What are the -weights of the random walk with drift, and the 80 % half-width at for
?
Answer
All (the drift does not change them). , so the half-width is . - Why does ARIMA(0,1,1) with close to behave almost like a constant mean model?
Answer
with makes both sides share the factor , which cancels: . In SES terms, : the level hardly moves, so the forecast is close to the long-run average. - A monthly series shows, after , a single significant ACF spike at lag 12 and
PACF spikes at lags 12, 24 and 36 that shrink. Which seasonal term do you add?
Answer
A seasonal MA(1): , the factor . A cut-off in the ACF at the seasonal lag with a decaying seasonal PACF is the MA signature, one season level up. - You fit a model to and get with . Give the median and the mean
forecast of .
Answer
Median . Mean (the approximation also gives 151.4).
Write the ARIMA() model with the backshift operator.
, with and .
Which ARIMA model is simple exponential smoothing with parameter ?
ARIMA(0,1,1) with .
When you forecast with an ARIMA model, what do you put in for future shocks and for past shocks?
Future shocks: 0 (their conditional mean). Past shocks: the residuals .
Give the -step forecast error variance of an ARIMA model.
, with the -weights of .
How does the 95 % interval of a random walk grow with the horizon ?
Like : the half-width is , because all .
Compute the forecast of an AR(1) with , , .
.
What is the airline model, and at which lags does it have MA terms?
SARIMA : ; MA terms at lags 1, 12 and 13 (coefficient ).
What does a seasonal difference with do?
It replaces by , the change from the same season one period earlier; it removes a stable seasonal pattern.
You forecast . Is the mean or the median forecast of ?
The median. The mean is for Gaussian errors.
What do you need to forecast with a regression with ARIMA errors?
The future values of the covariates; they must be known (calendar) or forecast themselves.
9. Interview angle #
- "Explain ARIMA in one minute." — Difference the series times to make it stationary, model the differences as ARMA(), and sum back to forecast. Choose by unit-root tests, and by AICc, and check the residuals.
- "Why do ARIMA intervals widen?" — The forecast error is a sum of the future shocks weighted by the -weights. With differencing, every shock has a permanent effect, so the variance grows linearly with the horizon.
- "ARIMA or exponential smoothing?" — They overlap (SES = ARIMA(0,1,1), and some Holt models are ARIMA too), but neither contains the other. Choose by a backtest, not by habit.
- "How do you handle multiple seasonalities or daily data with a yearly cycle?" — Fourier terms in a regression with ARIMA errors, or a state-space / ML model; not a SARIMA with .
- "Your 95 % intervals cover only 85 % in the backtest. Why?" — Parameter uncertainty, model misspecification, non-Gaussian or heteroscedastic errors. Fixes: bootstrap residuals, GARCH, or conformal calibration.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
arma_forecast(y, resid, phi, theta, c, h): the forecast recursion, checked on AR(1) against and on the worked example (a).psi_weights(phi_star, theta, m): the recursion, checked on AR(1) () and MA(1).forecast_intervalsfor ARIMA(0,1,1) and their coverage by simulation.- Fit a seasonal AR model by least squares on CO₂, undo the differences to forecast, and compare it with the seasonal naive forecast on the last two years.
- SES = ARIMA(0,1,1): the same one-step forecasts with .
An optional cell fits the airline model with statsmodels SARIMAX if it is installed.
11. Watch and read #
- Hyndman and Athanasopoulos, Forecasting: Principles and Practice, 3rd ed. (free online): §9.5 Non-seasonal ARIMA models (the constant and table), §9.7 ARIMA modelling in fable (the workflow and the Hyndman–Khandakar algorithm), §9.8 Forecasting, §9.9 Seasonal ARIMA models, §9.10 ARIMA vs ETS, §5.6 Forecasting using transformations, and chapter 10 on regression with ARIMA errors and dynamic harmonic regression.
- R. J. Hyndman and Y. Khandakar (2008),
"Automatic time series forecasting: the forecast package for R",
Journal of Statistical Software 27(3): the
auto.arimaalgorithm. - Shumway and Stoffer, Time Series Analysis and Its Applications, 4th ed., Springer 2017, ch. 3.7–3.9: forecasting, integrated and seasonal ARIMA, with proofs.
- Robert Nau (Duke University), Introduction to ARIMA models: free notes with practical rules for identifying orders.
- T. Bollerslev (1986), "Generalized autoregressive conditional heteroskedasticity", Journal of Econometrics 31: the GARCH model.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.