Fit an AR(p) model by least squares and forecast several steps ahead

Autoregressive models predict the next value from the last p values. They are a fast baseline for metrics like request load, and the recursive forecast loop is the same shape as autoregressive text generation: each prediction becomes input to the next.

Write ar_forecast(y, p, h). y is a 1D array of length T, with T - p >= p + 1.
1. Build one training row for each t = p, ..., T - 1 with features [1, y[t-1], y[t-2], ..., y[t-p]] (most recent lag first) and target y[t]. Solve least squares to get coef = [c, phi_1, ..., phi_p].
2. Forecast recursively: start with history = list(y). For each of h steps, the next value is c + phi_1 * history[-1] + phi_2 * history[-2] + ... + phi_p * history[-p]. Append it to history and continue.

Return (coef, forecasts), both NumPy arrays (lengths p + 1 and h).

Signaturedef ar_forecast(y, p, h)

Example

y = [2, 2, 2, 2, 2] is not usable (the lag columns equal the constant column), so tests use series with real movement. For y generated exactly by y[t] = 1 + 0.5 * y[t-1], p = 1 recovers coef = [1.0, 0.5].

Understand the idea

An AR(p) model says the next value is a constant plus a weighted sum of the last p values. You learn the weights by ordinary least squares on lagged copies of the series, then forecast by feeding each prediction back in as the newest lag, the same loop a language model uses when it generates text. Worked example: y = [4, 3, 2.5, 2.25], p = 1. Rows are [1, 4] with target 3, [1, 3] with target 2.5, [1, 2.5] with target 2.25. These fit exactly with c = 1, phi_1 = 0.5. Forecast: 1 + 0.5 * 2.25 = 2.125, then 1 + 0.5 * 2.125 = 2.0625. Rule: feature row for time t is [1, y[t-1], y[t-2], ..., y[t-p]] with the most recent lag first, target y[t]; solve least squares for [c, phi_1, ..., phi_p]; each forecast is c + phi_1 * newest + phi_2 * second newest and so on. Pairing phi_1 with the oldest lag is the classic mistake. Used as a fast baseline for load and metric forecasting.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exact AR(1)ar_forecast(_y1, 1, 3)
  • Sample 2: noisy AR(2)ar_forecast(_y2, 2, 5)