File size: 8,073 Bytes
f02626b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
230
231
232
233
234
235
236
237
238
239
240
241
"""Feature-group filter for the 5-step context ablation (A--E).

The ablation isolates the marginal value of each context source on the
panel-best LLM. Settings nest:

    A: OHLCV only
    B: A + Fundamentals (XBRL stmt_* + derived_* + shares_outstanding + fullTimeEmployees)
    C: B + Macro (fred_* + eia_*)
    D: C + Scenario flags (days_since_filing, filing_8k_count_30d,
                            news_count_7d, has_press_release_7d)
    E: D + Filing text (handled in the LLM prompt; numeric features
                          identical to D)

Only the LLM ablation runs use this filter; classical / sequence / TSFM
methods always see the full feature set in the main panel results.
"""

from __future__ import annotations

import numpy as np
import pandas as pd

ABLATION_SETTINGS: tuple[str, ...] = ("A", "B", "C", "D", "E")

OHLCV: tuple[str, ...] = (
    "open", "high", "low", "close", "volume", "adj_close",
)

# Static fundamentals not following a prefix
_STATIC_FUNDAMENTALS: tuple[str, ...] = (
    "shares_outstanding", "fullTimeEmployees",
)

# Scenario / event flags (proxy for macro-event signal in the panel;
# the broader 1,130-event scenario layer enters via the prompt for T4
# and via news/8K density features here).
SCENARIO_FLAGS: tuple[str, ...] = (
    "days_since_filing",
    "filing_8k_count_30d",
    "news_count_7d",
    "has_press_release_7d",
)


def _is_fundamentals(name: str) -> bool:
    return (
        name.startswith("stmt_")
        or name.startswith("derived_")
        or name in _STATIC_FUNDAMENTALS
    )


def _is_macro(name: str) -> bool:
    return name.startswith("fred_") or name.startswith("eia_")


def _is_scenario(name: str) -> bool:
    return name in SCENARIO_FLAGS


def column_mask(feature_names: list[str], setting: str) -> list[bool]:
    """Return a per-column bool mask for the requested setting.

    The mask is over ``feature_names``; elements set to True are KEPT.
    """
    if setting not in ABLATION_SETTINGS:
        raise ValueError(
            f"setting must be one of {ABLATION_SETTINGS}, got {setting!r}"
        )

    keep: list[bool] = []
    for n in feature_names:
        if n in OHLCV:
            keep.append(True)
            continue
        if setting == "A":
            keep.append(False)
            continue
        if _is_fundamentals(n):
            keep.append(True)
            continue
        if setting == "B":
            keep.append(False)
            continue
        if _is_macro(n):
            keep.append(True)
            continue
        if setting == "C":
            keep.append(False)
            continue
        if _is_scenario(n):
            keep.append(True)
            continue
        # setting D or E: keep nothing else (unknown columns excluded)
        keep.append(False)
    return keep


def filter_columns(
    feature_names: list[str], setting: str,
) -> list[str]:
    """Return the kept feature names for ``setting``."""
    mask = column_mask(feature_names, setting)
    return [n for n, k in zip(feature_names, mask) if k]


def apply_to_t1_array(
    X: np.ndarray, feature_names: list[str], setting: str,
) -> tuple[np.ndarray, list[str]]:
    """Filter T1 ``(N, L, F)`` array to the columns of ``setting``."""
    if X.ndim != 3:
        raise ValueError(f"T1 X must be 3D (N,L,F); got shape={X.shape}")
    if X.shape[2] != len(feature_names):
        raise ValueError(
            f"T1 X feature dim {X.shape[2]} != len(feature_names) "
            f"{len(feature_names)}"
        )
    mask = column_mask(feature_names, setting)
    keep_idx = [i for i, k in enumerate(mask) if k]
    if not keep_idx:
        raise RuntimeError(
            f"setting={setting!r} produced 0 kept columns from "
            f"{len(feature_names)} features"
        )
    new_X = X[:, :, keep_idx].astype(X.dtype, copy=False)
    new_names = [feature_names[i] for i in keep_idx]
    return new_X, new_names


def apply_to_dataframe(
    X: pd.DataFrame, setting: str, *, lookback_cell_col: str | None = None,
) -> pd.DataFrame:
    """Filter a 2D DataFrame to the columns of ``setting``.

    For T4 the dataframe carries a ``lookback`` cell column whose values
    are ``(L, F)`` numpy arrays; pass ``lookback_cell_col`` so we can also
    project the cell-arrays to the same column subset. The prefix-based
    test on the dataframe's own columns still runs for any side-by-side
    numeric columns.
    """
    df = X.copy()

    if lookback_cell_col and lookback_cell_col in df.columns:
        # The (L, F) arrays in this column do not carry their feature
        # names with them. Trust meta.attrs["feature_names"]; resolve at
        # the call site that has access to it. This branch is wired
        # through ``apply_to_loaded`` below.
        pass

    # Project numeric columns if any exist
    keep = []
    for c in df.columns:
        if c in OHLCV:
            keep.append(c)
            continue
        if setting == "A":
            continue
        if _is_fundamentals(c):
            keep.append(c)
            continue
        if setting == "B":
            continue
        if _is_macro(c):
            keep.append(c)
            continue
        if setting == "C":
            continue
        if _is_scenario(c):
            keep.append(c)
            continue
    # Always preserve non-feature object cols (sector dummies, text fields
    # that the method may consume) by keeping any column that has no
    # known prefix and is not numeric.
    extra = [c for c in df.columns if c not in keep and df[c].dtype == object]
    return df[keep + extra]


def apply_to_loaded(
    loaded: "Any", setting: str,  # type: ignore[name-defined]
):  # -> LoadedData
    """Filter a ``LoadedData`` tuple in-place semantics; returns a new tuple.

    Handles the four ablation tasks:
        T1: 3D ndarray (N, L, F) -- mask axis 2
        T2 / T5: 2D DataFrame -- drop columns
        T4: DataFrame with `lookback` cell column -- project each cell
    """
    from typing import NamedTuple
    X, y, meta = loaded

    feat_names = list(meta.attrs.get("feature_names") or [])
    task = meta.attrs.get("task")

    if task == "T1":
        new_X, new_names = apply_to_t1_array(X, feat_names, setting)
        new_meta = meta.copy()
        new_meta.attrs.update(meta.attrs)
        new_meta.attrs["feature_names"] = new_names
        new_meta.attrs["ablation_setting"] = setting
        return type(loaded)(new_X, y, new_meta)

    if task in ("T2", "T5"):
        if not isinstance(X, pd.DataFrame):
            raise TypeError(f"T2/T5 X expected DataFrame, got {type(X)}")
        new_X = apply_to_dataframe(X, setting)
        new_meta = meta.copy()
        new_meta.attrs.update(meta.attrs)
        new_meta.attrs["feature_names"] = list(new_X.columns)
        new_meta.attrs["ablation_setting"] = setting
        return type(loaded)(new_X, y, new_meta)

    if task == "T4":
        if not isinstance(X, pd.DataFrame):
            raise TypeError(f"T4 X expected DataFrame, got {type(X)}")
        if not feat_names:
            raise RuntimeError(
                "T4 ablation requires meta.attrs['feature_names'] to be "
                "set by the loader; was None/empty."
            )
        mask = column_mask(feat_names, setting)
        keep_idx = [i for i, k in enumerate(mask) if k]
        new_X = X.copy()
        if "lookback" in new_X.columns:
            def _project(arr):
                if arr is None:
                    return arr
                if hasattr(arr, "shape") and arr.ndim == 2:
                    return arr[:, keep_idx]
                return arr
            new_X["lookback"] = new_X["lookback"].apply(_project)
        new_meta = meta.copy()
        new_meta.attrs.update(meta.attrs)
        new_meta.attrs["feature_names"] = [feat_names[i] for i in keep_idx]
        new_meta.attrs["ablation_setting"] = setting
        return type(loaded)(new_X, y, new_meta)

    raise ValueError(
        f"Ablation not supported for task={task!r}; "
        "ABLATION_TASKS = (T1, T2, T4, T5)"
    )