Latticework

Command Palette

Search for a command to run...

Time Series

Stationarity

16 min

Explanation

A stationary time series has statistical properties (mean, variance) that stay roughly constant over time — it might wiggle up and down, but it doesn't systematically drift. Most time series models (including ARIMA, in the next module but one) assume stationarity — applying them to non-stationary data (like a stock price with a clear upward trend) gives unreliable results.

def is_approximately_stationary(series, threshold):
    n = len(series)
    half = n // 2
    mean1 = sum(series[:half]) / half
    mean2 = sum(series[half:]) / (n - half)
    return abs(mean1 - mean2) < threshold

Comparing the mean of the first half against the second half is a crude but genuinely useful stationarity check — a real trend shows up as a large difference between them.

Try it

A real stationarity test (like the Augmented Dickey-Fuller test) is more statistically rigorous than this split-in-half comparison -- but the core intuition (does the series' behavior change systematically over its length?) is exactly the same.

Loading editor…
Explanation

Differencing — replacing each value with the CHANGE from the previous one — is the standard fix for a trending, non-stationary series:

def difference_series(series):
    return [series[i] - series[i - 1] for i in range(1, len(series))]

trending = [10, 12, 14, 16, 18]
print(difference_series(trending))   # [2, 2, 2, 2] -- constant differences, much more stationary

A series with a steady upward trend has wildly non-constant VALUES, but its DIFFERENCES can be nearly constant — that's exactly what "removing the trend" means. The "I" in ARIMA (covered next) stands for "Integrated" — literally referring to how many times you need to difference a series before it becomes stationary.

Exercise

Write `is_approximately_stationary(series, threshold)`: split `series` into two halves, compute each half's mean, and return True if their absolute difference is below `threshold`.

Exercise

Write `difference_series(series)`: return the first differences — `series[i] - series[i-1]` for every valid `i` — a standard technique for removing a trend.

Quiz

What does it mean for a time series to be 'stationary'?

Checkpoint

You can check a series for approximate stationarity, and apply differencing to remove a trend and make a series more stationary.