File size: 4,262 Bytes
49f3de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""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()