"""F3-conf-03: rolling-origin ridge vs naive / expanding-mean forecasts of US IP growth (h=1). Reads only data/ip_predictors.csv; writes out/results.json, out/forecasts.csv, out/exclusions.csv. Deterministic: no randomness used (random_seed = null).""" import json, hashlib from pathlib import Path import numpy as np import pandas as pd ROOT = Path(__file__).resolve().parent.parent DATA = ROOT / "data" / "ip_predictors.csv" OUT = ROOT / "out" LAM = 50.0 FIRST_ORIGIN, LAST_ORIGIN = 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"].diff().dropna().dt.days.between(28, 31)).all(), "non-contiguous months" d = d.set_index("month") # Lags/leads by row position (months verified contiguous). Lags use only past values. 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 of feature row s is ip_growth_{s+1} origins = d.index[(d.index >= FIRST_ORIGIN) & (d.index <= LAST_ORIGIN)] assert len(origins) == 60 rows = [] n_train_last = None for t in origins: t_next = d.index[d.index.get_loc(t) + 1] actual = float(d.loc[t_next, "ip_growth"]) # Information set: rows dated <= t only. info = d.loc[d.index <= t] # naive f_naive = float(info.loc[t, "ip_growth"]) # expanding mean 1992-04..t f_mean = float(info.loc[info.index >= MEAN_START, "ip_growth"].mean()) # ridge training rows: TRAIN_START <= s, s+1 <= t (so target y_{s+1} dated <= t) s_idx = info.index[(info.index >= TRAIN_START) & (info.index < t)] tr = info.loc[s_idx, FEATS].copy() y = info["ip_growth"].shift(-1).loc[s_idx].to_numpy() # ip_growth_{s+1}, all dated <= t X = tr.to_numpy(dtype=float) assert np.isfinite(X).all() and np.isfinite(y).all() mu = X.mean(axis=0) sd = X.std(axis=0, ddof=1) Z = (X - mu) / sd ybar = y.mean() b = np.linalg.solve(Z.T @ Z + LAM * np.eye(Z.shape[1]), Z.T @ (y - ybar)) zt = (info.loc[t, FEATS].to_numpy(dtype=float) - mu) / sd f_ridge = float(ybar + zt @ b) n_train_last = len(s_idx) 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=t_next.strftime("%Y-%m-%d"), horizon=1, forecast=f, actual=actual, model=m)) fc = pd.DataFrame(rows) fc.to_csv(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))) def dm_test(m1, m2): """Diebold-Mariano test on squared-error loss differential d = e1^2 - e2^2 (h=1: plain sample variance, i.e. Newey-West with 0 lags), with the Harvey-Leybourne-Newbold small-sample correction and t_{n-1} reference distribution. Positive stat => m1 worse.""" from scipy import stats e1 = (fc.loc[fc.model == m1, "forecast"] - fc.loc[fc.model == m1, "actual"]).to_numpy() e2 = (fc.loc[fc.model == m2, "forecast"] - fc.loc[fc.model == m2, "actual"]).to_numpy() dd = e1 ** 2 - e2 ** 2 n = len(dd) stat = dd.mean() / np.sqrt(dd.var(ddof=0) / n) stat *= np.sqrt((n + 1 - 2 * 1 + 1 * 0) / n) # HLN correction for h=1: sqrt((n+1-2h+h(h-1)/n)/n) p = 2 * stats.t.sf(abs(stat), df=n - 1) return float(stat), float(p) rn, an = metrics("naive"); rm, am = metrics("mean"); rr, ar = metrics("ridge") # Exclusion ledger: raw rows -> training rows at the last origin last = origins[-1] n1 = int((d.index >= TRAIN_START).sum()) n2 = int(((d.index >= TRAIN_START) & (d.index < last)).sum()) assert n2 == n_train_last excl = pd.DataFrame([ dict(step=1, rule="drop months before 1992-03-01 (lags ip_growth_{s-2} and neworder_chg undefined/not in spec)", n_before=n_raw, n_after=n1, n_removed=n_raw - n1, rationale="TASK.md training window starts at s=1992-03-01"), dict(step=2, rule="keep feature months s with s+1 <= last origin 2026-08-01 (s <= 2026-07-01)", n_before=n1, n_after=n2, n_removed=n1 - n2, rationale="target y_{s+1} must be dated <= origin; later months unavailable"), ]) excl.to_csv(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": rn, "mae_naive": an, "rmse_mean": rm, "mae_mean": am, "rmse_ridge": rr, "mae_ridge": ar, "rel_improvement_vs_naive": 1 - rr / rn, "rel_improvement_vs_mean": 1 - rr / rm, "feasibility": "complete", "feasibility_reason": None, "data_issues": [ {"issue": "neworder_chg missing for 1992-01 and 1992-02 (NEWORDER starts 1992-02)", "handling": "Not used: training rows start at s=1992-03 per TASK.md; no imputation needed."}, {"issue": "data/README.md states the first month (1992-01) of each change series is empty, but ip_growth, oil_chg and permit_chg are populated for 1992-01", "handling": "Values used as given; only ip_growth_1992-01 enters (as lag ip_growth_{s-2} for s=1992-03). oil_chg/permit_chg 1992-01 are not used."}, {"issue": "Extreme ip_growth values in training windows (e.g. 2020-04 = -14.1, 2020-06 = +6.3, 2008-09 = -4.5)", "handling": "Kept: the ridge specification is fixed by TASK.md; no outlier treatment. Noted as a limitation."}, {"issue": "Current-vintage (revised) data with publication lags ignored", "handling": "Errors computed on data as given; no real-time validity claimed."}, ], "n_input_rows": {"ip_predictors.csv": int(n_raw)}, "n_analysed": int(n_train_last), "random_seed": None, "dm_stat_naive_vs_ridge": dm_test("naive", "ridge")[0], "dm_pvalue_naive_vs_ridge": dm_test("naive", "ridge")[1], "dm_stat_mean_vs_ridge": dm_test("mean", "ridge")[0], "dm_pvalue_mean_vs_ridge": dm_test("mean", "ridge")[1], "sha256_input": hashlib.sha256(DATA.read_bytes()).hexdigest(), "baseline_best_rmse_model": "naive" if rn < rm else "mean", } with open(OUT / "results.json", "w") as f: json.dump(res, f, indent=2) print(json.dumps({k: res[k] for k in ["rmse_naive", "rmse_mean", "rmse_ridge", "mae_naive", "mae_mean", "mae_ridge", "rel_improvement_vs_naive", "rel_improvement_vs_mean", "n_analysed"]}, indent=2))