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.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Example 1 - x=[1,2,3,4,5], max_lag=2
- •Reference - constant series gives 1 at lag 0 and 0 elsewhere
- •Sample - alternating series