"""F2-conf-02: OLS slope of y on x with Newey-West HAC standard errors. Run from workspace root: ~/wp29/venv/bin/python out/analysis.py""" import json import numpy as np import 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 m = pd.PeriodIndex(d["month"], freq="M") gaps = int(((m[1:] - m[:-1]).map(lambda o: o.n) != 1).sum()) if d[["x", "y"]].isna().any().any(): issues.append({"issue": "missing values", "handling": "rows dropped"}) d = d.dropna(subset=["x", "y"]) if d["month"].duplicated().any(): issues.append({"issue": "duplicate months", "handling": "first kept"}) d = d.drop_duplicates("month") if gaps: issues.append({"issue": f"{gaps} gaps in monthly index", "handling": "kept; HAC lags count observations"}) X = sm.add_constant(d["x"].to_numpy()) y = d["y"].to_numpy() n = 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 # score series v_t = (x_t - xbar) u_t, which is what the HAC long-run variance targets. v = (d["x"].to_numpy() - d["x"].mean()) * u rv = float(np.sum((v[1:] - v.mean()) * (v[:-1] - v.mean())) / np.sum((v - v.mean()) ** 2)) a1 = 4 * rv ** 2 / ((1 - rv) ** 2 * (1 + rv) ** 2) hac_lags = int(np.floor(1.1447 * (a1 * n) ** (1 / 3))) nw_rule = int(np.floor(4 * (n / 100) ** (2 / 9))) # Newey-West (1994) rule of thumb, for sensitivity def hac(L): r = sm.OLS(y, X).fit(cov_type="HAC", cov_kwds={"maxlags": L, "kernel": "bartlett", "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) sens = {} for L in sorted(set([nw_rule, hac_lags, 12, 18, 24])): s = hac(L) sens[str(L)] = {"se_hac": s, "t": beta_hat / s, "p": float(2 * stats.norm.sf(abs(beta_hat / s)))} res = { "task_id": "F2-conf-02", "beta_hat": float(beta_hat), "alpha_hat": float(alpha_hat), "se_iid": float(se_iid), "t_iid": float(ols.tvalues[1]), "p_iid": float(ols.pvalues[1]), "rho_resid": rho_resid, "rho_score": rv, "se_hac": se_hac, "hac_lags": hac_lags, "hac_lags_nw_rule_of_thumb": nw_rule, "t_hac": float(t_hac), "p_hac": float(p_hac), "beta_ci_low": float(beta_hat - z * se_hac), "beta_ci_high": float(beta_hat + z * se_hac), "memo_claim_supported": bool(p_hac < 0.05), "hac_sensitivity": sens, "n_analysed": int(n), "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) print(json.dumps(res, indent=2))