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,241 @@
1
+ """The working container for feature engineering.
2
+
3
+ :class:`~forecastforge.schemas.time_series.TimeSeries` deliberately rejects
4
+ NaN so that every downstream consumer can assume clean numbers. Feature
5
+ engineering cannot honour that contract: a 20-day rolling mean has no value
6
+ for the first 19 rows, and pretending otherwise (forward-filling, dropping
7
+ rows silently, or substituting zeros) is exactly how look-ahead bugs and
8
+ quietly wrong metrics get introduced.
9
+
10
+ :class:`FeatureSet` therefore sits *between* the validated time series and
11
+ the model. It keeps the strict index and target guarantees, allows NaN in
12
+ generated feature columns, and makes the warm-up region an explicit,
13
+ inspectable number rather than an accident.
14
+
15
+ Typical use::
16
+
17
+ features = FeaturePipeline([Lag(5), RollingStat(20)]).apply(series)
18
+ print(features.warmup) # rows that are not usable yet
19
+ model_input = features.drop_warmup()
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from dataclasses import dataclass
25
+ from typing import cast
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ from forecastforge.core.errors import DataValidationError
31
+ from forecastforge.schemas.time_series import TimeSeries, TimeSeriesMetadata
32
+ from forecastforge.schemas.validation import validate_frame
33
+
34
+ __all__ = ["FeatureSet"]
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class FeatureSet:
39
+ """A validated time series plus generated feature columns.
40
+
41
+ The index and the target column keep the full :class:`TimeSeries`
42
+ guarantees (sorted unique ``DatetimeIndex``, numeric finite non-null
43
+ target). Feature columns must exist and be numeric, but are *allowed* to
44
+ contain NaN in their warm-up region.
45
+
46
+ Args:
47
+ frame: Dataset whose index is the shared timeline. Contains the
48
+ target column and every column named in ``features``.
49
+ target: Column to forecast. Must be free of NaN and infinite values.
50
+ features: Generated columns, in creation order. May be empty when a
51
+ pipeline produced nothing.
52
+ metadata: Provenance details carried over from the source series.
53
+
54
+ Raises:
55
+ DataValidationError: If the index, target, or feature columns violate
56
+ the contract.
57
+ """
58
+
59
+ frame: pd.DataFrame
60
+ target: str
61
+ features: tuple[str, ...]
62
+ metadata: TimeSeriesMetadata
63
+
64
+ def __post_init__(self) -> None:
65
+ if not isinstance(self.frame, pd.DataFrame):
66
+ raise DataValidationError(
67
+ f"expected a pandas DataFrame, got {type(self.frame).__name__}"
68
+ )
69
+
70
+ duplicated = self.frame.columns[self.frame.columns.duplicated()]
71
+ if len(duplicated) > 0:
72
+ names = ", ".join(repr(str(name)) for name in duplicated)
73
+ raise DataValidationError(f"duplicate column name(s): {names}")
74
+
75
+ # Reuse the strict contract for the index and the target: it already
76
+ # rejects a non-DatetimeIndex, duplicates, unsorted rows, and a
77
+ # non-numeric or NaN-bearing target.
78
+ if self.target not in self.frame.columns:
79
+ available = ", ".join(repr(str(name)) for name in self.frame.columns[:6])
80
+ raise DataValidationError(
81
+ f"target column {self.target!r} is missing; available columns: {available}"
82
+ )
83
+ validate_frame(self.frame[[self.target]], target=self.target)
84
+
85
+ missing = [name for name in self.features if name not in self.frame.columns]
86
+ if missing:
87
+ available = ", ".join(repr(str(name)) for name in self.frame.columns[:6])
88
+ raise DataValidationError(
89
+ f"feature column(s) {missing} are missing; available columns: {available}"
90
+ )
91
+
92
+ for name in self.features:
93
+ if not pd.api.types.is_numeric_dtype(self.frame[name]):
94
+ raise DataValidationError(
95
+ f"feature column {name!r} must be numeric, got dtype {self.frame[name].dtype}"
96
+ )
97
+
98
+ object.__setattr__(self, "frame", self.frame.copy())
99
+
100
+ # -- constructors -----------------------------------------------------
101
+
102
+ @classmethod
103
+ def from_time_series(cls, series: TimeSeries) -> FeatureSet:
104
+ """Wrap a validated :class:`TimeSeries` with no features yet."""
105
+ return cls(
106
+ frame=series.frame,
107
+ target=series.target,
108
+ features=(),
109
+ metadata=series.metadata,
110
+ )
111
+
112
+ # -- properties -------------------------------------------------------
113
+
114
+ def __len__(self) -> int:
115
+ """Return the number of observations, including the warm-up rows."""
116
+ return len(self.frame)
117
+
118
+ @property
119
+ def index(self) -> pd.DatetimeIndex:
120
+ """The shared, validated timeline."""
121
+ return cast("pd.DatetimeIndex", self.frame.index)
122
+
123
+ @property
124
+ def target_series(self) -> pd.Series:
125
+ """The target column as a series."""
126
+ return self.frame[self.target]
127
+
128
+ @property
129
+ def matrix(self) -> pd.DataFrame:
130
+ """Only the feature columns, in creation order."""
131
+ return self.frame[list(self.features)]
132
+
133
+ @property
134
+ def warmup(self) -> int:
135
+ """Number of leading rows that still contain a NaN feature value.
136
+
137
+ This is the count a caller must drop before the rows are usable for
138
+ training. It is a prefix length: if a NaN appears *after* a complete
139
+ row, the data is inconsistent and :attr:`is_complete` will be false
140
+ even though ``warmup`` alone does not describe the problem.
141
+ """
142
+ if not self.features:
143
+ return 0
144
+ incomplete = self.matrix.isna().any(axis=1).to_numpy()
145
+ if not incomplete.any():
146
+ return 0
147
+ first_complete = int(np.argmin(incomplete))
148
+ if incomplete[first_complete]:
149
+ return len(incomplete)
150
+ return first_complete
151
+
152
+ @property
153
+ def is_complete(self) -> bool:
154
+ """True when no feature column contains a NaN anywhere."""
155
+ return not bool(self.matrix.isna().to_numpy().any())
156
+
157
+ @property
158
+ def n_incomplete_rows(self) -> int:
159
+ """Total rows with at least one NaN feature, warm-up included."""
160
+ if not self.features:
161
+ return 0
162
+ return int(self.matrix.isna().any(axis=1).to_numpy().sum())
163
+
164
+ # -- derivation -------------------------------------------------------
165
+
166
+ def extend(self, added: pd.DataFrame) -> FeatureSet:
167
+ """Return a new set with ``added`` columns appended.
168
+
169
+ Args:
170
+ added: Columns aligned to :attr:`index`. Must not collide with an
171
+ existing column name.
172
+
173
+ Returns:
174
+ A new :class:`FeatureSet` whose ``features`` include ``added``.
175
+
176
+ Raises:
177
+ DataValidationError: If the index differs or a name collides.
178
+ """
179
+ if not added.index.equals(self.frame.index):
180
+ raise DataValidationError(
181
+ "added columns must share the FeatureSet index; "
182
+ "transform output was not aligned to the input timeline"
183
+ )
184
+
185
+ collisions = [name for name in added.columns if name in self.frame.columns]
186
+ if collisions:
187
+ names = ", ".join(repr(str(name)) for name in collisions)
188
+ raise DataValidationError(
189
+ f"transform would overwrite existing column(s) {names}; "
190
+ "give the transform a distinct column name"
191
+ )
192
+
193
+ frame = pd.concat([self.frame, added], axis=1)
194
+ return FeatureSet(
195
+ frame=frame,
196
+ target=self.target,
197
+ features=(*self.features, *(str(name) for name in added.columns)),
198
+ metadata=self.metadata,
199
+ )
200
+
201
+ def drop_warmup(self) -> FeatureSet:
202
+ """Return a new set with the leading incomplete rows removed."""
203
+ warmup = self.warmup
204
+ if warmup == 0:
205
+ return self
206
+ return FeatureSet(
207
+ frame=self.frame.iloc[warmup:],
208
+ target=self.target,
209
+ features=self.features,
210
+ metadata=self.metadata,
211
+ )
212
+
213
+ def dropna(self) -> FeatureSet:
214
+ """Return a new set with every row containing a NaN feature removed.
215
+
216
+ Prefer :meth:`drop_warmup` when the NaNs are a prefix: it keeps the
217
+ timeline contiguous, which matters for backtesting windows.
218
+ """
219
+ if not self.features:
220
+ return self
221
+ keep = ~self.matrix.isna().any(axis=1).to_numpy()
222
+ return FeatureSet(
223
+ frame=self.frame.loc[keep],
224
+ target=self.target,
225
+ features=self.features,
226
+ metadata=self.metadata,
227
+ )
228
+
229
+ def to_time_series(self) -> TimeSeries:
230
+ """Convert back to a NaN-free :class:`TimeSeries`.
231
+
232
+ Raises:
233
+ DataValidationError: If any feature value is still NaN, since a
234
+ ``TimeSeries`` may not contain NaN.
235
+ """
236
+ return TimeSeries(
237
+ frame=self.frame,
238
+ target=self.target,
239
+ metadata=self.metadata,
240
+ covariates=self.features,
241
+ )
@@ -0,0 +1,84 @@
1
+ """Composable feature pipelines.
2
+
3
+ A :class:`FeaturePipeline` chains transforms so that later steps can consume
4
+ columns produced by earlier ones — the common case being "compute returns,
5
+ then take the rolling volatility of those returns".
6
+
7
+ Ordering matters and is the caller's responsibility: a pipeline is a list, not
8
+ a dependency graph. Keeping it explicit is deliberate — a pipeline that
9
+ silently reorders itself is much harder to review for leakage.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterator, Sequence
15
+
16
+ from forecastforge.features.frame import FeatureSet
17
+ from forecastforge.features.transform import Transform
18
+ from forecastforge.schemas.time_series import TimeSeries
19
+
20
+ __all__ = ["FeaturePipeline"]
21
+
22
+
23
+ class FeaturePipeline:
24
+ """An ordered sequence of transforms.
25
+
26
+ Args:
27
+ steps: Transforms to apply, first to last.
28
+
29
+ Example::
30
+
31
+ pipeline = FeaturePipeline(
32
+ [
33
+ Returns(periods=1, log=True),
34
+ RollingStat(window=20, stat="std", column="close_logret1"),
35
+ CalendarFeatures(["dayofweek", "month_cyclic"]),
36
+ ]
37
+ )
38
+ features = pipeline.apply(series)
39
+ """
40
+
41
+ def __init__(self, steps: Sequence[Transform]) -> None:
42
+ self.steps: tuple[Transform, ...] = tuple(steps)
43
+
44
+ def __len__(self) -> int:
45
+ """Return the number of steps."""
46
+ return len(self.steps)
47
+
48
+ def __iter__(self) -> Iterator[Transform]:
49
+ """Iterate over the steps in order."""
50
+ return iter(self.steps)
51
+
52
+ def __repr__(self) -> str:
53
+ """Return a representation listing every step."""
54
+ inner = ", ".join(repr(step) for step in self.steps)
55
+ return f"FeaturePipeline([{inner}])"
56
+
57
+ def apply(self, data: TimeSeries | FeatureSet) -> FeatureSet:
58
+ """Apply every step in order.
59
+
60
+ Args:
61
+ data: A validated series, or an existing set to extend. Passing a
62
+ :class:`FeatureSet` lets callers compose pipelines
63
+ incrementally.
64
+
65
+ Returns:
66
+ The enriched set. Feature columns may contain NaN in the warm-up
67
+ region; inspect :attr:`FeatureSet.warmup`.
68
+ """
69
+ features = data if isinstance(data, FeatureSet) else FeatureSet.from_time_series(data)
70
+ for step in self.steps:
71
+ features = step.apply(features)
72
+ return features
73
+
74
+ def feature_names(self, data: TimeSeries | FeatureSet) -> tuple[str, ...]:
75
+ """Return the column names :meth:`apply` would produce.
76
+
77
+ This runs the pipeline, because output names can depend on upstream
78
+ columns (for example a rolling statistic of a return column). It is a
79
+ convenience for introspection, not a cheap schema lookup.
80
+
81
+ Args:
82
+ data: A validated series, or an existing set to extend.
83
+ """
84
+ return self.apply(data).features
@@ -0,0 +1,104 @@
1
+ """The base contract for feature transforms.
2
+
3
+ A transform derives new columns from an existing
4
+ :class:`~forecastforge.features.frame.FeatureSet`. Two rules define the
5
+ framework:
6
+
7
+ **Causality.** The value of a feature at row *t* may depend only on rows
8
+ ``<= t``. This is what makes walk-forward backtesting honest, and it is the
9
+ single easiest thing to get wrong — a centred rolling window, a
10
+ ``shift(-1)``, or a z-score computed over the whole sample all look
11
+ reasonable and all leak the future. The framework cannot enforce causality
12
+ statically, so it is verified by tests: see ``tests/features/test_leakage.py``,
13
+ which truncates and perturbs the future for every built-in transform.
14
+
15
+ **Declared output.** :meth:`Transform.output_columns` must exactly match the
16
+ columns :meth:`Transform.compute` returns. :meth:`Transform.apply` checks
17
+ this on every call, so a mismatch surfaces at the point of the mistake rather
18
+ than as a confusing column error three stages downstream.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from abc import ABC, abstractmethod
24
+ from typing import ClassVar
25
+
26
+ import pandas as pd
27
+
28
+ from forecastforge.core.errors import DataValidationError
29
+ from forecastforge.features.frame import FeatureSet
30
+
31
+ __all__ = ["Transform"]
32
+
33
+
34
+ class Transform(ABC):
35
+ """Base class for a causal, stateless feature transform.
36
+
37
+ Subclasses set :attr:`name` for display purposes and implement
38
+ :meth:`output_columns` and :meth:`compute`. :meth:`apply` is provided and
39
+ should not normally be overridden.
40
+
41
+ Transforms must be **stateless**: the same input always produces the same
42
+ output, and a transform keeps no fitted parameters. Anything that needs
43
+ to learn from data (scalers, encoders) belongs to the model pipeline,
44
+ where the fit/transform split makes leakage auditable.
45
+ """
46
+
47
+ name: ClassVar[str] = "transform"
48
+
49
+ @abstractmethod
50
+ def output_columns(self, features: FeatureSet) -> tuple[str, ...]:
51
+ """Return the column names :meth:`compute` will produce, in order.
52
+
53
+ Args:
54
+ features: The input set. Output names may depend on its column
55
+ names (e.g. the target name) but never on its values.
56
+ """
57
+
58
+ @abstractmethod
59
+ def compute(self, features: FeatureSet) -> pd.DataFrame:
60
+ """Compute the new columns.
61
+
62
+ Args:
63
+ features: The input set. May be read freely, including columns
64
+ added by earlier transforms.
65
+
66
+ Returns:
67
+ A frame containing *only* the new columns, indexed like
68
+ ``features.frame``. NaN is allowed (warm-up).
69
+ """
70
+
71
+ def apply(self, features: FeatureSet) -> FeatureSet:
72
+ """Apply the transform and return the extended set.
73
+
74
+ Args:
75
+ features: The input set.
76
+
77
+ Returns:
78
+ A new set with this transform's columns appended.
79
+
80
+ Raises:
81
+ DataValidationError: If the produced columns do not match
82
+ :meth:`output_columns`, or if they would overwrite an existing
83
+ column.
84
+ """
85
+ added = self.compute(features)
86
+ expected = self.output_columns(features)
87
+ actual = tuple(str(column) for column in added.columns)
88
+ if actual != expected:
89
+ raise DataValidationError(
90
+ f"{type(self).__name__} declared columns {expected} but produced {actual}"
91
+ )
92
+ return features.extend(added)
93
+
94
+ def _describe(self) -> str:
95
+ """Return the parameter summary used by :meth:`__repr__`.
96
+
97
+ Subclasses override this so that a pipeline prints its configuration
98
+ rather than a list of bare class names.
99
+ """
100
+ return ""
101
+
102
+ def __repr__(self) -> str:
103
+ """Return a debug representation including the configuration."""
104
+ return f"{type(self).__name__}({self._describe()})"
@@ -0,0 +1,36 @@
1
+ """Forecasting models and their shared interface.
2
+
3
+ Every model implements :class:`~forecastforge.models.base.Forecaster`: fit on
4
+ a history, predict the next ``horizon`` values. The horizon is fixed at
5
+ construction because a direct multi-horizon model builds one estimator per
6
+ step and needs to know ``h`` while fitting.
7
+
8
+ Available without any optional dependency:
9
+
10
+ * :class:`~forecastforge.models.baselines.Naive`
11
+ * :class:`~forecastforge.models.baselines.SeasonalNaive`
12
+ * :class:`~forecastforge.models.baselines.MovingAverage`
13
+ * :class:`~forecastforge.models.baselines.Drift`
14
+
15
+ Optional, behind the ``models`` extra:
16
+
17
+ * :class:`~forecastforge.models.statistical.ETSForecaster` (statsmodels)
18
+ * :class:`~forecastforge.models.statistical.ARIMAForecaster` (statsmodels)
19
+ * :class:`~forecastforge.models.gbm.LightGBMForecaster` (lightgbm)
20
+
21
+ The optional models are importable without their dependency installed; the
22
+ error is raised when you construct one, and it names the extra to install.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from forecastforge.models.base import Forecaster
28
+ from forecastforge.models.baselines import Drift, MovingAverage, Naive, SeasonalNaive
29
+
30
+ __all__ = [
31
+ "Drift",
32
+ "Forecaster",
33
+ "MovingAverage",
34
+ "Naive",
35
+ "SeasonalNaive",
36
+ ]
@@ -0,0 +1,178 @@
1
+ """The forecaster interface.
2
+
3
+ Every model in ForecastForge — from the naive baseline to a gradient-boosted
4
+ one — is fitted on a history and asked for the next ``horizon`` values. The
5
+ horizon is fixed at construction rather than passed to :meth:`Forecaster.predict`
6
+ because a direct multi-horizon model has to build one estimator per step: it
7
+ needs to know ``h`` when it fits, not when it predicts.
8
+
9
+ The base class implements the parts that must not vary — input validation, the
10
+ fitted-before-predict guard, and the output-shape check — so a concrete model
11
+ only writes :meth:`_fit` and :meth:`_predict`. This mirrors
12
+ :class:`~forecastforge.features.transform.Transform`: the shared contract lives
13
+ in one place, so a subclass cannot quietly break it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import copy
19
+ from abc import ABC, abstractmethod
20
+ from typing import ClassVar, Self
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ from forecastforge.core.errors import DataValidationError
26
+
27
+ __all__ = ["Forecaster", "validate_history"]
28
+
29
+
30
+ class Forecaster(ABC):
31
+ """Base class for a fitted, horizon-fixed forecasting model.
32
+
33
+ Args:
34
+ horizon: Number of future periods to predict. Must be positive.
35
+
36
+ Attributes:
37
+ name: Short identifier used in reports and result frames.
38
+ requires_features: Whether :meth:`fit` needs an exogenous feature
39
+ frame. Models that read it raise if it is missing.
40
+ supports_intervals: Whether :meth:`predict_interval` is available.
41
+
42
+ Raises:
43
+ DataValidationError: If ``horizon`` is not positive.
44
+ """
45
+
46
+ name: ClassVar[str] = "forecaster"
47
+ requires_features: ClassVar[bool] = False
48
+ supports_intervals: ClassVar[bool] = False
49
+
50
+ def __init__(self, *, horizon: int = 1) -> None:
51
+ if horizon <= 0:
52
+ raise DataValidationError(f"horizon must be positive, got {horizon}")
53
+ self.horizon = horizon
54
+ self._fitted = False
55
+
56
+ # -- public API -------------------------------------------------------
57
+
58
+ def fit(self, series: pd.Series, features: pd.DataFrame | None = None) -> Self:
59
+ """Fit the model on ``series``.
60
+
61
+ Args:
62
+ series: The observable history, ending at the forecast origin.
63
+ Must be a non-empty, NaN-free ``Series`` with a sorted
64
+ ``DatetimeIndex``.
65
+ features: Exogenous columns aligned to ``series.index``. Required
66
+ when :attr:`requires_features` is true; ignored otherwise.
67
+
68
+ Returns:
69
+ ``self``, so calls can be chained.
70
+
71
+ Raises:
72
+ DataValidationError: If the history violates the contract.
73
+ """
74
+ validate_history(series, features, requires_features=type(self).requires_features)
75
+ self._fit(series, features)
76
+ self._fitted = True
77
+ return self
78
+
79
+ def predict(self) -> np.ndarray:
80
+ """Return the next :attr:`horizon` values.
81
+
82
+ Returns:
83
+ A float array of length :attr:`horizon`.
84
+
85
+ Raises:
86
+ RuntimeError: If called before :meth:`fit`.
87
+ DataValidationError: If the model returns the wrong number of
88
+ values.
89
+ """
90
+ if not self._fitted:
91
+ raise RuntimeError(f"{type(self).__name__}.predict() called before fit()")
92
+ values = np.asarray(self._predict(), dtype="float64").reshape(-1)
93
+ if values.shape[0] != self.horizon:
94
+ raise DataValidationError(
95
+ f"{type(self).__name__} produced {values.shape[0]} value(s) "
96
+ f"for horizon {self.horizon}"
97
+ )
98
+ return values
99
+
100
+ def predict_interval(self, level: float = 0.9) -> tuple[np.ndarray, np.ndarray]:
101
+ """Return lower and upper prediction bounds.
102
+
103
+ Only available when :attr:`supports_intervals` is true.
104
+
105
+ Args:
106
+ level: Central coverage probability, strictly between 0 and 1.
107
+
108
+ Raises:
109
+ NotImplementedError: When the model provides no intervals.
110
+ """
111
+ raise NotImplementedError(f"{type(self).__name__} does not provide prediction intervals")
112
+
113
+ def clone(self) -> Self:
114
+ """Return an unfitted copy carrying the same configuration.
115
+
116
+ The walk-forward backtester needs a fresh model per fold; cloning
117
+ keeps the caller from having to know how to rebuild each one.
118
+ """
119
+ duplicate = copy.deepcopy(self)
120
+ duplicate._fitted = False
121
+ return duplicate
122
+
123
+ def __repr__(self) -> str:
124
+ """Return a representation naming the class and horizon."""
125
+ return f"{type(self).__name__}(horizon={self.horizon})"
126
+
127
+ # -- subclass hooks ---------------------------------------------------
128
+
129
+ @abstractmethod
130
+ def _fit(self, series: pd.Series, features: pd.DataFrame | None) -> None:
131
+ """Learn from ``series``. Validated input; ``features`` may be None."""
132
+
133
+ @abstractmethod
134
+ def _predict(self) -> np.ndarray:
135
+ """Produce :attr:`horizon` values. Called only after :meth:`_fit`."""
136
+
137
+
138
+ def validate_history(
139
+ series: pd.Series,
140
+ features: pd.DataFrame | None,
141
+ *,
142
+ requires_features: bool,
143
+ ) -> None:
144
+ """Check the training history and its exogenous frame.
145
+
146
+ Args:
147
+ series: The candidate history.
148
+ features: Optional exogenous columns.
149
+ requires_features: Whether the model needs ``features``.
150
+
151
+ Raises:
152
+ DataValidationError: If any part of the contract is violated.
153
+ """
154
+ if not isinstance(series, pd.Series):
155
+ raise DataValidationError(f"expected a pandas Series, got {type(series).__name__}")
156
+ if series.empty:
157
+ raise DataValidationError("history is empty: at least one observation is required")
158
+ if not isinstance(series.index, pd.DatetimeIndex):
159
+ raise DataValidationError(
160
+ f"history index must be a pandas DatetimeIndex, got {type(series.index).__name__}"
161
+ )
162
+ if not series.index.is_monotonic_increasing:
163
+ raise DataValidationError("history index must be sorted in increasing order")
164
+ nulls = series.isna()
165
+ if nulls.any():
166
+ first = series.index[nulls][0]
167
+ raise DataValidationError(
168
+ f"history contains {int(nulls.sum())} NaN value(s), first at {first}; "
169
+ "fill or drop them before fitting"
170
+ )
171
+
172
+ if requires_features and features is None:
173
+ raise DataValidationError("this model requires a feature frame, but features=None")
174
+ if features is not None and not features.index.equals(series.index):
175
+ raise DataValidationError(
176
+ "feature frame must share the history index; "
177
+ "the exogenous rows are not aligned to the series"
178
+ )