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,98 @@
1
+ """Compute device detection for ForecastForge.
2
+
3
+ Provides a backend-agnostic abstraction over the compute devices
4
+ ForecastForge may eventually run on (CPU, NVIDIA CUDA, Apple MPS)
5
+ without requiring any specific ML framework to be installed at this
6
+ stage of the project. PyTorch is treated as an optional dependency: if
7
+ it is not installed, detection gracefully falls back to CPU rather than
8
+ raising an error.
9
+
10
+ This module performs *detection* only — it does not construct or
11
+ configure any model, tensor, or training component.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from enum import StrEnum
17
+ from functools import lru_cache
18
+
19
+ from forecastforge.config._optional import optional_import
20
+
21
+ __all__ = ["DeviceType", "detect_device", "resolve_device"]
22
+
23
+
24
+ class DeviceType(StrEnum):
25
+ """Supported (or requested) compute device types.
26
+
27
+ ``AUTO`` is a valid *preference* (e.g. in configuration) meaning
28
+ "pick the best available device"; it is never returned by
29
+ :func:`detect_device`, which always resolves to a concrete device.
30
+ """
31
+
32
+ AUTO = "auto"
33
+ CPU = "cpu"
34
+ CUDA = "cuda"
35
+ MPS = "mps"
36
+
37
+
38
+ @lru_cache(maxsize=1)
39
+ def detect_device() -> DeviceType:
40
+ """Detect the best available compute device on this machine.
41
+
42
+ Preference order: CUDA > Apple MPS > CPU. Returns
43
+ :data:`DeviceType.CPU` if PyTorch is not installed, or if it is
44
+ installed but no accelerator backend is available. Never returns
45
+ :data:`DeviceType.AUTO`.
46
+
47
+ The result is cached for the lifetime of the process, since
48
+ available hardware does not change at runtime. Call
49
+ ``detect_device.cache_clear()`` (e.g. in tests) to force
50
+ re-detection.
51
+ """
52
+ torch = optional_import("torch")
53
+ if torch is None:
54
+ return DeviceType.CPU
55
+
56
+ if torch.cuda.is_available():
57
+ return DeviceType.CUDA
58
+
59
+ mps_backend = getattr(torch.backends, "mps", None)
60
+ if mps_backend is not None and mps_backend.is_available():
61
+ return DeviceType.MPS
62
+
63
+ return DeviceType.CPU
64
+
65
+
66
+ def resolve_device(preference: DeviceType | str | None = None) -> DeviceType:
67
+ """Resolve a requested device preference to a concrete, available device.
68
+
69
+ Args:
70
+ preference: The requested device. ``None`` or
71
+ :data:`DeviceType.AUTO` triggers auto-detection via
72
+ :func:`detect_device`. An explicit request for
73
+ :data:`DeviceType.CUDA` or :data:`DeviceType.MPS` is honored
74
+ only if that backend is actually available; otherwise this
75
+ function falls back to the auto-detected device rather than
76
+ returning a device that cannot be used.
77
+ :data:`DeviceType.CPU` is always honored, since it is always
78
+ available.
79
+
80
+ Returns:
81
+ A concrete, usable :class:`DeviceType` (never ``AUTO``).
82
+ """
83
+ if preference is None:
84
+ return detect_device()
85
+
86
+ requested = DeviceType(preference)
87
+
88
+ if requested is DeviceType.AUTO:
89
+ return detect_device()
90
+
91
+ if requested is DeviceType.CPU:
92
+ return DeviceType.CPU
93
+
94
+ available = detect_device()
95
+ if requested == available:
96
+ return requested
97
+
98
+ return available
@@ -0,0 +1,50 @@
1
+ """Deployment environment detection for ForecastForge.
2
+
3
+ Defines the set of supported deployment environments (development,
4
+ testing, production) and the logic used to detect which one is active.
5
+
6
+ This module is intentionally independent of
7
+ :mod:`forecastforge.config.settings`: the active environment must be
8
+ known *before* `Settings` can decide which per-environment TOML overlay
9
+ (`configs/<environment>.toml`) to load, so resolving it here avoids a
10
+ circular dependency between the two modules.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ from enum import StrEnum
17
+
18
+ __all__ = ["Environment", "get_environment"]
19
+
20
+ _ENVIRONMENT_ENV_VAR = "FORECASTFORGE_ENV"
21
+ _DEFAULT_ENVIRONMENT = "development"
22
+
23
+
24
+ class Environment(StrEnum):
25
+ """Supported ForecastForge deployment environments."""
26
+
27
+ DEVELOPMENT = "development"
28
+ TESTING = "testing"
29
+ PRODUCTION = "production"
30
+
31
+
32
+ def get_environment() -> Environment:
33
+ """Resolve the currently active deployment environment.
34
+
35
+ Reads the ``FORECASTFORGE_ENV`` environment variable (case-
36
+ insensitive). Defaults to :data:`Environment.DEVELOPMENT` when the
37
+ variable is unset.
38
+
39
+ Raises:
40
+ ValueError: If ``FORECASTFORGE_ENV`` is set to a value that is
41
+ not one of ``development``, ``testing``, or ``production``.
42
+ """
43
+ raw = os.environ.get(_ENVIRONMENT_ENV_VAR, _DEFAULT_ENVIRONMENT).strip().lower()
44
+ try:
45
+ return Environment(raw)
46
+ except ValueError:
47
+ valid = ", ".join(member.value for member in Environment)
48
+ raise ValueError(
49
+ f"Invalid {_ENVIRONMENT_ENV_VAR}={raw!r}; expected one of: {valid}"
50
+ ) from None
@@ -0,0 +1,131 @@
1
+ """Filesystem path resolution utilities for ForecastForge.
2
+
3
+ Every filesystem path used elsewhere in the codebase should be derived
4
+ from the functions in this module rather than hardcoded, so the project
5
+ can be relocated, containerized, or installed without source changes.
6
+
7
+ Path resolution never touches the filesystem beyond checking for marker
8
+ files (it does not create directories) — callers are responsible for
9
+ creating a directory before writing to it.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from functools import lru_cache
16
+ from pathlib import Path
17
+
18
+ __all__ = [
19
+ "get_artifacts_dir",
20
+ "get_configs_dir",
21
+ "get_data_dir",
22
+ "get_external_data_dir",
23
+ "get_interim_data_dir",
24
+ "get_mlruns_dir",
25
+ "get_models_dir",
26
+ "get_processed_data_dir",
27
+ "get_project_root",
28
+ "get_raw_data_dir",
29
+ "resolve_path",
30
+ ]
31
+
32
+ _PROJECT_ROOT_ENV_VAR = "FORECASTFORGE_PROJECT_ROOT"
33
+ _ROOT_MARKER_FILES = ("pyproject.toml", ".git")
34
+
35
+
36
+ @lru_cache(maxsize=1)
37
+ def get_project_root() -> Path:
38
+ """Return the absolute path to the ForecastForge project root.
39
+
40
+ Resolution order:
41
+
42
+ 1. The ``FORECASTFORGE_PROJECT_ROOT`` environment variable, if set
43
+ — always honored as-is, useful in containers or installed
44
+ (non-editable) deployments where there is no source tree to
45
+ search.
46
+ 2. Walking upward from this file's own location until a directory
47
+ containing a root marker (``pyproject.toml`` or ``.git``) is
48
+ found — correct for an editable install
49
+ (``pip install -e .``) of the ``src``-layout package, which is
50
+ the expected local development setup.
51
+ 3. The current working directory, as a last resort.
52
+
53
+ The result is cached for the lifetime of the process. Call
54
+ ``get_project_root.cache_clear()`` (e.g. in tests) to force
55
+ re-resolution after changing ``FORECASTFORGE_PROJECT_ROOT``.
56
+ """
57
+ env_override = os.environ.get(_PROJECT_ROOT_ENV_VAR)
58
+ if env_override:
59
+ return Path(env_override).expanduser().resolve()
60
+
61
+ here = Path(__file__).resolve()
62
+ for candidate in (here, *here.parents):
63
+ if any((candidate / marker).exists() for marker in _ROOT_MARKER_FILES):
64
+ return candidate
65
+
66
+ return Path.cwd().resolve() # pragma: no cover - unreachable in this repo
67
+
68
+
69
+ def resolve_path(path: str | Path, *, base: Path | None = None) -> Path:
70
+ """Resolve ``path`` to an absolute :class:`~pathlib.Path`.
71
+
72
+ Args:
73
+ path: A relative or absolute path. ``~`` is expanded.
74
+ base: The directory relative paths are resolved against.
75
+ Defaults to :func:`get_project_root`.
76
+
77
+ Returns:
78
+ An absolute path. If ``path`` was already absolute (after ``~``
79
+ expansion), it is returned unchanged; otherwise it is joined to
80
+ ``base`` and resolved (normalizing ``.``/``..`` segments without
81
+ requiring the path to exist).
82
+ """
83
+ candidate = Path(path).expanduser()
84
+ if candidate.is_absolute():
85
+ return candidate
86
+ return ((base or get_project_root()) / candidate).resolve()
87
+
88
+
89
+ def get_configs_dir() -> Path:
90
+ """Return the absolute path to the ``configs/`` directory."""
91
+ return get_project_root() / "configs"
92
+
93
+
94
+ def get_data_dir(data_dir: str | Path = "data") -> Path:
95
+ """Return the absolute path to the root data directory."""
96
+ return resolve_path(data_dir)
97
+
98
+
99
+ def get_raw_data_dir(data_dir: str | Path = "data") -> Path:
100
+ """Return the absolute path to the immutable, as-received data directory."""
101
+ return get_data_dir(data_dir) / "raw"
102
+
103
+
104
+ def get_interim_data_dir(data_dir: str | Path = "data") -> Path:
105
+ """Return the absolute path to the intermediate, partially-processed data directory."""
106
+ return get_data_dir(data_dir) / "interim"
107
+
108
+
109
+ def get_processed_data_dir(data_dir: str | Path = "data") -> Path:
110
+ """Return the absolute path to the final, model-ready data directory."""
111
+ return get_data_dir(data_dir) / "processed"
112
+
113
+
114
+ def get_external_data_dir(data_dir: str | Path = "data") -> Path:
115
+ """Return the absolute path to the third-party/external data directory."""
116
+ return get_data_dir(data_dir) / "external"
117
+
118
+
119
+ def get_models_dir(models_dir: str | Path = "models") -> Path:
120
+ """Return the absolute path to the serialized model artifact directory."""
121
+ return resolve_path(models_dir)
122
+
123
+
124
+ def get_artifacts_dir(artifacts_dir: str | Path = "artifacts") -> Path:
125
+ """Return the absolute path to the general run-artifact directory."""
126
+ return resolve_path(artifacts_dir)
127
+
128
+
129
+ def get_mlruns_dir(mlruns_dir: str | Path = "mlruns") -> Path:
130
+ """Return the absolute path to the experiment-tracking store directory."""
131
+ return resolve_path(mlruns_dir)
@@ -0,0 +1,76 @@
1
+ """Runtime execution context detection for ForecastForge.
2
+
3
+ Distinct from :mod:`forecastforge.config.environment` (which answers
4
+ *which deployment stage* is configured — development, testing, or
5
+ production), this module answers *what machine and process*
6
+ ForecastForge is currently executing in/as: the interpreter, platform,
7
+ host, and whether the process is running under a test runner or CI.
8
+ This is intended for diagnostics and logging, not for branching core
9
+ application behavior.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import platform
16
+ import sys
17
+ from dataclasses import dataclass
18
+ from functools import lru_cache
19
+
20
+ __all__ = ["RuntimeInfo", "get_runtime_info"]
21
+
22
+ _CI_ENV_VARS = ("CI", "GITHUB_ACTIONS", "GITLAB_CI", "CIRCLECI", "JENKINS_URL")
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class RuntimeInfo:
27
+ """An immutable snapshot of the current runtime execution context."""
28
+
29
+ python_version: str
30
+ platform_system: str
31
+ platform_release: str
32
+ hostname: str
33
+ process_id: int
34
+ is_ci: bool
35
+ is_pytest: bool
36
+ is_interactive: bool
37
+
38
+
39
+ def _detect_is_ci() -> bool:
40
+ """Return True if common CI environment indicators are present."""
41
+ return any(os.environ.get(var) for var in _CI_ENV_VARS)
42
+
43
+
44
+ def _detect_is_pytest() -> bool:
45
+ """Return True if the current process is running under pytest."""
46
+ return "PYTEST_CURRENT_TEST" in os.environ or "pytest" in sys.modules
47
+
48
+
49
+ def _detect_is_interactive() -> bool:
50
+ """Return True if attached to an interactive terminal session."""
51
+ if hasattr(sys, "ps1"):
52
+ return True
53
+ try:
54
+ return sys.stdin.isatty()
55
+ except (AttributeError, ValueError): # pragma: no cover - defensive
56
+ return False
57
+
58
+
59
+ @lru_cache(maxsize=1)
60
+ def get_runtime_info() -> RuntimeInfo:
61
+ """Return a cached snapshot of the current runtime execution context.
62
+
63
+ The result is cached for the lifetime of the process. Call
64
+ ``get_runtime_info.cache_clear()`` (e.g. in tests) to force a fresh
65
+ snapshot.
66
+ """
67
+ return RuntimeInfo(
68
+ python_version=platform.python_version(),
69
+ platform_system=platform.system(),
70
+ platform_release=platform.release(),
71
+ hostname=platform.node(),
72
+ process_id=os.getpid(),
73
+ is_ci=_detect_is_ci(),
74
+ is_pytest=_detect_is_pytest(),
75
+ is_interactive=_detect_is_interactive(),
76
+ )
@@ -0,0 +1,56 @@
1
+ """Deterministic random seed configuration for ForecastForge.
2
+
3
+ Seeds Python's :mod:`random` module, NumPy's global generator, and PyTorch's
4
+ CPU, CUDA, and MPS generators. NumPy is a core dependency; PyTorch is
5
+ optional, so it is resolved through
6
+ :func:`forecastforge.config._optional.optional_import` and its absence is
7
+ handled gracefully rather than raising an :class:`ImportError`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import random
14
+
15
+ from forecastforge.config._optional import optional_import
16
+
17
+ __all__ = ["set_seed"]
18
+
19
+
20
+ def set_seed(seed: int) -> None:
21
+ """Seed every available random number generator for reproducibility.
22
+
23
+ Always seeds:
24
+
25
+ - the ``PYTHONHASHSEED`` environment variable (affects hash-based
26
+ iteration order in *subprocesses* spawned afterward; it has no
27
+ effect on the already-running interpreter, but is set here so
28
+ that any child process inherits a consistent seed)
29
+ - the standard library :mod:`random` module
30
+
31
+ Additionally seeds NumPy's global RNG and PyTorch's CPU, CUDA, and
32
+ MPS generators if the respective library is installed.
33
+
34
+ Args:
35
+ seed: The seed value to apply everywhere.
36
+ """
37
+ os.environ["PYTHONHASHSEED"] = str(seed)
38
+ random.seed(seed)
39
+
40
+ numpy = optional_import("numpy")
41
+ if numpy is not None:
42
+ numpy.random.seed(seed)
43
+
44
+ torch = optional_import("torch")
45
+ if torch is None:
46
+ return
47
+
48
+ torch.manual_seed(seed)
49
+
50
+ if torch.cuda.is_available():
51
+ torch.cuda.manual_seed_all(seed)
52
+
53
+ mps_backend = getattr(torch.backends, "mps", None)
54
+ mps_module = getattr(torch, "mps", None)
55
+ if mps_backend is not None and mps_backend.is_available() and mps_module is not None:
56
+ mps_module.manual_seed(seed)
@@ -0,0 +1,249 @@
1
+ """Central application settings for ForecastForge.
2
+
3
+ :class:`Settings` is the single source of truth for application
4
+ configuration. It is a :class:`pydantic_settings.BaseSettings`
5
+ subclass, which provides:
6
+
7
+ - strong typing and validation (pydantic v2)
8
+ - environment variable overrides (prefixed ``FORECASTFORGE_``)
9
+ - ``.env`` file loading (via python-dotenv, through pydantic-settings)
10
+ - custom TOML file loading and merging (via :class:`_TomlConfigSource`
11
+ below)
12
+
13
+ Configuration precedence, from highest to lowest priority:
14
+
15
+ 1. Explicit keyword arguments passed to ``Settings(...)``.
16
+ 2. Environment variables (``FORECASTFORGE_<FIELD_NAME>``).
17
+ 3. A ``.env`` file in the project root.
18
+ 4. TOML configuration files: ``configs/settings.toml`` merged with
19
+ ``configs/<environment>.toml`` (the environment overlay wins on
20
+ conflicting keys).
21
+ 5. The field defaults declared on :class:`Settings` below.
22
+
23
+ Use :func:`get_settings` to obtain the process-wide singleton instance
24
+ rather than constructing ``Settings()`` directly, so configuration is
25
+ parsed and validated exactly once per process. See
26
+ ``docs/development.md`` for a full description of this hierarchy.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import tomllib
32
+ from functools import lru_cache
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ from pydantic import Field, PositiveInt, field_validator
37
+ from pydantic.fields import FieldInfo
38
+ from pydantic_settings import (
39
+ BaseSettings,
40
+ PydanticBaseSettingsSource,
41
+ SettingsConfigDict,
42
+ )
43
+
44
+ from forecastforge.config.device import DeviceType, resolve_device
45
+ from forecastforge.config.environment import Environment, get_environment
46
+ from forecastforge.config.paths import get_configs_dir, get_project_root, resolve_path
47
+
48
+ __all__ = ["Settings", "get_settings", "reload_settings"]
49
+
50
+ _ENV_PREFIX = "FORECASTFORGE_"
51
+ _BASE_CONFIG_FILENAME = "settings.toml"
52
+
53
+
54
+ class _TomlConfigSource(PydanticBaseSettingsSource):
55
+ """A pydantic-settings source that loads and merges TOML config files.
56
+
57
+ Reads ``configs/settings.toml`` as a base layer, then merges
58
+ ``configs/<environment>.toml`` on top of it, where the environment
59
+ is resolved via :func:`forecastforge.config.environment.get_environment`
60
+ — kept independent of the `Settings` model under construction to
61
+ avoid a circular dependency.
62
+
63
+ Only the nested TOML sections consumed by :class:`Settings`
64
+ (``project``, ``logging``, ``paths``, ``defaults``) are read; each
65
+ is flattened into the flat field names `Settings` expects.
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ settings_cls: type[BaseSettings],
71
+ configs_dir: Path | None = None,
72
+ ) -> None:
73
+ super().__init__(settings_cls)
74
+ self._configs_dir = configs_dir or get_configs_dir()
75
+
76
+ def _load_toml(self, path: Path) -> dict[str, Any]:
77
+ if not path.is_file():
78
+ return {}
79
+ with path.open("rb") as fh:
80
+ return tomllib.load(fh)
81
+
82
+ def _merge(self, base: dict[str, Any], overlay: dict[str, Any]) -> dict[str, Any]:
83
+ merged: dict[str, Any] = {**base}
84
+ for section, values in overlay.items():
85
+ if isinstance(values, dict) and isinstance(merged.get(section), dict):
86
+ merged[section] = {**merged[section], **values}
87
+ else:
88
+ merged[section] = values
89
+ return merged
90
+
91
+ def _flatten(self, raw: dict[str, Any]) -> dict[str, Any]:
92
+ project = raw.get("project", {})
93
+ logging_section = raw.get("logging", {})
94
+ paths_section = raw.get("paths", {})
95
+ defaults_section = raw.get("defaults", {})
96
+
97
+ flat: dict[str, Any] = {
98
+ "app_name": project.get("name"),
99
+ "environment": project.get("environment"),
100
+ "random_seed": project.get("random_seed"),
101
+ "log_level": logging_section.get("level"),
102
+ "data_dir": paths_section.get("data_dir"),
103
+ "models_dir": paths_section.get("models_dir"),
104
+ "artifacts_dir": paths_section.get("artifacts_dir"),
105
+ "mlruns_dir": paths_section.get("mlruns_dir"),
106
+ "default_asset_symbol": defaults_section.get("asset_symbol"),
107
+ "default_timeframe": defaults_section.get("timeframe"),
108
+ "sequence_length": defaults_section.get("sequence_length"),
109
+ "batch_size": defaults_section.get("batch_size"),
110
+ "num_workers": defaults_section.get("num_workers"),
111
+ "device_preference": defaults_section.get("device_preference"),
112
+ }
113
+ return {key: value for key, value in flat.items() if value is not None}
114
+
115
+ def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]:
116
+ # Required by the PydanticBaseSettingsSource ABC. Unused in
117
+ # practice because __call__ below builds the full settings dict
118
+ # in one pass rather than resolving fields individually.
119
+ return None, field_name, False
120
+
121
+ def __call__(self) -> dict[str, Any]:
122
+ base = self._load_toml(self._configs_dir / _BASE_CONFIG_FILENAME)
123
+ environment = get_environment()
124
+ overlay = self._load_toml(self._configs_dir / f"{environment.value}.toml")
125
+ return self._flatten(self._merge(base, overlay))
126
+
127
+
128
+ class Settings(BaseSettings):
129
+ """Application-wide, validated ForecastForge configuration.
130
+
131
+ Do not construct this directly in application code — use
132
+ :func:`get_settings` so configuration is parsed once and shared.
133
+ Direct construction (``Settings()`` or ``Settings(**overrides)``) is
134
+ intended for tests and for the singleton factory itself.
135
+ """
136
+
137
+ model_config = SettingsConfigDict(
138
+ env_prefix=_ENV_PREFIX,
139
+ env_file=str(get_project_root() / ".env"),
140
+ env_file_encoding="utf-8",
141
+ extra="ignore",
142
+ validate_default=True,
143
+ frozen=True,
144
+ )
145
+
146
+ app_name: str = Field(
147
+ default="forecastforge",
148
+ description="Application/package name, used in logs and diagnostics.",
149
+ )
150
+ environment: Environment = Field(
151
+ default_factory=get_environment,
152
+ validation_alias="FORECASTFORGE_ENV",
153
+ description="Active deployment environment.",
154
+ )
155
+ random_seed: int = Field(default=42, description="Default global random seed.")
156
+ log_level: str = Field(default="INFO", description="Root logging level.")
157
+
158
+ data_dir: Path = Field(default=Path("data"), description="Root data directory.")
159
+ models_dir: Path = Field(
160
+ default=Path("models"), description="Trained model artifact directory."
161
+ )
162
+ artifacts_dir: Path = Field(
163
+ default=Path("artifacts"), description="General run-artifact directory."
164
+ )
165
+ mlruns_dir: Path = Field(
166
+ default=Path("mlruns"), description="Experiment-tracking store directory."
167
+ )
168
+
169
+ default_asset_symbol: str = Field(
170
+ default="SPY", description="Default forecasting asset/instrument symbol."
171
+ )
172
+ default_timeframe: str = Field(
173
+ default="1d", description="Default forecasting timeframe/bar size."
174
+ )
175
+
176
+ sequence_length: PositiveInt = Field(
177
+ default=64, description="Default input sequence length for windowed models."
178
+ )
179
+ batch_size: PositiveInt = Field(
180
+ default=32, description="Default training/inference batch size."
181
+ )
182
+ num_workers: int = Field(default=4, ge=0, description="Default data-loading worker count.")
183
+
184
+ device_preference: DeviceType = Field(
185
+ default=DeviceType.AUTO, description="Preferred compute device."
186
+ )
187
+
188
+ @field_validator("log_level")
189
+ @classmethod
190
+ def _validate_log_level(cls, value: str) -> str:
191
+ normalized = value.upper()
192
+ valid_levels = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
193
+ if normalized not in valid_levels:
194
+ raise ValueError(f"log_level must be one of {sorted(valid_levels)}, got {value!r}")
195
+ return normalized
196
+
197
+ @field_validator("data_dir", "models_dir", "artifacts_dir", "mlruns_dir", mode="after")
198
+ @classmethod
199
+ def _resolve_absolute(cls, value: Path) -> Path:
200
+ return resolve_path(value)
201
+
202
+ @classmethod
203
+ def settings_customise_sources(
204
+ cls,
205
+ settings_cls: type[BaseSettings],
206
+ init_settings: PydanticBaseSettingsSource,
207
+ env_settings: PydanticBaseSettingsSource,
208
+ dotenv_settings: PydanticBaseSettingsSource,
209
+ file_secret_settings: PydanticBaseSettingsSource,
210
+ ) -> tuple[PydanticBaseSettingsSource, ...]:
211
+ # Priority, highest to lowest: init kwargs > env vars > .env
212
+ # file > TOML files. Field defaults are pydantic-settings'
213
+ # implicit final fallback and need no explicit source here.
214
+ return (
215
+ init_settings,
216
+ env_settings,
217
+ dotenv_settings,
218
+ _TomlConfigSource(settings_cls),
219
+ )
220
+
221
+ def resolved_device(self) -> DeviceType:
222
+ """Resolve :attr:`device_preference` to a concrete, available device.
223
+
224
+ Convenience wrapper around
225
+ :func:`forecastforge.config.device.resolve_device`.
226
+ """
227
+ return resolve_device(self.device_preference)
228
+
229
+
230
+ @lru_cache(maxsize=1)
231
+ def get_settings() -> Settings:
232
+ """Return the process-wide :class:`Settings` singleton.
233
+
234
+ Configuration is parsed and validated once per process; subsequent
235
+ calls return the cached instance, avoiding repeated environment
236
+ variable lookups and TOML file parsing.
237
+ """
238
+ return Settings()
239
+
240
+
241
+ def reload_settings() -> Settings:
242
+ """Clear the cached :class:`Settings` singleton and reconstruct it.
243
+
244
+ Primarily useful in tests that mutate environment variables or
245
+ config files and need :func:`get_settings` to reflect the change on
246
+ its next call.
247
+ """
248
+ get_settings.cache_clear()
249
+ return get_settings()
@@ -0,0 +1,21 @@
1
+ """Core domain types, interfaces, and shared abstractions.
2
+
3
+ Currently provides the exception hierarchy every other subpackage raises
4
+ from; see :mod:`forecastforge.core.errors`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from forecastforge.core.errors import (
10
+ DataError,
11
+ DataValidationError,
12
+ ForecastForgeError,
13
+ MissingOptionalDependencyError,
14
+ )
15
+
16
+ __all__ = [
17
+ "DataError",
18
+ "DataValidationError",
19
+ "ForecastForgeError",
20
+ "MissingOptionalDependencyError",
21
+ ]