Spaces:
Running

File size: 9,180 Bytes
628ab0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""Small CPU benchmark: calibration, selection, test are chronological and disjoint."""
import hashlib
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
from statsmodels.tsa.statespace.sarimax import SARIMAX
from arch import arch_model

MODELS = ["Seasonal naive", "Seasonal drift", "SARIMA", "SARIMA + frozen bias", "Grokked SARIMA · 80/20 blend", "SARIMAX · calendar", "SARIMAX + GARCH · calendar mean, residual volatility"]

class Candidates(dict):
    volatility = None

def fitted(model):
    fit = model.fit(disp=False, maxiter=200)
    if not fit.mle_retvals.get("converged", False):
        fit = model.fit(method="powell", disp=False, maxiter=300)
    if not fit.mle_retvals.get("converged", False):
        raise ValueError("Statistical mean model did not converge; no score published.")
    return fit

def calendar(index):
    return np.array([[d.days_in_month, sum(x.weekday() < 5 for x in pd.date_range(d, d + pd.offsets.MonthEnd(0), freq="D"))] for d in index], dtype=float)

def clean_monthly(frame, kind="demand"):
    required = {"timestamp", "value", "unit", "coverage"}
    if not required <= set(frame.columns):
        raise ValueError("Monthly CSV needs timestamp,value,unit,coverage columns.")
    if len(frame) > 600:
        raise ValueError("Maximum 600 monthly observations per run.")
    d = frame[list(sorted(required))].copy()
    parsed = pd.to_datetime(d["timestamp"], errors="raise", format="ISO8601")
    if parsed.dt.tz is not None:
        raise ValueError("Use timezone-free local month-start dates in monthly CSVs.")
    if not (parsed == parsed.dt.to_period("M").dt.to_timestamp()).all():
        raise ValueError("Use local month-start dates (YYYY-MM-01), not interval timestamps.")
    d["timestamp"] = parsed
    d = d.sort_values("timestamp").reset_index(drop=True)
    if d.timestamp.duplicated().any():
        raise ValueError("Duplicate months are not allowed.")
    expected = pd.date_range(d.timestamp.iloc[0], periods=len(d), freq="MS") if len(d) else []
    if len(d) < 72 or not np.array_equal(d.timestamp.to_numpy(), np.array(expected)):
        raise ValueError("Need at least 72 consecutive complete months; no interpolation is performed.")
    d["value"] = pd.to_numeric(d.value, errors="raise")
    d["coverage"] = pd.to_numeric(d.coverage, errors="raise")
    if not np.isfinite(d.value).all() or not (d.coverage == 1).all():
        raise ValueError("Only finite values and coverage=1 are accepted.")
    units = set(d.unit)
    allowed = {"GWh"} if kind == "demand" else {"EUR/MWh", "AUD/MWh"}
    if len(units) != 1 or not units <= allowed:
        raise ValueError(f"Use one unit from {sorted(allowed)}.")
    if kind == "demand" and (d.value < 0).any():
        raise ValueError("Monthly grid energy must be nonnegative; negative wholesale prices are allowed in price mode.")
    # The current month is incomplete; timestamps must precede its start.
    if d.timestamp.iloc[-1] >= pd.Timestamp.now(tz="UTC").tz_localize(None).to_period("M").to_timestamp():
        raise ValueError("Current or future months cannot be treated as complete actuals.")
    return d

def predict_candidates(history, timestamps=None):
    y = np.asarray(history, dtype=float)
    naive = y[-12:].copy()
    drift = naive + (np.mean(y[-12:]) - np.mean(y[-24:-12]))
    out = Candidates({"Seasonal naive": naive, "Seasonal drift": drift})
    mean, std = float(y.mean()), max(float(y.std()), 1e-8)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        model = SARIMAX((y - mean) / std, order=(1, 1, 1), seasonal_order=(1, 0, 1, 12),
                        enforce_stationarity=False, enforce_invertibility=False)
        fit = fitted(model)
    forecast = np.asarray(fit.forecast(12)) * std + mean
    if not np.isfinite(forecast).all():
        raise ValueError("SARIMA produced nonfinite forecasts.")
    out["SARIMA"] = forecast
    out["Grokked SARIMA · 80/20 blend"] = .8 * forecast + .2 * naive
    if timestamps is not None:
        index = pd.DatetimeIndex(timestamps)
        future = pd.date_range(index[-1] + pd.offsets.MonthBegin(1), periods=12, freq="MS")
        x, xf = calendar(index), calendar(future)
        xm, xs = x.mean(axis=0), np.maximum(x.std(axis=0), 1e-8)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            mean_fit = fitted(SARIMAX((y-mean)/std, exog=(x-xm)/xs, order=(1,1,1), seasonal_order=(1,0,1,12), enforce_stationarity=False, enforce_invertibility=False))
            point = np.asarray(mean_fit.forecast(12, exog=(xf-xm)/xs)) * std + mean
            residuals = np.asarray(mean_fit.resid)[12:]
            vol_fit = arch_model(residuals, mean="Zero", vol="GARCH", p=1, q=1, dist="normal", rescale=False).fit(disp="off", show_warning=False, options={"maxiter":300})
        if vol_fit.convergence_flag != 0:
            raise ValueError("GARCH residual fit did not converge; no volatility score published.")
        variance = np.asarray(vol_fit.forecast(horizon=12, reindex=False).residual_variance.iloc[-1]) * std**2
        if not np.isfinite(point).all() or not np.isfinite(variance).all() or (variance < 0).any():
            raise ValueError("Nonfinite SARIMAX/GARCH forecast.")
        out["SARIMAX · calendar"] = point
        out["SARIMAX + GARCH · calendar mean, residual volatility"] = point.copy()
        out.volatility = {"residual_variance":variance.tolist(), "method":"GARCH(1,1) on training-only calendar SARIMAX residuals after 12-month burn-in; normal innovations. Same mean forecast as SARIMAX; this is residual volatility, not a calibrated multi-step prediction interval."}
    return out

def metrics(actual, forecast, scale):
    err = np.asarray(forecast) - np.asarray(actual)
    den = np.sum(np.abs(actual))
    return {"MAE": float(np.mean(np.abs(err))), "RMSE": float(np.sqrt(np.mean(err ** 2))),
            "WAPE_pct": float(100 * np.sum(np.abs(err)) / den) if den else None,
            "MASE": float(np.mean(np.abs(err)) / scale) if scale else None,
            "mean_error": float(np.mean(err))}

def run_benchmark(frame, kind="demand", predictor=predict_candidates):
    d = clean_monthly(frame, kind)
    y = d.value.to_numpy(dtype=float)
    n = len(y)
    if predictor is predict_candidates:
        predictor = lambda history: predict_candidates(history, d.timestamp.iloc[:len(history)])
    calibration = predictor(y[:n - 36])
    # Additive correction handles negative or near-zero electricity prices.
    cap = max(float(np.mean(np.abs(y[:n - 36]))) * .05, 1e-8)
    correction = float(np.clip(np.median(y[n - 36:n - 24] - calibration["SARIMA"]), -cap, cap))
    forecasts, scores, predictions, volatility = {}, [], [], {}
    winner = None
    for label, cut in [("validation", n - 24), ("test", n - 12)]:
        candidates = predictor(y[:cut])
        if getattr(candidates, "volatility", None):
            volatility[label] = candidates.volatility
        candidates["SARIMA + frozen bias"] = candidates["SARIMA"] + correction
        if kind == "demand":
            candidates = {k: np.maximum(v, 0) for k, v in candidates.items()}
        scale = float(np.mean(np.abs(y[12:cut] - y[:cut - 12])))
        forecasts[label] = candidates
        block = []
        for model, pred in candidates.items():
            m = metrics(y[cut:cut + 12], pred, scale)
            row = {"split": label, "model": model, **m}
            scores.append(row); block.append(row)
            for month, actual, estimate in zip(d.timestamp.iloc[cut:cut + 12], y[cut:cut + 12], pred):
                predictions.append({"split": label, "model": model, "timestamp": month.isoformat(),
                                    "actual": float(actual), "forecast": float(estimate)})
        if label == "validation":
            best = min(block, key=lambda r: r["MAE"])
            baseline = next(r for r in block if r["model"] == "Seasonal naive")
            winner = best["model"] if best["MAE"] < .95 * baseline["MAE"] else "Seasonal naive"
    for row in scores:
        row["selected_on_validation"] = row["model"] == winner
    return {"protocol": "electrocheap-monthly-v2", "input_sha256": hashlib.sha256(d.to_csv(index=False).encode()).hexdigest(),
            "implementation_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
            "unit": d.unit.iloc[0], "selected_model": winner, "bias_correction": correction,
            "calibration_start": d.timestamp.iloc[n - 36].date().isoformat(),
            "validation_start": d.timestamp.iloc[n - 24].date().isoformat(),
            "test_start": d.timestamp.iloc[n - 12].date().isoformat(),
            "scores": scores, "predictions": predictions,
            "residual_volatility": volatility,
            "claim": "Descriptive retrospective benchmark; no independent superiority claim. Validation winner is frozen before test scoring. Three 12-month forecast blocks with training-only scaling, calibration-only capped additive bias and a 5% validation improvement gate. SARIMA uses L-BFGS with a fixed Powell fallback on nonconvergence. Repeated use of these test data is exploratory."}