Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs
Compute the autocorrelation function (ACF) for a time series to measure how similar the series is to a lagged version of itself. You’ll implement a simple, beginner-friendly ACF that returns correlations for lags from 0 up to a given maximum lag.
The autocorrelation at lag (k) is defined as:
Implement the function
Rules:
k = 0, 1, ..., max_lag.mu computed from the full series x for every lag.rho(0) should be 1.0).np.correlate or pd.Series.autocorr).Output:
| Argument | Type |
|---|---|
| x | np.ndarray |
| max_lag | int |
| Return Name | Type |
|---|---|
| value | np.ndarray |
Return NumPy array length max_lag+1
No np.correlate or built-in ACF utilities
Use vectorized operations
Compute a single mean mu = np.mean(x) from the full series, and reuse it for every lag.
Precompute the deviatiations diff = x - mu.
Compute the denominator denom = np.sum(diff**2) once.
For each lag k, use slicing diff[:-k] and diff[k:] to vectorize the numerator calculation.