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,42 @@
|
|
|
1
|
+
"""Exception hierarchy shared across ForecastForge.
|
|
2
|
+
|
|
3
|
+
Every error the package raises deliberately derives from
|
|
4
|
+
:class:`ForecastForgeError`, so callers can catch library failures without
|
|
5
|
+
also catching unrelated built-ins. Errors that describe invalid *input* also
|
|
6
|
+
inherit from the matching built-in (``ValueError``, ``ImportError``) so that
|
|
7
|
+
they behave as a reader would expect.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"DataError",
|
|
14
|
+
"DataValidationError",
|
|
15
|
+
"ForecastForgeError",
|
|
16
|
+
"MissingOptionalDependencyError",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ForecastForgeError(Exception):
|
|
21
|
+
"""Base class for every exception raised deliberately by ForecastForge."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class DataError(ForecastForgeError):
|
|
25
|
+
"""Raised when data cannot be loaded, parsed, or produced."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DataValidationError(DataError, ValueError):
|
|
29
|
+
"""Raised when a dataset violates the time-series contract.
|
|
30
|
+
|
|
31
|
+
Inherits from :class:`ValueError` so that ``except ValueError`` — the
|
|
32
|
+
conventional way to handle rejected input — keeps working.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class MissingOptionalDependencyError(ForecastForgeError, ImportError):
|
|
37
|
+
"""Raised when a feature needs an optional dependency that is not installed.
|
|
38
|
+
|
|
39
|
+
Inherits from :class:`ImportError` so that callers treating a missing
|
|
40
|
+
module conventionally still catch it. The message always names the extra
|
|
41
|
+
to install.
|
|
42
|
+
"""
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Data ingestion and access layer.
|
|
2
|
+
|
|
3
|
+
Connectors, loaders, and the shared source interface for reading raw and
|
|
4
|
+
external data into a validated
|
|
5
|
+
:class:`~forecastforge.schemas.time_series.TimeSeries`.
|
|
6
|
+
|
|
7
|
+
The :class:`~forecastforge.data.synthetic.SyntheticSource` is fully offline and
|
|
8
|
+
deterministic and is the project's default dataset; the
|
|
9
|
+
:class:`~forecastforge.data.yfinance_source.YFinanceSource` is an optional,
|
|
10
|
+
network-backed connector installed via the ``data`` extra.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from forecastforge.data.loaders import read_csv, read_parquet, write_csv, write_parquet
|
|
16
|
+
from forecastforge.data.source import BaseDataSource, DataSource
|
|
17
|
+
from forecastforge.data.synthetic import Regime, SyntheticConfig, SyntheticSource
|
|
18
|
+
from forecastforge.data.yfinance_source import YFinanceSource
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"BaseDataSource",
|
|
22
|
+
"DataSource",
|
|
23
|
+
"Regime",
|
|
24
|
+
"SyntheticConfig",
|
|
25
|
+
"SyntheticSource",
|
|
26
|
+
"YFinanceSource",
|
|
27
|
+
"read_csv",
|
|
28
|
+
"read_parquet",
|
|
29
|
+
"write_csv",
|
|
30
|
+
"write_parquet",
|
|
31
|
+
]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""File-based readers and writers for time-series frames.
|
|
2
|
+
|
|
3
|
+
These helpers round-trip a pandas DataFrame with a
|
|
4
|
+
:class:`~pandas.DatetimeIndex` to/from Parquet and CSV, preserving the index.
|
|
5
|
+
They are the persistence layer behind caching and the file-backed data source.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import warnings
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
from forecastforge.core.errors import DataError
|
|
16
|
+
|
|
17
|
+
__all__ = ["read_csv", "read_parquet", "write_csv", "write_parquet"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def read_parquet(path: str | Path) -> pd.DataFrame:
|
|
21
|
+
"""Read a Parquet file into a DataFrame, preserving the index."""
|
|
22
|
+
return _coerce_index(pd.read_parquet(path))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def write_parquet(frame: pd.DataFrame, path: str | Path) -> Path:
|
|
26
|
+
"""Write ``frame`` to ``path`` as Parquet, creating parent directories."""
|
|
27
|
+
target = Path(path)
|
|
28
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
29
|
+
frame.to_parquet(target)
|
|
30
|
+
return target
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def read_csv(path: str | Path) -> pd.DataFrame:
|
|
34
|
+
"""Read a CSV written by :func:`write_csv`, restoring the DatetimeIndex."""
|
|
35
|
+
return _coerce_index(pd.read_csv(path, index_col=0))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def write_csv(frame: pd.DataFrame, path: str | Path) -> Path:
|
|
39
|
+
"""Write ``frame`` to ``path`` as CSV, keeping the index as a column."""
|
|
40
|
+
target = Path(path)
|
|
41
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
frame.to_csv(target)
|
|
43
|
+
return target
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _coerce_index(frame: pd.DataFrame) -> pd.DataFrame:
|
|
47
|
+
"""Ensure the index is a :class:`~pandas.DatetimeIndex`."""
|
|
48
|
+
if isinstance(frame.index, pd.DatetimeIndex):
|
|
49
|
+
if frame.index.name is None:
|
|
50
|
+
frame.index.name = "date"
|
|
51
|
+
return frame
|
|
52
|
+
with warnings.catch_warnings():
|
|
53
|
+
# pandas warns (and, under strict warning filters, errors) when it cannot
|
|
54
|
+
# infer a format even though we are explicitly coercing failures to NaT.
|
|
55
|
+
warnings.simplefilter("ignore")
|
|
56
|
+
parsed = pd.to_datetime(frame.index, errors="coerce")
|
|
57
|
+
if parsed.isna().any():
|
|
58
|
+
unparseable = [str(value) for value in frame.index[parsed.isna()]]
|
|
59
|
+
raise DataError(f"file index could not be parsed as timestamps: {unparseable}")
|
|
60
|
+
frame.index = parsed
|
|
61
|
+
frame.index.name = frame.index.name or "date"
|
|
62
|
+
return frame
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Data-source interface and shared fetch logic.
|
|
2
|
+
|
|
3
|
+
A :class:`DataSource` produces a validated
|
|
4
|
+
:class:`~forecastforge.schemas.time_series.TimeSeries` for a given symbol. The
|
|
5
|
+
protocol lets downstream code accept *any* source — synthetic, file-backed, or a
|
|
6
|
+
live vendor — interchangeably.
|
|
7
|
+
|
|
8
|
+
:class:`BaseDataSource` implements the common contract (load → slice → validate →
|
|
9
|
+
wrap) so concrete sources only decide *how* to obtain the raw frame and never
|
|
10
|
+
re-implement the slicing or validation bookkeeping.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from abc import ABC, abstractmethod
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from datetime import date, datetime
|
|
18
|
+
from typing import Any, Protocol, runtime_checkable
|
|
19
|
+
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
from forecastforge.core.errors import DataError
|
|
23
|
+
from forecastforge.schemas.time_series import TimeSeries, TimeSeriesMetadata
|
|
24
|
+
|
|
25
|
+
__all__ = ["BaseDataSource", "DataSource", "TimestampLike"]
|
|
26
|
+
|
|
27
|
+
TimestampLike = str | pd.Timestamp | date | datetime
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@runtime_checkable
|
|
31
|
+
class DataSource(Protocol):
|
|
32
|
+
"""Anything that can produce a validated :class:`TimeSeries` for a symbol."""
|
|
33
|
+
|
|
34
|
+
def fetch(
|
|
35
|
+
self,
|
|
36
|
+
*,
|
|
37
|
+
symbol: str,
|
|
38
|
+
start: TimestampLike | None = None,
|
|
39
|
+
end: TimestampLike | None = None,
|
|
40
|
+
target: str = "close",
|
|
41
|
+
covariates: Sequence[str] = (),
|
|
42
|
+
frequency: str | None = None,
|
|
43
|
+
force_refresh: bool = False,
|
|
44
|
+
) -> TimeSeries:
|
|
45
|
+
"""Fetch a validated time series for ``symbol`` within ``[start, end]``."""
|
|
46
|
+
...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class BaseDataSource(ABC):
|
|
50
|
+
"""Shared fetch/slice/validate orchestration for concrete sources.
|
|
51
|
+
|
|
52
|
+
Subclasses implement :meth:`_load_frame` (how to obtain the raw frame for a
|
|
53
|
+
symbol) and :meth:`_attributes` (provenance to attach). The base class then
|
|
54
|
+
slices the frame to the requested window and wraps it in a validated
|
|
55
|
+
:class:`TimeSeries`.
|
|
56
|
+
|
|
57
|
+
Concrete subclasses set the ``source_name`` and ``default_frequency`` class
|
|
58
|
+
attributes to describe themselves.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
source_name: str = "base"
|
|
62
|
+
default_frequency: str | None = None
|
|
63
|
+
|
|
64
|
+
def fetch(
|
|
65
|
+
self,
|
|
66
|
+
*,
|
|
67
|
+
symbol: str,
|
|
68
|
+
start: TimestampLike | None = None,
|
|
69
|
+
end: TimestampLike | None = None,
|
|
70
|
+
target: str = "close",
|
|
71
|
+
covariates: Sequence[str] = (),
|
|
72
|
+
frequency: str | None = None,
|
|
73
|
+
force_refresh: bool = False,
|
|
74
|
+
) -> TimeSeries:
|
|
75
|
+
"""Fetch a validated time series for ``symbol`` within ``[start, end]``.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
symbol: Instrument identifier passed through to the source.
|
|
79
|
+
start: First timestamp to include (inclusive). ``None`` means from
|
|
80
|
+
the beginning of the source's data.
|
|
81
|
+
end: Last timestamp to include (inclusive). ``None`` means through
|
|
82
|
+
the end of the source's data.
|
|
83
|
+
target: Column to forecast.
|
|
84
|
+
covariates: Additional columns used as exogenous inputs.
|
|
85
|
+
frequency: Expected spacing as a pandas offset alias. Falls back to
|
|
86
|
+
the source's :attr:`default_frequency` when omitted.
|
|
87
|
+
force_refresh: When a source caches, bypass the cache and obtain
|
|
88
|
+
fresh data.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
A validated :class:`TimeSeries`.
|
|
92
|
+
|
|
93
|
+
Raises:
|
|
94
|
+
DataError: If the resulting window is empty after slicing.
|
|
95
|
+
"""
|
|
96
|
+
frame = self._load_frame(symbol=symbol, force_refresh=force_refresh)
|
|
97
|
+
frame = self._slice(frame, start=start, end=end)
|
|
98
|
+
if frame.empty:
|
|
99
|
+
window = f" in [{start}, {end}]" if start is not None or end is not None else ""
|
|
100
|
+
raise DataError(f"{self.source_name} source returned no rows for {symbol!r}{window}")
|
|
101
|
+
|
|
102
|
+
return TimeSeries(
|
|
103
|
+
frame=frame,
|
|
104
|
+
target=target,
|
|
105
|
+
metadata=TimeSeriesMetadata(
|
|
106
|
+
symbol=symbol,
|
|
107
|
+
source=self.source_name,
|
|
108
|
+
frequency=frequency or self.default_frequency,
|
|
109
|
+
attributes=self._attributes(symbol=symbol),
|
|
110
|
+
),
|
|
111
|
+
covariates=tuple(covariates),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
@staticmethod
|
|
115
|
+
def _slice(
|
|
116
|
+
frame: pd.DataFrame,
|
|
117
|
+
*,
|
|
118
|
+
start: TimestampLike | None,
|
|
119
|
+
end: TimestampLike | None,
|
|
120
|
+
) -> pd.DataFrame:
|
|
121
|
+
"""Return the rows of ``frame`` whose index lies in ``[start, end]``."""
|
|
122
|
+
if start is None and end is None:
|
|
123
|
+
return frame
|
|
124
|
+
|
|
125
|
+
mask = pd.Series(True, index=frame.index)
|
|
126
|
+
if start is not None:
|
|
127
|
+
lower = pd.Series(frame.index >= pd.Timestamp(start), index=frame.index)
|
|
128
|
+
mask &= lower
|
|
129
|
+
if end is not None:
|
|
130
|
+
upper = pd.Series(frame.index <= pd.Timestamp(end), index=frame.index)
|
|
131
|
+
mask &= upper
|
|
132
|
+
return frame.loc[mask]
|
|
133
|
+
|
|
134
|
+
@abstractmethod
|
|
135
|
+
def _load_frame(self, *, symbol: str, force_refresh: bool) -> pd.DataFrame:
|
|
136
|
+
"""Return the full raw frame for ``symbol`` (before any slicing)."""
|
|
137
|
+
|
|
138
|
+
@abstractmethod
|
|
139
|
+
def _attributes(self, *, symbol: str) -> dict[str, Any]:
|
|
140
|
+
"""Return provenance attributes to attach to the series metadata."""
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Deterministic synthetic time-series generator.
|
|
2
|
+
|
|
3
|
+
The synthetic source produces realistic-looking OHLCV price paths from a fixed
|
|
4
|
+
seed, so every run — local, in CI, or on a contributor's laptop — yields the
|
|
5
|
+
identical series. This is the project's default offline dataset and the basis
|
|
6
|
+
for all deterministic tests.
|
|
7
|
+
|
|
8
|
+
The model is a log-price random walk with:
|
|
9
|
+
|
|
10
|
+
* a constant per-period drift (trend),
|
|
11
|
+
* sinusoidal seasonality,
|
|
12
|
+
* gaussian noise, and
|
|
13
|
+
* optional regimes that change the drift and/or the volatility from a given
|
|
14
|
+
row onward.
|
|
15
|
+
|
|
16
|
+
Regimes deliberately do **not** create a one-day price jump by default. A
|
|
17
|
+
sudden 8% overnight move is indistinguishable from a data error, and a single
|
|
18
|
+
outlier return sits inside every rolling volatility window that straddles it
|
|
19
|
+
for the whole window length, producing a flat plateau that looks like a
|
|
20
|
+
modelling artefact. Callers who genuinely want a discontinuity can ask for
|
|
21
|
+
one with :attr:`Regime.level_shift`.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
import pandas as pd
|
|
31
|
+
|
|
32
|
+
from forecastforge.core.errors import DataError
|
|
33
|
+
from forecastforge.data.source import BaseDataSource
|
|
34
|
+
|
|
35
|
+
__all__ = ["Regime", "SyntheticConfig", "SyntheticSource"]
|
|
36
|
+
|
|
37
|
+
_DEFAULT_COLUMNS = ("open", "high", "low", "close", "volume")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class Regime:
|
|
42
|
+
"""A structural break that takes effect at a specific row.
|
|
43
|
+
|
|
44
|
+
By default a regime changes the *process*, not the price level: drift and
|
|
45
|
+
volatility shift from ``at`` onward, so the path stays continuous and only
|
|
46
|
+
its statistical character changes. That is what a real regime change looks
|
|
47
|
+
like, and it keeps derived volatility estimates free of artificial spikes.
|
|
48
|
+
|
|
49
|
+
Attributes:
|
|
50
|
+
at: Zero-based index where the regime takes effect, inclusive.
|
|
51
|
+
Negative values count from the end of the series.
|
|
52
|
+
drift_shift: Additive change to the per-period log-return, applied
|
|
53
|
+
from ``at`` onward.
|
|
54
|
+
volatility_shift: Additive change to the per-period log-return
|
|
55
|
+
standard deviation, applied from ``at`` onward. The resulting
|
|
56
|
+
standard deviation must stay non-negative.
|
|
57
|
+
level_shift: Opt-in one-period jump in log-price at ``at``, producing
|
|
58
|
+
a discontinuity of ``exp(level_shift) - 1`` in the close price.
|
|
59
|
+
Off by default; see the module docstring for why.
|
|
60
|
+
|
|
61
|
+
Example:
|
|
62
|
+
A correction at row 126 — lower drift and higher volatility, with no
|
|
63
|
+
price jump::
|
|
64
|
+
|
|
65
|
+
Regime(at=126, drift_shift=-0.0004, volatility_shift=0.006)
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
at: int
|
|
69
|
+
drift_shift: float = 0.0
|
|
70
|
+
volatility_shift: float = 0.0
|
|
71
|
+
level_shift: float = 0.0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, slots=True)
|
|
75
|
+
class SyntheticConfig:
|
|
76
|
+
"""Knobs for the deterministic generator.
|
|
77
|
+
|
|
78
|
+
Attributes:
|
|
79
|
+
seed: Seed for the numpy generator. Same seed → same series.
|
|
80
|
+
length: Number of periods to generate.
|
|
81
|
+
frequency: pandas offset alias for the index spacing.
|
|
82
|
+
start: First timestamp of the index.
|
|
83
|
+
initial_price: Opening price at index 0.
|
|
84
|
+
drift: Constant per-period log-return (trend).
|
|
85
|
+
seasonality_amplitude: Peak sinusoidal amplitude in log space.
|
|
86
|
+
seasonality_period: Period of the sinusoid in samples.
|
|
87
|
+
volatility: Standard deviation of the gaussian log-return noise.
|
|
88
|
+
regimes: Structural breaks applied in order.
|
|
89
|
+
volume_base: Mean daily volume before multiplicative noise.
|
|
90
|
+
columns: Columns to emit; must include whatever target/covariates a
|
|
91
|
+
later :meth:`~forecastforge.data.source.BaseDataSource.fetch` requests.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
seed: int = 42
|
|
95
|
+
length: int = 1000
|
|
96
|
+
frequency: str = "B"
|
|
97
|
+
start: pd.Timestamp = field(default_factory=lambda: pd.Timestamp("2015-01-02"))
|
|
98
|
+
initial_price: float = 100.0
|
|
99
|
+
drift: float = 0.0002
|
|
100
|
+
seasonality_amplitude: float = 0.0015
|
|
101
|
+
seasonality_period: int = 252
|
|
102
|
+
volatility: float = 0.01
|
|
103
|
+
regimes: tuple[Regime, ...] = ()
|
|
104
|
+
volume_base: float = 1_000_000.0
|
|
105
|
+
columns: tuple[str, ...] = _DEFAULT_COLUMNS
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _build_frame(config: SyntheticConfig) -> pd.DataFrame:
|
|
109
|
+
"""Generate the full OHLCV frame for ``config`` (no slicing)."""
|
|
110
|
+
if config.length <= 0:
|
|
111
|
+
raise DataError(f"length must be positive, got {config.length}")
|
|
112
|
+
if config.volatility < 0:
|
|
113
|
+
raise DataError(f"volatility must be non-negative, got {config.volatility}")
|
|
114
|
+
|
|
115
|
+
index = pd.date_range(start=config.start, periods=config.length, freq=config.frequency)
|
|
116
|
+
n = len(index)
|
|
117
|
+
rng = np.random.default_rng(config.seed)
|
|
118
|
+
|
|
119
|
+
t = np.arange(n)
|
|
120
|
+
seasonal = config.seasonality_amplitude * np.sin(2.0 * np.pi * t / config.seasonality_period)
|
|
121
|
+
|
|
122
|
+
# The per-period volatility is a vector rather than a scalar so that a
|
|
123
|
+
# regime can change it without introducing a jump: the noise is scaled,
|
|
124
|
+
# the price path stays continuous.
|
|
125
|
+
sigma = np.full(n, config.volatility)
|
|
126
|
+
log_returns = np.full(n, config.drift) + seasonal
|
|
127
|
+
|
|
128
|
+
for regime in config.regimes:
|
|
129
|
+
pos = regime.at if regime.at >= 0 else n + regime.at
|
|
130
|
+
if not 0 <= pos < n:
|
|
131
|
+
raise DataError(f"regime at={regime.at} is out of range for length {n}")
|
|
132
|
+
if regime.drift_shift:
|
|
133
|
+
log_returns[pos:] += regime.drift_shift
|
|
134
|
+
if regime.volatility_shift:
|
|
135
|
+
sigma[pos:] += regime.volatility_shift
|
|
136
|
+
if regime.level_shift:
|
|
137
|
+
# Explicitly opt-in discontinuity; see the module docstring.
|
|
138
|
+
log_returns[pos] += regime.level_shift
|
|
139
|
+
|
|
140
|
+
if (sigma < 0.0).any():
|
|
141
|
+
first_bad = int(np.argmax(sigma < 0.0))
|
|
142
|
+
raise DataError(
|
|
143
|
+
f"volatility became negative at row {first_bad} "
|
|
144
|
+
f"({sigma[first_bad]:.6f}); volatility_shift values must keep "
|
|
145
|
+
f"the per-period standard deviation non-negative"
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
log_returns += rng.standard_normal(n) * sigma
|
|
149
|
+
|
|
150
|
+
log_price = np.log(config.initial_price) + np.cumsum(log_returns)
|
|
151
|
+
close = np.exp(log_price)
|
|
152
|
+
|
|
153
|
+
intraday = rng.standard_normal(n) * (sigma * 0.5)
|
|
154
|
+
open_ = np.empty(n)
|
|
155
|
+
open_[0] = config.initial_price * np.exp(intraday[0])
|
|
156
|
+
open_[1:] = close[:-1] * np.exp(intraday[1:])
|
|
157
|
+
|
|
158
|
+
upper = np.abs(rng.standard_normal(n) * (sigma * 0.6))
|
|
159
|
+
lower = np.abs(rng.standard_normal(n) * (sigma * 0.6))
|
|
160
|
+
high = np.maximum(open_, close) * np.exp(upper)
|
|
161
|
+
low = np.minimum(open_, close) * np.exp(-lower)
|
|
162
|
+
|
|
163
|
+
volume = config.volume_base * np.exp(rng.normal(0.0, 0.3, size=n))
|
|
164
|
+
volume = np.round(volume).astype("int64")
|
|
165
|
+
|
|
166
|
+
frame = pd.DataFrame(
|
|
167
|
+
{
|
|
168
|
+
"open": open_,
|
|
169
|
+
"high": high,
|
|
170
|
+
"low": low,
|
|
171
|
+
"close": close,
|
|
172
|
+
"volume": volume,
|
|
173
|
+
},
|
|
174
|
+
index=index,
|
|
175
|
+
)
|
|
176
|
+
frame.index.name = "date"
|
|
177
|
+
|
|
178
|
+
unknown = set(config.columns) - set(frame.columns)
|
|
179
|
+
if unknown:
|
|
180
|
+
available = ", ".join(map(str, frame.columns))
|
|
181
|
+
raise DataError(f"unknown synthetic columns {sorted(unknown)}; available: {available}")
|
|
182
|
+
return frame[list(config.columns)]
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@dataclass(frozen=True, slots=True)
|
|
186
|
+
class SyntheticSource(BaseDataSource):
|
|
187
|
+
"""A fully deterministic, offline :class:`DataSource`.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
config: Generator configuration. Defaults to a 1000-business-day,
|
|
191
|
+
SPY-like path seeded with ``42``.
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
config: SyntheticConfig = field(default_factory=SyntheticConfig)
|
|
195
|
+
|
|
196
|
+
source_name = "synthetic"
|
|
197
|
+
default_frequency = "B"
|
|
198
|
+
|
|
199
|
+
def _load_frame(self, *, symbol: str, force_refresh: bool) -> pd.DataFrame:
|
|
200
|
+
return _build_frame(self.config)
|
|
201
|
+
|
|
202
|
+
def _attributes(self, *, symbol: str) -> dict[str, Any]:
|
|
203
|
+
cfg = self.config
|
|
204
|
+
return {
|
|
205
|
+
"seed": cfg.seed,
|
|
206
|
+
"length": cfg.length,
|
|
207
|
+
"frequency": cfg.frequency,
|
|
208
|
+
"initial_price": cfg.initial_price,
|
|
209
|
+
"drift": cfg.drift,
|
|
210
|
+
"volatility": cfg.volatility,
|
|
211
|
+
"regimes": [r.at for r in cfg.regimes],
|
|
212
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Optional Yahoo Finance data source.
|
|
2
|
+
|
|
3
|
+
This is an *optional* connector: it depends on the ``yfinance`` package, which
|
|
4
|
+
is only installed with the ``data`` extra. The import is resolved lazily through
|
|
5
|
+
:func:`forecastforge.config._optional.optional_import`, so the core package and
|
|
6
|
+
every test import cleanly without network access or the dependency present.
|
|
7
|
+
|
|
8
|
+
Downloaded data is cached to Parquet under ``cache_dir`` (default ``data/raw``).
|
|
9
|
+
A subsequent fetch for the same symbol reads the cache unless ``force_refresh``
|
|
10
|
+
is set, which keeps repeat runs and offline tests fast and network-free.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from types import ModuleType
|
|
18
|
+
from typing import Any, cast
|
|
19
|
+
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
from forecastforge.config._optional import optional_import
|
|
23
|
+
from forecastforge.core.errors import DataError, MissingOptionalDependencyError
|
|
24
|
+
from forecastforge.data.loaders import read_parquet, write_parquet
|
|
25
|
+
from forecastforge.data.source import BaseDataSource
|
|
26
|
+
|
|
27
|
+
__all__ = ["YFinanceSource"]
|
|
28
|
+
|
|
29
|
+
_COLUMN_RENAME = {
|
|
30
|
+
"Open": "open",
|
|
31
|
+
"High": "high",
|
|
32
|
+
"Low": "low",
|
|
33
|
+
"Close": "close",
|
|
34
|
+
"Adj Close": "adj_close",
|
|
35
|
+
"Volume": "volume",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True, slots=True)
|
|
40
|
+
class YFinanceSource(BaseDataSource):
|
|
41
|
+
"""A cached Yahoo Finance connector, lazily importing ``yfinance``.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
cache_dir: Directory for the Parquet cache. Created on first write.
|
|
45
|
+
default_start: Default download window start (ISO date string).
|
|
46
|
+
default_end: Default download window end; ``None`` means "up to now".
|
|
47
|
+
auto_adjust: Forwarded to ``yfinance.download`` to adjust for splits/
|
|
48
|
+
dividends on the ``close`` column.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
cache_dir: Path = field(default_factory=lambda: Path("data/raw"))
|
|
52
|
+
default_start: str = "2015-01-01"
|
|
53
|
+
default_end: str | None = None
|
|
54
|
+
auto_adjust: bool = True
|
|
55
|
+
|
|
56
|
+
source_name = "yfinance"
|
|
57
|
+
default_frequency = "B"
|
|
58
|
+
|
|
59
|
+
def _cache_path(self, symbol: str) -> Path:
|
|
60
|
+
safe = symbol.replace("/", "_").replace("\\", "_")
|
|
61
|
+
return Path(self.cache_dir) / f"{safe}.parquet"
|
|
62
|
+
|
|
63
|
+
def _load_frame(self, *, symbol: str, force_refresh: bool) -> pd.DataFrame:
|
|
64
|
+
cache_path = self._cache_path(symbol)
|
|
65
|
+
if not force_refresh and cache_path.exists():
|
|
66
|
+
return read_parquet(cache_path)
|
|
67
|
+
|
|
68
|
+
yf = optional_import("yfinance")
|
|
69
|
+
if yf is None:
|
|
70
|
+
raise MissingOptionalDependencyError(
|
|
71
|
+
"the yfinance data source requires the optional 'data' extra: "
|
|
72
|
+
"install with `pip install 'forecastforge[data]'`"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
frame = self._download(symbol, yf)
|
|
76
|
+
write_parquet(frame, cache_path)
|
|
77
|
+
return frame
|
|
78
|
+
|
|
79
|
+
def _download(self, symbol: str, yf: ModuleType) -> pd.DataFrame:
|
|
80
|
+
"""Download and normalize a frame for ``symbol`` using ``yf``."""
|
|
81
|
+
raw = yf.download(
|
|
82
|
+
symbol,
|
|
83
|
+
start=self.default_start,
|
|
84
|
+
end=self.default_end,
|
|
85
|
+
auto_adjust=self.auto_adjust,
|
|
86
|
+
progress=False,
|
|
87
|
+
)
|
|
88
|
+
if raw is None or (isinstance(raw, pd.DataFrame) and raw.empty):
|
|
89
|
+
raise DataError(f"yfinance returned no data for {symbol!r}")
|
|
90
|
+
|
|
91
|
+
frame = raw
|
|
92
|
+
if isinstance(frame.columns, pd.MultiIndex):
|
|
93
|
+
level_values = frame.columns.get_level_values(1)
|
|
94
|
+
if symbol in set(level_values):
|
|
95
|
+
frame = frame.xs(symbol, axis=1, level=1)
|
|
96
|
+
else:
|
|
97
|
+
frame = frame.droplevel(1)
|
|
98
|
+
frame = frame.rename(columns=_COLUMN_RENAME)
|
|
99
|
+
frame.index.name = "date"
|
|
100
|
+
|
|
101
|
+
keep = [col for col in _COLUMN_RENAME.values() if col in frame.columns]
|
|
102
|
+
return cast("pd.DataFrame", frame[keep])
|
|
103
|
+
|
|
104
|
+
def _attributes(self, *, symbol: str) -> dict[str, Any]:
|
|
105
|
+
return {"cache_dir": str(self.cache_dir), "default_start": self.default_start}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Forecast evaluation: metrics and walk-forward backtesting.
|
|
2
|
+
|
|
3
|
+
* :mod:`forecastforge.evaluation.metrics` — MAE, RMSE, sMAPE, MASE,
|
|
4
|
+
directional accuracy, and interval coverage, each a pure function.
|
|
5
|
+
* :mod:`forecastforge.evaluation.backtest` — the leakage-safe walk-forward
|
|
6
|
+
backtester that produces the tidy prediction frame every report is built
|
|
7
|
+
from.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from forecastforge.evaluation.backtest import (
|
|
13
|
+
BacktestConfig,
|
|
14
|
+
BacktestResult,
|
|
15
|
+
Fold,
|
|
16
|
+
WalkForwardBacktester,
|
|
17
|
+
)
|
|
18
|
+
from forecastforge.evaluation.metrics import (
|
|
19
|
+
MetricSet,
|
|
20
|
+
directional_accuracy,
|
|
21
|
+
evaluate,
|
|
22
|
+
interval_coverage,
|
|
23
|
+
mae,
|
|
24
|
+
mase,
|
|
25
|
+
mase_scale,
|
|
26
|
+
rmse,
|
|
27
|
+
smape,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"BacktestConfig",
|
|
32
|
+
"BacktestResult",
|
|
33
|
+
"Fold",
|
|
34
|
+
"MetricSet",
|
|
35
|
+
"WalkForwardBacktester",
|
|
36
|
+
"directional_accuracy",
|
|
37
|
+
"evaluate",
|
|
38
|
+
"interval_coverage",
|
|
39
|
+
"mae",
|
|
40
|
+
"mase",
|
|
41
|
+
"mase_scale",
|
|
42
|
+
"rmse",
|
|
43
|
+
"smape",
|
|
44
|
+
]
|