Sign in

Time series analysis

Time series exploratory analysis

The standard first questions about a series of evenly spaced observations: is it stationary, how does it depend on its past, and what are its trend and seasonal parts.

Overview

A time series is a sequence of values recorded at even steps, such as monthly sales. Unlike rows of an ordinary table, neighbouring values are related, and that relation is the thing to study. Three ideas organise the study. Stationarity means the series behaves the same way throughout: its level and spread do not drift, and most forecasting methods need that. Autocorrelation is the correlation of the series with a copy of itself shifted by some number of steps, called the lag. It shows how long the memory of the series is and whether a cycle repeats. Decomposition splits the series into a slow trend, a repeating seasonal pattern and what is left over, so that each can be examined on its own.

A short history

Udny Yule introduced autoregressive models in 1927 to study sunspot numbers, and classical decomposition into trend and seasonal parts was developed in the same era for economic series. George Box and Gwilym Jenkins published Time Series Analysis: Forecasting and Control in 1970, which made stationarity checks and the autocorrelation and partial autocorrelation plots the standard first steps. David Dickey and Wayne Fuller published their unit root test in 1979.

How it works

  1. Test for stationarity with adf, the augmented Dickey-Fuller test. It regresses each change of the series on the previous level and on earlier changes, and compares a t statistic with MacKinnon's critical values.
  2. Compute acf, the autocorrelation at each lag up to nlags.
  3. Compute pacf, the partial autocorrelation: the correlation at each lag once the shorter lags are accounted for, by the Durbin-Levinson recursion.
  4. Compare both against confidence_bound, the band inside which the values of pure noise would fall.
  5. Find the seasonal period with detect_period, which removes a straight-line trend and looks for the highest peak in the ACF.
  6. Split the series with decompose: a centred moving average over one full cycle gives the trend, the average of the detrended values at each position in the cycle gives the seasonal part, and the rest is the residual.
  7. Read trend_strength and seasonal_strength, which compare each part with the residual on a scale from 0 to 1.

Watch out for

  • The ADF test here returns a statistic, critical values and a decision, not a p-value. It looks for a unit root only, so a series with a steady trend or changing variance can pass and still be non-stationary.
  • Failing to reject the unit root is not proof of one. With short series the test has little power to tell a random walk from a slowly reverting series.
  • The classical decomposition assumes the seasonal pattern never changes, and its moving average leaves half a period of missing trend at each end.
  • A trend makes the ACF decay very slowly and hides everything else. Remove the trend, or difference the series, before reading the ACF for seasonality or model order.
  • About one lag in twenty falls outside the 95 percent band by chance alone, so a single spike at an odd lag is weak evidence.

Use cases

When to use it

Before forecasting or regressing on time-indexed data: to decide whether to difference a series, to choose autoregressive and moving-average orders from the ACF and PACF, to find the cycle length, and to examine trend and seasonality separately.

In industry

Retail and supply chain
Forecasters decompose weekly sales into trend and seasonal parts to separate real growth from the yearly holiday pattern before fitting a model.
Energy
Grid operators examine the daily and weekly autocorrelation of electricity load to choose the lags used in demand forecasts.
Economics
Central bank analysts test series such as prices or output for a unit root before modelling, since regressions between non stationary series can be spurious.

Choosing it: what must hold

  • Observations in time order at even intervals, with gaps filled or accounted for.
  • Enough history to cover several full seasonal cycles if you want to estimate seasonality.
  • One consistent definition of the measured quantity over the whole period.
  • A decision on whether seasonal swings are of constant size (additive) or grow with the level (multiplicative).

When to choose something else

IfUse instead
Observations arrive at irregular timesResample to a regular grid first, or use methods for event data
Rows are independent and their order carries no meaningDistribution analysis and summary statistics
There are several seasonal periods, such as daily and weekly togetherA multiple seasonal decomposition such as MSTL

Math foundations

  1. Autocorrelation

    rk=∑t=1n−k(xt−xˉ)(xt+k−xˉ)∑t=1n(xt−xˉ)2r_k = \frac{\sum_{t=1}^{n-k} (x_t - \bar{x})(x_{t+k} - \bar{x})}{\sum_{t=1}^{n} (x_t - \bar{x})^{2}}

    The correlation between the series and itself kk steps later. r0r_0 is 1. A peak at lag kk means values kk steps apart tend to be alike.

  2. White-noise band

    ∣rk∣≤z1−α/2n|r_k| \le \frac{z_{1-\alpha/2}}{\sqrt{n}}

    If the series were pure noise, its autocorrelations would fall inside this band with probability 1−α1 - \alpha. For α=0.05\alpha = 0.05 the numerator is 1.96. Values outside the band suggest real dependence.

  3. Partial autocorrelation

    ϕkk=rk−∑j=1k−1ϕk−1,j rk−j1−∑j=1k−1ϕk−1,j rj\phi_{kk} = \frac{r_k - \sum_{j=1}^{k-1} \phi_{k-1,j} \, r_{k-j}}{1 - \sum_{j=1}^{k-1} \phi_{k-1,j} \, r_j}

    The Durbin-Levinson step. It gives the link between xtx_t and xt−kx_{t-k} that the lags in between do not already explain. For an autoregression of order pp it is near zero beyond lag pp.

  4. The Dickey-Fuller regression

    Δxt=α+γ xt−1+∑i=1pδi Δxt−i+εt\Delta x_t = \alpha + \gamma \, x_{t-1} + \sum_{i=1}^{p} \delta_i \, \Delta x_{t-i} + \varepsilon_t

    If the series is a random walk, its changes do not depend on its level, so γ=0\gamma = 0. A clearly negative γ\gamma means the series is pulled back towards a fixed level. The test statistic is γ^\hat{\gamma} divided by its standard error.

  5. Additive decomposition

    xt=Tt+St+Rtx_t = T_t + S_t + R_t

    Trend plus seasonal plus residual. The multiplicative model uses a product instead and suits series whose seasonal swings grow with the level.

  6. Centred moving average for an even period

    Tt=1m(12xt−m/2+∑j=−m/2+1m/2−1xt+j+12xt+m/2)T_t = \frac{1}{m} \left( \tfrac{1}{2} x_{t-m/2} + \sum_{j=-m/2+1}^{m/2-1} x_{t+j} + \tfrac{1}{2} x_{t+m/2} \right)

    An average over exactly one cycle, so the seasonal ups and downs cancel and only the trend is left. The half weights at the two ends keep the window centred on tt when mm is even.

  7. Strength of a component

    F=max⁡ ⁣(0,  1−var⁡(R)var⁡(C+R))F = \max\!\left(0, \; 1 - \frac{\operatorname{var}(R)}{\operatorname{var}(C + R)}\right)

    With CC the trend or the seasonal part: near 1 when the component dominates the residual and near 0 when it is lost in the noise.

Symbols

xtx_t
the value of the series at time step t
nn
number of observations
xˉ\bar{x}
the mean of the series
kk
the lag: number of steps between the two values compared
rkr_k
autocorrelation at lag k
z1−α/2z_{1-\alpha/2}
standard normal quantile for significance level alpha
ϕk,j\phi_{k,j}
j-th coefficient of the order-k autoregression; the last one is the partial autocorrelation at lag k
Δxt\Delta x_t
the change from the previous step
α,γ,δi\alpha, \gamma, \delta_i
constant, level coefficient and lagged-change coefficients of the Dickey-Fuller regression (alpha is also the significance level in the band)
εt\varepsilon_t
the regression error at step t
pp
number of lagged changes in the regression (adf_lags)
Tt,St,RtT_t, S_t, R_t
trend, seasonal and residual parts at step t
mm
the seasonal period in observations
CC
the component whose strength is measured: the trend or the seasonal part

Worked by hand

A series of n=240n = 240 monthly values has autocorrelations r1=0.5r_1 = 0.5 and r2=0.25r_2 = 0.25. Find the 95 percent noise band and the partial autocorrelation at lag 2. At lag 1, ϕ11=r1\phi_{11} = r_1.

1.96240=1.9615.49=0.127\frac{1.96}{\sqrt{240}} = \frac{1.96}{15.49} = 0.127
ϕ11=r1=0.5\phi_{11} = r_1 = 0.5
ϕ22=r2−ϕ11 r11−ϕ11 r1=0.25−0.5×0.51−0.5×0.5=00.75=0\phi_{22} = \frac{r_2 - \phi_{11} \, r_1}{1 - \phi_{11} \, r_1} = \frac{0.25 - 0.5 \times 0.5}{1 - 0.5 \times 0.5} = \frac{0}{0.75} = 0

Both autocorrelations are well outside the band of 0.127, so the dependence is real. But the partial autocorrelation at lag 2 is zero: the link two steps back is fully explained by the link one step back. That is the signature of an autoregression of order 1.

Visual example

Loading the example.

Try this

  • Click each stage of the diagram in turn and watch the series come apart into trend, seasonal part and residual.
  • Set the trend slope to 0 and the carry-over to 0.9, then compare the test verdict with the plain series: slow wandering looks like a trend.
  • Click Residual and set the season height to 0: the autocorrelation bars beyond the first few fall inside the noise band.

Code sample

import numpy as np
from impl import TimeSeriesAnalysis
from config import TimeSeriesAnalysisConfig

rng = np.random.default_rng(0)
t = np.arange(240)
x = 50 + 0.2 * t + 5 * np.sin(2 * np.pi * t / 12) + rng.normal(0, 0.5, size=240)   # trend + yearly cycle + noise

ts = TimeSeriesAnalysis(TimeSeriesAnalysisConfig(nlags=24))
print(ts.detect_period(x))                       # 12
parts = ts.decompose(x)                          # trend, seasonal, residual arrays of shape (240,)
print(parts["seasonal_strength"], parts["trend_strength"])
print(ts.adf(np.cumsum(rng.normal(size=500)))["stationary"])   # False: a random walk has a unit root
print(ts.adf(rng.normal(size=500))["stationary"])              # True
print(ts.acf(x)[:4], ts.pacf(x)[:4])
Read the implementation (204 lines)
"""Time series analysis for one evenly spaced series.

NumPy and the standard library only. Autocorrelation (ACF) and partial autocorrelation (PACF, Durbin-Levinson
recursion), the augmented Dickey-Fuller test for a unit root with MacKinnon's critical values, detection of the
seasonal period from the ACF, and the classical decomposition into trend, seasonal and residual parts.
"""
from __future__ import annotations

import math
from statistics import NormalDist

import numpy as np

try:
    from .config import TimeSeriesAnalysisConfig
except ImportError:  # run from the template's own folder
    from config import TimeSeriesAnalysisConfig

# MacKinnon (2010) response surface for the ADF test with a constant and no trend:
# critical value = b0 + b1 / T + b2 / T^2 + b3 / T^3 for T observations in the regression.
_ADF_SURFACE = {
    "1%": (-3.43035, -6.5393, -16.786, -79.433),
    "5%": (-2.86154, -2.8903, -4.234, -40.040),
    "10%": (-2.56677, -1.5384, -2.809, 0.0),
}
_LEVEL_NAME = {0.01: "1%", 0.05: "5%", 0.1: "10%"}


class TimeSeriesAnalysis:
    """Stationarity, autocorrelation, seasonality and decomposition of a series x of shape (n,)."""

    def __init__(self, config: TimeSeriesAnalysisConfig | None = None) -> None:
        self.config = config or TimeSeriesAnalysisConfig()

    @staticmethod
    def _series(values, minimum: int = 3) -> np.ndarray:
        x = np.asarray(values, dtype=float).ravel()
        if np.isnan(x).any():
            raise ValueError("the series holds NaN; fill or interpolate missing observations first")
        if x.size < minimum:
            raise ValueError(f"the series needs at least {minimum} observations, got {x.size}")
        return x

    # ---- autocorrelation -----------------------------------------------------------------------------------
    def acf(self, values, nlags: int | None = None) -> np.ndarray:
        """Autocorrelation r[k] = sum((x_t - m)(x_{t+k} - m)) / sum((x_t - m)^2) for k = 0..nlags.

        Returns shape (nlags + 1,) with r[0] = 1. nlags defaults to config.nlags and is capped at n - 1.
        """
        x = self._series(values)
        nlags = min(self.config.nlags if nlags is None else nlags, x.size - 1)
        d = x - x.mean()
        total = float(d @ d)
        if total == 0:
            raise ValueError("a constant series has no autocorrelation")
        return np.array([1.0] + [float(d[k:] @ d[:-k]) / total for k in range(1, nlags + 1)])

    def pacf(self, values, nlags: int | None = None) -> np.ndarray:
        """Partial autocorrelation for lags 0..nlags by the Durbin-Levinson recursion. Shape (nlags + 1,).

        pacf[k] is the correlation between x_t and x_{t-k} once the lags in between are accounted for. For an
        autoregression of order p it is (close to) zero beyond lag p, which is how the order is read off.
        """
        r = self.acf(values, nlags)
        nlags = r.size - 1
        out = np.zeros(nlags + 1)
        out[0] = 1.0
        previous = np.zeros(0)  # AR coefficients of the order k - 1 fit
        for k in range(1, nlags + 1):
            denominator = 1.0 - float(previous @ r[1:k])
            if abs(denominator) < 1e-12:  # the series is perfectly predicted already
                break
            reflection = (r[k] - float(previous @ r[k - 1:0:-1])) / denominator
            previous = np.append(previous - reflection * previous[::-1], reflection)
            out[k] = reflection
        return out

    def confidence_bound(self, n: int) -> float:
        """Half-width of the band around zero for the ACF and PACF of white noise: z_(1 - alpha/2) / sqrt(n)."""
        return NormalDist().inv_cdf(1.0 - self.config.alpha / 2.0) / math.sqrt(n)

    # ---- stationarity --------------------------------------------------------------------------------------
    @staticmethod
    def _adf_regression(x: np.ndarray, lags: int, start: int) -> tuple[float, float, int, int]:
        """OLS of dx_t on [1, x_{t-1}, dx_{t-1}, ..., dx_{t-lags}], using differences from index `start` on.

        Returns (t statistic of the x_{t-1} coefficient, residual sum of squares, rows used, regressors).
        """
        dx = np.diff(x)
        rows = np.arange(start, dx.size)
        design = np.column_stack([np.ones(rows.size), x[rows]] + [dx[rows - j] for j in range(1, lags + 1)])
        target = dx[rows]
        coefficients, *_ = np.linalg.lstsq(design, target, rcond=None)
        residual = target - design @ coefficients
        rss = float(residual @ residual)
        dof = rows.size - design.shape[1]
        if dof <= 0:
            raise ValueError("the series is too short for this many lags")
        covariance = rss / dof * np.linalg.pinv(design.T @ design)
        return float(coefficients[1] / math.sqrt(covariance[1, 1])), rss, int(rows.size), int(design.shape[1])

    def adf(self, values) -> dict:
        """Augmented Dickey-Fuller test (constant, no trend). Null hypothesis: the series has a unit root.

        Returns {"statistic", "lags", "n_obs", "critical_values" {"1%", "5%", "10%"}, "stationary"}.
        "stationary" is True when the statistic is below (more negative than) the critical value at
        config.alpha, i.e. the unit root is rejected. A series with a deterministic trend or a changing
        variance is also non-stationary but is not what this test looks for.
        """
        x = self._series(values, 12)
        if x.std() == 0:
            raise ValueError("a constant series cannot be tested")
        lags = self.config.adf_lags
        if lags is None:
            max_lag = min(int(12.0 * (x.size / 100.0) ** 0.25), (x.size - 4) // 3)
            best = None
            for candidate in range(max_lag + 1):  # same rows for every candidate so the AICs compare fairly
                _, rss, rows, k = self._adf_regression(x, candidate, max_lag)
                aic = rows * math.log(max(rss, 1e-300) / rows) + 2 * k
                if best is None or aic < best[0]:
                    best = (aic, candidate)
            lags = best[1]
        statistic, _, rows, _ = self._adf_regression(x, lags, lags)
        critical = {name: b0 + b1 / rows + b2 / rows**2 + b3 / rows**3 for name, (b0, b1, b2, b3) in _ADF_SURFACE.items()}
        return {
            "statistic": statistic,
            "lags": int(lags),
            "n_obs": rows,
            "critical_values": critical,
            "stationary": bool(statistic < critical[_LEVEL_NAME[self.config.alpha]]),
        }

    # ---- seasonality ---------------------------------------------------------------------------------------
    def detect_period(self, values, max_period: int | None = None) -> int | None:
        """Seasonal period read from the ACF of the linearly detrended series, or None when there is none.

        The period is the lag (2 <= lag <= max_period, default n // 2) at which the ACF has its highest local
        peak, provided that peak exceeds both config.min_seasonal_acf and the white-noise confidence bound.
        """
        x = self._series(values, 8)
        t = np.arange(x.size)
        detrended = x - np.polyval(np.polyfit(t, x, 1), t)
        if np.allclose(detrended, 0.0, atol=1e-12 * max(1.0, float(np.abs(x).max()))):
            return None
        max_period = min(max_period or x.size // 2, x.size - 2)
        r = self.acf(detrended, max_period + 1)
        floor = max(self.config.min_seasonal_acf, self.confidence_bound(x.size))
        best = None
        for lag in range(2, min(max_period, r.size - 2) + 1):
            if r[lag] > r[lag - 1] and r[lag] >= r[lag + 1] and r[lag] > floor and (best is None or r[lag] > r[best]):
                best = lag
        return best

    # ---- decomposition -------------------------------------------------------------------------------------
    def decompose(self, values, period: int | None = None) -> dict:
        """Classical decomposition into trend, seasonal and residual parts.

        values: shape (n,) with n >= 2 * period. period: cycle length (default config.period, else detected).
        Returns {"trend" (n,), "seasonal" (n,), "residual" (n,), "period", "trend_strength",
        "seasonal_strength"}. The trend is a centred moving average over one full cycle, so its first and last
        period // 2 values are NaN (and the residual's with them). The seasonal part repeats one value per
        position in the cycle: the average detrended value there, centred to sum to zero (additive) or to
        average one (multiplicative). The two strengths are 1 - var(residual) / var(component + residual),
        floored at 0: near 1 when the component dominates the noise, near 0 when it does not.
        """
        x = self._series(values, 4)
        period = period or self.config.period or self.detect_period(x)
        if period is None:
            raise ValueError("no seasonal period was given or detected; pass period")
        if period < 2 or x.size < 2 * period:
            raise ValueError(f"the series must cover at least two full periods of length {period}")
        multiplicative = self.config.model == "multiplicative"
        if multiplicative and (x <= 0).any():
            raise ValueError("a multiplicative decomposition needs a strictly positive series")
        if period % 2:
            window = np.full(period, 1.0 / period)
        else:  # even cycle: half weight on both ends keeps the window centred
            window = np.r_[0.5, np.ones(period - 1), 0.5] / period
        half = window.size // 2
        trend = np.full(x.size, np.nan)
        trend[half:x.size - half] = np.convolve(x, window, mode="valid")
        detrended = x / trend if multiplicative else x - trend
        cycle = np.array([np.nanmean(detrended[position::period]) for position in range(period)])
        cycle = cycle / cycle.mean() if multiplicative else cycle - cycle.mean()
        seasonal = np.tile(cycle, x.size // period + 1)[:x.size]
        residual = x / (trend * seasonal) if multiplicative else x - trend - seasonal
        inside = ~np.isnan(trend)
        if multiplicative:  # logs turn the product into a sum for the strength measures
            t_part, s_part, r_part = np.log(trend[inside]), np.log(seasonal[inside]), np.log(residual[inside])
        else:
            t_part, s_part, r_part = trend[inside], seasonal[inside], residual[inside]

        def strength(component: np.ndarray) -> float:
            total = float(np.var(component + r_part))
            return max(0.0, 1.0 - float(np.var(r_part)) / total) if total > 0 else 0.0

        return {
            "trend": trend,
            "seasonal": seasonal,
            "residual": residual,
            "period": int(period),
            "trend_strength": strength(t_part),
            "seasonal_strength": strength(s_part),
        }
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
11, run with python3 -m unittest -v

Practice

Build 240 values as a straight-line trend plus a sine wave of period 12 plus noise, as in the template's README. Call detect_period, then decompose and read seasonal_strength and trend_strength. Run adf on a cumulative sum of random noise and on the noise itself, and compare the statistic with the critical values in each case.

Check on learning

  1. A random walk and a noisy series around a fixed level can look alike over a short stretch. What does the coefficient γ\gamma distinguish, and why does it matter for forecasting?
    A way to think about it

    Ask what each series does after a large upward move. One tends to come back, the other has no level to come back to.

  2. The ACF of a series decays slowly over 30 lags, while the PACF has one large spike at lag 1 and nothing after. What simple model does that point to?
    A way to think about it

    Each value depends on the one before, which depends on the one before that. Think about how indirect links show in the ACF but not in the PACF.

  3. Monthly sales grow each year, and the December peak grows with them. Why would an additive decomposition leave a pattern in the residual, and what would you change?
    A way to think about it

    An additive seasonal part has a fixed size. Compare with a model in which the seasonal effect is a percentage of the level.

  4. Why does a moving average over exactly one seasonal period remove the seasonality, when one over half a period would not?
    A way to think about it

    Every window of one full cycle contains each position of the cycle once, so the seasonal effects sum to the same amount wherever the window sits.

  5. You check 40 lags of the ACF of a series you believe is noise, and two lie just outside the 95 percent band. Is the series not noise after all?
    A way to think about it

    Count how many of 40 values you would expect outside a 95 percent band by chance.