File size: 5,245 Bytes
ff4becd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
"""``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/<gran>/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"]