Autocorrelation function
Background
The autocorrelation function (ACF) measures how a time series correlates with a lagged copy of itself. At lag it answers: "how similar is the series to itself steps ago?" The ACF is the basis for detecting seasonality and choosing the order of AR/MA models — for example, a slowly decaying ACF signals a trend, while a spike at lag 12 on monthly data signals yearly seasonality.
Problem statement
Implement autocorrelation(x, max_lag) returning the (biased) sample ACF for lags .
With the mean and the length, define the autocovariance and the ACF:
(The same divisor is used for every lag — the standard biased estimator.)
Input
x— 1-D sequence (np.ndarrayor list) of length .max_lag—int, the largest lag to compute ().
Output
An np.ndarray of length max_lag + 1 with ; is always 1.
Examples
Example 1
Input: x = [1, 2, 3, 4, 5], max_lag = 2
Output: [1.0, 0.4, -0.1]
Explanation: the mean is 3, so deviations are and . Then , and .
Constraints
- Divide every autocovariance by (not ) — the biased estimator used by most ACF tools.
- Normalize by so .
- If the series is constant (), return 1.0 at lag 0 and 0.0 for all other lags.
Notes
- The biased estimator (dividing by ) guarantees a positive-semidefinite ACF and is what
statsmodels.acfuses by default. - Confidence bands of roughly are used to judge which lags are significantly nonzero.
This problem ships 5 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Reference example
- •Lag 0 autocorrelation is always 1
- •Constant series: 1 at lag 0, 0 elsewhere
- •Output length is max_lag + 1
- •All autocorrelations lie within [-1, 1]