"""Backtest the submitted model and the three reference baselines on pre-2019 data only. For each forecast origin (1990, 1994, ..., 2011) the models see data up to the origin and forecast the next 7 years (2012-2018 for the last origin); scored like the challenge. Writes results/backtest.csv. """ import warnings; warnings.filterwarnings("ignore") import pandas as pd from common import ROOT, METRICS from backtest import run, ORIGINS import models, final_model def last_year(lv, o, yrs, coords, metric): W = models.wide(lv, metric, o) last = W.ffill(axis=1).iloc[:, -1] return pd.concat([pd.DataFrame({"ID": W.index, "metric": metric, "Year": y, "pred": last.values}) for y in yrs]) MODELS = {"last_year": last_year, "avg_30yr": models.baseline30_model, "linear_trend": models.linear30_model, "ours": final_model.forecast} rows = [] for name, fn in MODELS.items(): for m in METRICS: r = run(fn, m) rows += [dict(model=name, metric=m, origin=o, mae=e, S=s) for o, e, s in zip(r.origin, r.mae, r.S)] df = pd.DataFrame(rows) (ROOT / "results").mkdir(exist_ok=True) df.to_csv(ROOT / "results" / "backtest.csv", index=False) score = df.groupby(["model", "origin"]).S.mean().clip(lower=0).mul(100).unstack() score["mean"] = score.mean(1) print("Composite Score (0-100) by forecast origin:\n", score.round(1)) print("\nMean skill S_m by metric (over origins):\n", df.groupby(["model", "metric"]).S.mean().unstack().round(3)) print("\nMAE, last origin (2012-2018):\n", df[df.origin == ORIGINS[-1]].pivot(index="model", columns="metric", values="mae").round(2))