Time-Series Fundamentals: Stationarity, ARIMA & Prophet
train_test_split will silently leak the future into the past and make your model look ten times better than it is. This lesson teaches you how to handle data that arrives one timestamp at a time: how to spot stationarity, how to read ACF and PACF plots like radiographs, how ARIMA, Holt-Winters, Prophet, and lag-feature-fed XGBoost actually differ, and how to validate without cheating.After this lesson, you will be able to:
- Explain why time-series data violates the i.i.d. assumption and why standard k-fold cross-validation produces fantastically optimistic estimates
- Decompose a series into trend, seasonality, and residual using additive and multiplicative models
- Test for stationarity with the Augmented Dickey-Fuller (ADF) test and apply differencing to achieve it
- Read ACF and PACF plots to choose the order (p, d, q) of an ARIMA model
- Compare ARIMA, SARIMA, Holt-Winters exponential smoothing, Prophet, and lag-feature regression, and pick the right tool for the job
- Validate forecasts honestly with TimeSeriesSplit, walk-forward validation, and forecasting-appropriate metrics (MAE, MAPE, sMAPE, MASE)
Before you start
Don't worry if "stationarity" sounds like physics — by the end of this lesson it will mean nothing more than "the series doesn't drift, doesn't change variance over time, and its autocorrelation depends only on the gap between two points, not where you are on the timeline." That's it. Three checkboxes.
#Why Time Series Is Different
Concretely, time-series data brings four inconveniences that ordinary tabular ML simply does not have to deal with:
- Order matters. Row 5 must come before row 6. You cannot shuffle the rows.
- Autocorrelation.
y_tis strongly correlated withy_{t-1},y_{t-7},y_{t-365}, etc. Standard error formulas that assume independence will under-report the true uncertainty. - Non-stationarity. Means and variances drift. A model trained on 2018-2019 data may be calibrated for a world that no longer exists in 2024 (regime shifts, COVID, policy changes, viral TikTok trends).
- Train/test split must respect time. The test set must come strictly after the training set in real time. Any leak of the future into the past — through preprocessing, through cross-validation folds, or through engineered features — produces a model that looks spectacular in development and humiliates you in production.
#Decomposing a Time Series
Most real-world series are built from a small number of building blocks:
- Trend. The long, slow drift (housing prices going up over decades, mobile-phone shipments growing then plateauing)
- Seasonality. Strict periodic cycles tied to a calendar (every December, every Monday at 9am)
- Cycle. Repeating but irregular patterns not tied to a fixed calendar (business cycles, El Niño, fashion)
- Residual / noise. What's left after removing the above; ideally white noise
Two ways to combine them:
Here is the workhorse exercise — we load the classic 1949-1960 monthly airline-passengers series, decompose it both ways, and look at its ACF and PACF. This is the diagnostic ritual every time-series analyst performs before fitting a single model.
H0, then model the residue.#Stationarity, Precisely
You will hear two flavors of stationarity. The strict definition is rarely what people mean in practice:
- Strict (strong) stationarity. The full joint distribution of
(y_t, y_{t+1}, …, y_{t+k})is invariant to shifts int, for everyk. This is too strong for any real dataset to satisfy. - Weak (covariance) stationarity.
E[y_t]is constant,Var[y_t]is constant and finite, andCov(y_t, y_{t+h})depends only on the lagh, not ont. This is what ARIMA needs, and what every test you will run targets.
y_t with Δy_t = y_t − y_{t-1} and test again. Most series become stationary after one or two regular differences plus (for seasonal data) one seasonal difference.Two short derivations explain the differencing advice above. The first shows why a random walk is the standard non-stationary series and what one difference does to it.
The second shows what differencing does to a trend and to a seasonal pattern.
An ACF plot decays very slowly (still significant at lag 30+). The PACF cuts off sharply after lag 1. The raw series looks like a slow upward drift with no clear seasonality. What does this pattern suggest about the appropriate AR order?
#Reading ACF and PACF Plots
h is the correlation between y_t and y_{t-h}. The partial autocorrelation function (PACF) is the correlation between y_t and y_{t-h} after removing the linear effects of y_{t-1}, …, y_{t-h+1}. Together they are how you read the "fingerprint" of a series:The ACF is a definition, but writing it as a ratio of autocovariances is a consequence of stationarity. Open the derivation to see how.
(p, q) once the series is stationary:| Pattern | Suggests |
|---|---|
ACF cuts off after lag q, PACF decays slowly | MA(q) — set q |
ACF decays slowly, PACF cuts off after lag p | AR(p) — set p |
| Both decay slowly (geometrically) | ARMA — try both small p and q, use AIC/BIC to pick |
| ACF still significant at lag 12 (or 7 for daily, 24 for hourly) | seasonal component — switch to SARIMA |
| ACF significant at every lag, never decays | not stationary — difference and re-plot |
#Classical Forecasting Models
#AR: Autoregression
y_t as a linear combination of its own past p values:For the first-order case AR(1) everything can be computed by hand, and it explains the geometric ACF decay in the cheat sheet. The derivation assumes the series is stationary, which needs the absolute value of phi below 1.
#MA: Moving Average
y_t as a linear combination of past forecast errors:The MA(q) variance and the ACF cut-off in the cheat sheet follow from one calculation, in which each shock appears in the sum only a few times.
#ARMA, ARIMA(p, d, q)
y_t is a function of past values and past errors. ARIMA adds an "I" for Integrated, which is just a fancy word for "we differenced the series d times before fitting":- p. Number of autoregressive lags (read from PACF)
- d. Number of times the series was differenced to make it stationary (read from ADF test)
- q. Number of moving-average lags (read from ACF)
(P,D,Q) block operating at seasonal lag s (12 for monthly-yearly, 7 for daily-weekly, 24 for hourly-daily, etc.).The notation ARIMA(p, d, q) and SARIMA(p, d, q)(P, D, Q)[s] is compact because of one device, the backshift operator. Open the derivation to see how the letters become one equation.
#Exponential Smoothing
A simpler family that often wins in practice:
- Simple exponential smoothing (SES). Forecast = weighted average of past observations with exponentially decaying weights. Good for series with no trend, no seasonality.
- Holt's linear method. SES + a separate exponentially-smoothed trend term. Good when there's a linear trend.
- Holt-Winters. Holt + a seasonal term. Comes in additive and multiplicative flavors. This is the workhorse for monthly retail data.
Where do "exponentially decaying weights" come from? Open the derivation to see them appear by unrolling one update rule.
#Prophet
y(t) = g(t) + s(t) + h(t) + ε:- g(t). A piecewise-linear or logistic trend with automatically detected changepoints
- s(t). Fourier-series seasonality at multiple periods (yearly, weekly, daily)
- h(t). A regression on user-supplied holiday indicators
- ε. Gaussian noise
You're forecasting daily sales for a retail chain. The series has strong yearly seasonality, a clear weekly pattern (Saturdays peak, Tuesdays trough), several years of history with occasional missing days, and the marketing team can hand you a CSV of every major US holiday plus the chain's promotional calendar. Which model is the most natural fit?
Why is standard k-fold cross-validation wrong for time series?
#The ML Approach: Lag Features + Boosting
The exercise below fits ARIMA, Holt-Winters, and an XGBoost-on-lags model to the airline-passengers series, walk-forward validated on the last two years.
A few things to notice about the cross-validation block above:
- The fold uses an expanding window — each fold uses more training data than the previous one, just like in production. The alternative is a sliding window (fixed-length training history that rolls forward), which is better when you suspect the dynamics change over time and old data hurts more than it helps.
- The ML model uses iterated 1-step forecasting: it predicts one step, feeds the prediction back in, and predicts the next. This is honest but the errors compound. An alternative is to train a separate model per horizon (a direct-strategy multi-output model).
- Ridge is a stand-in for XGBoost — XGBoost runs in Pyodide but only after a hefty wasm download; the workflow and the diagnostic story are identical and that is the load-bearing point of the exercise.
#Forecasting Metrics: Why MAE Beats MAPE
The metrics you used in classification (accuracy, F1) make no sense for continuous forecasts. The standard four:
#Pitfalls That Quietly Sink Real Projects
#When to Use What
| Situation | Reach for | Why |
|---|---|---|
| Single short series (< 200 obs), clear trend + one seasonality, no holidays | SARIMA or Holt-Winters | Strong inductive bias, well-calibrated uncertainty intervals, decades of theory |
| Daily/weekly business series with multiple seasonalities and known holidays | Prophet | Built exactly for this; multiple seasonalities and holidays are first-class |
| Many features available (promotions, weather, prices) | Lag-feature regression + XGBoost/LightGBM | Trees handle interactions, scale to lots of features, no stationarity requirements |
| Many related series (every SKU, every sensor) | Global deep model (DeepAR, N-BEATS, TFT) | Learns shared structure across series; classical models train one-per-series |
| Long-context patterns matter (months ahead from minute-level data) | Attention-based (Informer, PatchTST, foundation models like Chronos/TimeGPT) | Designed for very long inputs |
| The series is genuinely random walk (financial returns) | Honest baseline + uncertainty model (GARCH) | The expected value is yesterday's; the interesting thing to forecast is the variance |
#Key Takeaways
- Time series breaks the i.i.d. assumption. Order matters. Autocorrelation is signal. Train/test splits must respect time, and standard k-fold cross-validation produces dishonestly optimistic estimates.
- Stationarity is the prerequisite for ARIMA. Test with ADF, achieve it with differencing. A series is weakly stationary if the mean and variance are stable and the autocovariance depends only on the lag, not on the timestamp.
- ACF and PACF are diagnostic plots. ACF cuts off at lag
q→ MA(q). PACF cuts off at lagp→ AR(p). Slow decay in either means you need to difference more. - Pick the model by data shape, not by hype. ARIMA and Holt-Winters dominate short univariate series; Prophet dominates daily business data with holidays; gradient-boosted lag features dominate when you have rich covariates; deep models dominate when you have many series or long-context dependencies.
- Validate honestly. Walk-forward (TimeSeriesSplit) with an expanding or sliding window, MAE in original units, MASE relative to a seasonal-naive baseline. A model that doesn't beat MASE = 1 is worse than telling a stakeholder "use last year's number."
#Quick Check
An ACF plot shows the autocorrelation at lag 1 is 0.95, at lag 2 is 0.90, at lag 12 is 0.65, at lag 24 is 0.45 — values stay significant for dozens of lags. What is the most likely problem?