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,172 @@
1
+ """Honest baselines that every model must beat.
2
+
3
+ These exist to be a hard floor. On near-random-walk price series a naive
4
+ forecast is genuinely hard to beat, and a project that hides that fact is
5
+ lying to its users. Every benchmark reports them alongside anything fancier.
6
+
7
+ All four are cheap, deterministic, and need no optional dependency.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+ from forecastforge.core.errors import DataValidationError
16
+ from forecastforge.models.base import Forecaster
17
+
18
+ __all__ = ["Drift", "MovingAverage", "Naive", "SeasonalNaive"]
19
+
20
+ # A slope needs two points: with one observation the denominator is zero.
21
+ _MIN_SLOPE_POINTS = 2
22
+
23
+
24
+ class Naive(Forecaster):
25
+ """Forecast the last observed value for every horizon step.
26
+
27
+ This is the "no change" model and the reference every other model is
28
+ measured against. MASE is scaled by its one-step in-sample error, so a
29
+ MASE above 1 means the model is worse than doing nothing.
30
+ """
31
+
32
+ name = "naive"
33
+
34
+ def _fit(self, series: pd.Series, features: pd.DataFrame | None) -> None:
35
+ """Record the last observed value."""
36
+ self._last_value = float(series.iloc[-1])
37
+
38
+ def _predict(self) -> np.ndarray:
39
+ """Return a flat forecast."""
40
+ return np.full(self.horizon, self._last_value, dtype="float64")
41
+
42
+
43
+ class SeasonalNaive(Forecaster):
44
+ """Repeat the value observed one season ago.
45
+
46
+ Args:
47
+ season: Period length in observations — 5 for a weekly cycle in daily
48
+ business data, 252 for an annual cycle.
49
+
50
+ Raises:
51
+ DataValidationError: If ``season`` is not positive, or the history is
52
+ shorter than one full season.
53
+ """
54
+
55
+ name = "seasonal_naive"
56
+
57
+ def __init__(self, *, season: int = 5, horizon: int = 1) -> None:
58
+ super().__init__(horizon=horizon)
59
+ if season <= 0:
60
+ raise DataValidationError(f"season must be positive, got {season}")
61
+ self.season = season
62
+
63
+ def _fit(self, series: pd.Series, features: pd.DataFrame | None) -> None:
64
+ """Store the history, which must span at least one season."""
65
+ if len(series) < self.season:
66
+ raise DataValidationError(
67
+ f"SeasonalNaive(season={self.season}) needs at least "
68
+ f"{self.season} observations, got {len(series)}"
69
+ )
70
+ self._values = series.to_numpy(dtype="float64")
71
+
72
+ def _predict(self) -> np.ndarray:
73
+ """Walk forward one season at a time.
74
+
75
+ Beyond the first season the model repeats its own forecasts, which is
76
+ what "seasonal naive" means once there is no observed value left to
77
+ copy.
78
+ """
79
+ values = list(self._values)
80
+ start = len(values)
81
+ for step in range(self.horizon):
82
+ values.append(values[start + step - self.season])
83
+ return np.asarray(values[start:], dtype="float64")
84
+
85
+ def __repr__(self) -> str:
86
+ """Return a representation including the season length."""
87
+ return f"{type(self).__name__}(season={self.season}, horizon={self.horizon})"
88
+
89
+
90
+ class MovingAverage(Forecaster):
91
+ """Forecast the mean of the last ``window`` observations, flat.
92
+
93
+ Args:
94
+ window: Number of trailing observations to average.
95
+
96
+ Raises:
97
+ DataValidationError: If ``window`` is not positive or the history is
98
+ shorter than ``window``.
99
+ """
100
+
101
+ name = "moving_average"
102
+
103
+ def __init__(self, *, window: int = 20, horizon: int = 1) -> None:
104
+ super().__init__(horizon=horizon)
105
+ if window <= 0:
106
+ raise DataValidationError(f"window must be positive, got {window}")
107
+ self.window = window
108
+
109
+ def _fit(self, series: pd.Series, features: pd.DataFrame | None) -> None:
110
+ """Average the trailing window."""
111
+ if len(series) < self.window:
112
+ raise DataValidationError(
113
+ f"MovingAverage(window={self.window}) needs at least "
114
+ f"{self.window} observations, got {len(series)}"
115
+ )
116
+ self._mean = float(series.iloc[-self.window :].mean())
117
+
118
+ def _predict(self) -> np.ndarray:
119
+ """Return a flat forecast at the trailing mean."""
120
+ return np.full(self.horizon, self._mean, dtype="float64")
121
+
122
+ def __repr__(self) -> str:
123
+ """Return a representation including the window."""
124
+ return f"{type(self).__name__}(window={self.window}, horizon={self.horizon})"
125
+
126
+
127
+ class Drift(Forecaster):
128
+ """Extrapolate the average change per period from the first to the last value.
129
+
130
+ Args:
131
+ window: When set, compute the slope over the trailing ``window``
132
+ observations instead of the whole history.
133
+
134
+ Raises:
135
+ DataValidationError: If fewer than two observations are available
136
+ after applying ``window``.
137
+ """
138
+
139
+ name = "drift"
140
+
141
+ def __init__(self, *, window: int | None = None, horizon: int = 1) -> None:
142
+ super().__init__(horizon=horizon)
143
+ if window is not None and window <= 1:
144
+ raise DataValidationError(f"window must be at least 2, got {window}")
145
+ self.window = window
146
+
147
+ def _fit(self, series: pd.Series, features: pd.DataFrame | None) -> None:
148
+ """Estimate the per-period slope."""
149
+ values = series.to_numpy(dtype="float64")
150
+ if self.window is not None:
151
+ if len(values) < self.window:
152
+ raise DataValidationError(
153
+ f"Drift(window={self.window}) needs at least "
154
+ f"{self.window} observations, got {len(values)}"
155
+ )
156
+ values = values[-self.window :]
157
+ if len(values) < _MIN_SLOPE_POINTS:
158
+ raise DataValidationError(
159
+ f"Drift needs at least {_MIN_SLOPE_POINTS} observations to estimate "
160
+ f"a slope, got {len(values)}"
161
+ )
162
+ self._last_value = float(values[-1])
163
+ self._slope = float((values[-1] - values[0]) / (len(values) - 1))
164
+
165
+ def _predict(self) -> np.ndarray:
166
+ """Add ``slope * k`` to the last value for each step ``k``."""
167
+ steps = np.arange(1, self.horizon + 1, dtype="float64")
168
+ return self._last_value + self._slope * steps
169
+
170
+ def __repr__(self) -> str:
171
+ """Return a representation including the optional window."""
172
+ return f"{type(self).__name__}(window={self.window}, horizon={self.horizon})"
@@ -0,0 +1,282 @@
1
+ """Optional gradient-boosting forecaster.
2
+
3
+ A tree ensemble cannot extrapolate a price level — it can only return values it
4
+ has already seen. Forecasting raw closes with one is therefore a category
5
+ error, which is why this model consumes :class:`~forecastforge.features.frame.FeatureSet`
6
+ columns instead of the target itself: returns, volatility, oscillators, and
7
+ calendar terms are stationary enough for a tree to say something useful about
8
+ them.
9
+
10
+ The model is *direct*: one booster per horizon step, each trained on
11
+ ``(features_t, y_{t+h} - y_t)`` pairs. The target is the **change**, not the
12
+ level. A tree can only return values inside the range it was trained on, so
13
+ regressing on the price level produces a forecast that is permanently pinned
14
+ to the middle of the historical range and drifts further from reality as the
15
+ series trends — measured on a synthetic path it was off by 15% after one
16
+ horizon. Regressing on the change removes that bias by construction: a booster
17
+ that learns nothing predicts zero change, which is exactly the naive forecast.
18
+
19
+ That construction is also where look-ahead bugs live, so the pairing loop stops
20
+ at ``t + h <= len(history) - 1`` — a row whose target would fall outside the
21
+ visible history is never used. The walk-forward backtester hands this model a
22
+ history that ends at the fold cutoff, so the cutoff is respected transitively.
23
+
24
+ LightGBM is driven through its native :func:`lightgbm.train` API rather than
25
+ the scikit-learn wrapper: the wrapper drags in scikit-learn for an estimator
26
+ protocol this class does not implement, and the native parameters are the ones
27
+ LightGBM's own documentation describes.
28
+
29
+ The module imports without LightGBM installed; the error naming the extra is
30
+ raised when the model is constructed.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import warnings
36
+ from typing import Any, ClassVar, 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.models.base import Forecaster
44
+
45
+ __all__ = ["LightGBMForecaster", "lightgbm_available"]
46
+
47
+ _LIGHTGBM = optional_import("lightgbm")
48
+
49
+ # A direct multi-horizon model fits one booster per step, so it needs enough
50
+ # (features_t, y_{t+h}) pairs for a split to mean anything.
51
+ _MIN_TRAINING_PAIRS = 10
52
+ _INSTALL_HINT = "Install it with: pip install -e '.[models]'"
53
+
54
+
55
+ def lightgbm_available() -> bool:
56
+ """Return whether :class:`LightGBMForecaster` can be constructed.
57
+
58
+ Callers that build a list of candidate models use this to skip the ones
59
+ that would raise, instead of catching the construction error.
60
+ """
61
+ return _LIGHTGBM is not None
62
+
63
+
64
+ def _require_lightgbm() -> Any:
65
+ """Return the lightgbm module, or raise naming the extra to install.
66
+
67
+ Returns:
68
+ The module, typed as ``Any`` because lightgbm ships no type stubs.
69
+
70
+ Raises:
71
+ DataValidationError: If lightgbm is not installed.
72
+ """
73
+ if _LIGHTGBM is None:
74
+ raise DataValidationError(
75
+ f"LightGBMForecaster requires the optional 'lightgbm' dependency. {_INSTALL_HINT}"
76
+ )
77
+ return cast("Any", _LIGHTGBM)
78
+
79
+
80
+ class LightGBMForecaster(Forecaster):
81
+ """Direct multi-horizon gradient boosting over precomputed features.
82
+
83
+ Args:
84
+ horizon: Number of future periods to predict. One booster is fitted
85
+ per step.
86
+ num_boost_round: Boosting rounds per step.
87
+ learning_rate: Shrinkage applied to each round.
88
+ num_leaves: Maximum leaves per tree.
89
+ min_data_in_leaf: Minimum rows a leaf may hold. Keeping this well
90
+ above one is what stops the ensemble from memorising a fold.
91
+ random_state: Seed, so a run is reproducible.
92
+ extra_params: Additional LightGBM parameters forwarded verbatim to
93
+ :func:`lightgbm.train`. Use this to tune without subclassing.
94
+
95
+ Raises:
96
+ DataValidationError: If lightgbm is not installed, ``horizon`` is not
97
+ positive, or a hyperparameter is out of range.
98
+
99
+ Note:
100
+ :attr:`requires_features` is true: pass the output of a
101
+ :class:`~forecastforge.features.pipeline.FeaturePipeline` (its
102
+ :attr:`~forecastforge.features.frame.FeatureSet.matrix`) as ``features``.
103
+ Warm-up rows may contain NaN; they are dropped while building the
104
+ training pairs, because a row with a missing feature cannot teach the
105
+ model anything. The final row of the history must be complete, since
106
+ it is the row the forecast is made from.
107
+ """
108
+
109
+ name = "lightgbm"
110
+ requires_features: ClassVar[bool] = True
111
+
112
+ def __init__(
113
+ self,
114
+ *,
115
+ horizon: int = 1,
116
+ num_boost_round: int = 200,
117
+ learning_rate: float = 0.05,
118
+ num_leaves: int = 15,
119
+ min_data_in_leaf: int = 20,
120
+ random_state: int = 0,
121
+ extra_params: dict[str, object] | None = None,
122
+ ) -> None:
123
+ super().__init__(horizon=horizon)
124
+ _require_lightgbm()
125
+ if num_boost_round <= 0:
126
+ raise DataValidationError(f"num_boost_round must be positive, got {num_boost_round}")
127
+ if learning_rate <= 0:
128
+ raise DataValidationError(f"learning_rate must be positive, got {learning_rate}")
129
+ if num_leaves <= 1:
130
+ raise DataValidationError(f"num_leaves must be at least 2, got {num_leaves}")
131
+ if min_data_in_leaf <= 0:
132
+ raise DataValidationError(
133
+ f"min_data_in_leaf must be positive, got {min_data_in_leaf}"
134
+ )
135
+ self.num_boost_round = num_boost_round
136
+ self.learning_rate = learning_rate
137
+ self.num_leaves = num_leaves
138
+ self.min_data_in_leaf = min_data_in_leaf
139
+ self.random_state = random_state
140
+ self.extra_params = dict(extra_params or {})
141
+ self._boosters: list[Any] = []
142
+ self._prediction_row: np.ndarray | None = None
143
+ self._last_value: float | None = None
144
+
145
+ # -- Forecaster hooks -------------------------------------------------
146
+
147
+ def _fit(self, series: pd.Series, features: pd.DataFrame | None) -> None:
148
+ """Fit one booster per horizon step.
149
+
150
+ Args:
151
+ series: The visible history, ending at the forecast origin.
152
+ features: Feature columns aligned to ``series.index``.
153
+
154
+ Raises:
155
+ DataValidationError: If the features are missing, non-numeric, or
156
+ leave too few complete rows to train on.
157
+ """
158
+ if features is None:
159
+ raise DataValidationError(
160
+ "LightGBMForecaster requires a feature frame, but features=None"
161
+ )
162
+ matrix = self._as_matrix(features)
163
+
164
+ values = series.to_numpy(dtype="float64")
165
+ n_rows = values.size
166
+ complete = ~np.isnan(matrix).any(axis=1)
167
+
168
+ # The row the forecast starts from has to be usable, otherwise there is
169
+ # nothing to hand the boosters at predict time.
170
+ if not bool(complete[-1]):
171
+ missing = [
172
+ str(name)
173
+ for name, bad in zip(features.columns, np.isnan(matrix[-1]), strict=True)
174
+ if bad
175
+ ]
176
+ raise DataValidationError(
177
+ "the last history row has NaN features, so no forecast can be made "
178
+ f"from it; incomplete column(s): {', '.join(missing)}"
179
+ )
180
+ self._prediction_row = matrix[-1]
181
+ self._last_value = float(values[-1])
182
+
183
+ self._boosters = []
184
+ for step in range(1, self.horizon + 1):
185
+ # Legal pairs only: the target at t + step must be inside the
186
+ # visible history. This is the boundary the backtester relies on.
187
+ last_origin = n_rows - 1 - step
188
+ origins = np.arange(0, last_origin + 1)
189
+ origins = origins[complete[origins]]
190
+ if origins.size < _MIN_TRAINING_PAIRS:
191
+ raise DataValidationError(
192
+ f"step {step} has {origins.size} complete training pair(s), "
193
+ f"but at least {_MIN_TRAINING_PAIRS} are required; "
194
+ "supply a longer history or a shorter warm-up"
195
+ )
196
+ # The booster learns the change, never the level: see the module
197
+ # docstring for why a tree cannot be trusted with a price level.
198
+ change = values[origins + step] - values[origins]
199
+ self._boosters.append(self._train_one(matrix[origins], change))
200
+
201
+ def _predict(self) -> np.ndarray:
202
+ """Forecast each horizon step from the final history row."""
203
+ row = self._prediction_row
204
+ last = self._last_value
205
+ if row is None or last is None: # pragma: no cover - guarded by _fit
206
+ raise RuntimeError("LightGBMForecaster.predict() called before fit()")
207
+ batch = row.reshape(1, -1)
208
+ changes = np.array(
209
+ [float(booster.predict(batch)[0]) for booster in self._boosters],
210
+ dtype="float64",
211
+ )
212
+ return last + changes
213
+
214
+ # -- internals --------------------------------------------------------
215
+
216
+ def _as_matrix(self, features: pd.DataFrame) -> np.ndarray:
217
+ """Return the feature frame as a float matrix.
218
+
219
+ Args:
220
+ features: Candidate feature columns.
221
+
222
+ Returns:
223
+ A ``(n_rows, n_columns)`` float array.
224
+
225
+ Raises:
226
+ DataValidationError: If there are no columns or one is not numeric.
227
+ """
228
+ if features.shape[1] == 0:
229
+ raise DataValidationError("the feature frame has no columns to train on")
230
+ non_numeric = [
231
+ str(name)
232
+ for name in features.columns
233
+ if not pd.api.types.is_numeric_dtype(features[name])
234
+ ]
235
+ if non_numeric:
236
+ raise DataValidationError(
237
+ f"feature column(s) {', '.join(non_numeric)} must be numeric"
238
+ )
239
+ return features.to_numpy(dtype="float64")
240
+
241
+ def _train_one(self, matrix: np.ndarray, target: np.ndarray) -> Any:
242
+ """Fit a single booster on one horizon step.
243
+
244
+ Args:
245
+ matrix: Training features, already restricted to legal pairs.
246
+ target: The matching outcomes.
247
+
248
+ Returns:
249
+ A fitted LightGBM booster.
250
+ """
251
+ lightgbm = _require_lightgbm()
252
+ params: dict[str, object] = {
253
+ "objective": "regression",
254
+ "metric": "l2",
255
+ "learning_rate": self.learning_rate,
256
+ "num_leaves": self.num_leaves,
257
+ "min_data_in_leaf": self.min_data_in_leaf,
258
+ "seed": self.random_state,
259
+ # Bit-identical folds are the whole point of a reproducible
260
+ # benchmark, so determinism is pinned and threading is disabled:
261
+ # a fixed seed alone does not guarantee the same summation order.
262
+ "deterministic": True,
263
+ "num_threads": 1,
264
+ "force_col_wise": True,
265
+ "verbose": -1,
266
+ }
267
+ params.update(self.extra_params)
268
+ dataset = lightgbm.Dataset(matrix, label=target, free_raw_data=True)
269
+ with warnings.catch_warnings():
270
+ # LightGBM reports "no further splits" for small folds through the
271
+ # warnings machinery, and the suite turns warnings into errors. A
272
+ # poor fit still shows up in the metrics.
273
+ warnings.simplefilter("ignore")
274
+ return lightgbm.train(params, dataset, num_boost_round=self.num_boost_round)
275
+
276
+ def __repr__(self) -> str:
277
+ """Return a representation including the boosting configuration."""
278
+ return (
279
+ f"{type(self).__name__}(horizon={self.horizon}, "
280
+ f"num_boost_round={self.num_boost_round}, "
281
+ f"learning_rate={self.learning_rate}, num_leaves={self.num_leaves})"
282
+ )
@@ -0,0 +1,213 @@
1
+ """Optional statistical forecasters backed by statsmodels.
2
+
3
+ ETS (exponential smoothing) and ARIMA are the two classical models a
4
+ practitioner reaches for before a learned one, so ForecastForge ships them
5
+ behind the ``models`` extra rather than in the core install.
6
+
7
+ The module is importable without statsmodels: the dependency is resolved
8
+ through :func:`~forecastforge.config._optional.optional_import`, and the
9
+ error naming the extra is raised when a model is constructed, not at import
10
+ time. That keeps ``import forecastforge.models`` cheap and lets the core
11
+ package install with no scientific stack beyond NumPy and pandas.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import warnings
17
+ from types import ModuleType
18
+ from typing import Any, cast
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ from forecastforge.config._optional import optional_import
24
+ from forecastforge.core.errors import DataValidationError
25
+ from forecastforge.models.base import Forecaster
26
+
27
+ __all__ = ["ARIMAForecaster", "ETSForecaster", "statsmodels_available"]
28
+
29
+ _HOLTWINTERS = optional_import("statsmodels.tsa.holtwinters")
30
+ _ARIMA = optional_import("statsmodels.tsa.arima.model")
31
+
32
+ _MIN_ORDER_TERMS = 3
33
+ _SEASONAL_ORDER_TERMS = 4
34
+ _INSTALL_HINT = "Install it with: pip install -e '.[models]'"
35
+
36
+
37
+ def statsmodels_available() -> bool:
38
+ """Return whether the models in this module can be constructed.
39
+
40
+ Callers that build a list of candidate models use this to skip the ones
41
+ that would raise, instead of catching the construction error.
42
+ """
43
+ return _HOLTWINTERS is not None and _ARIMA is not None
44
+
45
+
46
+ def _require(module: ModuleType | None, *, model: str, dependency: str) -> Any:
47
+ """Return an optional module, or raise naming the extra to install.
48
+
49
+ Args:
50
+ module: The result of :func:`optional_import`.
51
+ model: Model name, used in the error message.
52
+ dependency: The missing distribution, used in the error message.
53
+
54
+ Returns:
55
+ The module, typed as ``Any`` because its contents are untyped here.
56
+
57
+ Raises:
58
+ DataValidationError: If ``module`` is ``None``.
59
+ """
60
+ if module is None:
61
+ raise DataValidationError(
62
+ f"{model} requires the optional {dependency!r} dependency. {_INSTALL_HINT}"
63
+ )
64
+ return cast("Any", module)
65
+
66
+
67
+ def _validate_order(order: tuple[int, ...], *, terms: int, name: str) -> None:
68
+ """Reject an order tuple that is not ``terms`` non-negative integers.
69
+
70
+ Args:
71
+ order: The candidate order tuple.
72
+ terms: Required length of the tuple.
73
+ name: Parameter name, used in the error message.
74
+
75
+ Raises:
76
+ DataValidationError: If the length or a term is invalid.
77
+ """
78
+ if len(order) != terms:
79
+ raise DataValidationError(f"{name} must have {terms} terms, got {len(order)}")
80
+ if any(not isinstance(term, int) or term < 0 for term in order):
81
+ raise DataValidationError(f"{name} terms must be non-negative integers, got {order}")
82
+
83
+
84
+ class ETSForecaster(Forecaster):
85
+ """Exponential smoothing (ETS) via statsmodels' Holt-Winters.
86
+
87
+ Args:
88
+ trend: ``"add"``, ``"mul"``, or ``None`` for no trend component.
89
+ seasonal: ``"add"``, ``"mul"``, or ``None`` for no seasonal component.
90
+ seasonal_periods: Length of the seasonal cycle. Must be set together
91
+ with ``seasonal``.
92
+ horizon: Number of future periods to predict.
93
+
94
+ Raises:
95
+ DataValidationError: If statsmodels is not installed, ``seasonal`` and
96
+ ``seasonal_periods`` are not both set or both unset, or
97
+ ``horizon`` is not positive.
98
+
99
+ Note:
100
+ statsmodels emits convergence warnings for some series. They are
101
+ silenced during the fit because a point-forecast baseline should not
102
+ fail a test suite on an optimizer message; a genuinely bad fit still
103
+ shows up in the metrics.
104
+ """
105
+
106
+ name = "ets"
107
+
108
+ def __init__(
109
+ self,
110
+ *,
111
+ trend: str | None = "add",
112
+ seasonal: str | None = None,
113
+ seasonal_periods: int | None = None,
114
+ horizon: int = 1,
115
+ ) -> None:
116
+ super().__init__(horizon=horizon)
117
+ _require(_HOLTWINTERS, model=type(self).__name__, dependency="statsmodels")
118
+ if (seasonal is None) != (seasonal_periods is None):
119
+ raise DataValidationError(
120
+ "seasonal and seasonal_periods must be set together; "
121
+ f"got seasonal={seasonal!r}, seasonal_periods={seasonal_periods!r}"
122
+ )
123
+ if seasonal_periods is not None and seasonal_periods <= 0:
124
+ raise DataValidationError(f"seasonal_periods must be positive, got {seasonal_periods}")
125
+ self.trend = trend
126
+ self.seasonal = seasonal
127
+ self.seasonal_periods = seasonal_periods
128
+ self._result: Any = None
129
+
130
+ def _fit(self, series: pd.Series, features: pd.DataFrame | None) -> None:
131
+ """Fit the Holt-Winters model."""
132
+ holtwinters = _require(
133
+ _HOLTWINTERS, model=type(self).__name__, dependency="statsmodels"
134
+ )
135
+ model = holtwinters.ExponentialSmoothing(
136
+ series.to_numpy(dtype="float64"),
137
+ trend=self.trend,
138
+ seasonal=self.seasonal,
139
+ seasonal_periods=self.seasonal_periods,
140
+ initialization_method="estimated",
141
+ )
142
+ with warnings.catch_warnings():
143
+ warnings.simplefilter("ignore")
144
+ self._result = model.fit()
145
+
146
+ def _predict(self) -> np.ndarray:
147
+ """Forecast ``horizon`` steps ahead."""
148
+ return np.asarray(self._result.forecast(steps=self.horizon), dtype="float64")
149
+
150
+ def __repr__(self) -> str:
151
+ """Return a representation including the model structure."""
152
+ return (
153
+ f"{type(self).__name__}(trend={self.trend!r}, seasonal={self.seasonal!r}, "
154
+ f"seasonal_periods={self.seasonal_periods}, horizon={self.horizon})"
155
+ )
156
+
157
+
158
+ class ARIMAForecaster(Forecaster):
159
+ """ARIMA, with optional seasonal terms, via statsmodels.
160
+
161
+ Args:
162
+ order: ``(p, d, q)`` — autoregressive, differencing, and
163
+ moving-average orders.
164
+ seasonal_order: ``(P, D, Q, s)`` — seasonal orders and the seasonal
165
+ period. All zeros disables the seasonal component.
166
+ horizon: Number of future periods to predict.
167
+
168
+ Raises:
169
+ DataValidationError: If statsmodels is not installed, an order is not
170
+ a non-negative integer, or ``horizon`` is not positive.
171
+ """
172
+
173
+ name = "arima"
174
+
175
+ def __init__(
176
+ self,
177
+ *,
178
+ order: tuple[int, int, int] = (1, 1, 1),
179
+ seasonal_order: tuple[int, int, int, int] = (0, 0, 0, 0),
180
+ horizon: int = 1,
181
+ ) -> None:
182
+ super().__init__(horizon=horizon)
183
+ _require(_ARIMA, model=type(self).__name__, dependency="statsmodels")
184
+ _validate_order(order, terms=_MIN_ORDER_TERMS, name="order")
185
+ _validate_order(seasonal_order, terms=_SEASONAL_ORDER_TERMS, name="seasonal_order")
186
+ self.order = order
187
+ self.seasonal_order = seasonal_order
188
+ self._result: Any = None
189
+
190
+ def _fit(self, series: pd.Series, features: pd.DataFrame | None) -> None:
191
+ """Fit the ARIMA model."""
192
+ arima = _require(_ARIMA, model=type(self).__name__, dependency="statsmodels")
193
+ model = arima.ARIMA(
194
+ series.to_numpy(dtype="float64"),
195
+ order=self.order,
196
+ seasonal_order=self.seasonal_order,
197
+ enforce_stationarity=False,
198
+ enforce_invertibility=False,
199
+ )
200
+ with warnings.catch_warnings():
201
+ warnings.simplefilter("ignore")
202
+ self._result = model.fit()
203
+
204
+ def _predict(self) -> np.ndarray:
205
+ """Forecast ``horizon`` steps ahead."""
206
+ return np.asarray(self._result.forecast(steps=self.horizon), dtype="float64")
207
+
208
+ def __repr__(self) -> str:
209
+ """Return a representation including the model orders."""
210
+ return (
211
+ f"{type(self).__name__}(order={self.order}, "
212
+ f"seasonal_order={self.seasonal_order}, horizon={self.horizon})"
213
+ )
@@ -0,0 +1,6 @@
1
+ """Runtime and model monitoring.
2
+
3
+ This package will define observability hooks for data drift, model
4
+ performance, and system health once ForecastForge is deployed. No
5
+ monitoring logic is implemented yet.
6
+ """