Edd's Knowledge Base

An autoregressive (AR) model predicts a value from its own past values. It is the basic building block of classical time-series forecasting, and it extends into ARMA, ARIMA, and seasonal models. Autocorrelation ideas come from Correlation Coefficients; the tests and p-values below build on Statistical Inference Basics.

is the number of lags and is the unexplained error at time .

What Makes a Model Autoregressive

The defining question is whether the model uses earlier values of the thing it predicts, not the model type. “Autoregressive” is a property of the predictors.

ModelPredictorsAutoregressive?
Linear regression of on temperature or hour of dayOther variablesNo
Linear regression of on Its own pastYes: AR(2)
Logistic regression of “alert this hour?” on the previous hours’ alert statusIts own pastYes: autoregressive logistic
Logistic regression on speed and locationOther variablesNo

Swapping the link function gives autoregressive GLMs: a logistic link for binary outcomes, a Poisson or negative-binomial link for counts, each with a linear predictor built from lagged terms.

“Autoregressive” also is not limited to time. It means predicting the next element from earlier ones in some ordering:

FamilyOrderingNotes
AR, ARMA, ARIMA, SARIMA, VARTimeClassical statistics
Spatial autoregressive (SAR)Space (neighbors)Value depends on nearby locations
LLMs, PixelCNN, WaveNetToken, pixel, or sample orderGenerative models that predict the next element

The Model Family

ModelPredicts fromHandles
AR()Past valuesPersistence
MA()Past errors (shocks)Short-lived shocks that fade after steps
ARMA()Past values and past errorsBoth, in fewer parameters
ARIMA()ARMA on the series differenced timesTrends
SARIMA()()ARIMA plus seasonal terms with period Seasonality (for example for hourly data with a daily cycle)
ARIMAX / SARIMAXAdds external (exogenous) inputsWeather, holidays

An MA() model is . Here is whatever the model could not predict at time , and a one-off shock appears in the readings at and then vanishes. This is why the ACF of an MA() cuts off after lag . The name is misleading: it is not a smoothing moving average.

In ARIMA(): is the number of past values, the number of times the series is differenced, and the number of past errors.

OrderModel
AR()
MA()
ARMA()
Random walk

Assumptions: Linearity and Stationarity

See Stationarity and Unit Roots for the full treatment, ARMA and ARIMA Models for the mixed and integrated models, and Vector Autoregression for several series.

  • Linearity: classic AR is a linear combination of lags. Relaxations: threshold and smooth-transition AR, and neural autoregressive models (NARX, DeepAR, LSTM and Transformer forecasters). It is linear in its parameters, so transformed lags (squares, logs) are possible.
  • Stationarity: roughly constant mean, variance, and autocorrelation over time; formally, all roots of the characteristic polynomial lie outside the unit circle. It is needed for the standard theory and stable forecasts, not for being able to run the fit.
SituationWhat happens
Trend or seasonalityNot stationary; difference (the “I” in ARIMA), detrend, or add seasonal terms
Unit root (, a random walk)Fit runs but estimates and tests behave unusually; forecasts do not revert to a mean
Structural breaksOne fixed AR is wrong across the break; use regime-switching or time-varying AR, or refit on recent data
Several trending series with a stable relationshipCointegration (vector error-correction models)

Stationarity tests

TestNull hypothesisSmall p-value means
ADF (Augmented Dickey-Fuller)Unit root (non-stationary)Evidence the series is stationary
KPSSStationaryEvidence the series is non-stationary
ADFKPSSConclusion
RejectsDoes not rejectStationary
Does not rejectRejectsNon-stationary: difference it
RejectsRejectsConflicting: often trend-stationary or a structural change
Does not rejectDoes not rejectInconclusive: little data or low power

Choose the deterministic term (constant, or constant plus trend) to match the series. Both tests have low power on short series, so pair them with a plot.

Why Identify the Order

The true model is unknown: nature does not label a series “AR(2)”. We choose a model that approximates the data. Too few terms underfit and leave structure in the residuals; too many overfit and forecast worse; the wrong family (AR on a strongly trending series) gives misleading results. This is the identify, estimate, check cycle of the Box-Jenkins method.

Finding , ,

  1. : plot the series, run ADF/KPSS, difference until stationary; use the smallest that works (usually 0 or 1, rarely 2). Over-differencing adds noise, signaled by a strongly negative lag-1 autocorrelation.
  2. and : read the ACF and PACF of the stationary series.
PatternACFPACFSuggests
AR()Decays graduallyCuts off after lag AR
MA()Cuts off after lag Decays graduallyMA
Both decayDecaysDecaysARMA
Slowly decaying ACF with a strong trendBarely decaysDifference first

Real plots rarely show a clean cutoff, so the reading gives starting guesses only. 3. Confirm by search: fit a small grid of orders around the guess and keep the lowest AIC or BIC (the simpler model if scores are close). 4. Check the winner’s residuals, then validate on held-out data.

Information Criteria

A criterion scores a model by balancing fit against complexity. Fit alone always favors the biggest model, so a penalty per parameter is added:

CriterionFormulaTendency
AICFavors predictive accuracy; slightly larger models
HQCBetween AIC and BIC; consistent
BICStrictest for ; prefers simpler models; consistent
AICcAIC with a small-sample correctionUse when is small relative to

Illustrative numbers (, = lag coefficients plus constant and variance):

ModelAICBIC
AR(1)3540546555.9
AR(2)4520528541.2
AR(3)5518528544.5
AR(4)6517529548.8

AIC ties AR(2) and AR(3); BIC clearly picks AR(2). Rules of use:

  • Compare only models fit to the same observations (higher lags drop initial rows).
  • Read differences, not raw values: a gap under about 2 is a near tie, above about 10 is strong evidence.
  • They rank candidates, they do not validate them: check residuals.
  • AIC for forecasting, BIC for parsimony or interpretation.

Likelihood ratio test (LRT)

Not an information criterion but a significance test between nested models (AR(2) is AR(3) with ):

With the numbers above, AR(2) vs. AR(3) gives , , : the extra lag is not significant, agreeing with BIC. Information criteria rank any set of models in one pass and need no ; the LRT needs nesting and a chosen .

Fitting the Parameters

Orders are chosen; coefficients (, , , ) are estimated. Fitting means finding the parameters that best match the training data; it is not just computing an error. In-sample error after fitting is optimistic, which is why penalties and held-out tests exist.

ModelMethodGradient updates?
AROLS (conditional least squares): regress on lags, ; loses the first observationsNo, closed form
ARYule-Walker: solve from sample autocovariances; guarantees a stationary fit, can be biased on short seriesNo, closed form
ARBurg: minimizes forward and backward prediction errors; good for short seriesNo
AR, ARMA, ARIMAMaximum likelihood, basis of AIC/BICYes for MA terms
MA, ARMA, ARIMAPast errors are unobserved and depend on the parameters, so no closed form: numerical optimizer (quasi-Newton such as BFGS), likelihood via the Kalman filter, conditional sum of squares for starting valuesYes, a few iterations, not epochs
Neural autoregressive modelsStochastic gradient descent over epochsYes

When to fit: after identification, for each candidate on training data only; refit on all data before real forecasts; refit on a schedule or when forecast error rises. Check convergence, roots in the stationary region, and residuals.

import itertools
from statsmodels.tsa.ar_model import AutoReg
from statsmodels.tsa.arima.model import ARIMA
 
ar = AutoReg(train, lags=2).fit()                 # OLS
print(ar.aic, ar.bic)
 
d = 1
best = min(((p, d, q) for p, q in itertools.product(range(4), range(3))),
           key=lambda o: ARIMA(train, order=o).fit().aic)
 
fc = ar.predict(start=len(train), end=len(train) + 9)   # 10 steps ahead

Not executed: statsmodels was not installed when this was written. Related tooling: ar_select_order(series, maxlag, ic="aic") (also "bic", "hqic") compares lags automatically, and pmdarima.auto_arima automates the order search including seasonal terms.

Using a Fitted Model

UseHow
DiagnosticsResiduals should be white noise: no ACF spikes (Ljung-Box p-value large), no pattern, mean near zero
One-step forecastPredict from the observed past; most accurate
Multi-step forecastRecursive: feed each forecast back in; errors accumulate and a stationary AR reverts to the mean, so long horizons are uninformative
Prediction intervalsAlways report; they widen with the horizon
EvaluationTime-based split (never shuffle) or rolling-origin walk-forward evaluation; MAE, RMSE, or MAPE (avoid near zero); compare against a simple baseline such as last value or last season
Anomaly detectionLarge residual (for example beyond of training residuals) signals a fault, attack, or regime change
UnderstandingCoefficients show persistence and how fast shocks fade; simulate paths from the fitted model
MaintenanceRefit regularly; watch for structural breaks
flowchart LR
    A["Plot + stationarity<br/>ADF, KPSS, difference (d)"] --> B["ACF / PACF<br/>candidate p, q"]
    B --> C["Fit candidates<br/>on training data"]
    C --> D["Select<br/>AIC / BIC"]
    D --> E["Check residuals<br/>white noise?"]
    E -- "fail" --> B
    E -- "pass" --> F["Validate on held-out data"]
    F --> G["Forecast + monitor,<br/>refit as data drifts"]

Applications

DomainUse
FinanceForecast prices, inflation, interest rates
Wireless communicationsModel fading channels and signal variations
Medical signalsAnalyze ECG/EEG for anomalies
Predictive maintenanceDetect equipment wear from vibration data
Climate and weatherPredict temperature and rainfall
Social sciencesModel unemployment and consumer trends
Network trafficForecast next-minute packet rate or bandwidth

Example: network traffic forecasting. Data-center and 5G networks log traffic continuously. A typical big data pipeline ingests logs with Kafka or Flume, stores them in HDFS, S3, or Cassandra, and fits AR models per node or partition in Spark (Stream Processing and Event Streaming, Apache Spark). Forecasts support load balancing (reroute before congestion), capacity planning, and anomaly detection (predicted vs. actual flags DDoS or faults), with Grafana or Kibana comparing real and predicted traffic. Spark MLlib has no built-in AR or ARIMA model, so the usual approach is one statsmodels fit per group using a grouped pandas function (applyInPandas). Reported efficiency gains such as “10 to 20 percent” are illustrative and uncited.

Limitations

Assumes linearity and stationarity, is sensitive to noise, and cannot capture nonlinear dynamics without extensions. Extend it with ARIMA, SARIMA, nonlinear AR, or ML models, and keep a simple baseline to justify any added complexity.