Compute the partial autocorrelation function with Durbin-Levinson
Why it matters PACF plots are the classic tool for choosing the order p of an AR or ARIMA model, and Durbin-Levinson is how statistics libraries compute them.
The partial autocorrelation at lag k is the correlation between x_t and x_{t-k} after removing the effect of the lags in between. Its cutoff tells you the order of an AR model.
Write pacf_durbin_levinson(x, m). Compute autocorrelations r_0 = 1, r_1 .. r_m as in the standard (biased) estimator: r_k = sum_{t=k}^{n-1} (x_t - mean)(x_{t-k} - mean) / sum (x_t - mean)^2. Then run Durbin-Levinson: phi_11 = r_1; for k >= 2, phi_kk = (r_k - sum_{j=1}^{k-1} phi_{k-1,j} r_{k-j}) / (1 - sum_{j=1}^{k-1} phi_{k-1,j} r_j), and phi_kj = phi_{k-1,j} - phi_kk phi_{k-1,k-j} for j < k. Return the float array [phi_11, phi_22, ..., phi_mm].
def pacf_durbin_levinson(x, m)Example
x [1, 3, 2, 5, 4, 6, 5, 8], m 3 gives [0.244718, 0.374513, -0.415771] (rounded).
Understand the idea
Autocorrelation at lag 2 mixes two effects: x_t depends on x_{t-1}, which depends on x_{t-2}, so x_t and x_{t-2} look related even if there is no direct link. The partial autocorrelation (PACF) asks the cleaner question: after accounting for the lags in between, is there still a direct link?
For an AR(p) process, the PACF is nonzero up to lag p and then drops to about zero. That makes the PACF plot the classic way to pick p.
Durbin-Levinson computes it efficiently by fitting AR models of increasing order, reusing each one to build the next. Worked example: if r_1 = 0.5 and r_2 = 0.25 (exactly what an AR(1) with coefficient 0.5 gives), then phi_11 = 0.5 and phi_22 = (0.25 - 0.5 * 0.5) / (1 - 0.5 * 0.5) = 0. Lag 2 has no direct effect, as expected.
Rule: phi_kk = (r_k - sum phi_{k-1,j} r_{k-j}) / (1 - sum phi_{k-1,j} r_j), then phi_kj = phi_{k-1,j} - phi_kk phi_{k-1,k-j}.
Shapes and data flow
x (n,) -> r (m + 1,) -> phi rows of length 1 .. m -> pacf (m,)