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,41 @@
1
+ """ForecastForge: an open-source time-series forecasting library.
2
+
3
+ Implemented:
4
+ * Core exception hierarchy and validated ``TimeSeries`` container.
5
+ * Structural validation (sorted DatetimeIndex, numeric/finite/NaN checks,
6
+ optional gap detection).
7
+ * Data ingestion layer: ``DataSource`` protocol, deterministic synthetic
8
+ OHLCV generator, optional Yahoo Finance connector (cached to Parquet),
9
+ and CSV/Parquet file loaders.
10
+ * Feature engineering: ``FeatureSet`` container, causal transforms (lags,
11
+ rolling statistics, returns, volatility, RSI, MACD, calendar features),
12
+ and an ordered ``FeaturePipeline`` with a leakage test suite.
13
+ * Forecasting models: a ``Forecaster`` base class with the shared
14
+ fit/predict contract, four dependency-free baselines, and optional
15
+ ETS, ARIMA, and LightGBM forecasters behind the ``[models]`` extra.
16
+ * Evaluation: MAE, RMSE, sMAPE, MASE, directional accuracy, interval
17
+ coverage, a leakage-safe walk-forward backtester, and a reproducible
18
+ benchmark.
19
+ * Orchestration: a seed-to-backtest ``pipelines`` module and the
20
+ ``forecastforge`` console script (``info``, ``validate``, ``generate``,
21
+ ``features``, ``backtest``, ``pipeline``).
22
+
23
+ Still planned:
24
+ * Experiment tracking, serving, monitoring, and containerised deployment.
25
+
26
+ This module exposes package metadata so that the package is importable and
27
+ its version can be introspected by tooling (pip, build backends, CI, docs).
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ from importlib import metadata
33
+
34
+ try:
35
+ __version__: str = metadata.version("forecastforge")
36
+ except metadata.PackageNotFoundError: # pragma: no cover
37
+ # Package is not installed (e.g. running from a source checkout without
38
+ # `pip install -e .`). Fall back to a development sentinel version.
39
+ __version__ = "0.0.0.dev0"
40
+
41
+ __all__ = ["__version__"]
@@ -0,0 +1,12 @@
1
+ """Command-line interface for ForecastForge.
2
+
3
+ Exports :func:`main`, the console-script entry point declared in
4
+ ``pyproject.toml`` as ``forecastforge``, and :func:`build_parser` for
5
+ introspection and tests.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from forecastforge.cli.main import build_parser, main
11
+
12
+ __all__ = ["build_parser", "main"]
@@ -0,0 +1,13 @@
1
+ """``python -m forecastforge.cli`` entry point.
2
+
3
+ Mirrors the ``forecastforge`` console script so the CLI can be invoked from
4
+ a source checkout — or any environment where the entry-point script is not
5
+ on ``PATH`` — without an editable install.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from forecastforge.cli.main import main
11
+
12
+ if __name__ == "__main__":
13
+ raise SystemExit(main())
@@ -0,0 +1,477 @@
1
+ """The ForecastForge command-line interface.
2
+
3
+ Each subcommand drives one implemented stage end to end:
4
+
5
+ * ``info`` — package, runtime, environment, device, and seed summary.
6
+ * ``validate`` — load a CSV or Parquet file and check it against the
7
+ :class:`~forecastforge.schemas.TimeSeries` contract.
8
+ * ``generate`` — write a deterministic synthetic OHLCV series to disk.
9
+ * ``features`` — run the demo feature pipeline over a file and report the
10
+ warm-up region.
11
+ * ``backtest`` — walk-forward backtest the baselines over a file.
12
+ * ``forecast`` — fit the baselines on a file and forecast the next steps.
13
+ * ``pipeline`` — generate a series from a seed and backtest it in one call
14
+ (see :mod:`forecastforge.pipelines`).
15
+
16
+ All commands run offline; none of them touch the network.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import signal
23
+ import sys
24
+ import warnings
25
+ from collections.abc import Callable, Sequence
26
+ from pathlib import Path
27
+ from typing import cast
28
+
29
+ import pandas as pd
30
+
31
+ import forecastforge
32
+ from forecastforge.config import get_environment, get_runtime_info, get_settings
33
+ from forecastforge.core.errors import DataError, DataValidationError, ForecastForgeError
34
+ from forecastforge.data import (
35
+ SyntheticConfig,
36
+ SyntheticSource,
37
+ read_csv,
38
+ read_parquet,
39
+ write_csv,
40
+ write_parquet,
41
+ )
42
+ from forecastforge.evaluation import BacktestConfig, WalkForwardBacktester
43
+ from forecastforge.features import (
44
+ MACD,
45
+ RSI,
46
+ CalendarFeatures,
47
+ FeaturePipeline,
48
+ Lag,
49
+ Returns,
50
+ RollingStat,
51
+ Volatility,
52
+ )
53
+ from forecastforge.pipelines import PipelineConfig, build_models, run
54
+ from forecastforge.schemas import TimeSeries, TimeSeriesMetadata
55
+
56
+ __all__ = ["build_parser", "main"]
57
+
58
+ # The demo feature pipeline from examples/02_features.py, reused so the CLI
59
+ # and the example demonstrate the same transforms on the same terms.
60
+ DEMO_PIPELINE = FeaturePipeline(
61
+ [
62
+ Lag([1, 5, 10]),
63
+ RollingStat(window=20, stat="mean"),
64
+ Returns(periods=1, log=True),
65
+ Volatility(window=20),
66
+ RSI(window=14),
67
+ MACD(),
68
+ CalendarFeatures(["dayofweek", "month_cyclic"]),
69
+ ]
70
+ )
71
+
72
+
73
+ def _restore_sigpipe() -> None:
74
+ """Die silently when the output pipe closes early.
75
+
76
+ Python converts SIGPIPE into a ``BrokenPipeError`` flushed at shutdown,
77
+ which prints a traceback when a reader such as ``head`` closes the pipe
78
+ after the first lines. The default POSIX behavior -- exit quietly -- is
79
+ what a CLI user expects. Windows has no SIGPIPE, so it is left alone.
80
+ """
81
+ if hasattr(signal, "SIGPIPE"):
82
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
83
+
84
+
85
+ def _emit(text: str) -> None:
86
+ """Write ``text`` to standard output.
87
+
88
+ ``print`` is banned in the package by the lint configuration, and the CLI
89
+ is the place that legitimately needs raw output.
90
+ """
91
+ sys.stdout.write(text if text.endswith("\n") else f"{text}\n")
92
+
93
+
94
+ def _fail(text: str) -> None:
95
+ """Write ``text`` to standard error as the command's failure reason."""
96
+ sys.stderr.write(text if text.endswith("\n") else f"{text}\n")
97
+
98
+
99
+ def _split_models(raw: str) -> tuple[str, ...]:
100
+ """Split a comma-separated model list, dropping blanks and duplicates."""
101
+ names = tuple(dict.fromkeys(name.strip() for name in raw.split(",") if name.strip()))
102
+ if not names:
103
+ raise DataError("--models names at least one model")
104
+ return names
105
+
106
+
107
+ def _read_frame(path: Path) -> pd.DataFrame:
108
+ """Read a frame by file suffix; anything but CSV or Parquet is rejected."""
109
+ suffix = path.suffix.lower()
110
+ if suffix == ".csv":
111
+ return read_csv(path)
112
+ if suffix == ".parquet":
113
+ return read_parquet(path)
114
+ raise DataError(f"unsupported file format {suffix!r}: use .csv or .parquet")
115
+
116
+
117
+ def _load_series(path: Path, target: str) -> TimeSeries:
118
+ """Read ``path`` and wrap it in a validated :class:`TimeSeries`."""
119
+ frame = _read_frame(path)
120
+ metadata = TimeSeriesMetadata(symbol=path.stem, source="file")
121
+ return TimeSeries(frame=frame, target=target, metadata=metadata)
122
+
123
+
124
+ def _future_index(index: pd.DatetimeIndex, horizon: int) -> pd.DatetimeIndex:
125
+ """Build the timestamps the next ``horizon`` forecasts land on.
126
+
127
+ The cadence is the series' own frequency: the explicit ``freq`` attribute
128
+ when the loader preserved one, otherwise the cadence pandas can infer from
129
+ the timestamps. A series whose spacing is irregular cannot place its
130
+ forecast on the calendar, so the command refuses rather than invent dates.
131
+
132
+ Raises:
133
+ DataValidationError: If no regular frequency can be established.
134
+ """
135
+ # pandas 4 will return a BaseOffset from infer_freq instead of a string;
136
+ # both are accepted by pd.date_range. The transition warning is noise for
137
+ # this call site, and an outright error under the strict pytest filter,
138
+ # so it is scoped away for the duration of the call.
139
+ pandas4_warning = getattr(pd.errors, "Pandas4Warning", Warning)
140
+ with warnings.catch_warnings():
141
+ warnings.simplefilter("ignore", pandas4_warning)
142
+ try:
143
+ freq = index.freqstr or pd.infer_freq(index)
144
+ except ValueError:
145
+ freq = None
146
+ if freq is None:
147
+ raise DataValidationError(
148
+ "cannot infer a regular frequency from the series index; "
149
+ "fill the missing periods or resample the series first"
150
+ )
151
+ return pd.date_range(start=index[-1], periods=horizon + 1, freq=freq)[1:]
152
+
153
+
154
+ def _write_frame(frame: pd.DataFrame, path: Path) -> Path:
155
+ """Write ``frame`` to ``path``; the suffix picks CSV or Parquet."""
156
+ suffix = path.suffix.lower()
157
+ if suffix == ".csv":
158
+ return write_csv(frame, path)
159
+ if suffix == ".parquet":
160
+ return write_parquet(frame, path)
161
+ raise DataError(f"unsupported output format {suffix!r}: use .csv or .parquet")
162
+
163
+
164
+ def _cmd_info(args: argparse.Namespace) -> int:
165
+ """Report the package version and the resolved runtime configuration."""
166
+ del args # the info command takes no options
167
+ settings = get_settings()
168
+ runtime = get_runtime_info()
169
+ _emit(f"ForecastForge {forecastforge.__version__}")
170
+ _emit(f"Python {runtime.python_version}")
171
+ _emit(f"Platform {runtime.platform_system} {runtime.platform_release}")
172
+ _emit(f"Environment {get_environment().value}")
173
+ _emit(f"Device {settings.resolved_device().value}")
174
+ _emit(f"Random seed {settings.random_seed}")
175
+ _emit(f"CI run {'yes' if runtime.is_ci else 'no'}")
176
+ return 0
177
+
178
+
179
+ def _cmd_validate(args: argparse.Namespace) -> int:
180
+ """Load a file and validate it against the TimeSeries contract."""
181
+ series = _load_series(Path(args.path), args.target)
182
+ _emit(f"file : {args.path}")
183
+ _emit(f"rows : {len(series)}")
184
+ _emit(f"columns : {', '.join(series.frame.columns)}")
185
+ _emit(f"target : {series.target}")
186
+ _emit(f"range : {series.index[0].date()} to {series.index[-1].date()}")
187
+ _emit("validation: OK")
188
+ return 0
189
+
190
+
191
+ def _cmd_generate(args: argparse.Namespace) -> int:
192
+ """Generate a deterministic synthetic OHLCV series and write it to disk."""
193
+ output = Path(args.output) if args.output else Path("data/raw") / f"{args.symbol.lower()}.csv"
194
+ config = SyntheticConfig(
195
+ seed=args.seed,
196
+ length=args.length,
197
+ frequency=args.frequency,
198
+ start=pd.Timestamp(args.start),
199
+ )
200
+ series = SyntheticSource(config=config).fetch(symbol=args.symbol)
201
+ _write_frame(series.frame, output)
202
+ _emit(f"wrote {len(series)} rows ({args.symbol}, seed {args.seed}) to {output}")
203
+ return 0
204
+
205
+
206
+ def _cmd_features(args: argparse.Namespace) -> int:
207
+ """Run the demo feature pipeline over a file and report the warm-up."""
208
+ series = _load_series(Path(args.path), args.target)
209
+ features = DEMO_PIPELINE.apply(series)
210
+ _emit(f"series rows : {len(features)}")
211
+ _emit(f"feature columns: {len(features.features)}")
212
+ for name in features.features:
213
+ first_valid = features.frame[name].first_valid_index()
214
+ # The frame's DatetimeIndex guarantees Timestamp labels; the stubs
215
+ # type first_valid_index() as a broader scalar union.
216
+ label = "never" if first_valid is None else str(cast("pd.Timestamp", first_valid).date())
217
+ _emit(f" {name:36s} first valid {label}")
218
+ _emit(f"warm-up rows : {features.warmup} of {len(features)}")
219
+ usable = features.drop_warmup()
220
+ share = len(usable) / len(features)
221
+ _emit(f"usable rows : {len(usable)} ({share:.0%} of the series)")
222
+ _emit(f"complete : {usable.is_complete}")
223
+ if args.output:
224
+ _write_frame(features.frame, Path(args.output))
225
+ _emit(f"features written to {args.output}")
226
+ return 0
227
+
228
+
229
+ def _cmd_backtest(args: argparse.Namespace) -> int:
230
+ """Backtest the baselines over a file with the walk-forward harness."""
231
+ series = _load_series(Path(args.path), args.target)
232
+ models = build_models(
233
+ _split_models(args.models),
234
+ args.horizon,
235
+ seasonal_period=args.seasonal_period,
236
+ moving_average_window=args.ma_window,
237
+ drift_window=args.drift_window,
238
+ )
239
+ backtester = WalkForwardBacktester(
240
+ BacktestConfig(
241
+ horizon=args.horizon,
242
+ initial_train=args.initial_train,
243
+ step=args.step,
244
+ gap=args.gap,
245
+ window=args.window,
246
+ seasonal_period=args.seasonal_period,
247
+ )
248
+ )
249
+ result = backtester.run(series.target_series, models)
250
+ _emit(f"series : {len(series)} rows, {series.index[0].date()} to {series.index[-1].date()}")
251
+ _emit(
252
+ f"folds : {len(result.folds)} (horizon {args.horizon}, step {args.step}, "
253
+ f"gap {args.gap}, window {args.window or 'expanding'})"
254
+ )
255
+ _emit("")
256
+ _emit(result.summary().round(4).to_string())
257
+ return 0
258
+
259
+
260
+ def _cmd_forecast(args: argparse.Namespace) -> int:
261
+ """Fit the baselines on the full history and forecast the next steps."""
262
+ series = _load_series(Path(args.path), args.target)
263
+ models = build_models(
264
+ _split_models(args.models),
265
+ args.horizon,
266
+ seasonal_period=args.seasonal_period,
267
+ moving_average_window=args.ma_window,
268
+ drift_window=args.drift_window,
269
+ )
270
+ stamps = _future_index(series.index, args.horizon)
271
+ records: list[dict[str, object]] = []
272
+ for name, model in models.items():
273
+ model.fit(series.target_series)
274
+ for step, value in enumerate(model.predict(), start=1):
275
+ records.append(
276
+ {
277
+ "model": name,
278
+ "step": step,
279
+ "timestamp": stamps[step - 1],
280
+ "forecast": float(value),
281
+ }
282
+ )
283
+ frame = pd.DataFrame(records)
284
+ display = frame.copy()
285
+ display["timestamp"] = display["timestamp"].dt.strftime("%Y-%m-%d")
286
+ display["forecast"] = display["forecast"].round(4)
287
+ _emit(f"file : {args.path}")
288
+ _emit(f"history : {len(series)} rows, {series.index[0].date()} to {series.index[-1].date()}")
289
+ _emit(f"horizon : {args.horizon} steps, {stamps[0].date()} to {stamps[-1].date()}")
290
+ _emit("")
291
+ _emit(display.to_string(index=False))
292
+ if args.output:
293
+ # The package's file convention carries timestamps in the index
294
+ # column (write_csv keeps the index, read_csv restores it), so the
295
+ # tidy frame ships with timestamp as its index rather than a column.
296
+ _write_frame(frame.set_index("timestamp"), Path(args.output))
297
+ _emit(f"forecasts written to {args.output}")
298
+ return 0
299
+
300
+
301
+ def _cmd_pipeline(args: argparse.Namespace) -> int:
302
+ """Generate a series from a seed and backtest it in one call."""
303
+ config = PipelineConfig(
304
+ symbol=args.symbol,
305
+ seed=args.seed,
306
+ length=args.length,
307
+ horizon=args.horizon,
308
+ initial_train=args.initial_train,
309
+ step=args.step,
310
+ gap=args.gap,
311
+ window=args.window,
312
+ seasonal_period=args.seasonal_period,
313
+ models=_split_models(args.models),
314
+ moving_average_window=args.ma_window,
315
+ drift_window=args.drift_window,
316
+ )
317
+ outcome = run(config)
318
+ _emit(
319
+ f"series : {len(outcome.series)} rows ({config.symbol}, seed {config.seed}, "
320
+ f"{outcome.series.index[0].date()} to {outcome.series.index[-1].date()})"
321
+ )
322
+ _emit(f"folds : {len(outcome.result.folds)} (horizon {config.horizon}, step {config.step})")
323
+ _emit("")
324
+ _emit(outcome.result.summary().round(4).to_string())
325
+ return 0
326
+
327
+
328
+ def _add_file_options(parser: argparse.ArgumentParser) -> None:
329
+ """Add the positional input file and target column shared by file commands."""
330
+ parser.add_argument("path", type=Path, help="input file (.csv or .parquet)")
331
+ parser.add_argument("--target", default="close", help="column to forecast (default: close)")
332
+
333
+
334
+ def _add_baseline_options(parser: argparse.ArgumentParser) -> None:
335
+ """Add the shared baseline-model options to a subparser.
336
+
337
+ ``backtest``, ``forecast``, and ``pipeline`` all drive the same baseline
338
+ factory (see ``build_models``), so their model options are declared once
339
+ here instead of drifting apart in three copies.
340
+ """
341
+ parser.add_argument(
342
+ "--models",
343
+ default="naive,drift",
344
+ help="comma-separated baselines: naive, seasonal_naive, moving_average, drift",
345
+ )
346
+ parser.add_argument(
347
+ "--seasonal-period",
348
+ type=int,
349
+ default=5,
350
+ dest="seasonal_period",
351
+ help="season lag for seasonal_naive and the MASE scale",
352
+ )
353
+ parser.add_argument(
354
+ "--ma-window",
355
+ type=int,
356
+ default=20,
357
+ dest="ma_window",
358
+ help="trailing window for moving_average",
359
+ )
360
+ parser.add_argument(
361
+ "--drift-window",
362
+ type=int,
363
+ default=60,
364
+ dest="drift_window",
365
+ help="trailing window for drift",
366
+ )
367
+
368
+
369
+ def build_parser() -> argparse.ArgumentParser:
370
+ """Build the ``forecastforge`` argument parser."""
371
+ parser = argparse.ArgumentParser(
372
+ prog="forecastforge",
373
+ description=(
374
+ "Offline time-series forecasting utilities: validate data, generate "
375
+ "deterministic synthetic series, engineer features, backtest baselines, "
376
+ "and forecast the steps ahead."
377
+ ),
378
+ )
379
+ parser.add_argument(
380
+ "--version",
381
+ action="version",
382
+ version=f"ForecastForge {forecastforge.__version__}",
383
+ )
384
+ subparsers = parser.add_subparsers(dest="command", required=True, metavar="command")
385
+
386
+ info = subparsers.add_parser("info", help="show the resolved runtime configuration")
387
+ info.set_defaults(handler=_cmd_info)
388
+
389
+ validate = subparsers.add_parser("validate", help="validate a CSV or Parquet file")
390
+ _add_file_options(validate)
391
+ validate.set_defaults(handler=_cmd_validate)
392
+
393
+ generate = subparsers.add_parser(
394
+ "generate", help="write a deterministic synthetic OHLCV series"
395
+ )
396
+ generate.add_argument("--symbol", default="SPY", help="ticker id recorded in metadata")
397
+ generate.add_argument("--seed", type=int, default=42, help="generator seed (default: 42)")
398
+ generate.add_argument("--length", type=int, default=504, help="rows to generate")
399
+ generate.add_argument("--frequency", default="B", help="pandas offset alias (default: B)")
400
+ generate.add_argument("--start", default="2015-01-02", help="first timestamp")
401
+ generate.add_argument(
402
+ "--output",
403
+ help="destination file (.csv or .parquet); default data/raw/<symbol>.csv",
404
+ )
405
+ generate.set_defaults(handler=_cmd_generate)
406
+
407
+ features = subparsers.add_parser("features", help="run the demo feature pipeline over a file")
408
+ _add_file_options(features)
409
+ features.add_argument("--output", help="write the feature frame to this file")
410
+ features.set_defaults(handler=_cmd_features)
411
+
412
+ backtest = subparsers.add_parser(
413
+ "backtest", help="walk-forward backtest the baselines over a file"
414
+ )
415
+ _add_file_options(backtest)
416
+ backtest.add_argument("--horizon", type=int, default=1, help="rows forecast per origin")
417
+ backtest.add_argument(
418
+ "--initial-train",
419
+ type=int,
420
+ default=252,
421
+ dest="initial_train",
422
+ help="rows before the first origin",
423
+ )
424
+ backtest.add_argument("--step", type=int, default=1, help="rows between origins")
425
+ backtest.add_argument("--gap", type=int, default=0, help="embargoed rows per fold")
426
+ backtest.add_argument("--window", type=int, default=None, help="rolling window length")
427
+ _add_baseline_options(backtest)
428
+ backtest.set_defaults(handler=_cmd_backtest)
429
+
430
+ forecast = subparsers.add_parser(
431
+ "forecast", help="fit the baselines on a file and forecast the next steps"
432
+ )
433
+ _add_file_options(forecast)
434
+ forecast.add_argument("--horizon", type=int, default=1, help="rows to forecast")
435
+ _add_baseline_options(forecast)
436
+ forecast.add_argument(
437
+ "--output",
438
+ help="write the tidy forecast frame to this file (.csv or .parquet)",
439
+ )
440
+ forecast.set_defaults(handler=_cmd_forecast)
441
+
442
+ pipeline = subparsers.add_parser(
443
+ "pipeline", help="generate a series from a seed and backtest it"
444
+ )
445
+ pipeline.add_argument("--symbol", default="SPY")
446
+ pipeline.add_argument("--seed", type=int, default=42)
447
+ pipeline.add_argument("--length", type=int, default=504)
448
+ pipeline.add_argument("--horizon", type=int, default=1)
449
+ pipeline.add_argument("--initial-train", type=int, default=252, dest="initial_train")
450
+ pipeline.add_argument("--step", type=int, default=1)
451
+ pipeline.add_argument("--gap", type=int, default=0)
452
+ pipeline.add_argument("--window", type=int, default=None)
453
+ _add_baseline_options(pipeline)
454
+ pipeline.set_defaults(handler=_cmd_pipeline)
455
+
456
+ return parser
457
+
458
+
459
+ def main(argv: Sequence[str] | None = None) -> int:
460
+ """Run the CLI.
461
+
462
+ Args:
463
+ argv: Arguments to parse; ``sys.argv[1:]`` when ``None``.
464
+
465
+ Returns:
466
+ ``0`` on success, ``1`` when a command fails with a data, file, or
467
+ validation error. Usage errors exit with code ``2`` via argparse.
468
+ """
469
+ parser = build_parser()
470
+ _restore_sigpipe()
471
+ args = parser.parse_args(argv)
472
+ handler: Callable[[argparse.Namespace], int] = args.handler
473
+ try:
474
+ return handler(args)
475
+ except (ForecastForgeError, OSError) as error:
476
+ _fail(f"error: {error}")
477
+ return 1
@@ -0,0 +1,6 @@
1
+ """Common, dependency-light helpers shared across the codebase.
2
+
3
+ This package will hold small, broadly-reusable utilities that do not
4
+ belong to a specific pipeline stage (e.g. constants, shared type
5
+ aliases). No implementation exists yet.
6
+ """
@@ -0,0 +1,61 @@
1
+ """Configuration loading and validation for ForecastForge.
2
+
3
+ This is the entry point other ForecastForge packages should use to
4
+ access application configuration, path resolution, environment/runtime
5
+ detection, compute device detection, and reproducibility seeding. See
6
+ ``docs/development.md`` for a description of the configuration
7
+ hierarchy and file layout.
8
+
9
+ Typical usage::
10
+
11
+ from forecastforge.config import get_settings, set_seed
12
+
13
+ settings = get_settings()
14
+ set_seed(settings.random_seed)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from forecastforge.config.device import DeviceType, detect_device, resolve_device
20
+ from forecastforge.config.environment import Environment, get_environment
21
+ from forecastforge.config.paths import (
22
+ get_artifacts_dir,
23
+ get_configs_dir,
24
+ get_data_dir,
25
+ get_external_data_dir,
26
+ get_interim_data_dir,
27
+ get_mlruns_dir,
28
+ get_models_dir,
29
+ get_processed_data_dir,
30
+ get_project_root,
31
+ get_raw_data_dir,
32
+ resolve_path,
33
+ )
34
+ from forecastforge.config.runtime import RuntimeInfo, get_runtime_info
35
+ from forecastforge.config.seed import set_seed
36
+ from forecastforge.config.settings import Settings, get_settings, reload_settings
37
+
38
+ __all__ = [
39
+ "DeviceType",
40
+ "Environment",
41
+ "RuntimeInfo",
42
+ "Settings",
43
+ "detect_device",
44
+ "get_artifacts_dir",
45
+ "get_configs_dir",
46
+ "get_data_dir",
47
+ "get_environment",
48
+ "get_external_data_dir",
49
+ "get_interim_data_dir",
50
+ "get_mlruns_dir",
51
+ "get_models_dir",
52
+ "get_processed_data_dir",
53
+ "get_project_root",
54
+ "get_raw_data_dir",
55
+ "get_runtime_info",
56
+ "get_settings",
57
+ "reload_settings",
58
+ "resolve_device",
59
+ "resolve_path",
60
+ "set_seed",
61
+ ]
@@ -0,0 +1,39 @@
1
+ """Access to third-party modules that may or may not be installed.
2
+
3
+ NumPy and PyTorch are *optional* for ForecastForge: the package must import
4
+ and behave correctly whether or not they are present. A plain top-level
5
+ ``import numpy`` cannot express that requirement, while an ``import`` hidden
6
+ inside a function body hides the dependency from readers and from tooling
7
+ that builds an import graph.
8
+
9
+ This module centralises the optional-import policy in one documented place so
10
+ that call sites stay uniform and reviewable.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from importlib import import_module
16
+ from types import ModuleType
17
+
18
+ __all__ = ["optional_import"]
19
+
20
+
21
+ def optional_import(module_name: str) -> ModuleType | None:
22
+ """Import an optional module, returning ``None`` when it is unavailable.
23
+
24
+ A module that is installed but fails to import (for example a broken
25
+ native build) is treated as unavailable rather than propagating the
26
+ error: optional accelerators must never be able to break the core
27
+ package, and callers already have a well-defined fallback path.
28
+
29
+ Args:
30
+ module_name: Fully qualified name of the module to import, e.g.
31
+ ``"numpy"`` or ``"torch.backends"``.
32
+
33
+ Returns:
34
+ The imported module, or ``None`` if it could not be imported.
35
+ """
36
+ try:
37
+ return import_module(module_name)
38
+ except ImportError:
39
+ return None