sleonca's picture
Upload folder using huggingface_hub
b47743b verified
Raw History Blame Contribute Delete
1.56 kB
"""Does last year's anomaly persist? Adds res_last * phi**h to the model and reports relative MAE gain by horizon h."""
import sys, pathlib; sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
import warnings; warnings.filterwarnings("ignore")
import pandas as pd
from backtest import LV, COORDS
import models
def with_persist(metric, fn, phi, origins, **kw):
E = []
for o in origins:
yrs = list(range(o + 1, min(o + 7, 2018) + 1))
p = fn(LV, o, yrs, COORDS, metric, **kw)
p0 = fn(LV, o, [o], COORDS, metric, **kw).set_index("ID").pred
res = (models.wide(LV, metric, o)[o] - p0).fillna(0)
p = p.assign(h=p.Year - o); p["pred"] = p.pred + res.reindex(p.ID).values * phi ** p.h
t = LV[(LV.metric == metric) & LV.valid & LV.Year.isin(yrs)][["ID", "Year", "value"]]
m = t.merge(p, on=["ID", "Year"]); E.append(m.assign(e=(m.pred - m.value).abs()))
return pd.concat(E).groupby("h").e.mean()
for metric, fn, kw in [("annual_avg_temp", models.level_trend, dict(k=15, L=50, slope_scale=1.25)),
("cdd", models.cdd_shift, dict(N=10, L=50, slope_scale=1.25)),
("total_precip_in", models.level_trend, dict(k=50, slope_scale=0)),
("hottest_day_temp", models.level_trend, dict(k=30, slope_scale=0))]:
base = with_persist(metric, fn, 0.0, range(1970, 2012, 3), **kw)
for phi in [0.1, 0.2, 0.3]:
print(metric, phi, (1 - with_persist(metric, fn, phi, range(1970, 2012, 3), **kw) / base).round(4).to_dict())