🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Time Series Analysis: Stationarity and ARIMA

StatisticsTime SeriesđŸŸĸ Free Lesson

Observations in order are not independent rows

Row order carries information in a time series, and throwing it away destroys the structure you are trying to model. Yesterday's value helps predict today's, last December's traffic predicts this December's, and the correlation between neighbouring observations is exactly what ordinary regression assumes away. When that assumption is violated, standard errors shrink artificially, t statistics inflate, and a regression can report highly significant coefficients for predictors that are merely trending together.

The remedies all begin with the same admission: temporal dependence must be modelled rather than ignored. That means differencing to remove slow-moving structure, adding lagged values of the outcome as predictors, or moving to a model family — autoregressive, state-space, or smoothing-based — that writes the dependence down explicitly. Once the dependence is handled, the remaining uncertainty behaves the way familiar tools expect, and forecasting becomes extrapolation from a structure rather than a guess about a line.

Trend, seasonality, cycle, and noise

A useful decomposition separates a series into a trend component for long-run direction, a seasonal component for fixed-period repetition, a cyclical component for irregular longer-horizon swings, and residual noise for everything unexplained. Trend and seasonality are the two that matter operationally: trend sets the level you will be at next year, and seasonality sets the level you will be at next Tuesday. Classical decomposition estimates both by smoothing — a centred moving average for trend and an average of like periods for seasonality — and STL decomposition improves on it by letting the seasonal component itself evolve slowly over time.

Knowing which components are present decides the model. A series with a trend is non-stationary in the mean and must be differenced or modelled with an explicit trend term. A series with strong seasonality needs seasonal lags or seasonal differencing; ignoring them leaves autocorrelation in the residuals that inflates every subsequent interval. Cyclical behaviour with no fixed period is the hardest to separate from trend with limited data, and the honest answer is often that the horizon is too short to distinguish them.

Stationarity and how to achieve it

Stationarity means the statistical properties of the series — mean, variance, autocorrelation structure — do not change with time. It is not a natural state; almost every interesting economic or behavioural series trends, drifts, or changes regime. It is a modelling convenience, because a stationary series has a distribution you can estimate from its own history, which is the basis for forecasting from a single observed path.

The Augmented Dickey-Fuller test formalises the check. Its null hypothesis is that a unit root is present, meaning the series is non-stationary, so a large p-value means you cannot remove the trend and a small p-value means you can. Because failing to reject is the default outcome, practitioners difference repeatedly until the test rejects, which in the ARIMA language means choosing the integration order d. First differencing removes a linear trend, second differencing removes curvature, and over-differencing introduces negative autocorrelation that shows up as an oscillating residual pattern.

Reading ACF and PACF to pick an order

The autocorrelation function measures correlation between the series and a lagged copy of itself at each lag; the partial autocorrelation function measures the correlation at a lag after removing the contribution of all shorter lags. Their decay patterns identify the model family. An autoregressive process of order p shows a partial autocorrelation that cuts off after lag p while the autocorrelation tails off geometrically; a moving-average process of order q shows the mirror image, with the autocorrelation cutting off and the partial tailing off.

These rules are heuristics rather than proofs, and in practice they narrow the candidate set which is then chosen by an information criterion. AIC penalises each parameter by two, BIC penalises by the logarithm of the sample size and therefore favours smaller models on long series. The final arbiter is the residual diagnostics: fitted residuals should look like white noise, with no significant autocorrelation left, no seasonal pattern, and constant variance. Structure remaining in the residuals means structure missing from the model.

ModelAutocorrelationPartial autocorrelationSignature
AR(p)Tails off, exponential or sinusoidalCuts off after lag pMomentum with feedback
MA(q)Cuts off after lag qTails offShocks that decay
ARMA(p, q)Tails offTails offBoth mechanisms present
Seasonal componentSpikes at seasonal lagsSpikes at seasonal lagsRepeatable periodic pattern

ARIMA, seasonal variants, and exponential smoothing

ARIMA packages three decisions into one model: differencing d times to reach stationarity, regressing on p lagged values of the series, and conditioning on q lagged forecast errors. The backshift operator notation makes the differencing compact, and the full specification ARIMA(p, d, q) is a complete description of the structure. When seasonality with a known period is present, the seasonal extension adds a second set of the same three orders for the seasonal part, giving the familiar seasonal specification with both non-seasonal and seasonal components.

Exponential smoothing offers a competing and often more interpretable family. Simple exponential smoothing produces a weighted average of the current observation and the previous forecast, with weights decaying geometrically; Holt's method adds a trend term; Holt-Winters adds a seasonal term. The smoothing parameters are directly meaningful — a value near one reacts quickly to new data, near zero behaves like a long average — and the state-space formulation gives prediction intervals for free. For many business series these models match ARIMA on accuracy while being far easier to explain to a stakeholder.

A forecasting workflow in Python

python
import numpy as np
from statsmodels.tsa.stattools import adfuller, acf, pacf

def stationarity_report(series, name="series"):
    result = adfuller(series, autolag="AIC")
    print(f"{name}: ADF statistic = {result[0]:.3f}, "
          f"p-value = {result[1]:.4f}")
    return result[1] < 0.05

rng = np.random.default_rng(17)
t = np.arange(240)
level = np.cumsum(rng.normal(0.4, 1.0, 240)) + 50
seasonal = 8 * np.sin(2 * np.pi * t / 12)
walk = level + seasonal + rng.normal(0, 2, 240)

print("raw series stationary?", stationarity_report(walk, "raw"))
diffed = np.diff(walk)
print("first difference stationary?",
      stationarity_report(diffed, "differenced"))

acfs = acf(diffed, nlags=20, fft=True)
pacfs = pacf(diffed, nlags=20)
print("ACF  lags 1-5:", np.round(acfs[1:6], 3))
print("PACF lags 1-5:", np.round(pacfs[1:6], 3))

The raw series fails the stationarity test, which is the expected outcome for anything with a random-walk component, and the first difference passes. The autocorrelation and partial autocorrelation of the differenced series then narrow down the autoregressive and moving-average orders before any model is fitted.

The second block fits a seasonal model, validates the residuals, and produces a forecast with intervals.

python
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.stats.diagnostic import acorr_ljungbox

train, test = walk[:200], walk[200:]

model = SARIMAX(train,
                order=(1, 1, 1),
                seasonal_order=(1, 1, 1, 12),
                enforce_stationarity=False,
                enforce_invertibility=False)
fit = model.fit(disp=False)
print(fit.summary().tables[1])

resid = fit.resid
print("Ljung-Box on residuals:")
print(acorr_ljungbox(resid, lags=[12, 24], return_df=True))

forecast = fit.get_forecast(steps=len(test))
mean = forecast.predicted_mean
interval = forecast.conf_int(alpha=0.05)

rmse = np.sqrt(np.mean((mean.values - test) ** 2))
print(f"RMSE = {rmse:.2f}")

fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(np.arange(180, 240), walk[180:], label="actual")
ax.plot(np.arange(200, 240), mean, label="forecast")
ax.fill_between(np.arange(200, 240),
                interval.iloc[:, 0], interval.iloc[:, 1],
                alpha=0.2, label="95% interval")
ax.legend()
plt.show()

The Ljung-Box check is the important line: a large p-value means the residuals retain no autocorrelation, so the model has extracted the temporal structure that was available. The shaded band widens with the horizon, which is the honest representation of how forecasting uncertainty grows the further out you look.

Time series mistakes

Common Mistakes

Fitting an ordinary regression to trending data

Fix: Difference the series or include lagged terms; otherwise coefficients reflect shared trend, not relationship.

Treating a non-significant ADF result as proof of stationarity

Fix: The null is a unit root, so failing to reject means non-stationary; difference and retest.

Ignoring seasonality that is visible in the plot

Fix: Add seasonal lags or seasonal differencing, then confirm with autocorrelation spikes at seasonal offsets.

Stopping at a model with autocorrelated residuals

Fix: Run a Ljung-Box test; residual autocorrelation means structure was left on the table.

Reporting point forecasts without intervals

Fix: Publish prediction intervals and let them widen with the horizon rather than implying false precision.

Splitting train and test randomly

Fix: Hold out the most recent contiguous block; random splits leak the future into the training set.

Best Practices

  • Plot the series before modelling; most specification decisions are visible.
  • Always test stationarity and difference until the residuals behave.
  • Select orders with AIC among a small candidate set, then verify with residual diagnostics.
  • Compare against a seasonal-naive baseline before claiming a model works.
  • Evaluate on a chronological holdout and report interval coverage, not only point error.

Time series essentials

Where to go next

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Mathematics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement