File size: 9,911 Bytes
5995ef5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""Layer 3 – Step 8: Assemble benchmark artifacts from the processed panel.

Reads ``data/processed/{granularity}/panel.parquet`` and produces:

    data/benchmark/{granularity}/panel_train.parquet
    data/benchmark/{granularity}/panel_test.parquet
    data/benchmark/{granularity}/panel_full.csv      (CSV compatibility)
    data/benchmark/{granularity}/task_definition.json
    data/benchmark/{granularity}/filing_corpus.parquet
    data/benchmark/{granularity}/metadata.json

Does NOT re-process raw data.  All heavy lifting happened in
``preprocess.py`` (Layer 2).
"""

from __future__ import annotations

import json
import logging
from pathlib import Path

import numpy as np
import pandas as pd

from . import config

logger = logging.getLogger(__name__)


# ------------------------------------------------------------------
# Filing corpus
# ------------------------------------------------------------------

def _build_filing_corpus() -> pd.DataFrame:
    """Build a filing corpus index from ``data/filings/{TICKER}/*.md``.

    Stores only **metadata** (ticker, filing_type, filing_date, filing_path)
    -- NOT the full text -- to avoid OOM with thousands of large filings.
    Text is loaded on-demand by ``benchmark_loader.py`` using ``filing_path``.

    Columns: ticker, filing_type, filing_date, filing_path, text_length.
    """
    import re as _re

    rows: list[dict] = []
    if not config.FILINGS_DIR.is_dir():
        logger.warning("Filings directory does not exist: %s", config.FILINGS_DIR)
        return pd.DataFrame(columns=["ticker", "filing_type", "filing_date", "filing_path", "text_length"])

    for ticker_dir in sorted(config.FILINGS_DIR.iterdir()):
        if not ticker_dir.is_dir():
            continue
        ticker = ticker_dir.name
        for md_file in sorted(ticker_dir.glob("*.md")):
            ftype = "10-K" if "10-K" in md_file.name else "10-Q" if "10-Q" in md_file.name else "8-K" if "8-K" in md_file.name else "other"
            match = _re.search(r"(\d{4}-\d{2}-\d{2})", md_file.name)
            fdate = match.group(1) if match else None
            # Only measure length (not load entire text into memory)
            try:
                text_len = md_file.stat().st_size
            except Exception:
                text_len = 0
            rows.append({
                "ticker": ticker,
                "filing_type": ftype,
                "filing_date": fdate,
                "filing_path": str(md_file.relative_to(config.DATA_DIR)),
                "text_length": text_len,
            })

    df = pd.DataFrame(rows)
    if not df.empty and "filing_date" in df.columns:
        df["filing_date"] = pd.to_datetime(df["filing_date"], errors="coerce")
    logger.info("Filing corpus index: %d documents across %d tickers.",
                 len(df), df["ticker"].nunique() if not df.empty else 0)
    return df


# ------------------------------------------------------------------
# Task definition
# ------------------------------------------------------------------

def _build_task_definition(panel: pd.DataFrame, granularity: str) -> dict:
    """Create the formal forecasting-task contract."""
    # Read column roles from the processed output
    col_roles_path = config.DATA_DIR / "processed" / granularity / "columns.json"
    if col_roles_path.exists():
        column_roles = json.loads(col_roles_path.read_text())
    else:
        column_roles = {}

    return {
        "benchmark_name": "MacroLens",
        "version": "1.0",
        "granularity": granularity,
        "targets": {
            "primary": "close",
            "secondary": "volume",
        },
        "horizons": config.get_horizons(granularity),
        "lookback_windows": config.get_lookback_windows(granularity),
        "column_roles": column_roles,
        "context_taxonomy": {
            "historical": "10-K / 10-Q filing text (nearest filing as-of each date)",
            "covariate": "FRED / EIA macro indicators (exogenous_macro + exogenous_commodity)",
            "causal": "Fundamental ratios derived from statements + price (exogenous_fundamental)",
            "future_scenario": "Natural experiment events detected from macro data (scenarios.parquet)",
            "intemporal": "Sector / industry knowledge (metadata columns)",
        },
        "evaluation": {
            "metrics": ["MSE", "MAE", "RMSE", "directional_accuracy"],
            "baseline": "naive_last_value",
            "primary_metric": "MSE",
        },
        "scenario_method": "natural_experiments",
    }


# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------

def run(granularity: str | None = None) -> None:
    """Execute Layer 3 benchmark assembly."""
    if granularity is None:
        granularity = config.GRANULARITY

    panel_path = config.DATA_DIR / "processed" / granularity / "panel.parquet"
    if not panel_path.exists():
        raise FileNotFoundError(f"Run Step 7 (preprocess) first: {panel_path}")

    out_dir = config.DATA_DIR / "benchmark" / granularity
    out_dir.mkdir(parents=True, exist_ok=True)

    # ---- Load processed panel ------------------------------------------------
    panel = pd.read_parquet(panel_path)
    logger.info("Loaded processed panel: %d rows, %d tickers, %d columns.",
                 len(panel), panel["ticker"].nunique(), len(panel.columns))

    # ---- Temporal split ------------------------------------------------------
    if config.TEMPORAL_SPLIT_DATE is not None:
        split_date = pd.Timestamp(config.TEMPORAL_SPLIT_DATE)
    else:
        unique_dates = np.sort(panel["date"].unique())
        split_idx = int(len(unique_dates) * config.TEMPORAL_SPLIT_RATIO)
        split_idx = max(1, min(split_idx, len(unique_dates) - 1))
        split_date = pd.Timestamp(unique_dates[split_idx])
        logger.info("Ratio-based split (%.0f:%.0f): split date = %s (%d/%d unique dates)",
                     config.TEMPORAL_SPLIT_RATIO * 100,
                     (1 - config.TEMPORAL_SPLIT_RATIO) * 100,
                     split_date.date(), split_idx, len(unique_dates))

    panel["split"] = np.where(panel["date"] < split_date, "train", "test")
    train = panel[panel["split"] == "train"]
    test = panel[panel["split"] == "test"]

    # Cold-start tickers: IPOs that appear only in the test period.
    # Kept intentionally — tests model generalisation to unseen companies.
    train_tickers = set(train["ticker"].unique())
    test_only = set(test["ticker"].unique()) - train_tickers
    if test_only:
        logger.info("%d cold-start tickers in test (IPOs).", len(test_only))

    train.to_parquet(out_dir / "panel_train.parquet", index=False)
    test.to_parquet(out_dir / "panel_test.parquet", index=False)
    panel.to_csv(out_dir / "panel_full.csv", index=False)
    logger.info("Saved train (%d rows) + test (%d rows) + CSV.", len(train), len(test))

    # ---- Task definition -----------------------------------------------------
    task_def = _build_task_definition(panel, granularity)
    (out_dir / "task_definition.json").write_text(json.dumps(task_def, indent=2, default=str))
    logger.info("Saved task_definition.json.")

    # ---- Filing corpus -------------------------------------------------------
    corpus = _build_filing_corpus()
    if not corpus.empty:
        corpus.to_parquet(out_dir / "filing_corpus.parquet", index=False)
    logger.info("Saved filing_corpus.parquet (%d documents).", len(corpus))

    # ---- Metadata ------------------------------------------------------------
    metadata = {
        "format": "panel_data",
        "granularity": granularity,
        "primary_key": ["ticker", "date"],
        "total_rows": len(panel),
        "total_tickers": int(panel["ticker"].nunique()),
        "date_range": {
            "start": str(panel["date"].min().date()),
            "end": str(panel["date"].max().date()),
        },
        "temporal_split": {
            "split_date": str(split_date.date()),
            "split_method": (
                "fixed_date" if config.TEMPORAL_SPLIT_DATE
                else f"ratio_{config.TEMPORAL_SPLIT_RATIO}"
            ),
            "train_rows": len(train),
            "test_rows": len(test),
            "train_date_range": {
                "start": str(train["date"].min().date()) if len(train) > 0 else None,
                "end": str(train["date"].max().date()) if len(train) > 0 else None,
            },
            "test_date_range": {
                "start": str(test["date"].min().date()) if len(test) > 0 else None,
                "end": str(test["date"].max().date()) if len(test) > 0 else None,
            },
        },
        "label_distribution": panel["label"].value_counts().to_dict() if "label" in panel.columns else {},
        "columns": list(panel.columns),
        "column_count": len(panel.columns),
        "column_roles": task_def.get("column_roles", {}),
        "filing_corpus_stats": {
            "total_documents": len(corpus),
            "tickers_with_filings": int(corpus["ticker"].nunique()) if not corpus.empty else 0,
        },
        "evaluation_protocol": task_def.get("evaluation", {}),
    }
    (out_dir / "metadata.json").write_text(json.dumps(metadata, indent=2, default=str))
    logger.info("Saved metadata.json.  Base benchmark assembly complete -> %s", out_dir)

    # ---- Valuation benchmark (Tasks A–F) ---------------------------------
    try:
        from .build_valuation_tasks import build_valuation_benchmark
        logger.info("Building valuation benchmark artifacts (%s) …", granularity)
        val_summary = build_valuation_benchmark(granularity=granularity)
        logger.info("Valuation benchmark: %s", val_summary)
    except Exception:
        logger.warning("Valuation benchmark build skipped or failed", exc_info=True)