forecastforge 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- forecastforge/__init__.py +41 -0
- forecastforge/cli/__init__.py +12 -0
- forecastforge/cli/__main__.py +13 -0
- forecastforge/cli/main.py +477 -0
- forecastforge/common/__init__.py +6 -0
- forecastforge/config/__init__.py +61 -0
- forecastforge/config/_optional.py +39 -0
- forecastforge/config/device.py +98 -0
- forecastforge/config/environment.py +50 -0
- forecastforge/config/paths.py +131 -0
- forecastforge/config/runtime.py +76 -0
- forecastforge/config/seed.py +56 -0
- forecastforge/config/settings.py +249 -0
- forecastforge/core/__init__.py +21 -0
- forecastforge/core/errors.py +42 -0
- forecastforge/data/__init__.py +31 -0
- forecastforge/data/loaders.py +62 -0
- forecastforge/data/source.py +140 -0
- forecastforge/data/synthetic.py +212 -0
- forecastforge/data/yfinance_source.py +105 -0
- forecastforge/evaluation/__init__.py +44 -0
- forecastforge/evaluation/backtest.py +372 -0
- forecastforge/evaluation/benchmark.py +557 -0
- forecastforge/evaluation/metrics.py +318 -0
- forecastforge/features/__init__.py +67 -0
- forecastforge/features/builtins.py +540 -0
- forecastforge/features/frame.py +241 -0
- forecastforge/features/pipeline.py +84 -0
- forecastforge/features/transform.py +104 -0
- forecastforge/models/__init__.py +36 -0
- forecastforge/models/base.py +178 -0
- forecastforge/models/baselines.py +172 -0
- forecastforge/models/gbm.py +282 -0
- forecastforge/models/statistical.py +213 -0
- forecastforge/monitoring/__init__.py +6 -0
- forecastforge/pipelines/__init__.py +25 -0
- forecastforge/pipelines/synthetic_backtest.py +168 -0
- forecastforge/py.typed +0 -0
- forecastforge/schemas/__init__.py +19 -0
- forecastforge/schemas/time_series.py +101 -0
- forecastforge/schemas/validation.py +222 -0
- forecastforge/serving/__init__.py +5 -0
- forecastforge/tracking/__init__.py +6 -0
- forecastforge/utils/__init__.py +6 -0
- forecastforge-0.4.0.dist-info/METADATA +609 -0
- forecastforge-0.4.0.dist-info/RECORD +49 -0
- forecastforge-0.4.0.dist-info/WHEEL +4 -0
- forecastforge-0.4.0.dist-info/entry_points.txt +2 -0
- forecastforge-0.4.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
"""Offline model benchmark.
|
|
2
|
+
|
|
3
|
+
Runs every available forecaster over several deterministic synthetic series
|
|
4
|
+
and reports the mean and standard deviation across seeds. The point is not to
|
|
5
|
+
crown a winner but to state plainly what happens: on a near-random-walk price
|
|
6
|
+
path the naive forecast is hard to beat, and a benchmark that hides that is
|
|
7
|
+
worse than no benchmark at all.
|
|
8
|
+
|
|
9
|
+
Nothing here is tuned on the test folds. The backtester only ever shows a model
|
|
10
|
+
the history at or before each fold's cutoff, the hyperparameters are fixed in
|
|
11
|
+
:func:`build_models`, and no model is selected or adjusted after its scores are
|
|
12
|
+
known. The series are generated from fixed seeds, so a rerun reproduces every
|
|
13
|
+
number in the report.
|
|
14
|
+
|
|
15
|
+
Usage::
|
|
16
|
+
|
|
17
|
+
python -m forecastforge.evaluation.benchmark
|
|
18
|
+
python -m forecastforge.evaluation.benchmark --seeds 1 2 3 --length 1200
|
|
19
|
+
python -m forecastforge.evaluation.benchmark --fast # 1 seed, short series
|
|
20
|
+
BENCHMARK_FAST=1 python -m forecastforge.evaluation.benchmark
|
|
21
|
+
|
|
22
|
+
The optional forecasters are included only when their extra is installed; the
|
|
23
|
+
report names the models it actually ran, so a core install produces a shorter
|
|
24
|
+
but still honest table.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import argparse
|
|
30
|
+
import os
|
|
31
|
+
import sys
|
|
32
|
+
from collections.abc import Sequence
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from types import ModuleType
|
|
36
|
+
from typing import cast
|
|
37
|
+
|
|
38
|
+
import numpy as np
|
|
39
|
+
import pandas as pd
|
|
40
|
+
|
|
41
|
+
from forecastforge.config._optional import optional_import
|
|
42
|
+
from forecastforge.core.errors import DataValidationError
|
|
43
|
+
from forecastforge.data import SyntheticConfig, SyntheticSource
|
|
44
|
+
from forecastforge.evaluation.backtest import BacktestConfig, BacktestResult, WalkForwardBacktester
|
|
45
|
+
from forecastforge.evaluation.metrics import mae
|
|
46
|
+
from forecastforge.features.builtins import CalendarFeatures, Returns, RollingStat
|
|
47
|
+
from forecastforge.features.frame import FeatureSet
|
|
48
|
+
from forecastforge.features.pipeline import FeaturePipeline
|
|
49
|
+
from forecastforge.models import Drift, Forecaster, MovingAverage, Naive, SeasonalNaive
|
|
50
|
+
from forecastforge.models.gbm import LightGBMForecaster, lightgbm_available
|
|
51
|
+
from forecastforge.models.statistical import (
|
|
52
|
+
ARIMAForecaster,
|
|
53
|
+
ETSForecaster,
|
|
54
|
+
statsmodels_available,
|
|
55
|
+
)
|
|
56
|
+
from forecastforge.schemas.time_series import TimeSeries
|
|
57
|
+
|
|
58
|
+
__all__ = [
|
|
59
|
+
"BenchmarkConfig",
|
|
60
|
+
"BenchmarkResult",
|
|
61
|
+
"build_models",
|
|
62
|
+
"main",
|
|
63
|
+
"render_markdown",
|
|
64
|
+
"run_benchmark",
|
|
65
|
+
"save_report",
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
_PYPLOT = optional_import("matplotlib.pyplot")
|
|
69
|
+
|
|
70
|
+
# Reported in this order, headline metric first.
|
|
71
|
+
_METRICS = ("mase", "mae", "rmse", "smape", "directional_accuracy")
|
|
72
|
+
|
|
73
|
+
# Per-metric display precision: errors in price units need more digits than a
|
|
74
|
+
# unit-free ratio.
|
|
75
|
+
_DIGITS = {"mase": 3, "mae": 3, "rmse": 3, "smape": 2, "directional_accuracy": 1}
|
|
76
|
+
|
|
77
|
+
_BAR_COLOR = "#4C78A8"
|
|
78
|
+
_REFERENCE_COLOR = "#C44E52"
|
|
79
|
+
_GRID_COLOR = "#D8DCE3"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True, slots=True)
|
|
83
|
+
class BenchmarkConfig:
|
|
84
|
+
"""What to run and over which series.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
seeds: Generator seeds. One synthetic path per seed, so the spread
|
|
88
|
+
across seeds is the uncertainty the table reports. Duplicates are
|
|
89
|
+
rejected because they would silently double-weight a path.
|
|
90
|
+
length: Rows per synthetic series. Short series make every model look
|
|
91
|
+
alike, so the default is long enough for the fold count to matter.
|
|
92
|
+
horizon: Forecast horizon in periods.
|
|
93
|
+
initial_train: Rows in the first training window.
|
|
94
|
+
step: Rows between forecast origins.
|
|
95
|
+
gap: Embargo between the training window and the origin.
|
|
96
|
+
season: Period the seasonal naive baseline uses. Five business days is
|
|
97
|
+
one week, the shortest calendar cycle in the data.
|
|
98
|
+
|
|
99
|
+
The MASE scale is always the one-step naive error, so 1.0 means "exactly
|
|
100
|
+
the naive forecast" and the table can be read without checking a footnote.
|
|
101
|
+
Scaling by a seasonal error instead would make the same scores look better
|
|
102
|
+
by a factor of roughly ``sqrt(season)`` on a random walk, which is a
|
|
103
|
+
presentation choice, not a finding.
|
|
104
|
+
|
|
105
|
+
Raises:
|
|
106
|
+
DataValidationError: If the configuration cannot produce folds.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
seeds: tuple[int, ...] = (11, 23, 37, 53, 71)
|
|
110
|
+
length: int = 2000
|
|
111
|
+
horizon: int = 1
|
|
112
|
+
initial_train: int = 500
|
|
113
|
+
step: int = 20
|
|
114
|
+
gap: int = 0
|
|
115
|
+
season: int = 5
|
|
116
|
+
|
|
117
|
+
def __post_init__(self) -> None:
|
|
118
|
+
if not self.seeds:
|
|
119
|
+
raise DataValidationError("at least one seed is required")
|
|
120
|
+
if len(set(self.seeds)) != len(self.seeds):
|
|
121
|
+
raise DataValidationError(f"seeds must be distinct, got {self.seeds}")
|
|
122
|
+
if self.season <= 0:
|
|
123
|
+
raise DataValidationError(f"season must be positive, got {self.season}")
|
|
124
|
+
if self.length <= self.initial_train + self.horizon:
|
|
125
|
+
raise DataValidationError(
|
|
126
|
+
f"length={self.length} leaves no out-of-sample rows after "
|
|
127
|
+
f"initial_train={self.initial_train} and horizon={self.horizon}"
|
|
128
|
+
)
|
|
129
|
+
# Constructing the backtest config validates step, gap, and the rest.
|
|
130
|
+
_ = self.backtest_config
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def backtest_config(self) -> BacktestConfig:
|
|
134
|
+
"""The fold layout these settings describe."""
|
|
135
|
+
return BacktestConfig(
|
|
136
|
+
horizon=self.horizon,
|
|
137
|
+
initial_train=self.initial_train,
|
|
138
|
+
step=self.step,
|
|
139
|
+
gap=self.gap,
|
|
140
|
+
# One-step scale on purpose; see the class docstring.
|
|
141
|
+
seasonal_period=1,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass(frozen=True, slots=True)
|
|
146
|
+
class BenchmarkResult:
|
|
147
|
+
"""Every per-seed score, plus the per-fold MASE behind them.
|
|
148
|
+
|
|
149
|
+
Attributes:
|
|
150
|
+
metrics: Long frame with one row per (seed, model) and one column per
|
|
151
|
+
metric.
|
|
152
|
+
fold_mase: Long frame with one row per (seed, model, fold), used for
|
|
153
|
+
the distribution plot.
|
|
154
|
+
models: Model names in the order they were run.
|
|
155
|
+
config: The configuration that produced the run.
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
metrics: pd.DataFrame
|
|
159
|
+
fold_mase: pd.DataFrame
|
|
160
|
+
models: tuple[str, ...]
|
|
161
|
+
config: BenchmarkConfig
|
|
162
|
+
|
|
163
|
+
def summary(self) -> pd.DataFrame:
|
|
164
|
+
"""Return mean and standard deviation per model, across seeds."""
|
|
165
|
+
grouped = self.metrics.groupby("model", sort=False)
|
|
166
|
+
columns: dict[str, pd.Series] = {}
|
|
167
|
+
for metric in _METRICS:
|
|
168
|
+
columns[f"{metric}_mean"] = grouped[metric].mean()
|
|
169
|
+
columns[f"{metric}_std"] = grouped[metric].std(ddof=0)
|
|
170
|
+
return pd.DataFrame(columns).loc[list(self.models)]
|
|
171
|
+
|
|
172
|
+
def n_folds(self) -> int:
|
|
173
|
+
"""Return the number of folds in one seed's backtest."""
|
|
174
|
+
return int(self.fold_mase["fold"].nunique())
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _feature_matrix(time_series: TimeSeries) -> FeatureSet:
|
|
178
|
+
"""Build the feature set the learned model consumes.
|
|
179
|
+
|
|
180
|
+
The pipeline is causal — the feature tests prove it — so computing it once
|
|
181
|
+
over the full series and slicing it per fold cannot leak. The backtester
|
|
182
|
+
slices it with the history, which keeps the alignment honest.
|
|
183
|
+
"""
|
|
184
|
+
pipeline = FeaturePipeline(
|
|
185
|
+
[
|
|
186
|
+
Returns(periods=1, log=True),
|
|
187
|
+
RollingStat(window=20, stat="std", column="close_logret1"),
|
|
188
|
+
RollingStat(window=10, stat="mean", column="close_logret1"),
|
|
189
|
+
CalendarFeatures(["dayofweek", "month_cyclic"]),
|
|
190
|
+
]
|
|
191
|
+
)
|
|
192
|
+
return pipeline.apply(time_series)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def build_models(config: BenchmarkConfig) -> dict[str, Forecaster]:
|
|
196
|
+
"""Return the models to compare, keyed by report name.
|
|
197
|
+
|
|
198
|
+
Args:
|
|
199
|
+
config: Supplies the horizon and the seasonal period.
|
|
200
|
+
|
|
201
|
+
Returns:
|
|
202
|
+
The four dependency-free baselines, plus ETS, ARIMA, and LightGBM when
|
|
203
|
+
their extra is installed.
|
|
204
|
+
"""
|
|
205
|
+
horizon = config.horizon
|
|
206
|
+
models: dict[str, Forecaster] = {
|
|
207
|
+
"naive": Naive(horizon=horizon),
|
|
208
|
+
"seasonal_naive": SeasonalNaive(season=config.season, horizon=horizon),
|
|
209
|
+
"moving_average": MovingAverage(window=20, horizon=horizon),
|
|
210
|
+
"drift": Drift(window=20, horizon=horizon),
|
|
211
|
+
}
|
|
212
|
+
if statsmodels_available():
|
|
213
|
+
models["ets"] = ETSForecaster(horizon=horizon)
|
|
214
|
+
models["arima"] = ARIMAForecaster(order=(1, 1, 0), horizon=horizon)
|
|
215
|
+
if lightgbm_available():
|
|
216
|
+
models["lightgbm"] = LightGBMForecaster(horizon=horizon)
|
|
217
|
+
return models
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _per_fold_mase(result: BacktestResult, model: str, seed: int) -> list[dict[str, object]]:
|
|
221
|
+
"""Return one row per fold holding ``MAE / scale`` for ``model``."""
|
|
222
|
+
subset = result.predictions[result.predictions["model"] == model]
|
|
223
|
+
rows: list[dict[str, object]] = []
|
|
224
|
+
for fold, group in subset.groupby("fold", sort=True):
|
|
225
|
+
scale = float(result.fold_scales.loc[fold])
|
|
226
|
+
rows.append(
|
|
227
|
+
{
|
|
228
|
+
"seed": seed,
|
|
229
|
+
"model": model,
|
|
230
|
+
"fold": int(cast("int", fold)),
|
|
231
|
+
"mase": mae(
|
|
232
|
+
group["y_true"].to_numpy(dtype="float64"),
|
|
233
|
+
group["y_pred"].to_numpy(dtype="float64"),
|
|
234
|
+
)
|
|
235
|
+
/ scale,
|
|
236
|
+
}
|
|
237
|
+
)
|
|
238
|
+
return rows
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def run_benchmark(config: BenchmarkConfig | None = None) -> BenchmarkResult:
|
|
242
|
+
"""Run every model over every seed.
|
|
243
|
+
|
|
244
|
+
Args:
|
|
245
|
+
config: Benchmark settings. Defaults to :class:`BenchmarkConfig`.
|
|
246
|
+
|
|
247
|
+
Returns:
|
|
248
|
+
The per-seed scores and the per-fold MASE they came from.
|
|
249
|
+
"""
|
|
250
|
+
cfg = config or BenchmarkConfig()
|
|
251
|
+
metric_rows: list[dict[str, object]] = []
|
|
252
|
+
fold_rows: list[dict[str, object]] = []
|
|
253
|
+
models: tuple[str, ...] = ()
|
|
254
|
+
|
|
255
|
+
for seed in cfg.seeds:
|
|
256
|
+
time_series = SyntheticSource(config=SyntheticConfig(seed=seed, length=cfg.length)).fetch(
|
|
257
|
+
symbol="SPY"
|
|
258
|
+
)
|
|
259
|
+
candidates = build_models(cfg)
|
|
260
|
+
if not models:
|
|
261
|
+
models = tuple(candidates)
|
|
262
|
+
result = WalkForwardBacktester(cfg.backtest_config).run(
|
|
263
|
+
time_series.target_series, candidates, _feature_matrix(time_series).matrix
|
|
264
|
+
)
|
|
265
|
+
for name in candidates:
|
|
266
|
+
metric_rows.append({"seed": seed, "model": name, **result.metrics_for(name).as_dict()})
|
|
267
|
+
fold_rows.extend(_per_fold_mase(result, name, seed))
|
|
268
|
+
|
|
269
|
+
return BenchmarkResult(
|
|
270
|
+
metrics=pd.DataFrame.from_records(metric_rows),
|
|
271
|
+
fold_mase=pd.DataFrame.from_records(fold_rows),
|
|
272
|
+
models=models,
|
|
273
|
+
config=cfg,
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _format(mean: float, std: float, *, digits: int) -> str:
|
|
278
|
+
"""Return ``mean ± std`` at the given precision."""
|
|
279
|
+
return f"{mean:.{digits}f} ± {std:.{digits}f}"
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def render_markdown(result: BenchmarkResult) -> str:
|
|
283
|
+
"""Render the benchmark table as markdown.
|
|
284
|
+
|
|
285
|
+
Args:
|
|
286
|
+
result: A completed benchmark.
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
A document with a short method note, the table, and the reading of it.
|
|
290
|
+
"""
|
|
291
|
+
summary = result.summary()
|
|
292
|
+
cfg = result.config
|
|
293
|
+
header = [
|
|
294
|
+
"# ForecastForge benchmark",
|
|
295
|
+
"",
|
|
296
|
+
"Generated by `python -m forecastforge.evaluation.benchmark`. Every number is",
|
|
297
|
+
"reproducible: the series come from fixed seeds and no model is tuned on the",
|
|
298
|
+
"scored folds.",
|
|
299
|
+
"",
|
|
300
|
+
f"* {len(cfg.seeds)} synthetic series of {cfg.length} business days, seeds "
|
|
301
|
+
f"{', '.join(str(seed) for seed in cfg.seeds)}",
|
|
302
|
+
f"* horizon {cfg.horizon}, {result.n_folds()} walk-forward folds per series "
|
|
303
|
+
f"(first training window {cfg.initial_train} rows, step {cfg.step}, gap {cfg.gap})",
|
|
304
|
+
"* MASE is scaled by the one-step naive error",
|
|
305
|
+
f"* models: {', '.join(result.models)}",
|
|
306
|
+
"",
|
|
307
|
+
"| Model | MASE | MAE | RMSE | sMAPE (%) | Directional accuracy (%) |",
|
|
308
|
+
"| --- | ---: | ---: | ---: | ---: | ---: |",
|
|
309
|
+
]
|
|
310
|
+
rows = []
|
|
311
|
+
# A plain mapping keeps the rendering free of pandas indexers, whose
|
|
312
|
+
# return types depend on the key in ways that are awkward to annotate.
|
|
313
|
+
scores: dict[str, dict[str, float]] = {
|
|
314
|
+
str(model): {str(column): float(value) for column, value in row.items()}
|
|
315
|
+
for model, row in summary.to_dict(orient="index").items()
|
|
316
|
+
}
|
|
317
|
+
for model in result.models:
|
|
318
|
+
cells = [
|
|
319
|
+
_format(
|
|
320
|
+
scores[model][f"{metric}_mean"],
|
|
321
|
+
scores[model][f"{metric}_std"],
|
|
322
|
+
digits=_DIGITS[metric],
|
|
323
|
+
)
|
|
324
|
+
for metric in _METRICS
|
|
325
|
+
]
|
|
326
|
+
rows.append(f"| {model} | " + " | ".join(cells) + " |")
|
|
327
|
+
|
|
328
|
+
best = min(result.models, key=lambda name: scores[name]["mase_mean"])
|
|
329
|
+
best_value = scores[best]["mase_mean"]
|
|
330
|
+
naive_mean = scores["naive"]["mase_mean"]
|
|
331
|
+
naive_std = scores["naive"]["mase_std"]
|
|
332
|
+
# A model only counts as better if it clears the seed-to-seed spread of the
|
|
333
|
+
# naive baseline itself. Without this rule a 0.001 gap on a 0.14 spread
|
|
334
|
+
# would be reported as a win, which is not what the numbers say.
|
|
335
|
+
threshold = naive_mean - naive_std
|
|
336
|
+
qualifiers = [
|
|
337
|
+
model
|
|
338
|
+
for model in result.models
|
|
339
|
+
if model != "naive" and scores[model]["mase_mean"] < threshold
|
|
340
|
+
]
|
|
341
|
+
|
|
342
|
+
footer = [
|
|
343
|
+
"",
|
|
344
|
+
"Values are mean ± standard deviation across seeds. MASE is unit-free and",
|
|
345
|
+
"scaled by the one-step naive error on each fold's training window, so 1.0",
|
|
346
|
+
"is exactly the naive forecast: below 1 beats it, above 1 is worse than",
|
|
347
|
+
"doing nothing.",
|
|
348
|
+
"",
|
|
349
|
+
"A model is only described as better when its mean MASE is at least one",
|
|
350
|
+
"naive standard deviation below the naive mean; anything closer is within",
|
|
351
|
+
"seed noise and is reported as a tie.",
|
|
352
|
+
"",
|
|
353
|
+
]
|
|
354
|
+
if qualifiers:
|
|
355
|
+
winner = min(qualifiers, key=lambda name: scores[name]["mase_mean"])
|
|
356
|
+
verdict = (
|
|
357
|
+
f"**{winner} beats the naive forecast.** Its mean MASE is "
|
|
358
|
+
f"{scores[winner]['mase_mean']:.3f} against {naive_mean:.3f} for naive, "
|
|
359
|
+
f"a gap wider than the {naive_std:.3f} seed-to-seed spread of naive "
|
|
360
|
+
"itself. That is a result about this synthetic generator, not a promise "
|
|
361
|
+
"about real prices."
|
|
362
|
+
)
|
|
363
|
+
else:
|
|
364
|
+
verdict = (
|
|
365
|
+
"**No model beats the naive forecast.** Naive scores "
|
|
366
|
+
f"{naive_mean:.3f} ± {naive_std:.3f} and nothing is more than one "
|
|
367
|
+
f"standard deviation below it; the closest is {best} at {best_value:.3f}, "
|
|
368
|
+
"which is a tie. That is what a near-random-walk price path implies: "
|
|
369
|
+
"there is no exploitable structure left to find, and every additional "
|
|
370
|
+
"parameter mostly adds noise."
|
|
371
|
+
)
|
|
372
|
+
return "\n".join([*header, *rows, *footer, verdict, ""])
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _require_pyplot() -> ModuleType:
|
|
376
|
+
"""Return ``matplotlib.pyplot``, or explain how to install it.
|
|
377
|
+
|
|
378
|
+
Raises:
|
|
379
|
+
ImportError: If matplotlib is not installed.
|
|
380
|
+
"""
|
|
381
|
+
if _PYPLOT is None:
|
|
382
|
+
raise ImportError(
|
|
383
|
+
'matplotlib is required for the benchmark plots. Install with: pip install -e ".[viz]"'
|
|
384
|
+
)
|
|
385
|
+
return _PYPLOT
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _plot(result: BenchmarkResult, path: Path) -> Path:
|
|
389
|
+
"""Draw the MASE summary and the per-fold distribution.
|
|
390
|
+
|
|
391
|
+
Args:
|
|
392
|
+
result: A completed benchmark.
|
|
393
|
+
path: Destination image.
|
|
394
|
+
|
|
395
|
+
Returns:
|
|
396
|
+
``path``, for chaining.
|
|
397
|
+
"""
|
|
398
|
+
pyplot = _require_pyplot()
|
|
399
|
+
summary = result.summary()
|
|
400
|
+
models = list(result.models)
|
|
401
|
+
positions = np.arange(len(models), dtype="float64")
|
|
402
|
+
|
|
403
|
+
figure, axes = pyplot.subplots(1, 2, figsize=(12.0, 4.8), constrained_layout=True)
|
|
404
|
+
|
|
405
|
+
left = axes[0]
|
|
406
|
+
left.bar(
|
|
407
|
+
positions,
|
|
408
|
+
summary.loc[models, "mase_mean"].to_numpy(dtype="float64"),
|
|
409
|
+
yerr=summary.loc[models, "mase_std"].to_numpy(dtype="float64"),
|
|
410
|
+
capsize=4,
|
|
411
|
+
color=_BAR_COLOR,
|
|
412
|
+
edgecolor="white",
|
|
413
|
+
)
|
|
414
|
+
left.axhline(
|
|
415
|
+
1.0, color=_REFERENCE_COLOR, linestyle="--", linewidth=1.2, label="naive (MASE = 1)"
|
|
416
|
+
)
|
|
417
|
+
left.set_xticks(positions, models, rotation=20)
|
|
418
|
+
left.set_ylabel("MASE, mean ± std across seeds")
|
|
419
|
+
left.set_title("Mean MASE (lower is better)")
|
|
420
|
+
left.grid(axis="y", color=_GRID_COLOR, linewidth=0.8, alpha=0.8)
|
|
421
|
+
left.set_axisbelow(True)
|
|
422
|
+
left.legend(frameon=False, fontsize=9)
|
|
423
|
+
|
|
424
|
+
right = axes[1]
|
|
425
|
+
distributions = [
|
|
426
|
+
result.fold_mase.loc[result.fold_mase["model"] == model, "mase"].to_numpy(dtype="float64")
|
|
427
|
+
for model in models
|
|
428
|
+
]
|
|
429
|
+
right.boxplot(distributions, tick_labels=models, showfliers=False, widths=0.6)
|
|
430
|
+
right.axhline(1.0, color=_REFERENCE_COLOR, linestyle="--", linewidth=1.2)
|
|
431
|
+
right.set_ylabel("per-fold MASE")
|
|
432
|
+
right.set_title("Distribution of per-fold MASE")
|
|
433
|
+
right.grid(axis="y", color=_GRID_COLOR, linewidth=0.8, alpha=0.8)
|
|
434
|
+
right.set_axisbelow(True)
|
|
435
|
+
right.tick_params(axis="x", rotation=20)
|
|
436
|
+
|
|
437
|
+
for axis in axes:
|
|
438
|
+
for label in axis.get_xticklabels():
|
|
439
|
+
label.set_horizontalalignment("right")
|
|
440
|
+
|
|
441
|
+
figure.suptitle(
|
|
442
|
+
"ForecastForge baselines on synthetic price paths "
|
|
443
|
+
f"({len(result.config.seeds)} seeds, {result.config.length} days)",
|
|
444
|
+
fontsize=12,
|
|
445
|
+
)
|
|
446
|
+
figure.savefig(path, dpi=150)
|
|
447
|
+
pyplot.close(figure)
|
|
448
|
+
return path
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def save_report(
|
|
452
|
+
result: BenchmarkResult, directory: Path, *, plot: bool = True
|
|
453
|
+
) -> tuple[Path, Path | None]:
|
|
454
|
+
"""Write the markdown table and, when asked and possible, the plot.
|
|
455
|
+
|
|
456
|
+
Args:
|
|
457
|
+
result: A completed benchmark.
|
|
458
|
+
directory: Destination directory, created if missing.
|
|
459
|
+
plot: Whether to draw the figure. Ignored when matplotlib is absent.
|
|
460
|
+
|
|
461
|
+
Returns:
|
|
462
|
+
The table path and the plot path (``None`` when no figure was drawn).
|
|
463
|
+
"""
|
|
464
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
465
|
+
table = directory / "benchmark_results.md"
|
|
466
|
+
# newline="\n" so a rerun on Windows produces the same bytes as one on
|
|
467
|
+
# Linux, otherwise the committed report shows a spurious diff every time.
|
|
468
|
+
table.write_text(render_markdown(result), encoding="utf-8", newline="\n")
|
|
469
|
+
if not plot or _PYPLOT is None:
|
|
470
|
+
return table, None
|
|
471
|
+
return table, _plot(result, directory / "benchmark_mase.png")
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _emit(text: str) -> None:
|
|
475
|
+
"""Write ``text`` to standard output.
|
|
476
|
+
|
|
477
|
+
``print`` is banned in the package by the lint configuration, and this is
|
|
478
|
+
the one place a command-line report legitimately needs raw output.
|
|
479
|
+
"""
|
|
480
|
+
sys.stdout.write(text if text.endswith("\n") else f"{text}\n")
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
484
|
+
"""Run the benchmark and write the report.
|
|
485
|
+
|
|
486
|
+
Args:
|
|
487
|
+
argv: Command-line arguments, defaulting to ``sys.argv[1:]``.
|
|
488
|
+
|
|
489
|
+
Returns:
|
|
490
|
+
``0`` on success.
|
|
491
|
+
"""
|
|
492
|
+
defaults = BenchmarkConfig()
|
|
493
|
+
parser = argparse.ArgumentParser(
|
|
494
|
+
prog="python -m forecastforge.evaluation.benchmark",
|
|
495
|
+
description="Benchmark every available forecaster on synthetic series.",
|
|
496
|
+
)
|
|
497
|
+
parser.add_argument("--seeds", type=int, nargs="+", default=list(defaults.seeds))
|
|
498
|
+
parser.add_argument("--length", type=int, default=defaults.length)
|
|
499
|
+
parser.add_argument("--initial-train", type=int, default=defaults.initial_train)
|
|
500
|
+
parser.add_argument("--step", type=int, default=defaults.step)
|
|
501
|
+
parser.add_argument("--horizon", type=int, default=defaults.horizon)
|
|
502
|
+
parser.add_argument("--season", type=int, default=defaults.season)
|
|
503
|
+
parser.add_argument("--output-dir", type=Path, default=Path("docs/assets"))
|
|
504
|
+
parser.add_argument(
|
|
505
|
+
"--no-plot",
|
|
506
|
+
action="store_true",
|
|
507
|
+
help="skip the figure (useful on a machine without the viz extra)",
|
|
508
|
+
)
|
|
509
|
+
parser.add_argument(
|
|
510
|
+
"--fast",
|
|
511
|
+
action="store_true",
|
|
512
|
+
help="reduced run for CI smoke checks: 1 seed, short series, no plot",
|
|
513
|
+
)
|
|
514
|
+
arguments = parser.parse_args(argv)
|
|
515
|
+
|
|
516
|
+
# A reduced run for CI so `make benchmark` can never silently break: one
|
|
517
|
+
# seed, a short series, and no figure. The same effect can be forced
|
|
518
|
+
# without CLI access through the BENCHMARK_FAST environment variable.
|
|
519
|
+
fast = arguments.fast or os.environ.get("BENCHMARK_FAST", "").lower() in {
|
|
520
|
+
"1",
|
|
521
|
+
"true",
|
|
522
|
+
"yes",
|
|
523
|
+
}
|
|
524
|
+
if fast:
|
|
525
|
+
seeds: tuple[int, ...] = (1,)
|
|
526
|
+
length = 600
|
|
527
|
+
initial_train = 300
|
|
528
|
+
step = 100
|
|
529
|
+
plot = False
|
|
530
|
+
else:
|
|
531
|
+
seeds = tuple(arguments.seeds)
|
|
532
|
+
length = arguments.length
|
|
533
|
+
initial_train = arguments.initial_train
|
|
534
|
+
step = arguments.step
|
|
535
|
+
plot = not arguments.no_plot
|
|
536
|
+
|
|
537
|
+
config = BenchmarkConfig(
|
|
538
|
+
seeds=seeds,
|
|
539
|
+
length=length,
|
|
540
|
+
horizon=arguments.horizon,
|
|
541
|
+
initial_train=initial_train,
|
|
542
|
+
step=step,
|
|
543
|
+
season=arguments.season,
|
|
544
|
+
)
|
|
545
|
+
result = run_benchmark(config)
|
|
546
|
+
_emit(render_markdown(result))
|
|
547
|
+
table, figure = save_report(result, Path(arguments.output_dir), plot=plot)
|
|
548
|
+
_emit(f"wrote {table}")
|
|
549
|
+
if figure is not None:
|
|
550
|
+
_emit(f"wrote {figure}")
|
|
551
|
+
elif not arguments.no_plot:
|
|
552
|
+
_emit('matplotlib is not installed, so the figure was skipped (pip install -e ".[viz]")')
|
|
553
|
+
return 0
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
if __name__ == "__main__": # pragma: no cover - exercised through main()
|
|
557
|
+
raise SystemExit(main())
|