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,25 @@
|
|
|
1
|
+
"""Pipeline orchestration.
|
|
2
|
+
|
|
3
|
+
The implemented pipeline composes the data and evaluation stages into one
|
|
4
|
+
reproducible call: :func:`forecastforge.pipelines.run` generates a validated
|
|
5
|
+
synthetic series from a seed and runs the walk-forward backtester over it
|
|
6
|
+
with a chosen set of baselines.
|
|
7
|
+
|
|
8
|
+
Typical usage::
|
|
9
|
+
|
|
10
|
+
from forecastforge.pipelines import PipelineConfig, run
|
|
11
|
+
|
|
12
|
+
result = run(PipelineConfig(seed=3, length=600, models=("naive", "drift")))
|
|
13
|
+
print(result.result.summary())
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from forecastforge.pipelines.synthetic_backtest import (
|
|
19
|
+
PipelineConfig,
|
|
20
|
+
PipelineResult,
|
|
21
|
+
build_models,
|
|
22
|
+
run,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = ["PipelineConfig", "PipelineResult", "build_models", "run"]
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""End-to-end orchestration: synthetic data in, backtest report out.
|
|
2
|
+
|
|
3
|
+
The first pipeline wires the three implemented stages together in one
|
|
4
|
+
reproducible call: generate a validated series from a seed, run the
|
|
5
|
+
walk-forward backtester over it with a chosen set of baselines, and return
|
|
6
|
+
both. Everything downstream of the seed is deterministic, so two runs with
|
|
7
|
+
the same configuration produce the same table.
|
|
8
|
+
|
|
9
|
+
This is deliberately narrow. Feature engineering and the optional
|
|
10
|
+
statistical models are not wired in yet; the pipeline exists so that the
|
|
11
|
+
CLI has a single command that exercises the full implemented path.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
20
|
+
|
|
21
|
+
from forecastforge.core.errors import DataValidationError
|
|
22
|
+
from forecastforge.data import SyntheticConfig, SyntheticSource
|
|
23
|
+
from forecastforge.evaluation import BacktestConfig, BacktestResult, WalkForwardBacktester
|
|
24
|
+
from forecastforge.models import Drift, Forecaster, MovingAverage, Naive, SeasonalNaive
|
|
25
|
+
from forecastforge.schemas import TimeSeries
|
|
26
|
+
|
|
27
|
+
__all__ = ["PipelineConfig", "PipelineResult", "build_models", "run"]
|
|
28
|
+
|
|
29
|
+
# Baseline names are handled by build_models below. The optional statsmodels
|
|
30
|
+
# and LightGBM forecasters stay out of the pipeline: they pull heavyweight
|
|
31
|
+
# dependencies into a path whose point is to run anywhere, and the benchmark
|
|
32
|
+
# module already covers them.
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class PipelineConfig(BaseModel):
|
|
36
|
+
"""A reproducible synthetic backtest, from seed to metrics table.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
symbol: Identifier recorded in the series metadata.
|
|
40
|
+
seed: Generator seed; the whole run is a function of this value.
|
|
41
|
+
length: Number of periods to generate.
|
|
42
|
+
horizon: Rows forecast from each fold origin.
|
|
43
|
+
initial_train: Rows available before the first forecast origin.
|
|
44
|
+
step: Rows between consecutive forecast origins.
|
|
45
|
+
gap: Embargoed rows between each training window and its origin.
|
|
46
|
+
window: Rolling training-window length; ``None`` means expanding.
|
|
47
|
+
seasonal_period: Season lag for the seasonal-naive model and the
|
|
48
|
+
MASE scale.
|
|
49
|
+
models: Baseline names to run; see ``build_models`` for the accepted
|
|
50
|
+
names.
|
|
51
|
+
moving_average_window: Trailing window for the moving-average model.
|
|
52
|
+
drift_window: Trailing window for the drift model.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
model_config = ConfigDict(frozen=True)
|
|
56
|
+
|
|
57
|
+
symbol: str = Field(default="SPY", min_length=1)
|
|
58
|
+
seed: int = Field(default=42, ge=0)
|
|
59
|
+
length: int = Field(default=504, gt=0)
|
|
60
|
+
horizon: int = Field(default=1, gt=0)
|
|
61
|
+
initial_train: int = Field(default=252, gt=0)
|
|
62
|
+
step: int = Field(default=1, gt=0)
|
|
63
|
+
gap: int = Field(default=0, ge=0)
|
|
64
|
+
window: int | None = Field(default=None, gt=0)
|
|
65
|
+
seasonal_period: int = Field(default=5, gt=0)
|
|
66
|
+
models: tuple[str, ...] = Field(default=("naive", "drift"), min_length=1)
|
|
67
|
+
moving_average_window: int = Field(default=20, gt=0)
|
|
68
|
+
drift_window: int = Field(default=60, gt=0)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True, slots=True)
|
|
72
|
+
class PipelineResult:
|
|
73
|
+
"""Everything produced by one pipeline run.
|
|
74
|
+
|
|
75
|
+
Attributes:
|
|
76
|
+
config: The configuration that produced the run.
|
|
77
|
+
series: The generated, validated series.
|
|
78
|
+
result: The walk-forward backtest outcome.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
config: PipelineConfig
|
|
82
|
+
series: TimeSeries
|
|
83
|
+
result: BacktestResult
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def build_models(
|
|
87
|
+
names: list[str] | tuple[str, ...],
|
|
88
|
+
horizon: int,
|
|
89
|
+
*,
|
|
90
|
+
seasonal_period: int = 5,
|
|
91
|
+
moving_average_window: int = 20,
|
|
92
|
+
drift_window: int = 60,
|
|
93
|
+
) -> dict[str, Forecaster]:
|
|
94
|
+
"""Construct the named baselines at a shared horizon.
|
|
95
|
+
|
|
96
|
+
Every model must be built with the horizon the backtester will use, so
|
|
97
|
+
construction is centralised here: the callers cannot accidentally pair a
|
|
98
|
+
``horizon=1`` model with a ``horizon=5`` backtest.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
names: Model names. Accepted: ``naive``, ``seasonal_naive``,
|
|
102
|
+
``moving_average``, ``drift``. Duplicates are dropped.
|
|
103
|
+
horizon: Forecast horizon each model is constructed with.
|
|
104
|
+
seasonal_period: Season length for ``seasonal_naive``.
|
|
105
|
+
moving_average_window: Trailing window for ``moving_average``.
|
|
106
|
+
drift_window: Trailing window for ``drift``.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
A mapping from model name to an unfitted forecaster, in request
|
|
110
|
+
order.
|
|
111
|
+
|
|
112
|
+
Raises:
|
|
113
|
+
DataValidationError: If a name is unknown.
|
|
114
|
+
"""
|
|
115
|
+
known: dict[str, Callable[[], Forecaster]] = {
|
|
116
|
+
"naive": lambda: Naive(horizon=horizon),
|
|
117
|
+
"seasonal_naive": lambda: SeasonalNaive(season=seasonal_period, horizon=horizon),
|
|
118
|
+
"moving_average": lambda: MovingAverage(window=moving_average_window, horizon=horizon),
|
|
119
|
+
"drift": lambda: Drift(window=drift_window, horizon=horizon),
|
|
120
|
+
}
|
|
121
|
+
models: dict[str, Forecaster] = {}
|
|
122
|
+
for name in dict.fromkeys(names):
|
|
123
|
+
factory = known.get(name)
|
|
124
|
+
if factory is None:
|
|
125
|
+
raise DataValidationError(
|
|
126
|
+
f"unknown model name {name!r}; available models: {', '.join(sorted(known))}"
|
|
127
|
+
)
|
|
128
|
+
models[name] = factory()
|
|
129
|
+
return models
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def run(config: PipelineConfig | None = None) -> PipelineResult:
|
|
133
|
+
"""Generate a series from the config's seed and backtest the models on it.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
config: The pipeline configuration; defaults to
|
|
137
|
+
:class:`PipelineConfig`'s own defaults.
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
A :class:`PipelineResult` bundling the config, the generated series,
|
|
141
|
+
and the backtest outcome.
|
|
142
|
+
|
|
143
|
+
Raises:
|
|
144
|
+
DataValidationError: If the backtester's configuration is invalid or
|
|
145
|
+
no fold fits in the generated series.
|
|
146
|
+
"""
|
|
147
|
+
config = config or PipelineConfig()
|
|
148
|
+
models = build_models(
|
|
149
|
+
config.models,
|
|
150
|
+
config.horizon,
|
|
151
|
+
seasonal_period=config.seasonal_period,
|
|
152
|
+
moving_average_window=config.moving_average_window,
|
|
153
|
+
drift_window=config.drift_window,
|
|
154
|
+
)
|
|
155
|
+
source = SyntheticSource(config=SyntheticConfig(seed=config.seed, length=config.length))
|
|
156
|
+
series = source.fetch(symbol=config.symbol)
|
|
157
|
+
backtester = WalkForwardBacktester(
|
|
158
|
+
BacktestConfig(
|
|
159
|
+
horizon=config.horizon,
|
|
160
|
+
initial_train=config.initial_train,
|
|
161
|
+
step=config.step,
|
|
162
|
+
gap=config.gap,
|
|
163
|
+
window=config.window,
|
|
164
|
+
seasonal_period=config.seasonal_period,
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
result = backtester.run(series.target_series, models)
|
|
168
|
+
return PipelineResult(config=config, series=series, result=result)
|
forecastforge/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Data and configuration schemas.
|
|
2
|
+
|
|
3
|
+
Currently provides the validated time-series container
|
|
4
|
+
(:class:`~forecastforge.schemas.time_series.TimeSeries`) and the structural
|
|
5
|
+
validation it enforces (:mod:`forecastforge.schemas.validation`).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from forecastforge.schemas.time_series import TimeSeries, TimeSeriesMetadata
|
|
11
|
+
from forecastforge.schemas.validation import Gap, find_gaps, validate_frame
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"Gap",
|
|
15
|
+
"TimeSeries",
|
|
16
|
+
"TimeSeriesMetadata",
|
|
17
|
+
"find_gaps",
|
|
18
|
+
"validate_frame",
|
|
19
|
+
]
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""The validated time-series container.
|
|
2
|
+
|
|
3
|
+
:class:`TimeSeries` pairs a pandas DataFrame with the metadata needed to
|
|
4
|
+
interpret it, and validates the frame on construction so that every
|
|
5
|
+
downstream stage can assume a clean, sorted, NaN-free dataset.
|
|
6
|
+
|
|
7
|
+
Immutability is shallow by design: the dataclass cannot be rebound, and the
|
|
8
|
+
frame is copied on construction so later mutation of the caller's frame
|
|
9
|
+
cannot corrupt the container. The returned ``frame`` should still be treated
|
|
10
|
+
as read-only; callers that need to derive new columns should copy it first.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any, cast
|
|
17
|
+
|
|
18
|
+
import pandas as pd
|
|
19
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
20
|
+
|
|
21
|
+
from forecastforge.schemas.validation import validate_frame
|
|
22
|
+
|
|
23
|
+
__all__ = ["TimeSeries", "TimeSeriesMetadata"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class TimeSeriesMetadata(BaseModel):
|
|
27
|
+
"""Validated provenance and interpretation details for a :class:`TimeSeries`."""
|
|
28
|
+
|
|
29
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
30
|
+
|
|
31
|
+
symbol: str = Field(
|
|
32
|
+
min_length=1,
|
|
33
|
+
description="Instrument or dataset identifier, e.g. 'SPY'.",
|
|
34
|
+
)
|
|
35
|
+
source: str = Field(
|
|
36
|
+
default="unknown",
|
|
37
|
+
min_length=1,
|
|
38
|
+
description="Name of the component that produced the data, e.g. 'synthetic'.",
|
|
39
|
+
)
|
|
40
|
+
frequency: str | None = Field(
|
|
41
|
+
default=None,
|
|
42
|
+
description=(
|
|
43
|
+
"Expected spacing as a pandas offset alias ('B' for business days, "
|
|
44
|
+
"'D' for calendar days). Used to detect gaps; None means unknown."
|
|
45
|
+
),
|
|
46
|
+
)
|
|
47
|
+
attributes: dict[str, Any] = Field(
|
|
48
|
+
default_factory=dict,
|
|
49
|
+
description="Free-form provenance details, e.g. the generator seed.",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, slots=True, eq=False)
|
|
54
|
+
class TimeSeries:
|
|
55
|
+
"""An immutable, validated univariate time series with optional covariates.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
frame: The dataset. Must have a sorted, unique
|
|
59
|
+
:class:`~pandas.DatetimeIndex`; ``target`` and every name in
|
|
60
|
+
``covariates`` must be present, numeric, finite, and non-null.
|
|
61
|
+
target: Column to forecast.
|
|
62
|
+
metadata: Provenance details; see :class:`TimeSeriesMetadata`.
|
|
63
|
+
covariates: Additional numeric columns used as exogenous inputs.
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
DataValidationError: If ``frame`` violates the contract.
|
|
67
|
+
|
|
68
|
+
Note:
|
|
69
|
+
Equality is identity-based (``eq=False``). Comparing two DataFrames
|
|
70
|
+
with ``==`` is element-wise and returns a frame, which makes value
|
|
71
|
+
equality ambiguous and easy to misuse; compare ``frame.equals(...)``
|
|
72
|
+
explicitly when that is what you mean.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
frame: pd.DataFrame
|
|
76
|
+
target: str
|
|
77
|
+
metadata: TimeSeriesMetadata
|
|
78
|
+
covariates: tuple[str, ...] = field(default=())
|
|
79
|
+
|
|
80
|
+
def __post_init__(self) -> None:
|
|
81
|
+
validate_frame(
|
|
82
|
+
self.frame,
|
|
83
|
+
target=self.target,
|
|
84
|
+
covariates=self.covariates,
|
|
85
|
+
frequency=self.metadata.frequency,
|
|
86
|
+
)
|
|
87
|
+
object.__setattr__(self, "frame", self.frame.copy())
|
|
88
|
+
|
|
89
|
+
def __len__(self) -> int:
|
|
90
|
+
"""Return the number of observations."""
|
|
91
|
+
return len(self.frame)
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def index(self) -> pd.DatetimeIndex:
|
|
95
|
+
"""The validated time index, guaranteed to be sorted and unique."""
|
|
96
|
+
return cast("pd.DatetimeIndex", self.frame.index)
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def target_series(self) -> pd.Series:
|
|
100
|
+
"""The target column as a series."""
|
|
101
|
+
return self.frame[self.target]
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Structural validation for the ForecastForge time-series contract.
|
|
2
|
+
|
|
3
|
+
A time series is a :class:`pandas.DataFrame` whose index is a sorted, unique
|
|
4
|
+
:class:`~pandas.DatetimeIndex` and which contains at least one numeric target
|
|
5
|
+
column, plus any declared numeric covariates. Everything downstream — feature
|
|
6
|
+
engineering, backtesting, serving — relies on that contract, so it is checked
|
|
7
|
+
once at the boundary and never re-derived.
|
|
8
|
+
|
|
9
|
+
Validation is deliberately strict: silent gaps, duplicate timestamps, and
|
|
10
|
+
NaNs propagate into features and metrics as quietly wrong numbers, which is
|
|
11
|
+
far more expensive to debug than an explicit rejection here.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
from forecastforge.core.errors import DataValidationError
|
|
23
|
+
|
|
24
|
+
__all__ = ["Gap", "find_gaps", "validate_frame"]
|
|
25
|
+
|
|
26
|
+
_MAX_EXAMPLES = 3
|
|
27
|
+
_MAX_LISTED_COLUMNS = 6
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class Gap:
|
|
32
|
+
"""A contiguous run of periods that the index is missing.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
start: First expected-but-absent timestamp in the run.
|
|
36
|
+
end: Last expected-but-absent timestamp in the run.
|
|
37
|
+
missing: Number of absent periods in the run.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
start: pd.Timestamp
|
|
41
|
+
end: pd.Timestamp
|
|
42
|
+
missing: int
|
|
43
|
+
|
|
44
|
+
def __str__(self) -> str:
|
|
45
|
+
return f"{self.start.date()}..{self.end.date()} ({self.missing} missing)"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def validate_frame(
|
|
49
|
+
frame: pd.DataFrame,
|
|
50
|
+
*,
|
|
51
|
+
target: str,
|
|
52
|
+
covariates: Sequence[str] = (),
|
|
53
|
+
frequency: str | None = None,
|
|
54
|
+
require_complete: bool = False,
|
|
55
|
+
) -> None:
|
|
56
|
+
"""Check that ``frame`` satisfies the time-series contract.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
frame: The candidate dataset. Its index must be a
|
|
60
|
+
:class:`~pandas.DatetimeIndex` that is sorted and free of
|
|
61
|
+
duplicates.
|
|
62
|
+
target: Name of the numeric column holding the value to forecast.
|
|
63
|
+
covariates: Names of additional numeric columns that will be used as
|
|
64
|
+
exogenous inputs.
|
|
65
|
+
frequency: pandas offset alias (``"B"``, ``"D"``, ...) used only to
|
|
66
|
+
detect gaps. Required when ``require_complete`` is true.
|
|
67
|
+
require_complete: When true, a series with missing periods is
|
|
68
|
+
rejected. Off by default because real market data legitimately
|
|
69
|
+
skips weekends, holidays, and trading halts.
|
|
70
|
+
|
|
71
|
+
Raises:
|
|
72
|
+
DataValidationError: If any part of the contract is violated. The
|
|
73
|
+
message names the offending column or timestamp.
|
|
74
|
+
"""
|
|
75
|
+
if not isinstance(frame, pd.DataFrame):
|
|
76
|
+
raise DataValidationError(f"expected a pandas DataFrame, got {type(frame).__name__}")
|
|
77
|
+
|
|
78
|
+
if frame.empty:
|
|
79
|
+
raise DataValidationError("time series is empty: at least one row is required")
|
|
80
|
+
|
|
81
|
+
index = _validate_index(frame.index)
|
|
82
|
+
_validate_columns(frame, target=target, covariates=covariates)
|
|
83
|
+
_validate_values(frame, [target, *covariates])
|
|
84
|
+
|
|
85
|
+
if require_complete:
|
|
86
|
+
if frequency is None:
|
|
87
|
+
raise DataValidationError(
|
|
88
|
+
"require_complete=True needs a frequency to know which periods are expected, "
|
|
89
|
+
"e.g. frequency='B' for business days"
|
|
90
|
+
)
|
|
91
|
+
gaps = find_gaps(index, frequency)
|
|
92
|
+
if gaps:
|
|
93
|
+
listed = ", ".join(str(gap) for gap in gaps[:_MAX_EXAMPLES])
|
|
94
|
+
more = "" if len(gaps) <= _MAX_EXAMPLES else f" (+{len(gaps) - _MAX_EXAMPLES} more)"
|
|
95
|
+
raise DataValidationError(
|
|
96
|
+
f"time series is incomplete at frequency {frequency!r}: "
|
|
97
|
+
f"{len(gaps)} gap(s) found — {listed}{more}"
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def find_gaps(index: pd.DatetimeIndex, frequency: str) -> tuple[Gap, ...]:
|
|
102
|
+
"""Return the contiguous runs of periods missing from ``index``.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
index: A sorted, unique :class:`~pandas.DatetimeIndex`.
|
|
106
|
+
frequency: pandas offset alias describing the expected spacing,
|
|
107
|
+
e.g. ``"B"`` for business days.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
One :class:`Gap` per contiguous run of missing periods, in
|
|
111
|
+
chronological order. Empty when the index is complete.
|
|
112
|
+
|
|
113
|
+
Raises:
|
|
114
|
+
DataValidationError: If ``frequency`` is not a valid pandas offset
|
|
115
|
+
alias.
|
|
116
|
+
"""
|
|
117
|
+
if len(index) <= 1:
|
|
118
|
+
return ()
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
expected = pd.date_range(start=index.min(), end=index.max(), freq=frequency)
|
|
122
|
+
except (ValueError, TypeError) as exc:
|
|
123
|
+
raise DataValidationError(
|
|
124
|
+
f"frequency {frequency!r} is not a valid pandas offset alias "
|
|
125
|
+
"(use e.g. 'B' for business days or 'D' for calendar days)"
|
|
126
|
+
) from exc
|
|
127
|
+
|
|
128
|
+
present = set(index)
|
|
129
|
+
gaps: list[Gap] = []
|
|
130
|
+
run: list[pd.Timestamp] = []
|
|
131
|
+
|
|
132
|
+
for timestamp in expected:
|
|
133
|
+
if timestamp in present:
|
|
134
|
+
if run:
|
|
135
|
+
gaps.append(Gap(start=run[0], end=run[-1], missing=len(run)))
|
|
136
|
+
run = []
|
|
137
|
+
continue
|
|
138
|
+
run.append(timestamp)
|
|
139
|
+
|
|
140
|
+
if run:
|
|
141
|
+
gaps.append(Gap(start=run[0], end=run[-1], missing=len(run)))
|
|
142
|
+
|
|
143
|
+
return tuple(gaps)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _validate_index(index: pd.Index) -> pd.DatetimeIndex:
|
|
147
|
+
"""Check the index is a clean, sorted DatetimeIndex and return it narrowed."""
|
|
148
|
+
if not isinstance(index, pd.DatetimeIndex):
|
|
149
|
+
raise DataValidationError(
|
|
150
|
+
f"index must be a pandas DatetimeIndex, got {type(index).__name__}"
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
if index.hasnans:
|
|
154
|
+
raise DataValidationError("index contains NaT values; every row must have a real timestamp")
|
|
155
|
+
|
|
156
|
+
duplicated = index[index.duplicated()]
|
|
157
|
+
if len(duplicated) > 0:
|
|
158
|
+
examples = ", ".join(str(ts) for ts in duplicated[:_MAX_EXAMPLES])
|
|
159
|
+
raise DataValidationError(
|
|
160
|
+
f"index contains {len(duplicated)} duplicate timestamp(s), e.g. {examples}; "
|
|
161
|
+
"each timestamp may appear only once"
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
if not index.is_monotonic_increasing:
|
|
165
|
+
for position in range(1, len(index)):
|
|
166
|
+
if index[position] <= index[position - 1]:
|
|
167
|
+
raise DataValidationError(
|
|
168
|
+
f"index is not sorted in increasing order: {index[position]} "
|
|
169
|
+
f"at position {position} follows {index[position - 1]}"
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
return index
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _validate_columns(frame: pd.DataFrame, *, target: str, covariates: Sequence[str]) -> None:
|
|
176
|
+
"""Check that every declared column exists."""
|
|
177
|
+
if target not in frame.columns:
|
|
178
|
+
raise DataValidationError(
|
|
179
|
+
f"target column {target!r} is missing; available columns: {_describe_columns(frame)}"
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
missing = [name for name in covariates if name not in frame.columns]
|
|
183
|
+
if missing:
|
|
184
|
+
raise DataValidationError(
|
|
185
|
+
f"covariate column(s) {missing} are missing; "
|
|
186
|
+
f"available columns: {_describe_columns(frame)}"
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _validate_values(frame: pd.DataFrame, columns: Sequence[str]) -> None:
|
|
191
|
+
"""Check every declared column is numeric, finite, and free of NaN."""
|
|
192
|
+
for column in columns:
|
|
193
|
+
series = frame[column]
|
|
194
|
+
|
|
195
|
+
if not pd.api.types.is_numeric_dtype(series):
|
|
196
|
+
raise DataValidationError(
|
|
197
|
+
f"column {column!r} must be numeric, got dtype {series.dtype}"
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
nulls = series.isna()
|
|
201
|
+
if nulls.any():
|
|
202
|
+
first = series.index[nulls][0]
|
|
203
|
+
raise DataValidationError(
|
|
204
|
+
f"column {column!r} contains {int(nulls.sum())} NaN value(s), "
|
|
205
|
+
f"first at {first}; drop or fill them before constructing a TimeSeries"
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
infinite = np.isinf(series.to_numpy(dtype="float64"))
|
|
209
|
+
if infinite.any():
|
|
210
|
+
first = series.index[infinite][0]
|
|
211
|
+
raise DataValidationError(
|
|
212
|
+
f"column {column!r} contains {int(infinite.sum())} infinite value(s), "
|
|
213
|
+
f"first at {first}"
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _describe_columns(frame: pd.DataFrame) -> str:
|
|
218
|
+
"""Render the available column names for an error message."""
|
|
219
|
+
names = [repr(str(name)) for name in frame.columns[:_MAX_LISTED_COLUMNS]]
|
|
220
|
+
if len(frame.columns) > _MAX_LISTED_COLUMNS:
|
|
221
|
+
names.append("...")
|
|
222
|
+
return ", ".join(names) if names else "(none)"
|