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.
Files changed (49) hide show
  1. forecastforge/__init__.py +41 -0
  2. forecastforge/cli/__init__.py +12 -0
  3. forecastforge/cli/__main__.py +13 -0
  4. forecastforge/cli/main.py +477 -0
  5. forecastforge/common/__init__.py +6 -0
  6. forecastforge/config/__init__.py +61 -0
  7. forecastforge/config/_optional.py +39 -0
  8. forecastforge/config/device.py +98 -0
  9. forecastforge/config/environment.py +50 -0
  10. forecastforge/config/paths.py +131 -0
  11. forecastforge/config/runtime.py +76 -0
  12. forecastforge/config/seed.py +56 -0
  13. forecastforge/config/settings.py +249 -0
  14. forecastforge/core/__init__.py +21 -0
  15. forecastforge/core/errors.py +42 -0
  16. forecastforge/data/__init__.py +31 -0
  17. forecastforge/data/loaders.py +62 -0
  18. forecastforge/data/source.py +140 -0
  19. forecastforge/data/synthetic.py +212 -0
  20. forecastforge/data/yfinance_source.py +105 -0
  21. forecastforge/evaluation/__init__.py +44 -0
  22. forecastforge/evaluation/backtest.py +372 -0
  23. forecastforge/evaluation/benchmark.py +557 -0
  24. forecastforge/evaluation/metrics.py +318 -0
  25. forecastforge/features/__init__.py +67 -0
  26. forecastforge/features/builtins.py +540 -0
  27. forecastforge/features/frame.py +241 -0
  28. forecastforge/features/pipeline.py +84 -0
  29. forecastforge/features/transform.py +104 -0
  30. forecastforge/models/__init__.py +36 -0
  31. forecastforge/models/base.py +178 -0
  32. forecastforge/models/baselines.py +172 -0
  33. forecastforge/models/gbm.py +282 -0
  34. forecastforge/models/statistical.py +213 -0
  35. forecastforge/monitoring/__init__.py +6 -0
  36. forecastforge/pipelines/__init__.py +25 -0
  37. forecastforge/pipelines/synthetic_backtest.py +168 -0
  38. forecastforge/py.typed +0 -0
  39. forecastforge/schemas/__init__.py +19 -0
  40. forecastforge/schemas/time_series.py +101 -0
  41. forecastforge/schemas/validation.py +222 -0
  42. forecastforge/serving/__init__.py +5 -0
  43. forecastforge/tracking/__init__.py +6 -0
  44. forecastforge/utils/__init__.py +6 -0
  45. forecastforge-0.4.0.dist-info/METADATA +609 -0
  46. forecastforge-0.4.0.dist-info/RECORD +49 -0
  47. forecastforge-0.4.0.dist-info/WHEEL +4 -0
  48. forecastforge-0.4.0.dist-info/entry_points.txt +2 -0
  49. forecastforge-0.4.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,318 @@
1
+ """Forecast accuracy metrics.
2
+
3
+ Each function is a pure function of arrays, so every number in a report can be
4
+ recomputed by hand. The definitions are stated in the docstrings because
5
+ forecasting metrics are easy to implement subtly differently — sMAPE in
6
+ particular has several incompatible conventions in the literature, and MASE is
7
+ meaningless without saying exactly what the scale is.
8
+
9
+ Scale-dependent metrics (MAE, RMSE) are reported in the units of the target.
10
+ sMAPE and directional accuracy are percentages. MASE is unit-free by
11
+ construction.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Sequence
17
+ from dataclasses import asdict, dataclass
18
+
19
+ import numpy as np
20
+
21
+ from forecastforge.core.errors import DataValidationError
22
+
23
+ __all__ = [
24
+ "MetricSet",
25
+ "directional_accuracy",
26
+ "evaluate",
27
+ "interval_coverage",
28
+ "mae",
29
+ "mase",
30
+ "mase_scale",
31
+ "rmse",
32
+ "smape",
33
+ ]
34
+
35
+
36
+ @dataclass(frozen=True, slots=True)
37
+ class MetricSet:
38
+ """An immutable bundle of the standard accuracy metrics.
39
+
40
+ Attributes:
41
+ mae: Mean absolute error, in target units.
42
+ rmse: Root mean squared error, in target units.
43
+ smape: Symmetric mean absolute percentage error, in percent.
44
+ mase: Mean absolute scaled error; 1.0 means "as good as the naive
45
+ one-step forecast on the training window".
46
+ directional_accuracy: Share of correctly signed changes, in percent.
47
+ n_observations: Number of scored predictions.
48
+ """
49
+
50
+ mae: float
51
+ rmse: float
52
+ smape: float
53
+ mase: float
54
+ directional_accuracy: float
55
+ n_observations: int
56
+
57
+ def as_dict(self) -> dict[str, float]:
58
+ """Return the metrics as a plain mapping, without the sample count."""
59
+ values = asdict(self)
60
+ values.pop("n_observations")
61
+ return values
62
+
63
+
64
+ def _as_array(values: Sequence[float] | np.ndarray, *, name: str) -> np.ndarray:
65
+ """Convert input to a 1-D float array, rejecting empties.
66
+
67
+ Args:
68
+ values: Array-like of numbers.
69
+ name: Parameter name, used in the error message.
70
+
71
+ Returns:
72
+ A 1-D ``float64`` array.
73
+
74
+ Raises:
75
+ DataValidationError: If the input is empty.
76
+ """
77
+ array = np.asarray(values, dtype="float64").reshape(-1)
78
+ if array.size == 0:
79
+ raise DataValidationError(f"{name} is empty: at least one value is required")
80
+ return array
81
+
82
+
83
+ def _paired(
84
+ y_true: Sequence[float] | np.ndarray,
85
+ y_pred: Sequence[float] | np.ndarray,
86
+ ) -> tuple[np.ndarray, np.ndarray]:
87
+ """Return ``y_true`` and ``y_pred`` as equal-length float arrays.
88
+
89
+ Args:
90
+ y_true: Observed values.
91
+ y_pred: Predicted values.
92
+
93
+ Raises:
94
+ DataValidationError: If the arrays are empty or differ in length.
95
+ """
96
+ actual = _as_array(y_true, name="y_true")
97
+ predicted = _as_array(y_pred, name="y_pred")
98
+ if actual.shape != predicted.shape:
99
+ raise DataValidationError(
100
+ f"y_true and y_pred must have the same length, "
101
+ f"got {actual.shape[0]} and {predicted.shape[0]}"
102
+ )
103
+ return actual, predicted
104
+
105
+
106
+ def mae(y_true: Sequence[float] | np.ndarray, y_pred: Sequence[float] | np.ndarray) -> float:
107
+ """Mean absolute error.
108
+
109
+ Args:
110
+ y_true: Observed values.
111
+ y_pred: Predicted values.
112
+
113
+ Returns:
114
+ ``mean(|y_true - y_pred|)``.
115
+ """
116
+ actual, predicted = _paired(y_true, y_pred)
117
+ return float(np.mean(np.abs(actual - predicted)))
118
+
119
+
120
+ def rmse(y_true: Sequence[float] | np.ndarray, y_pred: Sequence[float] | np.ndarray) -> float:
121
+ """Root mean squared error.
122
+
123
+ Args:
124
+ y_true: Observed values.
125
+ y_pred: Predicted values.
126
+
127
+ Returns:
128
+ ``sqrt(mean((y_true - y_pred) ** 2))``.
129
+ """
130
+ actual, predicted = _paired(y_true, y_pred)
131
+ return float(np.sqrt(np.mean((actual - predicted) ** 2)))
132
+
133
+
134
+ def smape(y_true: Sequence[float] | np.ndarray, y_pred: Sequence[float] | np.ndarray) -> float:
135
+ """Symmetric mean absolute percentage error, in percent.
136
+
137
+ Uses the ``2 * |e| / (|y| + |y_hat|)`` convention. When both the actual
138
+ and the predicted value are zero the term is defined as 0 — the forecast
139
+ is exactly right, and the ratio is otherwise undefined.
140
+
141
+ Args:
142
+ y_true: Observed values.
143
+ y_pred: Predicted values.
144
+
145
+ Returns:
146
+ The mean percentage error. A perfect forecast scores 0; a forecast of
147
+ equal magnitude and opposite sign scores 200, which is the ceiling of
148
+ this convention.
149
+ """
150
+ actual, predicted = _paired(y_true, y_pred)
151
+ numerator = 2.0 * np.abs(actual - predicted)
152
+ denominator = np.abs(actual) + np.abs(predicted)
153
+ with np.errstate(divide="ignore", invalid="ignore"):
154
+ terms = np.where(denominator == 0.0, 0.0, numerator / denominator)
155
+ return float(np.mean(terms) * 100.0)
156
+
157
+
158
+ def mase_scale(y_train: Sequence[float] | np.ndarray, *, seasonal_period: int = 1) -> float:
159
+ """Return the in-sample naive error used to scale MASE.
160
+
161
+ This is ``mean(|y[t] - y[t - m]|)`` over the training window, where ``m``
162
+ is the seasonal period. It is the denominator of MASE and the reason MASE
163
+ is comparable across series of different scale.
164
+
165
+ Args:
166
+ y_train: The training observations the model saw.
167
+ seasonal_period: The naive forecast's lag; 1 for a random-walk naive.
168
+
169
+ Returns:
170
+ The mean absolute naive error.
171
+
172
+ Raises:
173
+ DataValidationError: If ``seasonal_period`` is not positive, the
174
+ training window is too short, or the series is constant (a zero
175
+ scale makes MASE undefined).
176
+ """
177
+ if seasonal_period <= 0:
178
+ raise DataValidationError(f"seasonal_period must be positive, got {seasonal_period}")
179
+ values = _as_array(y_train, name="y_train")
180
+ if values.shape[0] <= seasonal_period:
181
+ raise DataValidationError(
182
+ f"y_train needs more than seasonal_period={seasonal_period} observations "
183
+ f"to compute the naive scale, got {values.shape[0]}"
184
+ )
185
+ errors = np.abs(values[seasonal_period:] - values[:-seasonal_period])
186
+ scale = float(np.mean(errors))
187
+ if scale == 0.0:
188
+ raise DataValidationError(
189
+ "the training series is constant at this seasonal period, so the "
190
+ "naive error is zero and MASE is undefined"
191
+ )
192
+ return scale
193
+
194
+
195
+ def mase(
196
+ y_true: Sequence[float] | np.ndarray,
197
+ y_pred: Sequence[float] | np.ndarray,
198
+ y_train: Sequence[float] | np.ndarray,
199
+ *,
200
+ seasonal_period: int = 1,
201
+ ) -> float:
202
+ """Mean absolute scaled error.
203
+
204
+ Args:
205
+ y_true: Observed values.
206
+ y_pred: Predicted values.
207
+ y_train: The training observations, used only to derive the scale.
208
+ seasonal_period: The naive forecast's lag used for the scale.
209
+
210
+ Returns:
211
+ ``MAE / mase_scale(y_train)``. Below 1 beats the naive forecast;
212
+ above 1 is worse than doing nothing.
213
+ """
214
+ scale = mase_scale(y_train, seasonal_period=seasonal_period)
215
+ return mae(y_true, y_pred) / scale
216
+
217
+
218
+ def directional_accuracy(
219
+ y_true: Sequence[float] | np.ndarray,
220
+ y_pred: Sequence[float] | np.ndarray,
221
+ previous: Sequence[float] | np.ndarray,
222
+ ) -> float:
223
+ """Share of predictions that got the direction of change right, in percent.
224
+
225
+ The direction of a prediction is the sign of ``y_pred - previous``; the
226
+ direction of the outcome is the sign of ``y_true - previous``. A forecast
227
+ that predicts no change is credited only when the outcome also did not
228
+ change.
229
+
230
+ Args:
231
+ y_true: Observed values.
232
+ y_pred: Predicted values.
233
+ previous: The actual value immediately before each predicted point.
234
+
235
+ Returns:
236
+ The percentage of correctly signed changes, or ``nan`` when every
237
+ actual change is zero (no direction existed to predict).
238
+
239
+ Raises:
240
+ DataValidationError: If the arrays differ in length.
241
+ """
242
+ actual, predicted = _paired(y_true, y_pred)
243
+ reference = _as_array(previous, name="previous")
244
+ if reference.shape != actual.shape:
245
+ raise DataValidationError(
246
+ f"previous must have the same length as y_true, "
247
+ f"got {reference.shape[0]} and {actual.shape[0]}"
248
+ )
249
+ actual_direction = np.sign(actual - reference)
250
+ predicted_direction = np.sign(predicted - reference)
251
+ if np.count_nonzero(actual_direction) == 0:
252
+ # No actual change occurred, so there is no direction to predict.
253
+ return float("nan")
254
+ return float(np.mean(actual_direction == predicted_direction) * 100.0)
255
+
256
+
257
+ def interval_coverage(
258
+ y_true: Sequence[float] | np.ndarray,
259
+ lower: Sequence[float] | np.ndarray,
260
+ upper: Sequence[float] | np.ndarray,
261
+ ) -> float:
262
+ """Share of outcomes that fall inside the predicted interval, in percent.
263
+
264
+ Only meaningful for models that emit intervals; a model without them
265
+ should not be scored here at all rather than scored as zero.
266
+
267
+ Args:
268
+ y_true: Observed values.
269
+ lower: Lower bound of each interval.
270
+ upper: Upper bound of each interval.
271
+
272
+ Returns:
273
+ The percentage of ``y_true`` values inside ``[lower, upper]``.
274
+
275
+ Raises:
276
+ DataValidationError: If the arrays differ in length, or a lower bound
277
+ exceeds its upper bound.
278
+ """
279
+ actual, low = _paired(y_true, lower)
280
+ high = _as_array(upper, name="upper")
281
+ if high.shape != actual.shape:
282
+ raise DataValidationError(
283
+ f"upper must have the same length as y_true, got {high.shape[0]} and {actual.shape[0]}"
284
+ )
285
+ if (low > high).any():
286
+ raise DataValidationError("lower bound exceeds upper bound for at least one interval")
287
+ inside = (actual >= low) & (actual <= high)
288
+ return float(np.mean(inside) * 100.0)
289
+
290
+
291
+ def evaluate(
292
+ y_true: Sequence[float] | np.ndarray,
293
+ y_pred: Sequence[float] | np.ndarray,
294
+ *,
295
+ previous: Sequence[float] | np.ndarray,
296
+ y_train: Sequence[float] | np.ndarray,
297
+ seasonal_period: int = 1,
298
+ ) -> MetricSet:
299
+ """Compute every standard metric in one call.
300
+
301
+ Args:
302
+ y_true: Observed values.
303
+ y_pred: Predicted values.
304
+ previous: Actual value immediately before each predicted point.
305
+ y_train: Training observations, used only for the MASE scale.
306
+ seasonal_period: The naive lag used for the MASE scale.
307
+
308
+ Returns:
309
+ A :class:`MetricSet`.
310
+ """
311
+ return MetricSet(
312
+ mae=mae(y_true, y_pred),
313
+ rmse=rmse(y_true, y_pred),
314
+ smape=smape(y_true, y_pred),
315
+ mase=mase(y_true, y_pred, y_train, seasonal_period=seasonal_period),
316
+ directional_accuracy=directional_accuracy(y_true, y_pred, previous),
317
+ n_observations=int(np.asarray(y_true, dtype="float64").size),
318
+ )
@@ -0,0 +1,67 @@
1
+ """Leakage-safe feature engineering.
2
+
3
+ The pipeline turns a validated
4
+ :class:`~forecastforge.schemas.time_series.TimeSeries` into a
5
+ :class:`~forecastforge.features.frame.FeatureSet`: the same timeline and
6
+ target, plus derived columns that may still contain NaN during their warm-up
7
+ period.
8
+
9
+ Two guarantees hold for every transform in this package:
10
+
11
+ * **Causality** — a feature at row *t* depends only on rows ``<= t``, so a
12
+ walk-forward backtest never sees information the model would not have had.
13
+ * **Declared output** — each transform states the columns it produces, and
14
+ :meth:`~forecastforge.features.transform.Transform.apply` verifies it.
15
+
16
+ Example::
17
+
18
+ from forecastforge.data import SyntheticSource
19
+ from forecastforge.features import (
20
+ CalendarFeatures,
21
+ FeaturePipeline,
22
+ Lag,
23
+ Returns,
24
+ RollingStat,
25
+ )
26
+
27
+ series = SyntheticSource().fetch(symbol="SPY")
28
+ features = FeaturePipeline(
29
+ [
30
+ Lag([1, 5, 10]),
31
+ Returns(periods=1, log=True),
32
+ RollingStat(window=20, stat="std", column="close_logret1"),
33
+ CalendarFeatures(["dayofweek", "month_cyclic"]),
34
+ ]
35
+ ).apply(series)
36
+
37
+ print(features.warmup) # rows that are not usable yet
38
+ model_input = features.drop_warmup()
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ from forecastforge.features.builtins import (
44
+ MACD,
45
+ RSI,
46
+ CalendarFeatures,
47
+ Lag,
48
+ Returns,
49
+ RollingStat,
50
+ Volatility,
51
+ )
52
+ from forecastforge.features.frame import FeatureSet
53
+ from forecastforge.features.pipeline import FeaturePipeline
54
+ from forecastforge.features.transform import Transform
55
+
56
+ __all__ = [
57
+ "MACD",
58
+ "RSI",
59
+ "CalendarFeatures",
60
+ "FeaturePipeline",
61
+ "FeatureSet",
62
+ "Lag",
63
+ "Returns",
64
+ "RollingStat",
65
+ "Transform",
66
+ "Volatility",
67
+ ]