Autocorrelation and Seasonality Detection

medium
Unit 14 · Time Series0/3 to milestone

Does a metric repeat every 7 days? Every 24 hours? The autocorrelation function (ACF) measures how correlated a series is with a lagged copy of itself:

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

(the standard estimator, dividing by the full-series variance).

Implement acf(x, max_lag) returning an array for lags 0..max_lag (lag 0 is always 1), and dominant_period(x, min_lag=2, max_lag=None): the lag in [min_lag, max_lag] with the highest ACF (lowest lag on ties), where max_lag defaults to len(x) // 2. Return 0.0s for a constant series' non-zero lags.

#time-series#statistics2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Autocorrelation and Seasonality Detection · TechGradify