DRegression models · regression.ar1
Regression with AR(1) errors (Prais–Winsten)
How does a numeric outcome depend on predictors when each residual carries over part of the previous one?
Feasible GLS for rows in time order: least squares first, then the first-order autocorrelation ρ of the residuals, then least squares on quasi-differenced data (Prais–Winsten keeps the first row, Cochrane–Orcutt drops it), optionally iterated until ρ settles. Coefficients with t intervals, ρ, and the Durbin–Watson statistic before and after the correction.
A real result
Example “Prais two step”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
ρ = 0.63, DW = 1.90
- ρ (AR(1))
- 0.6312
- Durbin–Watson (OLS)
- 0.7285
- Durbin–Watson (GLS)
- 1.901
- Residual SE
- 0.9469
Assumptions
- Remaining autocorrelation — Durbin–Watson of the transformed residuals = 1.90 (before the correction 0.73).
- Stationary errors — ρ = 0.631.
Coefficients (feasible GLS)
| Term | Estimate | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| (Intercept) | 1.425 | 0.5549 | 2.568 | .011 | 0.3260 | 2.524 |
| x1 | 1.038 | 0.0914 | 11.352 | < .001 | 0.8570 | 1.219 |
| x2 | −0.4144 | 0.0741 | −5.591 | < .001 | −0.5612 | −0.2676 |
Prais–Winsten, two-step; rows ordered by t; t tests with 117 df.
- Least squares on quasi-differenced data y_t − ρ·y_(t−1); Prais–Winsten keeps the first row scaled by √(1 − ρ²).
ρ = 0.63, DW = 1.90
- ρ (AR(1))
- 0.6312
- Durbin–Watson (OLS)
- 0.7285
- Durbin–Watson (GLS)
- 1.901
- Residual SE
- 0.9469
Assumptions
- Remaining autocorrelation — Durbin–Watson of the transformed residuals = 1.90 (before the correction 0.73).
- Stationary errors — ρ = 0.631.
Coefficients (feasible GLS)
| Term | Estimate | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| (Intercept) | 1.425 | 0.5549 | 2.568 | .011 | 0.3260 | 2.524 |
| x1 | 1.038 | 0.0914 | 11.352 | < .001 | 0.8570 | 1.219 |
| x2 | −0.4144 | 0.0741 | −5.591 | < .001 | −0.5612 | −0.2676 |
Prais–Winsten, two-step; rows ordered by t; t tests with 117 df.
- Least squares on quasi-differenced data y_t − ρ·y_(t−1); Prais–Winsten keeps the first row scaled by √(1 − ρ²).
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Prais two stepreg_ts · order: t · outcome: y · predictors: x1, x2
- Cochrane iteratedreg_ts · order: t · outcome: y · predictors: x1, regime
- Degenerate constantreg_ts · order: t · outcome: y · predictors: x1, x2
- Degenerate n3reg_ts · order: t · outcome: y · predictors: x1, x2
In the guides
Where it sits in the decision guides
- Continuous outcome: linear regression · Statistics Guide · D — Predict an outcome
- Independence · Statistics Guide · Step 2 — Check assumptions
What you need
- Outcomenumeric · 1 column
- The numeric variable you are analyzing.
- Predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
- Numeric predictors enter as is; categorical ones as dummy variables against their first level.
- Order bynumeric / temporal · 0–1 column
- Time order of the rows (the AR(1) model links each row to the one before it). Without it, the stored row order.
Choices you make
hypothesis
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- First rowdefault prais_winsten
Prais–Winsten keeps the first observation (better in short series); Cochrane–Orcutt drops it.
- Keep it (Prais–Winsten)(default) — The first row is scaled by √(1 − ρ²): no data are lost (better for short series).
- Drop it (Cochrane–Orcutt) — The first row is dropped after quasi-differencing (the classic textbook procedure).
- Iterate until ρ settlesdefault off
Off is the two-step estimator; on repeats the estimate of ρ and the refit until ρ changes by less than 1e-8.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Remaining autocorrelation
The Durbin–Watson statistic of the transformed residuals should be close to 2.
Stationary errors
|ρ| < 1: the errors return to their mean; ρ near 1 suggests differencing the series instead.
What it reports
- rho
- A number from −1 to 1 for how closely two variables move together; Pearson measures straight-line association.
- rho_first
- Correlation of a series with its own past; it breaks independence and shrinks the effective sample size.
- iterations
- Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
- dw_before
- Checks residuals for first-order autocorrelation. Values near 2 suggest none, and values well below 2 suggest positive correlation.
- dw_after
- Checks residuals for first-order autocorrelation. Values near 2 suggest none, and values well below 2 suggest positive correlation.
- n
- How many independent units the analysis used; it sets precision and power.
- n_used
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- sigma
- The distance between two distributions' average kernel embeddings; zero when they are equal.
- df_resid
- How much independent information is left to estimate variability after fitting the model.
Per group, level or term: coef[<term>], se[…], t[…], p[…], ci_low[…], ci_high[…]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines use the codesplash twin (least squares by QR / lstsq); statsmodels' GLSAR and R's prais package use the same estimator with different defaults (GLSAR drops the first row; prais iterates).
The exact script CodeSplash ran for example “Prais two step” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Regression with AR(1) errors (Prais–Winsten)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.ar1 1.0.1 · spec fabc213c76f4d6f3
# Dataset: reg_ts (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import linalg, stats
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import regdiag as rd
from codesplash.stats import regression as csreg
# %% Data
df = pd.read_parquet("tests/parity/fixtures/reg_ts.parquet", columns=["y", "x1", "x2", "t"])
n_input = len(df)
df = df.dropna(subset=["y", "x1", "x2", "t"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["y", "x1", "x2", "t"]) # infinite values stop the run (registry/errors.yaml)
# %% Rows in time order
y = "y"
predictors = ["x1", "x2"]
conf = 0.95
method = "prais_winsten" # prais_winsten | cochrane_orcutt
iterate = False
order_col = "t"
df = df.iloc[np.argsort(df[order_col].to_numpy(), kind="stable")]
X = csreg.design_matrix(df, predictors, "none", intercept=True)
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than coefficients (Cochrane–Orcutt drops the first row, so it needs one more).
cs.check_rows(len(df), X.shape[1] + (2 if method == "cochrane_orcutt" else 1), "Regression with AR(1) errors")
for col in [y] + predictors:
check_not_constant(df[col], col) # one value (or one level with data) is no variation
if np.linalg.matrix_rank(X.to_numpy()) < X.shape[1]:
cs.cs_error("CS_E_COLLINEAR")
n, k = X.shape
yv = df[y].to_numpy(dtype=float)
terms = list(X.columns)
# %% Feasible GLS
fg = rd.prais_winsten(X.to_numpy(), yv, method, iterate)
Xs, ys, b = fg["Xs"], fg["ys"], fg["coef"]
u = ys - Xs @ b
n_used = len(ys)
df_resid = n_used - k
s2 = float(u @ u) / df_resid
r_inv = linalg.solve_triangular(np.linalg.qr(Xs, mode="r"), np.eye(k))
V = s2 * (r_inv @ r_inv.T)
se = np.sqrt(np.diag(V))
tval = b / se
pval = 2 * stats.t.sf(np.abs(tval), df_resid)
crit = stats.t.ppf(1 - (1 - conf) / 2, df_resid)
dw_before = float((np.diff(fg["ols_resid"]) ** 2).sum() / (fg["ols_resid"] @ fg["ols_resid"]))
dw_after = float((np.diff(u) ** 2).sum() / (u @ u))
rho = fg["rho"]
# %% Assumptions
assumptions = [
{"key": "independence", "label": "Remaining autocorrelation", "status": "pass" if 1.5 <= dw_after <= 2.5 else "warn", "statistic": dw_after,
"detail": f"Durbin–Watson of the transformed residuals = {dw_after:.2f} (before the correction {dw_before:.2f})."
+ ("" if 1.5 <= dw_after <= 2.5 else " Autocorrelation remains: consider more lags (an ARIMA error model) or Newey–West errors.")},
{"key": "stationarity", "label": "Stationary errors", "status": "warn" if abs(rho) > 0.9 else "pass", "statistic": rho,
"detail": f"ρ = {rho:.3f}" + ("; close to 1 — the series may need differencing rather than an AR(1) correction." if abs(rho) > 0.9 else ".")},
]
# %% Result
values = {"rho": rho, "rho_first": fg["rho_first"], "iterations": fg["iterations"], "dw_before": dw_before, "dw_after": dw_after,
"n": n, "n_used": n_used, "k": k, "sigma": float(np.sqrt(s2)), "df_resid": df_resid}
rows = []
for j, term in enumerate(terms):
row = {"term": term, "estimate": float(b[j]), "se": float(se[j]), "t": float(tval[j]), "p": float(pval[j]),
"ci_low": float(b[j] - crit * se[j]), "ci_high": float(b[j] + crit * se[j])}
rows.append(row)
values.update({f"{key}[{term}]": row[key2] for key, key2 in
(("coef", "estimate"), ("se", "se"), ("t", "t"), ("p", "p"), ("ci_low", "ci_low"), ("ci_high", "ci_high"))})
pct = f"{conf:.0%}"
label = "Prais–Winsten" if method == "prais_winsten" else "Cochrane–Orcutt"
order_note = f"rows ordered by {order_col}" if order_col else "rows in stored order"
cs.publish({
"method": "regression.ar1",
"methodVersion": "1.0.1",
"title": "Regression with AR(1) errors",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": f"With AR(1) errors (ρ = {rho:.3f}), {label} feasible GLS gives the coefficients below; the Durbin–Watson statistic moved from {dw_before:.2f} to {dw_after:.2f}.",
"apa": f"ρ = {cs.fmt_num(rho)}, DW = {cs.fmt_num(dw_after)}",
"statistics": [
{"key": "rho", "label": "ρ (AR(1))", "value": rho}, {"key": "dw_before", "label": "Durbin–Watson (OLS)", "value": dw_before},
{"key": "dw_after", "label": "Durbin–Watson (GLS)", "value": dw_after}, {"key": "sigma", "label": "Residual SE", "value": float(np.sqrt(s2))},
],
"tables": [{"key": "coefficients", "title": "Coefficients (feasible GLS)", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": rows, "note": f"{label}, {'iterated (' + str(fg['iterations']) + ' steps)' if iterate else 'two-step'}; {order_note}; t tests with {df_resid} df."}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Least squares on quasi-differenced data y_t − ρ·y_(t−1); {label} {'keeps the first row scaled by √(1 − ρ²)' if method == 'prais_winsten' else 'drops the first row'}."],
"charts": [],
"values": values,
})
The exact script CodeSplash ran for example “Prais two step” · R version 4.5.1 (2025-06-13)
# Regression with AR(1) errors (Prais–Winsten)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.ar1 1.0.1 · spec fabc213c76f4d6f3
# Dataset: reg_ts (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/reg_ts.parquet", col_select = c("y", "x1", "x2", "t")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("y", "x1", "x2", "t")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("y", "x1", "x2", "t")) # infinite values stop the run (registry/errors.yaml)
# %% Rows in time order
y <- "y"
predictors <- c("x1", "x2")
conf <- 0.95
method <- "prais_winsten" # prais_winsten | cochrane_orcutt
iterate <- FALSE
order_col <- "t"
df <- df[order(df[[order_col]], method = "radix"), , drop = FALSE]
terms <- cs_design_labels(df, predictors, "none", intercept = TRUE)
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than coefficients (Cochrane-Orcutt drops the first row, so it needs one more).
cs_check_rows(nrow(df), length(terms) + (if (method == "cochrane_orcutt") 2 else 1), "Regression with AR(1) errors")
for (col in c(y, predictors)) cs_check_not_constant(df[[col]], col) # one value (or one level with data) is no variation
fml <- cs_model_formula(y, predictors, "none", intercept = TRUE)
X <- model.matrix(fml, data = df)
colnames(X) <- terms
if (qr(X)$rank < ncol(X)) cs_error("CS_E_COLLINEAR")
n <- nrow(X)
k <- ncol(X)
yv <- df[[y]]
# %% Feasible GLS
fg <- cs_prais_winsten(X, yv, method, iterate)
b <- fg$coef
u <- as.vector(fg$ys - fg$Xs %*% b)
n_used <- length(fg$ys)
df_resid <- n_used - k
s2 <- sum(u^2) / df_resid
V <- s2 * chol2inv(qr.R(qr(fg$Xs)))
se <- sqrt(diag(V))
tval <- b / se
pval <- 2 * pt(abs(tval), df_resid, lower.tail = FALSE)
crit <- qt(1 - (1 - conf) / 2, df_resid)
dw_before <- sum(diff(fg$ols_resid)^2) / sum(fg$ols_resid^2)
dw_after <- sum(diff(u)^2) / sum(u^2)
rho <- fg$rho
# %% Assumptions
ok_dw <- dw_after >= 1.5 && dw_after <= 2.5
assumptions <- list(
list(key = "independence", label = "Remaining autocorrelation", status = if (ok_dw) "pass" else "warn", statistic = dw_after,
detail = paste0(sprintf("Durbin–Watson of the transformed residuals = %.2f (before the correction %.2f).", dw_after, dw_before),
if (ok_dw) "" else " Autocorrelation remains: consider more lags (an ARIMA error model) or Newey–West errors.")),
list(key = "stationarity", label = "Stationary errors", status = if (abs(rho) > 0.9) "warn" else "pass", statistic = rho,
detail = paste0(sprintf("ρ = %.3f", rho), if (abs(rho) > 0.9) "; close to 1 — the series may need differencing rather than an AR(1) correction." else "."))
)
# %% Result
values <- list(rho = rho, rho_first = fg$rho_first, iterations = fg$iterations, dw_before = dw_before, dw_after = dw_after,
n = n, n_used = n_used, k = k, sigma = sqrt(s2), df_resid = df_resid)
rows <- lapply(seq_along(terms), function(j) list(term = terms[j], estimate = b[j], se = se[j], t = tval[j], p = pval[j],
ci_low = b[j] - crit * se[j], ci_high = b[j] + crit * se[j]))
for (r in rows) {
for (pair in list(c("coef", "estimate"), c("se", "se"), c("t", "t"), c("p", "p"), c("ci_low", "ci_low"), c("ci_high", "ci_high"))) {
values[[sprintf("%s[%s]", pair[1], r$term)]] <- r[[pair[2]]]
}
}
pct <- sprintf("%.0f%%", conf * 100)
label <- if (method == "prais_winsten") "Prais–Winsten" else "Cochrane–Orcutt"
order_note <- if (!is.null(order_col)) sprintf("rows ordered by %s", order_col) else "rows in stored order"
cs_publish(list(
method = "regression.ar1",
methodVersion = "1.0.1",
title = "Regression with AR(1) errors",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = sprintf("With AR(1) errors (ρ = %.3f), %s feasible GLS gives the coefficients below; the Durbin–Watson statistic moved from %.2f to %.2f.",
rho, label, dw_before, dw_after),
apa = sprintf("ρ = %s, DW = %s", cs_fmt_num(rho), cs_fmt_num(dw_after)),
statistics = list(
list(key = "rho", label = "ρ (AR(1))", value = rho), list(key = "dw_before", label = "Durbin–Watson (OLS)", value = dw_before),
list(key = "dw_after", label = "Durbin–Watson (GLS)", value = dw_after), list(key = "sigma", label = "Residual SE", value = sqrt(s2))
),
tables = list(list(key = "coefficients", title = "Coefficients (feasible GLS)", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = rows, note = sprintf("%s, %s; %s; t tests with %d df.", label,
if (iterate) sprintf("iterated (%d steps)", as.integer(fg$iterations)) else "two-step", order_note, as.integer(df_resid)))),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Least squares on quasi-differenced data y_t − ρ·y_(t−1); %s %s.", label,
if (method == "prais_winsten") "keeps the first row scaled by √(1 − ρ²)" else "drops the first row")),
charts = list(),
values = values
))
Sources
- Prais, S. J., & Winsten, C. B. (1954). Trend estimators and serial correlation. Cowles Commission Discussion Paper 383.
- Cochrane, D., & Orcutt, G. H. (1949). Application of least squares regression to relationships containing auto-correlated error terms. JASA, 44, 32–61.
- Greene, W. H. (2018). Econometric Analysis (8th ed.), §20.9. Pearson.
From the CodeSplash method registry · regression.ar1 v1.0.1.