Key ideas
- A time series is a sequence of observations indexed in time order, usually at equally spaced times. Examples: daily sales, hourly temperature, decades of seismic records.
- Patterns1: a trend is a long-term increase or decrease (not necessarily linear); a seasonal pattern repeats with a fixed, known period (day of week, month of year); a cycle is a rise and fall without a fixed period. Separately, outliers are points far outside the usual spread.
- Stationarity: the statistical properties do not depend on when you look2. Weak stationarity asks only for a constant mean, a constant finite variance and autocovariances that depend only on the lag3. Trend and seasonality make a series non-stationary; white noise is stationary, and so is a series with only aperiodic cycles2.
- Differencing removes a trend (each difference lowers a polynomial trend's degree by one); a seasonal difference removes a period- season2,3. A random walk has white-noise differences, and its best forecast is the last value2.
- AR() regresses on its own lags; MA() on past forecast errors; ARIMA() fits an ARMA model to the series differenced times ("Integrated")2. Seasonal ARIMA adds terms at lags 2; statsmodels' SARIMAX also takes exogenous regressors.
- An AR() process is stationary iff all roots of lie outside the unit circle; for AR(1), , and is a unit root (random walk)2. With near the series wanders in long runs; with it oscillates around the mean, zig-zagging for near 2.
- ACF/PACF: the autocorrelation at lag is the correlation of with ; the partial autocorrelation removes what the shorter lags already explain, so at lag 1 they coincide. AR(): PACF cuts off after lag , ACF decays. MA(): ACF cuts off after lag , PACF decays. ARMA: both decay2. For white noise, 95% of ACF spikes lie within 1. Both measure only linear dependence: no structure means uncorrelated, not independent.
- Simple exponential smoothing forecasts a weighted average whose weights fall geometrically with age; its forecast is flat for every horizon4.
- Forecasting with ML turns the series into a table5:
- a time dummy for the trend (quadratic and higher-order trends give unrealistic forecasts when extrapolated5);
- seasonal indicators ( one-hot columns, one season as baseline) or Fourier sine/cosine pairs, which need fewer columns for long periods;
- holiday/event indicators and lagged values.
- Leakage: a feature for time may only use information available when the forecast is made. A rolling mean must be shifted first (
y.shift(1).rolling(7).mean()); a variable that is planned in advance, such as a promotion calendar, may be used for future dates. - A tree predicts the mean target of a leaf, so a tree ensemble never predicts outside the range of targets it was trained on: beyond the training range of a feature such as time its prediction stays flat and cannot continue a trend. With a growing trend, predict the change , or fit the trend with linear regression and boost its residuals (hybrid).
- Validation: never shuffle. Use walk-forward (rolling-origin) evaluation: each test block is forecast by a model trained only on earlier data, then the origin moves forward. scikit-learn's
TimeSeriesSplitdoes this with growing training sets (see the code below). A good in-sample fit says little about forecast accuracy5. - State-space models: an HMM has a discrete hidden state; the Kalman filter is the analogue with a continuous, linear-Gaussian state6. In an HMM the observations alone are not a Markov chain: their dependence runs through the hidden states.
Formulas
- ARIMA on the differenced series: 2.
- AR(1) : mean (take expectations of both sides); forecasts are made recursively, feeding each forecast back in as a lag2.
- SES: 4.
- 1-D Kalman step for , 6: predict ; gain ; update , . As the filter trusts the measurement (, ); as it keeps its prediction.
Worked example
with last value .
- Stationary: the root of is , outside the unit circle. Long-run mean .
- Forecasts: , , then , , decaying towards 6.
- Its ACF is (), while its PACF is at lag 1 and 0 afterwards. With observations, sample autocorrelations beyond are significant at 5%.
In code
import numpy as np
import pandas as pd
from sklearn.model_selection import TimeSeriesSplit
y = pd.Series(np.arange(1.0, 11.0)) # toy series 1, 2, ..., 10
X = pd.DataFrame({"lag1": y.shift(1), # value at t-1
"mean3": y.shift(1).rolling(3).mean()}) # mean of t-3..t-1, no leakage
print(X.iloc[3].tolist()) # [3.0, 2.0] features for y = 4
for tr, te in TimeSeriesSplit(n_splits=3).split(X):
print(len(tr), te) # 4 [4 5] / 6 [6 7] / 8 [8 9]
Common pitfalls
- Random -fold splits train on the future; for forecasting use time-ordered splits.
- Weak stationarity needs constant mean, variance and autocovariances, not an unchanging distribution; strict stationarity (with finite variance) implies weak, not the other way round3.
- AR stationarity is about roots outside the unit circle, not about every : has a root at , inside the circle, so it is not stationary; has the roots 1 and 2, a unit root.
- A high lag-2 autocorrelation may just be lag-1 dependence carried over; look at the PACF before adding a lag-2 feature.
y.rolling(7).mean()withoutshift(1)includes today's value and leaks the target.- Differencing eliminates a trend (and, at lag , the seasonality) instead of merely smoothing it; differencing more often than needed adds spurious autocorrelation2.
References
- Hyndman & Athanasopoulos, Forecasting: Principles and Practice (3rd ed.), Ch. 2 Time series graphics — Sec. 2.3 Time series patterns; Sec. 2.9 White noise
- Hyndman & Athanasopoulos, Forecasting: Principles and Practice (3rd ed.), Ch. 9 ARIMA models — Sec. 9.1 Stationarity and differencing; 9.3 Autoregressive models; 9.4 Moving average models; 9.5 Non-seasonal ARIMA models (ACF and PACF plots); 9.7 ARIMA modelling in fable (Understanding constants in R; Plotting the characteristic roots); 9.8 Forecasting; 9.9 Seasonal ARIMA models
- Wikipedia: Stationary process — Strict-sense stationarity; Weak or wide-sense stationarity; Relationships between types of stationarity; Techniques to stationarize a non-stationary process
- Hyndman & Athanasopoulos, Forecasting: Principles and Practice (3rd ed.), Ch. 8 Exponential smoothing — Sec. 8.1 Simple exponential smoothing (Weighted average form; Flat forecasts)
- Hyndman & Athanasopoulos, Forecasting: Principles and Practice (3rd ed.), Ch. 7 Time series regression models — Sec. 7.2 Least squares estimation (Goodness-of-fit); Sec. 7.4 Some useful predictors; Sec. 7.7 Nonlinear regression
- Wikipedia: Kalman filter — Underlying dynamic system model; Details (Predict, Update)