macroforecast 0.1.0__tar.gz

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 (62) hide show
  1. macroforecast-0.1.0/.gitignore +49 -0
  2. macroforecast-0.1.0/LICENSE +21 -0
  3. macroforecast-0.1.0/PKG-INFO +156 -0
  4. macroforecast-0.1.0/README.md +83 -0
  5. macroforecast-0.1.0/macroforecast/__init__.py +85 -0
  6. macroforecast-0.1.0/macroforecast/cli.py +293 -0
  7. macroforecast-0.1.0/macroforecast/config.py +604 -0
  8. macroforecast-0.1.0/macroforecast/data/__init__.py +30 -0
  9. macroforecast-0.1.0/macroforecast/data/_base.py +390 -0
  10. macroforecast-0.1.0/macroforecast/data/fred_md.py +160 -0
  11. macroforecast-0.1.0/macroforecast/data/fred_qd.py +144 -0
  12. macroforecast-0.1.0/macroforecast/data/fred_sd.py +184 -0
  13. macroforecast-0.1.0/macroforecast/data/merge.py +283 -0
  14. macroforecast-0.1.0/macroforecast/data/schema.py +468 -0
  15. macroforecast-0.1.0/macroforecast/data/specs/__init__.py +0 -0
  16. macroforecast-0.1.0/macroforecast/data/specs/fred_md.json +144 -0
  17. macroforecast-0.1.0/macroforecast/data/specs/fred_qd.json +50 -0
  18. macroforecast-0.1.0/macroforecast/data/specs/fred_sd.json +31 -0
  19. macroforecast-0.1.0/macroforecast/data/vintages.py +174 -0
  20. macroforecast-0.1.0/macroforecast/evaluation/__init__.py +60 -0
  21. macroforecast-0.1.0/macroforecast/evaluation/combination.py +222 -0
  22. macroforecast-0.1.0/macroforecast/evaluation/cw.py +167 -0
  23. macroforecast-0.1.0/macroforecast/evaluation/decomposition.py +188 -0
  24. macroforecast-0.1.0/macroforecast/evaluation/dm.py +156 -0
  25. macroforecast-0.1.0/macroforecast/evaluation/gw.py +209 -0
  26. macroforecast-0.1.0/macroforecast/evaluation/horserace.py +441 -0
  27. macroforecast-0.1.0/macroforecast/evaluation/mcs.py +223 -0
  28. macroforecast-0.1.0/macroforecast/evaluation/metrics.py +78 -0
  29. macroforecast-0.1.0/macroforecast/evaluation/regime.py +236 -0
  30. macroforecast-0.1.0/macroforecast/interpretation/__init__.py +49 -0
  31. macroforecast-0.1.0/macroforecast/interpretation/dual.py +248 -0
  32. macroforecast-0.1.0/macroforecast/interpretation/marginal.py +634 -0
  33. macroforecast-0.1.0/macroforecast/interpretation/pbsv.py +259 -0
  34. macroforecast-0.1.0/macroforecast/interpretation/variable_importance.py +248 -0
  35. macroforecast-0.1.0/macroforecast/mcp/__init__.py +5 -0
  36. macroforecast-0.1.0/macroforecast/mcp/config.py +173 -0
  37. macroforecast-0.1.0/macroforecast/mcp/indexer.py +314 -0
  38. macroforecast-0.1.0/macroforecast/mcp/ingest_blog.py +105 -0
  39. macroforecast-0.1.0/macroforecast/mcp/ingest_pdf.py +83 -0
  40. macroforecast-0.1.0/macroforecast/mcp/server.py +245 -0
  41. macroforecast-0.1.0/macroforecast/pipeline/__init__.py +83 -0
  42. macroforecast-0.1.0/macroforecast/pipeline/components.py +176 -0
  43. macroforecast-0.1.0/macroforecast/pipeline/estimator.py +133 -0
  44. macroforecast-0.1.0/macroforecast/pipeline/experiment.py +693 -0
  45. macroforecast-0.1.0/macroforecast/pipeline/features.py +489 -0
  46. macroforecast-0.1.0/macroforecast/pipeline/horserace.py +169 -0
  47. macroforecast-0.1.0/macroforecast/pipeline/models.py +957 -0
  48. macroforecast-0.1.0/macroforecast/pipeline/r_models.py +506 -0
  49. macroforecast-0.1.0/macroforecast/pipeline/results.py +373 -0
  50. macroforecast-0.1.0/macroforecast/preprocessing/__init__.py +54 -0
  51. macroforecast-0.1.0/macroforecast/preprocessing/missing.py +200 -0
  52. macroforecast-0.1.0/macroforecast/preprocessing/panel.py +506 -0
  53. macroforecast-0.1.0/macroforecast/preprocessing/transforms.py +398 -0
  54. macroforecast-0.1.0/macroforecast/replication/__init__.py +8 -0
  55. macroforecast-0.1.0/macroforecast/replication/clss2021.py +340 -0
  56. macroforecast-0.1.0/macroforecast/utils/__init__.py +24 -0
  57. macroforecast-0.1.0/macroforecast/utils/cache.py +199 -0
  58. macroforecast-0.1.0/macroforecast/utils/latex.py +310 -0
  59. macroforecast-0.1.0/macroforecast/utils/registry.py +301 -0
  60. macroforecast-0.1.0/macroforecast/viz/__init__.py +19 -0
  61. macroforecast-0.1.0/macroforecast/viz/plots.py +966 -0
  62. macroforecast-0.1.0/pyproject.toml +119 -0
@@ -0,0 +1,49 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .eggs/
8
+ *.egg
9
+
10
+ # Virtual environments
11
+ .venv/
12
+ venv/
13
+
14
+ # IDE
15
+ .vscode/
16
+ .idea/
17
+ *.swp
18
+ *.swo
19
+
20
+ # macrocast cache
21
+ .macrocast/
22
+
23
+ # Data (downloaded, not committed)
24
+ data_cache/
25
+ *.csv.gz
26
+
27
+ # R
28
+ macrocastR/.Rproj.user
29
+ macrocastR/src/*.o
30
+ macrocastR/src/*.so
31
+
32
+ # OS
33
+ .DS_Store
34
+ Thumbs.db
35
+
36
+ # Secrets
37
+ .env
38
+ .env.local
39
+
40
+ # Claude Code local settings
41
+ .claude/settings.local.json
42
+ .claude/session-*.md
43
+
44
+ # mkdocs build output
45
+ site/
46
+
47
+ # Notebook outputs (examples/results/ is gitignored)
48
+ examples/results/
49
+ .worktrees/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.4
2
+ Name: macroforecast
3
+ Version: 0.1.0
4
+ Summary: Decomposing ML Forecast Gains in Macroeconomic Forecasting
5
+ Project-URL: Documentation, https://macroforecast.github.io/macroforecast
6
+ Project-URL: Repository, https://github.com/macroforecast/macroforecast
7
+ Project-URL: Issues, https://github.com/macroforecast/macroforecast/issues
8
+ Author: Chan
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: FRED,forecasting,machine-learning,macroeconomics
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: joblib>=1.3
19
+ Requires-Dist: numpy>=1.24
20
+ Requires-Dist: openpyxl>=3.1
21
+ Requires-Dist: pandas>=2.0
22
+ Requires-Dist: pyyaml>=6.0
23
+ Requires-Dist: requests>=2.31
24
+ Requires-Dist: scikit-learn>=1.3
25
+ Requires-Dist: scipy>=1.11
26
+ Requires-Dist: statsmodels>=0.14
27
+ Requires-Dist: tqdm>=4.65
28
+ Provides-Extra: all
29
+ Requires-Dist: beautifulsoup4>=4.12.0; extra == 'all'
30
+ Requires-Dist: chromadb>=0.4.0; extra == 'all'
31
+ Requires-Dist: einops>=0.8.2; extra == 'all'
32
+ Requires-Dist: lightgbm>=4.0; extra == 'all'
33
+ Requires-Dist: matplotlib>=3.7; extra == 'all'
34
+ Requires-Dist: mcp[cli]>=1.2.0; extra == 'all'
35
+ Requires-Dist: mkdocs-material>=9.4; extra == 'all'
36
+ Requires-Dist: mkdocstrings[python]>=0.23; extra == 'all'
37
+ Requires-Dist: mypy>=1.5; extra == 'all'
38
+ Requires-Dist: pre-commit>=3.4; extra == 'all'
39
+ Requires-Dist: pyarrow>=14.0; extra == 'all'
40
+ Requires-Dist: pymupdf>=1.23.0; extra == 'all'
41
+ Requires-Dist: pytest-cov>=4.1; extra == 'all'
42
+ Requires-Dist: pytest>=7.4; extra == 'all'
43
+ Requires-Dist: ruff>=0.4; extra == 'all'
44
+ Requires-Dist: seaborn>=0.13; extra == 'all'
45
+ Requires-Dist: sentence-transformers>=2.2.0; extra == 'all'
46
+ Requires-Dist: torch>=2.0; extra == 'all'
47
+ Requires-Dist: xgboost>=2.0; extra == 'all'
48
+ Provides-Extra: dev
49
+ Requires-Dist: mypy>=1.5; extra == 'dev'
50
+ Requires-Dist: pre-commit>=3.4; extra == 'dev'
51
+ Requires-Dist: pytest-cov>=4.1; extra == 'dev'
52
+ Requires-Dist: pytest>=7.4; extra == 'dev'
53
+ Requires-Dist: ruff>=0.4; extra == 'dev'
54
+ Provides-Extra: docs
55
+ Requires-Dist: mkdocs-material>=9.4; extra == 'docs'
56
+ Requires-Dist: mkdocstrings[python]>=0.23; extra == 'docs'
57
+ Provides-Extra: ml
58
+ Requires-Dist: lightgbm>=4.0; extra == 'ml'
59
+ Requires-Dist: pyarrow>=14.0; extra == 'ml'
60
+ Requires-Dist: torch>=2.0; extra == 'ml'
61
+ Requires-Dist: xgboost>=2.0; extra == 'ml'
62
+ Provides-Extra: rag
63
+ Requires-Dist: beautifulsoup4>=4.12.0; extra == 'rag'
64
+ Requires-Dist: chromadb>=0.4.0; extra == 'rag'
65
+ Requires-Dist: einops>=0.8.2; extra == 'rag'
66
+ Requires-Dist: mcp[cli]>=1.2.0; extra == 'rag'
67
+ Requires-Dist: pymupdf>=1.23.0; extra == 'rag'
68
+ Requires-Dist: sentence-transformers>=2.2.0; extra == 'rag'
69
+ Provides-Extra: viz
70
+ Requires-Dist: matplotlib>=3.7; extra == 'viz'
71
+ Requires-Dist: seaborn>=0.13; extra == 'viz'
72
+ Description-Content-Type: text/markdown
73
+
74
+ # macroforecast
75
+
76
+ Decomposing ML Forecast Gains in Macroeconomic Forecasting.
77
+
78
+ An open-source Python (+ R) framework for systematic evaluation of machine learning methods in macroeconomic forecasting, with built-in support for the FRED-MD, FRED-QD, and FRED-SD database ecosystem.
79
+
80
+ [![CI](https://github.com/macroforecast/macroforecast/actions/workflows/ci.yml/badge.svg)](https://github.com/macroforecast/macroforecast/actions/workflows/ci.yml)
81
+ [![Docs](https://github.com/macroforecast/macroforecast/actions/workflows/docs.yml/badge.svg)](https://macroforecast.github.io/macroforecast)
82
+ [![PyPI](https://img.shields.io/pypi/v/macroforecast)](https://pypi.org/project/macroforecast/)
83
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
84
+
85
+ ---
86
+
87
+ ## Status
88
+
89
+ | Layer | Version | Status |
90
+ |-------|---------|--------|
91
+ | Data (FRED-MD/QD/SD) | v0.1.0 | Complete |
92
+ | Forecasting Pipeline | v0.2.0 | Complete |
93
+ | Evaluation | v0.3.0 | Complete |
94
+
95
+ ---
96
+
97
+ ## Installation
98
+
99
+ ```bash
100
+ pip install macroforecast
101
+ # or with all extras
102
+ pip install macroforecast[all]
103
+ ```
104
+
105
+ ---
106
+
107
+ ## Quick Start
108
+
109
+ ```python
110
+ import macroforecast as mc
111
+
112
+ # Load and transform FRED-MD (latest vintage, cached locally)
113
+ md = mc.load_fred_md()
114
+ md_t = md.transform()
115
+
116
+ print(md_t)
117
+ # MacroFrame(dataset='FRED-MD', vintage='current', T=790, N=128,
118
+ # period=1959-01-01 to 2024-10-01, status=transformed)
119
+
120
+ # Subset by variable group
121
+ output = md_t.group("output_income") # INDPRO, RPI, ...
122
+ prices = md_t.group("prices") # CPI, PPI, ...
123
+
124
+ # Check missing values
125
+ report = md.missing_report()
126
+ print(report[["n_leading", "n_trailing", "n_intermittent"]].head())
127
+
128
+ # Method chaining
129
+ md_ready = (
130
+ mc.load_fred_md()
131
+ .trim(start="1970-01", end="2023-12")
132
+ .handle_missing("trim_start")
133
+ .transform()
134
+ )
135
+
136
+ # Load a specific vintage
137
+ md_2020 = mc.load_fred_md(vintage="2020-01")
138
+
139
+ # FRED-QD (quarterly)
140
+ qd = mc.load_fred_qd()
141
+
142
+ # FRED-SD (state-level)
143
+ sd = mc.load_fred_sd(states=["CA", "TX"], variables=["UR"])
144
+ ```
145
+
146
+ ---
147
+
148
+ ## Documentation
149
+
150
+ Full documentation is available at [macroforecast.github.io/macroforecast](https://macroforecast.github.io/macroforecast).
151
+
152
+ ---
153
+
154
+ ## License
155
+
156
+ MIT
@@ -0,0 +1,83 @@
1
+ # macroforecast
2
+
3
+ Decomposing ML Forecast Gains in Macroeconomic Forecasting.
4
+
5
+ An open-source Python (+ R) framework for systematic evaluation of machine learning methods in macroeconomic forecasting, with built-in support for the FRED-MD, FRED-QD, and FRED-SD database ecosystem.
6
+
7
+ [![CI](https://github.com/macroforecast/macroforecast/actions/workflows/ci.yml/badge.svg)](https://github.com/macroforecast/macroforecast/actions/workflows/ci.yml)
8
+ [![Docs](https://github.com/macroforecast/macroforecast/actions/workflows/docs.yml/badge.svg)](https://macroforecast.github.io/macroforecast)
9
+ [![PyPI](https://img.shields.io/pypi/v/macroforecast)](https://pypi.org/project/macroforecast/)
10
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
11
+
12
+ ---
13
+
14
+ ## Status
15
+
16
+ | Layer | Version | Status |
17
+ |-------|---------|--------|
18
+ | Data (FRED-MD/QD/SD) | v0.1.0 | Complete |
19
+ | Forecasting Pipeline | v0.2.0 | Complete |
20
+ | Evaluation | v0.3.0 | Complete |
21
+
22
+ ---
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ pip install macroforecast
28
+ # or with all extras
29
+ pip install macroforecast[all]
30
+ ```
31
+
32
+ ---
33
+
34
+ ## Quick Start
35
+
36
+ ```python
37
+ import macroforecast as mc
38
+
39
+ # Load and transform FRED-MD (latest vintage, cached locally)
40
+ md = mc.load_fred_md()
41
+ md_t = md.transform()
42
+
43
+ print(md_t)
44
+ # MacroFrame(dataset='FRED-MD', vintage='current', T=790, N=128,
45
+ # period=1959-01-01 to 2024-10-01, status=transformed)
46
+
47
+ # Subset by variable group
48
+ output = md_t.group("output_income") # INDPRO, RPI, ...
49
+ prices = md_t.group("prices") # CPI, PPI, ...
50
+
51
+ # Check missing values
52
+ report = md.missing_report()
53
+ print(report[["n_leading", "n_trailing", "n_intermittent"]].head())
54
+
55
+ # Method chaining
56
+ md_ready = (
57
+ mc.load_fred_md()
58
+ .trim(start="1970-01", end="2023-12")
59
+ .handle_missing("trim_start")
60
+ .transform()
61
+ )
62
+
63
+ # Load a specific vintage
64
+ md_2020 = mc.load_fred_md(vintage="2020-01")
65
+
66
+ # FRED-QD (quarterly)
67
+ qd = mc.load_fred_qd()
68
+
69
+ # FRED-SD (state-level)
70
+ sd = mc.load_fred_sd(states=["CA", "TX"], variables=["UR"])
71
+ ```
72
+
73
+ ---
74
+
75
+ ## Documentation
76
+
77
+ Full documentation is available at [macroforecast.github.io/macroforecast](https://macroforecast.github.io/macroforecast).
78
+
79
+ ---
80
+
81
+ ## License
82
+
83
+ MIT
@@ -0,0 +1,85 @@
1
+ """macroforecast: Decomposing ML Forecast Gains in Macroeconomic Forecasting.
2
+
3
+ Modules
4
+ -------
5
+ * ``macroforecast.data`` — FRED-MD/QD/SD loaders + MacroFrame
6
+ * ``macroforecast.preprocessing`` — tcode transforms, MARX/MAF, panel preprocessing
7
+ * ``macroforecast.pipeline`` — ForecastExperiment, models, features
8
+ * ``macroforecast.evaluation`` — MSFE, MCS, DM, CW statistical tests
9
+ * ``macroforecast.interpretation`` — dual weights, PBSV, variable importance
10
+ * ``macroforecast.viz`` — visualization
11
+ * ``macroforecast.utils`` — registry, LaTeX export, cache
12
+ * ``macroforecast.replication`` — paper-specific helpers (CLSS 2021 etc.)
13
+
14
+ Quick start::
15
+
16
+ from macroforecast import load_fred_md, ForecastExperiment
17
+ """
18
+
19
+ __version__ = "0.1.0"
20
+
21
+ from macroforecast.data import (
22
+ MacroFrame,
23
+ MacroFrameMetadata,
24
+ MergeResult,
25
+ RealTimePanel,
26
+ VariableMetadata,
27
+ list_available_vintages,
28
+ load_fred_md,
29
+ load_fred_qd,
30
+ load_fred_sd,
31
+ load_vintage_panel,
32
+ merge_macro_frames,
33
+ )
34
+ from macroforecast.pipeline import (
35
+ FeatureSpec,
36
+ ForecastExperiment,
37
+ ForecastRecord,
38
+ ModelSpec,
39
+ ResultSet,
40
+ )
41
+ from macroforecast.preprocessing import (
42
+ TransformCode,
43
+ apply_hamilton_filter,
44
+ apply_maf,
45
+ apply_marx,
46
+ apply_pca,
47
+ apply_tcode,
48
+ apply_tcodes,
49
+ apply_x_factors,
50
+ classify_missing,
51
+ handle_missing,
52
+ )
53
+
54
+ __all__ = [
55
+ "__version__",
56
+ # data
57
+ "load_fred_md",
58
+ "load_fred_qd",
59
+ "load_fred_sd",
60
+ "MacroFrame",
61
+ "MacroFrameMetadata",
62
+ "VariableMetadata",
63
+ "list_available_vintages",
64
+ "load_vintage_panel",
65
+ "RealTimePanel",
66
+ "merge_macro_frames",
67
+ "MergeResult",
68
+ # preprocessing
69
+ "TransformCode",
70
+ "apply_tcode",
71
+ "apply_tcodes",
72
+ "apply_marx",
73
+ "apply_maf",
74
+ "apply_x_factors",
75
+ "apply_pca",
76
+ "apply_hamilton_filter",
77
+ "classify_missing",
78
+ "handle_missing",
79
+ # pipeline
80
+ "ForecastExperiment",
81
+ "ModelSpec",
82
+ "FeatureSpec",
83
+ "ResultSet",
84
+ "ForecastRecord",
85
+ ]
@@ -0,0 +1,293 @@
1
+ """macroforecast command-line interface.
2
+
3
+ Usage
4
+ -----
5
+ macroforecast --help
6
+ macroforecast run experiment.yaml
7
+ macroforecast init [--output experiment.yaml]
8
+ macroforecast info experiment.yaml
9
+
10
+ Commands
11
+ --------
12
+ run Execute a forecast experiment from a YAML config file.
13
+ init Write a default YAML config template to disk.
14
+ info Print a summary of the resolved config without running.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import logging
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ logger = logging.getLogger("macroforecast")
25
+
26
+
27
+ # ---------------------------------------------------------------------------
28
+ # Logging setup
29
+ # ---------------------------------------------------------------------------
30
+
31
+
32
+ def _setup_logging(verbose: bool = False) -> None:
33
+ level = logging.DEBUG if verbose else logging.INFO
34
+ logging.basicConfig(
35
+ format="%(asctime)s %(levelname)-8s %(name)s — %(message)s",
36
+ datefmt="%H:%M:%S",
37
+ level=level,
38
+ )
39
+
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # run
43
+ # ---------------------------------------------------------------------------
44
+
45
+
46
+ def _cmd_run(args: argparse.Namespace) -> int:
47
+ """Execute a forecast experiment defined in a YAML config file."""
48
+ from macroforecast.config import load_config
49
+ from macroforecast.pipeline.experiment import ForecastExperiment
50
+
51
+ try:
52
+ cfg = load_config(args.config)
53
+ except (FileNotFoundError, ValueError) as exc:
54
+ logger.error("Config error: %s", exc)
55
+ return 1
56
+
57
+ logger.info("Experiment: %s", cfg.experiment_id)
58
+ logger.info(
59
+ "Dataset: %s (target=%s, vintage=%s)",
60
+ cfg.data.dataset,
61
+ cfg.data.target,
62
+ cfg.data.vintage or "current",
63
+ )
64
+ logger.info("Models: %d configured", len(cfg.model_specs))
65
+ logger.info("Horizons: %s", cfg.horizons)
66
+ logger.info("Window: %s", cfg.window.value)
67
+ logger.info("OOS range: %s → %s", cfg.oos_start or "auto", cfg.oos_end or "end")
68
+
69
+ # Load data
70
+ try:
71
+ panel, target = _load_data(cfg)
72
+ except Exception as exc:
73
+ logger.error("Data loading failed: %s", exc)
74
+ return 1
75
+
76
+ output_dir = cfg.output_dir / cfg.experiment_id
77
+ output_dir.mkdir(parents=True, exist_ok=True)
78
+
79
+ exp = ForecastExperiment(
80
+ panel=panel,
81
+ target=target,
82
+ horizons=cfg.horizons,
83
+ model_specs=cfg.model_specs,
84
+ feature_spec=cfg.feature_spec,
85
+ window=cfg.window,
86
+ rolling_size=cfg.rolling_size,
87
+ oos_start=cfg.oos_start,
88
+ oos_end=cfg.oos_end,
89
+ n_jobs=cfg.n_jobs,
90
+ experiment_id=cfg.experiment_id,
91
+ output_dir=output_dir,
92
+ )
93
+
94
+ logger.info("Running experiment...")
95
+ rs = exp.run()
96
+
97
+ logger.info("Done. %d forecast records.", len(rs))
98
+
99
+ if args.summary:
100
+ _print_summary(rs)
101
+
102
+ return 0
103
+
104
+
105
+ def _load_data(cfg):
106
+ """Load dataset and extract panel + target from MacroFrame."""
107
+ from macroforecast.data import load_fred_md, load_fred_qd
108
+
109
+ dataset = cfg.data.dataset.lower().replace("-", "_")
110
+ cache_dir = Path(cfg.data.cache_dir).expanduser() if cfg.data.cache_dir else None
111
+
112
+ if dataset == "fred_md":
113
+ mf = load_fred_md(vintage=cfg.data.vintage, cache_dir=cache_dir)
114
+ elif dataset == "fred_qd":
115
+ mf = load_fred_qd(vintage=cfg.data.vintage, cache_dir=cache_dir)
116
+ else:
117
+ raise ValueError(
118
+ f"Dataset '{cfg.data.dataset}' not supported via CLI. "
119
+ "Use fred_md or fred_qd. For fred_sd, load programmatically."
120
+ )
121
+
122
+ # Apply stationarity transforms if needed
123
+ if not mf.metadata.is_transformed:
124
+ mf = mf.transform()
125
+
126
+ df = mf.data
127
+
128
+ if cfg.data.target not in df.columns:
129
+ raise ValueError(
130
+ f"Target '{cfg.data.target}' not found in dataset. "
131
+ f"Available columns: {list(df.columns[:10])} ..."
132
+ )
133
+
134
+ target = df[cfg.data.target]
135
+ panel = df.drop(columns=[cfg.data.target])
136
+
137
+ # Drop columns with all NaN
138
+ panel = panel.dropna(axis=1, how="all")
139
+
140
+ # Restrict to rows where target is observed
141
+ mask = target.notna()
142
+ panel = panel.loc[mask]
143
+ target = target.loc[mask]
144
+
145
+ return panel, target
146
+
147
+
148
+ def _print_summary(rs) -> None:
149
+ """Print MSFE table to stdout."""
150
+ try:
151
+ summary = rs.msfe_by_model()
152
+ if summary.empty:
153
+ print("No results to summarise.")
154
+ return
155
+ print("\n--- MSFE Summary ---")
156
+ print(summary.to_string(index=False))
157
+ except Exception:
158
+ pass
159
+
160
+
161
+ # ---------------------------------------------------------------------------
162
+ # init
163
+ # ---------------------------------------------------------------------------
164
+
165
+
166
+ def _cmd_init(args: argparse.Namespace) -> int:
167
+ """Write the default YAML config template."""
168
+ from macroforecast.config import DEFAULT_CONFIG_YAML
169
+
170
+ out_path = Path(args.output)
171
+ if out_path.exists() and not args.force:
172
+ logger.error("File already exists: %s. Use --force to overwrite.", out_path)
173
+ return 1
174
+
175
+ out_path.write_text(DEFAULT_CONFIG_YAML)
176
+ logger.info("Config template written to: %s", out_path)
177
+ return 0
178
+
179
+
180
+ # ---------------------------------------------------------------------------
181
+ # info
182
+ # ---------------------------------------------------------------------------
183
+
184
+
185
+ def _cmd_info(args: argparse.Namespace) -> int:
186
+ """Print a resolved config summary without running."""
187
+ from macroforecast.config import load_config
188
+
189
+ try:
190
+ cfg = load_config(args.config)
191
+ except (FileNotFoundError, ValueError) as exc:
192
+ logger.error("Config error: %s", exc)
193
+ return 1
194
+
195
+ print(f"Experiment ID: {cfg.experiment_id}")
196
+ print(f"Output dir: {cfg.output_dir}")
197
+ print(f"Dataset: {cfg.data.dataset}")
198
+ print(f"Target: {cfg.data.target}")
199
+ print(f"Vintage: {cfg.data.vintage or 'current'}")
200
+ print(f"Horizons: {cfg.horizons}")
201
+ print(f"Window: {cfg.window.value}")
202
+ print(f"OOS start: {cfg.oos_start or 'auto'}")
203
+ print(f"OOS end: {cfg.oos_end or 'auto'}")
204
+ print(f"n_jobs: {cfg.n_jobs}")
205
+ print(f"Models ({len(cfg.model_specs)}):")
206
+ for spec in cfg.model_specs:
207
+ print(f" - {spec.model_id}")
208
+ print("Features:")
209
+ fs = cfg.feature_spec
210
+ print(
211
+ f" factor_type={fs.factor_type!r}, n_factors={fs.n_factors}, "
212
+ f"n_lags={fs.n_lags}, lookback={fs.lookback}"
213
+ )
214
+ return 0
215
+
216
+
217
+ # ---------------------------------------------------------------------------
218
+ # Argument parser
219
+ # ---------------------------------------------------------------------------
220
+
221
+
222
+ def _build_parser() -> argparse.ArgumentParser:
223
+ parser = argparse.ArgumentParser(
224
+ prog="macroforecast",
225
+ description="macroforecast — Decomposing ML Forecast Gains",
226
+ formatter_class=argparse.RawDescriptionHelpFormatter,
227
+ )
228
+ parser.add_argument(
229
+ "-v", "--verbose", action="store_true", help="Enable DEBUG logging."
230
+ )
231
+
232
+ subparsers = parser.add_subparsers(dest="command", metavar="COMMAND")
233
+ subparsers.required = True
234
+
235
+ # run
236
+ run_parser = subparsers.add_parser(
237
+ "run", help="Run a forecast experiment from a YAML config."
238
+ )
239
+ run_parser.add_argument(
240
+ "config", metavar="CONFIG.yaml", help="Path to the YAML experiment config file."
241
+ )
242
+ run_parser.add_argument(
243
+ "--summary", action="store_true", help="Print MSFE summary table after the run."
244
+ )
245
+
246
+ # init
247
+ init_parser = subparsers.add_parser(
248
+ "init", help="Write a default YAML config template."
249
+ )
250
+ init_parser.add_argument(
251
+ "--output",
252
+ "-o",
253
+ default="experiment.yaml",
254
+ help="Output file path (default: experiment.yaml).",
255
+ )
256
+ init_parser.add_argument(
257
+ "--force", action="store_true", help="Overwrite existing file."
258
+ )
259
+
260
+ # info
261
+ info_parser = subparsers.add_parser("info", help="Print a resolved config summary.")
262
+ info_parser.add_argument(
263
+ "config", metavar="CONFIG.yaml", help="Path to the YAML config file."
264
+ )
265
+
266
+ return parser
267
+
268
+
269
+ # ---------------------------------------------------------------------------
270
+ # Entry point
271
+ # ---------------------------------------------------------------------------
272
+
273
+
274
+ def main(argv: list[str] | None = None) -> int:
275
+ parser = _build_parser()
276
+ args = parser.parse_args(argv)
277
+ _setup_logging(verbose=args.verbose)
278
+
279
+ dispatch = {
280
+ "run": _cmd_run,
281
+ "init": _cmd_init,
282
+ "info": _cmd_info,
283
+ }
284
+ handler = dispatch.get(args.command)
285
+ if handler is None:
286
+ parser.print_help()
287
+ return 1
288
+
289
+ return handler(args)
290
+
291
+
292
+ if __name__ == "__main__":
293
+ sys.exit(main())