"""F2-conf-02: OLS slope of y on x with HAC (Newey-West, Bartlett) standard errors. Run from workspace root: ~/wp29/venv/bin/python out/analysis.py""" import json, math import numpy as np, pandas as pd import statsmodels.api as sm from scipy import stats d = pd.read_csv("data/series.csv") n_rows = len(d) issues = [] # data checks per = pd.PeriodIndex(d["month"], freq="M") if d[["x", "y"]].isna().any().any(): issues.append({"issue": "missing values", "handling": "rows dropped"}) d = d.dropna(subset=["x", "y"]) if per.duplicated().any(): issues.append({"issue": "duplicate months", "handling": "flagged"}) gaps = int(((per[1:] - per[:-1]).map(lambda o: o.n) != 1).sum()) if gaps: issues.append({"issue": f"{gaps} non-consecutive month steps", "handling": "flagged; HAC assumes equal spacing"}) d = d.sort_values("month").reset_index(drop=True) X = sm.add_constant(d["x"].values) y = d["y"].values T = len(y) ols = sm.OLS(y, X).fit() alpha_hat, beta_hat = ols.params se_iid = ols.bse[1] u = ols.resid rho_resid = float(np.sum(u[1:] * u[:-1]) / np.sum(u ** 2)) # Bandwidth: Andrews (1991) AR(1) plug-in for the Bartlett kernel, applied to the # slope score v_t = (x_t - xbar) u_t. Data-dependent, adapts to the strong persistence. v = (d["x"].values - d["x"].values.mean()) * u rv = float(np.sum(v[1:] * v[:-1]) / np.sum(v[:-1] ** 2)) a1 = 4 * rv ** 2 / ((1 - rv) ** 2 * (1 + rv) ** 2) andrews_bw = 1.1447 * (a1 * T) ** (1 / 3) hac_lags = int(math.ceil(andrews_bw)) # Bartlett weights 1 - j/(L+1), j<=L nw_rule = int(math.floor(4 * (T / 100) ** (2 / 9))) # Newey-West (1994) rule of thumb def hac(L): r = sm.OLS(y, X).fit(cov_type="HAC", cov_kwds={"maxlags": L, "use_correction": True}) return float(r.bse[1]) se_hac = hac(hac_lags) t_hac = beta_hat / se_hac p_hac = 2 * stats.norm.sf(abs(t_hac)) z = stats.norm.ppf(0.975) ci = (beta_hat - z * se_hac, beta_hat + z * se_hac) sens = {} for L in sorted({0, nw_rule, 8, 12, hac_lags, 18, 24, int(math.floor(0.75 * T ** (1 / 3)))}): s = hac(L) sens[L] = {"se": s, "t": beta_hat / s, "p_normal": 2 * stats.norm.sf(abs(beta_hat / s)), "p_t": 2 * stats.t.sf(abs(beta_hat / s), T - 2)} res = { "task_id": "F2-conf-02", "beta_hat": float(beta_hat), "alpha_hat": float(alpha_hat), "se_iid": float(se_iid), "rho_resid": rho_resid, "se_hac": se_hac, "hac_lags": hac_lags, "t_hac": float(t_hac), "p_hac": float(p_hac), "beta_ci_low": float(ci[0]), "beta_ci_high": float(ci[1]), "memo_claim_supported": bool(p_hac < 0.05), "n_analysed": int(T), "feasibility": "complete", "feasibility_reason": None, "data_issues": issues, "n_input_rows": {"series.csv": int(n_rows)}, "random_seed": None, } with open("out/results.json", "w") as f: json.dump(res, f, indent=2) diag = {"t_iid": float(beta_hat / se_iid), "p_iid": float(ols.pvalues[1]), "rho_score": rv, "andrews_bw": andrews_bw, "nw_rule_lags": nw_rule, "sensitivity": {str(k): v for k, v in sens.items()}} with open("out/diagnostics.json", "w") as f: json.dump(diag, f, indent=2) print(json.dumps(res, indent=2)); print(json.dumps(diag, indent=2))