"""F3-conf-03: rolling-origin ridge vs naive / expanding-mean forecasts of US IP growth (h=1). Run from workspace root: ~/wp29/venv/bin/python out/analysis.py Reads only data/; writes out/results.json, out/forecasts.csv, out/exclusions.csv. No randomness.""" import json, os import numpy as np import pandas as pd DATA = "data/ip_predictors.csv" OUT = "out" LAM = 50.0 FIRST, LAST = pd.Timestamp("2021-09-01"), pd.Timestamp("2026-08-01") TRAIN_START = pd.Timestamp("1992-03-01") MEAN_START = pd.Timestamp("1992-04-01") FEATS = ["ip_growth", "ip_lag1", "ip_lag2", "oil_chg", "fedfunds", "permit_chg", "neworder_chg", "tcu"] raw = pd.read_csv(DATA, parse_dates=["month"]) n_raw = len(raw) d = raw.sort_values("month").reset_index(drop=True) assert d["month"].is_unique assert (d["month"].values == pd.date_range(d.month.min(), d.month.max(), freq="MS").values).all() d["ip_lag1"] = d["ip_growth"].shift(1) d["ip_lag2"] = d["ip_growth"].shift(2) d["y_next"] = d["ip_growth"].shift(-1) # target y_{s+1}, aligned to row s d = d.set_index("month") origins = pd.date_range(FIRST, LAST, freq="MS") rows, ntrain = [], {} for t in origins: tgt = t + pd.DateOffset(months=1) actual = float(d.loc[tgt, "ip_growth"]) # naive f_naive = float(d.loc[t, "ip_growth"]) # expanding mean 1992-04..t f_mean = float(d.loc[MEAN_START:t, "ip_growth"].mean()) # ridge: training rows s in [1992-03, t-1]; y_{s+1} dated <= t tr = d.loc[TRAIN_START:t - pd.DateOffset(months=1)] X = tr[FEATS].to_numpy(float); y = tr["y_next"].to_numpy(float) assert np.isfinite(X).all() and np.isfinite(y).all() assert tr.index.max() + pd.DateOffset(months=1) <= t mu = X.mean(0); sd = X.std(0, ddof=1); ybar = y.mean() Z = (X - mu) / sd b = np.linalg.solve(Z.T @ Z + LAM * np.eye(len(FEATS)), Z.T @ (y - ybar)) zt = (d.loc[t, FEATS].to_numpy(float) - mu) / sd f_ridge = float(ybar + zt @ b) ntrain[t] = len(tr) for m, f in (("naive", f_naive), ("mean", f_mean), ("ridge", f_ridge)): rows.append(dict(origin_date=t.strftime("%Y-%m-%d"), target_date=tgt.strftime("%Y-%m-%d"), horizon=1, forecast=f, actual=actual, model=m)) fc = pd.DataFrame(rows) fc.to_csv(os.path.join(OUT, "forecasts.csv"), index=False, float_format="%.10f") def metrics(m): e = fc.loc[fc.model == m, "forecast"] - fc.loc[fc.model == m, "actual"] return float(np.sqrt(np.mean(e ** 2))), float(np.mean(np.abs(e))) r = {m: metrics(m) for m in ("naive", "mean", "ridge")} n_last = ntrain[origins[-1]] # Diebold-Mariano test (squared loss, h=1, HLN small-sample correction, t_{n-1} reference) from scipy import stats def dm(base): e_b = (fc.loc[fc.model == base, "forecast"].values - fc.loc[fc.model == base, "actual"].values) e_r = (fc.loc[fc.model == "ridge", "forecast"].values - fc.loc[fc.model == "ridge", "actual"].values) dd = e_b ** 2 - e_r ** 2 # >0 means ridge better n = len(dd); var = dd.var(ddof=0) / n stat = dd.mean() / np.sqrt(var) * np.sqrt((n - 1) / n) # HLN factor for h=1 p = 2 * stats.t.sf(abs(stat), df=n - 1) return float(stat), float(p) dm_naive, dm_mean = dm("naive"), dm("mean") # exclusion ledger: raw rows -> rows usable as ridge training rows at last origin n_after_start = int((d.index >= TRAIN_START).sum()) n_after_end = n_last excl = pd.DataFrame([ dict(step=1, rule="drop months before 1992-03-01 (missing neworder_chg / lags unavailable; spec training start)", n_before=n_raw, n_after=n_after_start, n_removed=n_raw - n_after_start, rationale="TASK.md fixes training start s >= 1992-03-01"), dict(step=2, rule="drop months s with s+1 > last origin 2026-08-01 (target not available at last origin)", n_before=n_after_start, n_after=n_after_end, n_removed=n_after_start - n_after_end, rationale="information-availability rule: y_{s+1} must be dated <= origin"), ]) excl.to_csv(os.path.join(OUT, "exclusions.csv"), index=False) res = { "task_id": "F3-conf-03", "n_origins": int(len(origins)), "first_origin": origins[0].strftime("%Y-%m-%d"), "last_origin": origins[-1].strftime("%Y-%m-%d"), "lambda": LAM, "normalisation_window": "expanding", "n_features": len(FEATS), "rmse_naive": r["naive"][0], "mae_naive": r["naive"][1], "rmse_mean": r["mean"][0], "mae_mean": r["mean"][1], "rmse_ridge": r["ridge"][0], "mae_ridge": r["ridge"][1], "rel_improvement_vs_naive": 1 - r["ridge"][0] / r["naive"][0], "rel_improvement_vs_mean": 1 - r["ridge"][0] / r["mean"][0], "dm_stat_vs_naive": dm_naive[0], "dm_pvalue_vs_naive": dm_naive[1], "dm_stat_vs_mean": dm_mean[0], "dm_pvalue_vs_mean": dm_mean[1], "feasibility": "complete", "feasibility_reason": None, "data_issues": [ {"issue": "neworder_chg missing for 1992-01 and 1992-02 (NEWORDER starts 1992-02)", "handling": "not used: ridge training rows start at 1992-03-01 as specified"}, {"issue": "data/README.md says the first month (1992-01) of every change series is empty, but the file contains values for ip_growth, oil_chg and permit_chg in 1992-01", "handling": "values used as given; ip_growth 1992-01 enters only as the 2nd lag of the 1992-03 training row, as implied by the TASK.md specification"}, {"issue": "extreme COVID-19 observations in 2020-03..2020-06 (ip_growth -14.1 to +6.3 percent) inside every training window", "handling": "kept, as the specification defines the training window without exclusions; noted as a limitation"}, {"issue": "current-vintage (revised) data with publication lags ignored", "handling": "results reported as pseudo-out-of-sample on revised data, not real-time"}, ], "n_input_rows": {"ip_predictors.csv": int(n_raw)}, "n_analysed": int(n_last), "random_seed": None, } with open(os.path.join(OUT, "results.json"), "w") as f: json.dump(res, f, indent=2) print(json.dumps({k: res[k] for k in res if k.startswith(("rmse", "mae", "rel", "n_"))}, indent=2))