Calculate lagged association only over valid pairs, report support by lag and distinguish a seasonal clue from a causal explanation.
Autocorrelation plots: align equal-spaced periods before reading lag peaks
A lag must mean the same elapsed time
An autocorrelation plot places lag on the horizontal axis and the association between a series and its own shifted values on the vertical axis. Lag two means two sampling intervals, not merely two available rows. If a daily series skips Tuesday and the values on Monday and Wednesday are adjacent in a database query, treating them as lag one silently changes the elapsed time. Choose a fixed sampling schedule, sort by period, reject duplicates and gaps or apply a separately documented missing-data policy. The simple ledger below requires consecutive integer period IDs and finite measurements. Gap and calendar rules establish the input contract; event-aligned charts answer a different timing question.
Show pair counts, not just spikes
At lag k, only N minus k aligned pairs remain from N complete observations. Large lags therefore have less support, and a dramatic coefficient based on four pairs is fragile. Print the number of pairs beside a selected coefficient or in a companion table. The worked code uses Pearson correlation with means recalculated for each aligned pair set. This is a descriptive lagged Pearson coefficient, not every software package's traditional autocorrelation-function estimator, which may use a full-series mean and normalization. Name the estimator before comparing values across tools. A constant member of a pair set has zero variance, so the coefficient is undefined; display a missing mark instead of a fabricated zero. Small-sample display keeps thin tails visible without overstating them.
Read repetition cautiously
An alternating workload may produce a negative lag-one value and a positive lag-two value. A slow trend can also produce several high positive lag values even without a repeating cycle. A weekly schedule, a changed product mix or an instrumentation reset may create peaks that disappear after appropriate stratification or differencing. Inspect the run chart and known operational calendar before calling a spike seasonality. Correlation at a lag is not evidence that an earlier observation causes a later one. If the goal is forecasting, validate the candidate lag on held-out future periods and avoid using future values while constructing features. Forecast intervals describe predictive uncertainty, while event annotations make causal claims easier to audit.
Treat reference bands as assumptions
A horizontal zero line helps read sign. Statistical confidence bands require a noise model, chosen estimator and a policy for many inspected lags; a generic shaded band is not a universal significance test. Adjacent lag estimates are related, and checking dozens of lags invites chance extremes. Freeze a practical maximum lag based on the question and available pairs, then disclose it. When input values are residuals from a fitted model, describe that fit and its validation window; residual autocorrelation can expose missing structure, but a model trained on the entire evaluation span can hide it. Compare adjacent operational phases on the same vertical scale and keep period count, gap policy and estimator in the export. An export manifest carries the needed calculation details.
Worked contract
from math import isfinite, sqrt
def lagged_pearson(readings: list[tuple[int, float]], max_lag: int):
if len(readings) < 4 or not 1 <= max_lag <= len(readings) - 3:
raise ValueError("retain at least three pairs at every requested lag")
periods = [period for period, _ in readings]
values = [value for _, value in readings]
if (any(not isinstance(period, int) for period in periods) or
any(current != previous + 1
for previous, current in zip(periods, periods[1:])) or
any(not isfinite(value) for value in values)):
raise ValueError("readings must be ordered, consecutive and finite")
coefficients = []
for lag in range(1, max_lag + 1):
before, after = values[:-lag], values[lag:]
count = len(before)
before_mean = sum(before) / count
after_mean = sum(after) / count
centered_before = [value - before_mean for value in before]
centered_after = [value - after_mean for value in after]
numerator = sum(left * right for left, right in zip(centered_before,
centered_after))
spread_before = sum(value * value for value in centered_before)
spread_after = sum(value * value for value in centered_after)
correlation = (numerator / sqrt(spread_before * spread_after)
if spread_before and spread_after else None)
coefficients.append((lag, count, correlation))
return coefficients
alternating_load = list(zip(range(47, 55), [47.0, 59.0] * 4))
lag_summary = lagged_pearson(alternating_load, 3)
assert lag_summary[0] == (1, 7, -1.0)
assert lag_summary[1] == (2, 6, 1.0)
assert lag_summary[2] == (3, 5, -1.0)
assert lagged_pearson([(47, 83.0), (48, 83.0), (49, 83.0),
(50, 83.0)], 1)[0][2] is NonePerformance and operating cost
For N readings and K requested lags, each lag builds and scans N minus k paired values, yielding O(N·K) time and O(N + K) extra space, including temporary centered lists and the result. This favors an inspectable short-lag audit over an optimized transform; large K and long series justify a separately tested faster estimator with its own normalization rules. The eight-period alternating example returns minus one at lags one and three, plus one at lag two, and support counts seven, six and five. Constant readings return an undefined coefficient rather than a false zero.
Common Mistakes
- Treating consecutive database rows as consecutive time periods after a gap.
- Comparing coefficients from different estimator conventions without naming the method.
- Calling a high-lag spike seasonality when only a handful of pairs remain.
- Adding generic significance bands without a noise model or multiple-lag policy.
Validation drill
Take 83 completed daily workload measurements. Audit dates for gaps and duplicates, predeclare seven lags, plot each lagged coefficient with its pair count, then compare the result with a run chart and the known weekly operating schedule.
Read next
- Time-series charts: distinguish missing days, zeros and provisional periods
- Event-aligned charts: choose a baseline before comparing trajectories
- Forecast fan charts: label interval meaning and forecast horizon
- Chart annotations: align events to the right clock without claiming causality
