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,372 @@
|
|
|
1
|
+
"""Leakage-safe walk-forward backtesting.
|
|
2
|
+
|
|
3
|
+
A backtest is only as honest as its fold boundaries. The rule this module
|
|
4
|
+
enforces is simple and absolute: **the model receives exactly the rows at or
|
|
5
|
+
before the fold's cutoff, and nothing else.** Every prediction is scored
|
|
6
|
+
against a target that lies strictly after that cutoff.
|
|
7
|
+
|
|
8
|
+
The ``gap`` parameter adds an embargo, following the convention of
|
|
9
|
+
``sklearn.model_selection.TimeSeriesSplit``: with ``gap = g``, the last ``g``
|
|
10
|
+
observations before the forecast origin are withheld, so the training window
|
|
11
|
+
ends ``g`` periods before the first predicted point. The embargo rows are
|
|
12
|
+
neither trained on nor predicted — they are discarded, which is what stops a
|
|
13
|
+
model from fitting on data adjacent to the target.
|
|
14
|
+
|
|
15
|
+
Training rows whose target extends past the cutoff are excluded by
|
|
16
|
+
construction: the model is only ever handed a history that ends at the
|
|
17
|
+
cutoff, so there is no row it could pair with a future target. A supervised
|
|
18
|
+
model that builds ``(features_t, y_{t+h})`` pairs must therefore stop at
|
|
19
|
+
``t + h <= len(history) - 1``, which is what
|
|
20
|
+
:class:`~forecastforge.models.gbm.LightGBMForecaster` does.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from collections.abc import Mapping
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
|
|
28
|
+
import numpy as np
|
|
29
|
+
import pandas as pd
|
|
30
|
+
|
|
31
|
+
from forecastforge.core.errors import DataValidationError
|
|
32
|
+
from forecastforge.evaluation.metrics import (
|
|
33
|
+
MetricSet,
|
|
34
|
+
directional_accuracy,
|
|
35
|
+
mae,
|
|
36
|
+
mase_scale,
|
|
37
|
+
rmse,
|
|
38
|
+
smape,
|
|
39
|
+
)
|
|
40
|
+
from forecastforge.models.base import Forecaster, validate_history
|
|
41
|
+
|
|
42
|
+
__all__ = ["BacktestConfig", "BacktestResult", "Fold", "WalkForwardBacktester"]
|
|
43
|
+
|
|
44
|
+
_PREDICTION_COLUMNS = (
|
|
45
|
+
"fold",
|
|
46
|
+
"timestamp",
|
|
47
|
+
"horizon",
|
|
48
|
+
"y_true",
|
|
49
|
+
"y_pred",
|
|
50
|
+
"model",
|
|
51
|
+
"previous",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
# A training window shorter than this cannot produce a naive error, and a
|
|
55
|
+
# rolling window shorter than this is not a window at all.
|
|
56
|
+
_MIN_TRAIN_ROWS = 2
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True, slots=True)
|
|
60
|
+
class BacktestConfig:
|
|
61
|
+
"""How to slice the series into walk-forward folds.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
horizon: Number of periods predicted from each origin.
|
|
65
|
+
initial_train: Rows available before the first forecast origin. The
|
|
66
|
+
first origin is the last of these rows, so the first training
|
|
67
|
+
window holds ``initial_train - gap`` rows.
|
|
68
|
+
step: Rows between consecutive forecast origins. A step above 1 trades
|
|
69
|
+
resolution for runtime.
|
|
70
|
+
gap: Observations withheld from the end of each training window, so
|
|
71
|
+
the model fits on data ending ``gap`` periods before the origin.
|
|
72
|
+
The embargo rows are skipped entirely: they are neither trained
|
|
73
|
+
on nor predicted.
|
|
74
|
+
window: Rolling training-window length. ``None`` means expanding.
|
|
75
|
+
seasonal_period: Naive lag used for the MASE scale and for the
|
|
76
|
+
seasonal baseline.
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
DataValidationError: If any value is out of range.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
horizon: int = 1
|
|
83
|
+
initial_train: int = 252
|
|
84
|
+
step: int = 1
|
|
85
|
+
gap: int = 0
|
|
86
|
+
window: int | None = None
|
|
87
|
+
seasonal_period: int = 1
|
|
88
|
+
|
|
89
|
+
def __post_init__(self) -> None:
|
|
90
|
+
if self.horizon <= 0:
|
|
91
|
+
raise DataValidationError(f"horizon must be positive, got {self.horizon}")
|
|
92
|
+
if self.initial_train < _MIN_TRAIN_ROWS:
|
|
93
|
+
raise DataValidationError(
|
|
94
|
+
f"initial_train must be at least {_MIN_TRAIN_ROWS}, got {self.initial_train}"
|
|
95
|
+
)
|
|
96
|
+
if self.step <= 0:
|
|
97
|
+
raise DataValidationError(f"step must be positive, got {self.step}")
|
|
98
|
+
if self.gap < 0:
|
|
99
|
+
raise DataValidationError(f"gap must be non-negative, got {self.gap}")
|
|
100
|
+
if self.gap >= self.initial_train - 1:
|
|
101
|
+
raise DataValidationError(
|
|
102
|
+
f"gap={self.gap} leaves no training data before the first origin: "
|
|
103
|
+
f"initial_train={self.initial_train} rows minus a gap of {self.gap} "
|
|
104
|
+
f"leaves {self.initial_train - self.gap} row(s), and at least "
|
|
105
|
+
f"{_MIN_TRAIN_ROWS} are required"
|
|
106
|
+
)
|
|
107
|
+
if self.window is not None and self.window < _MIN_TRAIN_ROWS:
|
|
108
|
+
raise DataValidationError(
|
|
109
|
+
f"window must be at least {_MIN_TRAIN_ROWS}, got {self.window}"
|
|
110
|
+
)
|
|
111
|
+
if self.seasonal_period <= 0:
|
|
112
|
+
raise DataValidationError(
|
|
113
|
+
f"seasonal_period must be positive, got {self.seasonal_period}"
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True, slots=True)
|
|
118
|
+
class Fold:
|
|
119
|
+
"""One training window and the origin it forecasts from.
|
|
120
|
+
|
|
121
|
+
Attributes:
|
|
122
|
+
number: Zero-based fold index.
|
|
123
|
+
train_start: First row of the training window, inclusive.
|
|
124
|
+
train_end: Last row of the training window, inclusive.
|
|
125
|
+
origin: Last row observed before the forecast. The first prediction
|
|
126
|
+
targets ``origin + 1``. With no embargo this equals ``train_end``;
|
|
127
|
+
with ``gap = g`` it is ``train_end + g``.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
number: int
|
|
131
|
+
train_start: int
|
|
132
|
+
train_end: int
|
|
133
|
+
origin: int
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def n_train(self) -> int:
|
|
137
|
+
"""Number of rows the model is allowed to see."""
|
|
138
|
+
return self.train_end - self.train_start + 1
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def gap(self) -> int:
|
|
142
|
+
"""Number of embargoed rows between the training window and the origin."""
|
|
143
|
+
return self.origin - self.train_end
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@dataclass(frozen=True, slots=True)
|
|
147
|
+
class BacktestResult:
|
|
148
|
+
"""The outcome of a walk-forward run.
|
|
149
|
+
|
|
150
|
+
Attributes:
|
|
151
|
+
predictions: Tidy frame with one row per (fold, horizon step, model).
|
|
152
|
+
fold_scales: MASE scale per fold, computed from that fold's training
|
|
153
|
+
window only.
|
|
154
|
+
config: The configuration that produced the run.
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
predictions: pd.DataFrame
|
|
158
|
+
fold_scales: pd.Series
|
|
159
|
+
config: BacktestConfig
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def models(self) -> tuple[str, ...]:
|
|
163
|
+
"""Model names present in the result, in insertion order."""
|
|
164
|
+
return tuple(dict.fromkeys(self.predictions["model"].tolist()))
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def folds(self) -> tuple[int, ...]:
|
|
168
|
+
"""Fold numbers present in the result."""
|
|
169
|
+
return tuple(sorted(self.predictions["fold"].unique().tolist()))
|
|
170
|
+
|
|
171
|
+
def metrics_for(self, model: str) -> MetricSet:
|
|
172
|
+
"""Compute the metric set for one model.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
model: A name present in :attr:`predictions`.
|
|
176
|
+
|
|
177
|
+
Returns:
|
|
178
|
+
The metrics, with MASE averaged over per-fold scaled errors so
|
|
179
|
+
that each fold contributes one comparable number.
|
|
180
|
+
|
|
181
|
+
Raises:
|
|
182
|
+
DataValidationError: If ``model`` is not in the result.
|
|
183
|
+
"""
|
|
184
|
+
subset = self.predictions[self.predictions["model"] == model]
|
|
185
|
+
if subset.empty:
|
|
186
|
+
available = ", ".join(self.models)
|
|
187
|
+
raise DataValidationError(
|
|
188
|
+
f"model {model!r} is not in this result; available: {available}"
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
per_fold_mase: list[float] = []
|
|
192
|
+
for fold, group in subset.groupby("fold", sort=True):
|
|
193
|
+
scale = float(self.fold_scales.loc[fold])
|
|
194
|
+
per_fold_mase.append(
|
|
195
|
+
mae(
|
|
196
|
+
group["y_true"].to_numpy(dtype="float64"),
|
|
197
|
+
group["y_pred"].to_numpy(dtype="float64"),
|
|
198
|
+
)
|
|
199
|
+
/ scale
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
y_true = subset["y_true"].to_numpy(dtype="float64")
|
|
203
|
+
y_pred = subset["y_pred"].to_numpy(dtype="float64")
|
|
204
|
+
previous = subset["previous"].to_numpy(dtype="float64")
|
|
205
|
+
return MetricSet(
|
|
206
|
+
mae=mae(y_true, y_pred),
|
|
207
|
+
rmse=rmse(y_true, y_pred),
|
|
208
|
+
smape=smape(y_true, y_pred),
|
|
209
|
+
mase=float(np.mean(per_fold_mase)),
|
|
210
|
+
directional_accuracy=directional_accuracy(y_true, y_pred, previous),
|
|
211
|
+
n_observations=int(y_true.size),
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def summary(self) -> pd.DataFrame:
|
|
215
|
+
"""Return one row of metrics per model, indexed by model name."""
|
|
216
|
+
rows = {model: self.metrics_for(model).as_dict() for model in self.models}
|
|
217
|
+
return pd.DataFrame.from_dict(rows, orient="index")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class WalkForwardBacktester:
|
|
221
|
+
"""Runs models over expanding or rolling walk-forward folds.
|
|
222
|
+
|
|
223
|
+
Args:
|
|
224
|
+
config: The fold layout.
|
|
225
|
+
|
|
226
|
+
Example:
|
|
227
|
+
::
|
|
228
|
+
|
|
229
|
+
backtester = WalkForwardBacktester(BacktestConfig(horizon=1))
|
|
230
|
+
result = backtester.run(series, {"naive": Naive()})
|
|
231
|
+
print(result.summary())
|
|
232
|
+
"""
|
|
233
|
+
|
|
234
|
+
def __init__(self, config: BacktestConfig | None = None) -> None:
|
|
235
|
+
self.config = config or BacktestConfig()
|
|
236
|
+
|
|
237
|
+
def folds(self, n_rows: int) -> tuple[Fold, ...]:
|
|
238
|
+
"""Return the fold layout for a series of ``n_rows`` rows.
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
n_rows: Length of the series being backtested.
|
|
242
|
+
|
|
243
|
+
Returns:
|
|
244
|
+
Folds in chronological order. Empty when the series is too short
|
|
245
|
+
for even one complete fold.
|
|
246
|
+
"""
|
|
247
|
+
config = self.config
|
|
248
|
+
folds: list[Fold] = []
|
|
249
|
+
number = 0
|
|
250
|
+
for origin in range(config.initial_train - 1, n_rows, config.step):
|
|
251
|
+
# The embargo pushes the training window back; the rows between
|
|
252
|
+
# train_end and origin are neither trained on nor predicted.
|
|
253
|
+
train_end = origin - config.gap
|
|
254
|
+
if train_end < 1:
|
|
255
|
+
continue
|
|
256
|
+
if origin + config.horizon > n_rows - 1:
|
|
257
|
+
break
|
|
258
|
+
train_start = 0 if config.window is None else max(0, train_end - config.window + 1)
|
|
259
|
+
# MASE needs at least one naive error in the training window.
|
|
260
|
+
if train_end - train_start + 1 <= config.seasonal_period:
|
|
261
|
+
continue
|
|
262
|
+
folds.append(
|
|
263
|
+
Fold(
|
|
264
|
+
number=number,
|
|
265
|
+
train_start=train_start,
|
|
266
|
+
train_end=train_end,
|
|
267
|
+
origin=origin,
|
|
268
|
+
)
|
|
269
|
+
)
|
|
270
|
+
number += 1
|
|
271
|
+
return tuple(folds)
|
|
272
|
+
|
|
273
|
+
def run(
|
|
274
|
+
self,
|
|
275
|
+
series: pd.Series,
|
|
276
|
+
models: Mapping[str, Forecaster],
|
|
277
|
+
features: pd.DataFrame | None = None,
|
|
278
|
+
) -> BacktestResult:
|
|
279
|
+
"""Backtest ``models`` over ``series``.
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
series: The full series. Only the rows a fold is allowed to see are
|
|
283
|
+
ever passed to a model.
|
|
284
|
+
models: Model name to an *unfitted* prototype. Each fold receives
|
|
285
|
+
a fresh clone, so state cannot carry across folds.
|
|
286
|
+
features: Optional exogenous columns aligned to ``series.index``.
|
|
287
|
+
Sliced to the same rows as the history for each fold.
|
|
288
|
+
|
|
289
|
+
Returns:
|
|
290
|
+
A :class:`BacktestResult`.
|
|
291
|
+
|
|
292
|
+
Raises:
|
|
293
|
+
DataValidationError: If the inputs are invalid, a model's horizon
|
|
294
|
+
does not match the config, or no fold fits in the series.
|
|
295
|
+
"""
|
|
296
|
+
validate_history(series, features, requires_features=False)
|
|
297
|
+
self._check_models(models)
|
|
298
|
+
|
|
299
|
+
folds = self.folds(len(series))
|
|
300
|
+
if not folds:
|
|
301
|
+
raise DataValidationError(
|
|
302
|
+
f"no fold fits in a series of {len(series)} rows with "
|
|
303
|
+
f"initial_train={self.config.initial_train}, "
|
|
304
|
+
f"gap={self.config.gap} and horizon={self.config.horizon}"
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
records: list[dict[str, object]] = []
|
|
308
|
+
scales: dict[int, float] = {}
|
|
309
|
+
|
|
310
|
+
for fold in folds:
|
|
311
|
+
history = series.iloc[fold.train_start : fold.train_end + 1]
|
|
312
|
+
history_features = None
|
|
313
|
+
if features is not None:
|
|
314
|
+
history_features = features.iloc[fold.train_start : fold.train_end + 1]
|
|
315
|
+
target_start = fold.origin + 1
|
|
316
|
+
target_slice = series.iloc[target_start : target_start + self.config.horizon]
|
|
317
|
+
# previous[k] is the observation immediately before the target at
|
|
318
|
+
# step k + 1; all of them are actual values, used only for scoring.
|
|
319
|
+
previous_slice = series.iloc[fold.origin : fold.origin + self.config.horizon]
|
|
320
|
+
|
|
321
|
+
scales[fold.number] = mase_scale(
|
|
322
|
+
history.to_numpy(dtype="float64"),
|
|
323
|
+
seasonal_period=self.config.seasonal_period,
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
for model_name, prototype in models.items():
|
|
327
|
+
fitted = prototype.clone().fit(history, history_features)
|
|
328
|
+
y_pred = fitted.predict()
|
|
329
|
+
records.extend(
|
|
330
|
+
{
|
|
331
|
+
"fold": fold.number,
|
|
332
|
+
"timestamp": target_slice.index[step],
|
|
333
|
+
"horizon": step + 1,
|
|
334
|
+
"y_true": float(target_slice.iloc[step]),
|
|
335
|
+
"y_pred": float(y_pred[step]),
|
|
336
|
+
"model": model_name,
|
|
337
|
+
"previous": float(previous_slice.iloc[step]),
|
|
338
|
+
}
|
|
339
|
+
for step in range(self.config.horizon)
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
predictions = pd.DataFrame.from_records(records, columns=list(_PREDICTION_COLUMNS))
|
|
343
|
+
return BacktestResult(
|
|
344
|
+
predictions=predictions,
|
|
345
|
+
fold_scales=pd.Series(scales, name="mase_scale", dtype="float64"),
|
|
346
|
+
config=self.config,
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
def _check_models(self, models: Mapping[str, Forecaster]) -> None:
|
|
350
|
+
"""Validate the model mapping before doing any work.
|
|
351
|
+
|
|
352
|
+
Args:
|
|
353
|
+
models: The prototypes supplied to :meth:`run`.
|
|
354
|
+
|
|
355
|
+
Raises:
|
|
356
|
+
DataValidationError: If the mapping is empty, a value is not a
|
|
357
|
+
``Forecaster``, or a prototype's horizon differs from the
|
|
358
|
+
config's.
|
|
359
|
+
"""
|
|
360
|
+
if not models:
|
|
361
|
+
raise DataValidationError("at least one model is required")
|
|
362
|
+
for model_name, prototype in models.items():
|
|
363
|
+
if not isinstance(prototype, Forecaster):
|
|
364
|
+
raise DataValidationError(
|
|
365
|
+
f"model {model_name!r} is a {type(prototype).__name__}, not a Forecaster"
|
|
366
|
+
)
|
|
367
|
+
if prototype.horizon != self.config.horizon:
|
|
368
|
+
raise DataValidationError(
|
|
369
|
+
f"model {model_name!r} was built with horizon={prototype.horizon} "
|
|
370
|
+
f"but the backtest config uses horizon={self.config.horizon}; "
|
|
371
|
+
"construct the model with the same horizon"
|
|
372
|
+
)
|