"""F2-conf-02: OLS slope of y on x with HAC (Newey-West, Bartlett) SE. Run from workspace root.""" import json, numpy as np, pandas as pd, statsmodels.api as sm from scipy import stats d = pd.read_csv("data/series.csv") n_rows = len(d) issues = [] per = pd.PeriodIndex(d["month"], freq="M") assert d[["x", "y"]].notna().all().all(), "missing values" assert not per.duplicated().any() assert ((per[1:] - per[:-1]).map(lambda o: o.n) == 1).all(), "gaps" d = d.sort_values("month").reset_index(drop=True) T = len(d) X = sm.add_constant(d["x"].values); y = d["y"].values ols = sm.OLS(y, X).fit() a, b = ols.params; se_iid = ols.bse[1] u = ols.resid rho_resid = float(np.corrcoef(u[1:], u[:-1])[0, 1]) # Bandwidth: Andrews (1991) AR(1) plug-in for the Bartlett kernel, applied to the # slope score v_t = (x_t - xbar) * u_t. This adapts to the stated persistence (rho~0.7) # unlike the fixed Newey-West (1994) rule-of-thumb floor(4(T/100)^(2/9)). v = (d["x"].values - d["x"].mean()) * u rv = float(np.sum(v[1:] * v[:-1]) / np.sum(v[:-1] ** 2)) alpha1 = 4 * rv**2 / ((1 - rv) ** 2 * (1 + rv) ** 2) andrews_bw = 1.1447 * (alpha1 * T) ** (1 / 3) hac_lags = int(np.ceil(andrews_bw)) nw_rule = int(np.floor(4 * (T / 100) ** (2 / 9))) def hac(L): r = sm.OLS(y, X).fit(cov_type="HAC", cov_kwds={"maxlags": L, "use_correction": True, "kernel": "bartlett"}) return float(r.bse[1]) se_hac = hac(hac_lags) t_hac = b / se_hac p_hac = 2 * stats.norm.sf(abs(t_hac)) z = stats.norm.ppf(0.975) sens = {} for L in sorted({0, nw_rule, 8, 12, hac_lags, 18, 24}): s = hac(L); sens[str(L)] = {"se": s, "t": b / s, "p": float(2 * stats.norm.sf(abs(b / s)))} res = { "task_id": "F2-conf-02", "beta_hat": float(b), "alpha_hat": float(a), "se_iid": float(se_iid), "t_iid": float(ols.tvalues[1]), "p_iid": float(ols.pvalues[1]), "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(b - z * se_hac), "beta_ci_high": float(b + z * se_hac), "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, "bandwidth_details": {"rule": "Andrews (1991) AR(1) plug-in, Bartlett kernel, on slope score", "score_ar1": rv, "andrews_bw_raw": andrews_bw, "nw1994_rule_of_thumb": nw_rule}, "hac_lag_sensitivity": sens, } json.dump(res, open("out/results.json", "w"), indent=2) print(json.dumps(res, indent=2))