"""Rolling-origin backtests on pre-2019 data only + pre-registered selection. Origins 1998/2004/2011, forecast origin+1..origin+7, valid rows only. Reference = mean30 at the same origin. Selection rule (fixed before running): highest mean skill across origins; must beat mean30 in >=2 of 3 origins; if within 0.01 of the runner-up, take the simpler method (SIMPLICITY order). """ from __future__ import annotations import json import sys from pathlib import Path import numpy as np import pandas as pd sys.path.insert(0, str(Path(__file__).parent)) from dataset import METRICS, download, load_annual, load_coverage, add_validity, long_valid from models import CANDIDATES, SIMPLICITY, forecast_metric from scorer import score_forecasts ORIGINS = [1998, 2004, 2011] HORIZON = 7 def run_backtest(long_df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]: detail_rows, skill_rows = [], [] for origin in ORIGINS: years = list(range(origin + 1, origin + HORIZON + 1)) truth = long_df[long_df["Year"].isin(years)][["city_id", "Year", "metric", "value"]] ref = pd.concat([ forecast_metric(long_df[long_df["metric"] == m], m, origin, years, "mean30") for m in METRICS]) ref_scored = score_forecasts(truth, ref, ref) for method in CANDIDATES: pred = pd.concat([ forecast_metric(long_df[long_df["metric"] == m], m, origin, years, method) for m in METRICS]) res = score_forecasts(truth, pred, ref) for m in METRICS: detail_rows.append({"origin": origin, "method": method, "metric": m, "mae": res["mae"].get(m), "mae_ref": res["mae_ref"].get(m), "skill": res["skill"].get(m), "n": res["n_rows"]}) skill_rows.append({"origin": origin, "method": method, "score": res["score"]}) return pd.DataFrame(detail_rows), pd.DataFrame(skill_rows) def select_methods(detail: pd.DataFrame) -> dict: """Per-metric selection following the pre-registered rule.""" chosen = {} summary = {} for metric in METRICS: sub = detail[detail["metric"] == metric] piv = sub.pivot_table(index="method", columns="origin", values="skill") mean_skill = piv.mean(axis=1) beats = (piv > piv.loc["mean30"]).sum(axis=1) ranked = mean_skill.sort_values(ascending=False) best, best_val = ranked.index[0], float(ranked.iloc[0]) # Near-tie -> simpler method among those within 0.01 of best and eligible. eligible = [m for m in ranked.index if best_val - float(ranked[m]) < 0.01 and (m == "mean30" or beats.get(m, 0) >= 2)] if not eligible or (best != "mean30" and beats.get(best, 0) < 2): pick = "mean30" else: pick = min(eligible, key=lambda m: SIMPLICITY.index(m)) chosen[metric] = pick summary[metric] = { "chosen": pick, "mean_skill_by_method": {k: float(v) for k, v in mean_skill.items()}, "origins_beating_mean30": {k: int(v) for k, v in beats.items()}, } return {"methods": chosen, "summary": summary} def main() -> None: root = Path(__file__).resolve().parent.parent data_root = download(root / "data" / "_source") annual = add_validity(load_annual(data_root), load_coverage(data_root)) long_df = long_valid(annual) print(f"valid obs: {len(long_df)} rows, {long_df['city_id'].nunique()} cities, " f"{long_df['Year'].min()}-{long_df['Year'].max()}") detail, _ = run_backtest(long_df) out = root / "outputs" out.mkdir(exist_ok=True) detail.to_csv(out / "backtest_detail.csv", index=False) decision = select_methods(detail) (out / "decision.json").write_text(json.dumps(decision, indent=2)) print("\nPer-metric mean skill across origins (skill vs mean30 at same origin):") piv = detail.pivot_table(index="method", columns="metric", values="skill", aggfunc="mean") print(piv.round(3).to_string()) print("\nChosen methods:", decision["methods"]) if __name__ == "__main__": main()