Autocorrelation asks how much a series resembles a delayed copy of itself. Shift it by lag steps, line it up against the original, and measure the correlation. It's how you find seasonality: daily sales will correlate strongly with themselves at a lag of 7.
Task: write autocorrelation(series, lag) returning that value, rounded to 4 decimal places.
The two halves are deliberately mismatched, and that's the part to get right:
Top: only the n - lag positions where both x_t and x_{t-lag} exist. Start at t = lag.
Bottom: the total squared deviation of the whole series — all n terms, regardless of lag.
Both use the mean of the entire series, not of the overlapping part.
lag is 0 or more and smaller than the length. The series is never constant, so the denominator is never zero.
At lag = 0 the two sums are identical and the result is exactly 1.0.
That asymmetric denominator is the standard definition, and it's deliberate: it guarantees the result stays within [-1, 1] and shrinks naturally as the lag grows and fewer pairs remain. Normalising by the overlap count instead gives an estimator that looks more "correct" and is in fact noisier and can exceed 1.
Watch what an alternating series does. At lag 1 every pair is opposite, giving a strong negative value; at lag 2 the series lines up with itself again and goes positive. That flip-flop is the signature of a period-2 cycle.