"""``info()`` and ``features()`` helpers for the MacroLens unified API. ``info()`` returns a dict summarising the benchmark (name, version, granularities, n_tickers, date range, per-task descriptions). All values are read from :mod:`whatif_bench.config` and (when available) the benchmark ``metadata.json`` written by the assembly pipeline; nothing is hard-coded except the version constant and the per-task names / predict shapes which are the contract documented in the design plan. ``features(granularity)`` returns ``{task: feature_names}`` by calling the data layer for one ``test`` split per task and reading ``meta.attrs["feature_names"]``. """ from __future__ import annotations import json from typing import Any from .. import config __version__ = "0.2.0" BENCHMARK_NAME = "MacroLens" # Per-task descriptions. ``predict_shape`` is the contract documented in # the unified-API design plan §1 (definitive) and §9 (coverage matrix); # kept here because the methods package doesn't carry shape annotations # directly on a task-by-task basis. _TASKS: dict[str, dict[str, str]] = { "T1": { "name": "Time-Series Forecasting (TSF)", "predict_shape": "(N, horizon) float32", "target": "Close-price trajectory over the forecast horizon", "headline_metric": "mse", }, "T2": { "name": "Public-Tail Equity Valuation (Val-PT)", "predict_shape": "(N,) float32", "target": "actual_market_cap", "headline_metric": "mape", }, "T3": { "name": "Statement Generation (Stmt-Gen)", "predict_shape": "long-form DataFrame [ticker, fiscal_year, field, pred]", "target": "Per-field XBRL value", "headline_metric": "overall_mape", }, "T4": { "name": "Scenario-Conditioned Return (Scen-Ret)", "predict_shape": "(N,) float32", "target": "Post-event return percentage", "headline_metric": "return_mae_pct", }, "T5": { "name": "Private-Company Valuation (Val-Priv)", "predict_shape": "(N,) float32", "target": "actual_market_cap (price-derived inputs stripped)", "headline_metric": "mape", }, "T6": { "name": "Generator Evaluation (Gen-Eval)", "predict_shape": "long-form DataFrame [ticker, fiscal_year, field, pred]", "target": "Per-field XBRL value (NL-only inputs)", "headline_metric": "overall_mape", }, "T7": { "name": "Real-Estate Valuation (RE-Val)", "predict_shape": "DataFrame [address, pred_rent, pred_price]", "target": "Property rent and price", "headline_metric": "rent_MAPE", }, } _GRANULARITIES = ("daily", "weekly", "monthly") def _read_metadata_json(granularity: str) -> dict[str, Any]: """Read ``benchmark//metadata.json`` if present, else return {}.""" p = config.get_benchmark_dir(granularity) / "metadata.json" if not p.exists(): return {} try: return json.loads(p.read_text()) except json.JSONDecodeError: return {} def info(granularity: str = "daily") -> dict[str, Any]: """Summarise the MacroLens benchmark at the requested granularity. Returns ------- dict Keys: ``name, version, granularity, granularities, n_tickers, date_range, horizons, lookbacks, tasks``. ``date_range`` is a ``(start, end)`` tuple of ISO date strings. """ md = _read_metadata_json(granularity) n_tickers = int(md.get("total_tickers", 0)) or None date_range_md = md.get("date_range") or {} start = str(date_range_md.get("start") or config.START_DATE) end = str(date_range_md.get("end") or config.END_DATE) return { "name": BENCHMARK_NAME, "version": __version__, "granularity": granularity, "granularities": list(_GRANULARITIES), "n_tickers": n_tickers, "date_range": (start, end), "horizons": list(config.get_horizons(granularity)), "lookbacks": list(config.get_lookback_windows(granularity)), "tasks": dict(_TASKS), } def features(granularity: str = "daily") -> dict[str, list[str]]: """Return ``{task: feature_names}`` for every public task at *granularity*. Implementation note: we call ``ml.load(task, "test", granularity=...)`` and read ``meta.attrs["feature_names"]``. T2/T3/T5/T6/T7 store column names; T1/T4 store the lookback-panel feature column names. Empty lists indicate the loader did not populate ``feature_names`` for the task. """ # Local import to avoid a circular module-load between # ``macrolens.__init__`` and ``macrolens.meta`` -- ``data`` only depends # on ``dataloader``, so the deferred import is safe. from .data import load out: dict[str, list[str]] = {} for task in ("T1", "T2", "T3", "T4", "T5", "T6", "T7"): try: ld = load(task, "test", granularity=granularity) except Exception: out[task] = [] continue feats = ld.meta.attrs.get("feature_names") if feats is None: out[task] = [] else: out[task] = list(feats) return out __all__ = ["info", "features", "__version__", "BENCHMARK_NAME"]