Forecast model comparison
Forecast model comparison
Purpose
From hourly data (electricity demand, generation, price), build forecasting models and compare them with a baseline on the same test period and the same metrics. The output is code plus report-ready results: a Markdown table file (`results.md`), CSV files and PNG figures, which also record why each model won, the environment and the worst days.
The AI fixes the forecast issue time, splits data in time order, builds features and a baseline, tunes hyperparameters, computes metrics, analyzes errors and logs the run. It never re-picks a model or setting after looking at test results. If the proposed model loses to the baseline or another model, it reports the number as is and lists possible causes. It never writes numbers from experiments it did not run, or performance figures from papers it did not read.
Input
- Required: a data file with a timestamp column, and the column to forecast. If missing, ask only: "Please send the data file with the values to forecast (with a timestamp column)."
- Helpful: issue time and horizon, allowed external data (temperature forecasts, holidays), required models, metrics or split, a class benchmark, format, deadline.
- If your school or instructor gave you a template or set the split, metrics, models or report format, that comes first. The defaults below apply only when nothing is set.
- Issue time unknown: use "at 24:00 on day D−1, forecast hours 0–23 of day D" and list it under "Points to check".
- No temperature forecast available: use measured temperature and put "perfect temperature forecast assumed" in the table title. Errors will look smaller than in real operation.
- Holidays come from the user's list or an official calendar. Days not confirmed stay `[check needed]`.
- Never edit text the user marked "keep as is" (assignment wording, model names).
Output
1. `forecast.py`, `results/results.md` (split, metrics, monthly bias, worst days, environment), `metrics.csv`, `predictions_test.csv`, `fig1_weeks.png`, `fig2_daily_mae.png`.
2. In the chat, "Points to check" only, 3–7 lines: split dates and hours, final model and why (validation MAE), test MAE and gain over the baseline, mean error, where it lost to the baseline or another model, assumptions (temperature forecast, holidays), whether it actually ran.
3. If code cannot run here, give the code and run command labeled "not run yet". Never fill tables with "expected results".
Rules
1. Steps
1) Write the issue time and horizon in one line: "At 24:00 on D−1, forecast load (kW) for hours 0–23 of D."
2) List as feature candidates only values known at that moment. Same-day measured temperature and same-day earlier hours are out.
3) Split train, validation and test in time order (section 3).
4) Report the baseline (same hour last week) first. That number is the zero point.
5) Add models one at a time. Change one thing per step: a feature or the model.
6) Choose hyperparameters and the final model by validation MAE, refit the chosen settings on train + validation, then look at test once.
7) Make tables, figures and the worst-day list; rerun and confirm identical files; run section 9.
2. Leakage
- Lags must be at least the horizon. Day-ahead means 24 h or more (lag 24, lag 168).
- Temperature is the forecast issued the day before. Measured temperature makes errors look smaller than they are.
- Means and standard deviations for scaling or filling come from the training period only.
- No random splits such as `train_test_split(shuffle=True)` or `KFold(shuffle=True)`. For cross-validation use `TimeSeriesSplit`.
- `HistGradientBoostingRegressor` turns on early stopping by itself above 10,000 samples and holds out a random 10 % of the training rows. Set `early_stopping=False` and pick the iteration count on the validation period.
3. Split and fair comparison
- Default: train 12 months → validation 6 months → test 6 months. Training covers every season at least once.
- The first 7 days leave training because lag 168 is empty there.
- An hour with any blank leaves every model at once. If models are scored on different hours, their metrics cannot be compared. Report the hour count of each period.
- Look at test once, at the end. If a setting changed after seeing test results, say so and give the numbers from before the change.
4. Metrics and tables
- MAE and RMSE (kW), MAPE (%), mean error (kW, negative = forecast too low) in one table, units in column names.
- If actual values near 0 occur (solar output at night), drop MAPE and say why. `sklearn`'s `mean_absolute_percentage_error` returns a ratio (0.05), not a percent.
- Gain over baseline = (1 − model MAE / baseline MAE) × 100. A negative gain stays negative.
- Decimals: kW one place, MAPE two places, gain one place with a sign.
- Validation MAE and the chosen hyperparameters are columns, so the table shows why that model won.
- Mean error by month too (Table 2). If every fitted model leans the same way, suspect a level change in the data.
5. Worst days
- Top 5 days by daily MAE of the final model: date, weekday, MAE, mean error, baseline MAE, possible cause.
- Possible causes are only those the code checks: holiday, day after a holiday, holiday a week earlier, temperature forecast off by more than 3 °C, temperature in the top 1 % of the fitting data, blank hours. If none applies, write "not found".
- Do not turn "not found" into a plausible story. Guesses go in a separate "to check" note.
- Equal daily MAE and mean error size means all 24 hours missed one way; read it with Table 2.
6. Figures
- Axes: "Load (kW)", "Daily MAE (kW)". Date ticks as month-day. Title with figure number, period and source such as "hypothetical data".
- Actual in black, baseline in grey, final model in blue. At most 3 lines per plot.
- Two normal weeks and two problem weeks (holidays, heat) in stacked panels with the same units. No twin y-axes.
- Gaps stay gaps; never draw a line across them. Mark the top 5 error days in Figure 2 with open circles and dates.
7. Sentences (before → after)
- "The proposed boosting model showed the best performance." → "M3, chosen by validation MAE, had a test MAE of 29.1 kW, 36.9 % below the baseline (46.1 kW). On the same test hours it was 1.0 kW worse than M2 (28.1 kW)."
- "The model follows actual demand well." → "Over the test period M1–M3 forecast 15–26 kW too low on average; the baseline's mean error was +0.5 kW (Tables 1 and 2)."
- "Forecasting is hard on holidays." → "On 10-10, the day after the holiday week, M3's daily MAE was 92.1 kW. The day before and the same weekday a week earlier were both holidays, so both lags held holiday-level load (possible cause)."
8. The file
`forecast.py` was run end to end on a hypothetical case: hourly load of a hypothetical campus research building for 2024–2025 (17,544 rows), with temperature and the previous day's temperature forecast. The data come from seeded code, not a real building. Planted on purpose: 9 blank meter hours, days when the forecast missed by 3–5 °C, base load +35 kW from 2025-03-04, and an August 2025 hot spell above the training range. The negative bias in Table 2 is the trace of that level shift.
- Run: `pip install numpy pandas scikit-learn matplotlib`, then `python forecast.py`. Columns of `data/building_load.csv`: `datetime, load_kW, temp_C, temp_fc_C`.
- Test MAE in this case: M0 46.1, M1 33.4, M2 28.1, M3 29.1 kW (4,398 h). M3, chosen on validation (30.7 vs 31.9 kW), was 1.0 kW worse than M2 on test, and that is what gets reported.
- For other data, change only the constants at the top (periods, base temperatures, holidays) and the part that builds `X`.
- Two runs in separate folders gave byte-identical `predictions_test.csv` and `results.md` (Python 3.13, scikit-learn 1.9.1, SEED = 0).
9. Final check
- No feature unknown at issue time (same-day measured temperature, lags under 24 h).
- Split in time order; no shuffle and no random early stopping.
- Every model scored on the same test hours; hour counts per period reported.
- Baseline row and gain column present; negative gains and losses to other models shown.
- Hyperparameters and final model chosen on validation, not changed after test.
- Mean error reported; worst-day causes limited to what the code checked.
- Environment (versions, SEED) recorded. You said whether you ran the code or only wrote it.
Attachment 1 · forecast.py (Python)
```python
forecast.py - day-ahead building load forecast: baseline (same hour last week) -> linear -> boosting
Run: python forecast.py (reads data/building_load.csv, writes tables, figures and a run log to results/)
Forecast is issued at 24:00 on day D-1, so features use only what is known then:
measured load up to D-1, the temperature forecast for D, and the calendar.
import platform
from itertools import product
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import Ridge
SEED = 0
TRAIN = ("2024-01-08", "2024-12-31") # first week dropped: no value from 168 h earlier
VALID = ("2025-01-01", "2025-06-30") # hyperparameters and the final model are chosen here only
TEST = ("2025-07-01", "2025-12-31") # looked at once, at the end
CDD_BASE, HDD_BASE = 20.0, 12.0 # base temperatures for cooling and heating degrees (°C)
FC_MISS_C = 3.0 # daily mean forecast error above this is a possible cause (°C)
HOLIDAYS = pd.to_datetime([ # holidays of the hypothetical case; check an official calendar
"2024-01-01", "2024-02-09", "2024-02-10", "2024-02-11", "2024-02-12", "2024-03-01", "2024-04-10",
"2024-05-05", "2024-05-06", "2024-05-15", "2024-06-06", "2024-08-15", "2024-09-16", "2024-09-17",
"2024-09-18", "2024-10-01", "2024-10-03", "2024-10-09", "2024-12-25",
"2025-01-01", "2025-01-27", "2025-01-28", "2025-01-29", "2025-01-30", "2025-03-01", "2025-03-03",
"2025-05-05", "2025-05-06", "2025-06-03", "2025-06-06", "2025-08-15", "2025-10-03", "2025-10-05",
"2025-10-06", "2025-10-07", "2025-10-08", "2025-10-09", "2025-12-25"])
OUT = Path("results")
OUT.mkdir(exist_ok=True)
df = pd.read_csv("data/building_load.csv", parse_dates=["datetime"], index_col="datetime").asfreq("h")
y = df.load_kW
X = pd.DataFrame({"hour": df.index.hour, "dow": df.index.dayofweek, "month": df.index.month}, index=df.index)
X["off"] = ((X.dow == 6) | df.index.normalize().isin(HOLIDAYS)).astype(int) # Sunday or holiday
X["sat"] = ((X.dow == 5) & (X.off == 0)).astype(int)
X["temp_fc"] = df.temp_fc_C # measured temp_C is unknown at forecast time: not used
X["lag24"] = y.shift(24) # same hour yesterday
X["lag168"] = y.shift(168) # same hour last week = the baseline forecast
def linear_design(lags):
"""Linear inputs: 72 hour x day-type dummies + temp forecast + cooling/heating degrees [+ lags]."""
kind = pd.Series(np.select([X.off == 1, X.sat == 1], ["off", "sat"], "work"), index=X.index)
D = pd.get_dummies(kind + "_" + X.hour.astype(str), dtype=float)
D["temp_fc"] = X.temp_fc
D["cdd"] = (X.temp_fc - CDD_BASE).clip(lower=0)
D["hdd"] = (HDD_BASE - X.temp_fc).clip(lower=0)
return D.join(X[["lag24", "lag168"]]) if lags else D
ok = X.notna().all(axis=1) & y.notna() # hours with any blank leave every model (same hours compared)
span = lambda p: ok & (X.index >= p[0]) & (X.index < pd.Timestamp(p[1]) + pd.Timedelta(days=1))
tr, va, te = span(TRAIN), span(VALID), span(TEST)
ridge = lambda **p: Ridge(**p)
gbm = lambda **p: HistGradientBoostingRegressor(early_stopping=False, random_state=SEED, **p) # no 'auto'
M0 = "M0 baseline: last week"
MODELS = { # name: (model, grid searched on validation, inputs). M1->M2 changes inputs, M2->M3 the model
"M1 linear: calendar+temp": (ridge, {"alpha": [0.1, 1, 10, 100]}, linear_design(lags=False)),
"M2 linear: +lags": (ridge, {"alpha": [0.1, 1, 10, 100]}, linear_design(lags=True)),
"M3 boosting: +lags": (gbm, {"learning_rate": [0.05, 0.1], "max_leaf_nodes": [15, 31],
"max_iter": [200, 400]}, X),
}
mae = lambda a, b: float(np.mean(np.abs(np.asarray(a) - np.asarray(b))))
pred = pd.DataFrame({"actual": y[te], M0: X.lag168[te]})
chosen = {M0: ("none", mae(y[va], X.lag168[va]))}
for name, (make, grid, F) in MODELS.items():
trials = [(mae(y[va], make(**p).fit(F[tr], y[tr]).predict(F[va])), p)
for p in (dict(zip(grid, v)) for v in product(*grid.values()))]
va_mae, p = min(trials, key=lambda r: r[0])
chosen[name] = (", ".join(f"{k}={v}" for k, v in p.items()), va_mae)
pred[name] = make(**p).fit(F[tr | va], y[tr | va]).predict(F[te]) # refit on train+valid
best = min(MODELS, key=lambda k: chosen[k][1]) # final model by validation MAE, never by test
err = pred.drop(columns="actual").sub(pred.actual, axis=0)
tab = pd.DataFrame({"MAE (kW)": err.abs().mean(), "RMSE (kW)": np.sqrt((err ** 2).mean()),
"MAPE (%)": err.abs().div(pred.actual, axis=0).mean() * 100, # sklearn gives 0.05
"Mean error (kW)": err.mean()}) # negative = too low
tab["MAE gain vs M0 (%)"] = (1 - tab["MAE (kW)"] / tab.loc[M0, "MAE (kW)"]) * 100
tab["Valid. MAE (kW)"] = [chosen[k][1] for k in tab.index]
tab["Chosen on valid."] = [chosen[k][0] for k in tab.index]
tab.round(2).to_csv(OUT / "metrics.csv")
pred.round(1).to_csv(OUT / "predictions_test.csv")
Worst days: top 5 daily MAE of the final model, with possible causes (candidates, not findings)
day_err = err.abs().groupby(err.index.normalize())
daily, nhour = day_err.mean(), day_err.size()
bias = err.groupby(err.index.normalize()).mean()
fc_err = (df.temp_fc_C - df.temp_C).abs().groupby(df.index.normalize()).mean()
fc_max = X.temp_fc.groupby(X.index.normalize()).max()
q_hot = X.temp_fc[tr | va].quantile(0.99) # top 1 % of the forecast temperatures used in fitting
def why(d):
c = [s for s, k in [("holiday", 0), ("day after holiday", 1), ("holiday a week earlier", 7)]
if d - pd.Timedelta(days=k) in HOLIDAYS]
c += [f"temp forecast off {fc_err[d]:.1f} °C"] if fc_err[d] > FC_MISS_C else []
c += [f"temp in top 1 % of fit data (≥ {q_hot:.1f} °C)"] if fc_max[d] >= q_hot else []
c += [f"{nhour[d]} hours compared (blanks)"] if nhour[d] < 24 else []
return ", ".join(c) or "not found"
top = daily[best].nlargest(5).index
worst = pd.DataFrame({"Day": top.strftime("%a"),
f"{best[:2]} MAE (kW)": daily.loc[top, best],
f"{best[:2]} mean error (kW)": bias.loc[top, best],
"M0 MAE (kW)": daily.loc[top, M0],
"Possible cause": [why(d) for d in top]}, index=top.strftime("%Y-%m-%d"))
Figures: units in axis labels, period and "hypothetical data" in titles, one y-axis only
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 9, "axes.grid": True, "grid.color": "#e7e7e7",
"axes.edgecolor": "#c2c2c2", "axes.spines.top": False, "axes.spines.right": False,
"savefig.dpi": 200})
style = {"actual": ("#191919", 1.6), M0: ("#9c9c9c", 1.2), best: ("#257de0", 1.6)}
fig, axes = plt.subplots(2, 1, figsize=(10, 5.6))
for ax, (a, b, title) in zip(axes, [("2025-07-07", "2025-07-20", "Two normal weeks"),
("2025-10-01", "2025-10-14", "Two weeks with the Oct 3-9 holidays")]):
w = pred.loc[a:b + " 23:00"].reindex(pd.date_range(a, b + " 23:00", freq="h")) # gaps stay gaps
for col, (c, lw) in style.items():
ax.plot(w.index, w[col], color=c, lw=lw, label=col)
ax.set_ylabel("Load (kW)")
ax.set_title(f"{title}: {a} to {b}", loc="left", fontsize=9)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m-%d"))
fig.legend(*axes[0].get_legend_handles_labels(), frameon=False, ncol=3, loc="upper right",
bbox_to_anchor=(1, 0.955)) # second line, under the title
fig.suptitle(f"Figure 1. Test period, actual vs day-ahead forecast (hypothetical data, final {best[:2]})",
x=0.01, ha="left")
fig.tight_layout(rect=(0, 0, 1, 0.96))
fig.savefig(OUT / "fig1_weeks.png")
fig, ax = plt.subplots(figsize=(10, 3.2))
for col, (c, lw) in list(style.items())[1:]:
ax.plot(daily.index, daily[col], color=c, lw=lw, label=col)
ax.scatter(top, daily.loc[top, best], s=40, facecolors="none", edgecolors="#191919", zorder=3)
used = []
for d in sorted(top): # a label within 8 days of another goes one level higher
lvl = min(set(range(5)) - {lv for e, lv in used if (d - e).days < 8})
used.append((d, lvl))
ax.annotate(d.strftime("%m-%d"), (d, daily.loc[d, best]), xytext=(0, 6 + 12 * lvl),
textcoords="offset points", ha="center", fontsize=8)
ax.set(ylabel="Daily MAE (kW)", xlabel="Date")
ax.legend(frameon=False, ncol=2, loc="upper left")
fig.suptitle(f"Figure 2. Daily mean absolute error; open circle = final model's top 5 days ({TEST[0]} to {TEST[1]})",
x=0.01, ha="left")
fig.tight_layout()
fig.savefig(OUT / "fig2_daily_mae.png")
def md(t, fmt):
"""Markdown table without tabulate. fmt maps column -> format. Numbers right-aligned, text left."""
rows = [[str(i)] + [format(v, fmt.get(c, "")) for c, v in r.items()] for i, r in t.iterrows()]
align = [":---"] + ["---:" if pd.api.types.is_numeric_dtype(t[c]) else ":---" for c in t.columns]
return "\n".join(["| " + " | ".join(x) + " |" for x in [["", *t.columns], align, *rows]])
env = (f"Python {platform.python_version()}, numpy {np.__version__}, pandas {pd.__version__}, "
f"scikit-learn {sklearn.__version__}, SEED = {SEED}")
n = {k: int(v.sum()) for k, v in [("train", tr), ("valid", va), ("test", te)]}
(OUT / "results.md").write_text("\n".join([
"# Day-ahead forecast comparison (hypothetical data)", "",
f"- Split (time order): train {TRAIN[0]} to {TRAIN[1]}, {n['train']:,} h; valid {VALID[0]} to {VALID[1]}, "
f"{n['valid']:,} h; test {TEST[0]} to {TEST[1]}, {n['test']:,} h",
f"- Final model (lowest validation MAE): {best}", f"- Environment: {env}", "",
"Table 1. Test metrics (all models on the same hours)", "",
md(tab, {"MAE (kW)": ".1f", "RMSE (kW)": ".1f", "MAPE (%)": ".2f", "Mean error (kW)": "+.1f",
"MAE gain vs M0 (%)": "+.1f", "Valid. MAE (kW)": ".1f"}), "",
"Table 2. Test mean error by month (kW, negative = forecast too low)", "",
md(err.groupby(err.index.strftime("%Y-%m")).mean(), {c: "+.1f" for c in err.columns}), "",
"Table 3. Worst days of the final model (possible causes, not findings)", "",
md(worst, {c: "+.1f" if "mean error" in c else ".1f" for c in worst.columns[1:4]}), ""]), encoding="utf-8")
print(env)
print(tab.round(2).to_string())
print(f"Final model: {best} / top 5 error days: {', '.join(worst.index)}")
```
Connect ChatGPT or Claude and use this prompt now · More prompts