Coverage for evaluation/model_audit.py: 100%
44 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""What the models could know (V6.6.1): rank IC of six fixed feature groups at three horizons, and how much fundamental data each year holds.
3These 18 looks read cell S, so each counts in N: a report that informs a round is a look at its data. Groups are equal-weight rank means with the
4sign published work gives each feature, so there is nothing to fit, and a single feature's IC is never shown.
5"""
7from __future__ import annotations
9from collections.abc import Mapping
10from typing import TYPE_CHECKING, Any
12import pandas as pd
14from evaluation.research_cells import CELLS, FREE_CELLS
15from features.wide_panel import wide_label
16from portfolio.wide_signals import rank_mean
18if TYPE_CHECKING:
19 from collections.abc import Callable
21 from evaluation.wide_context import WideCell
23# name: sign, higher is better after the sign. `resrev_5` already holds minus the return.
24FEATURE_GROUPS: dict[str, dict[str, float]] = {
25 "price_momentum": {"ret_60": 1.0, "ret_120": 1.0, "ret_252": 1.0, "mom_12_1": 1.0, "resmom_60": 1.0, "resmom_252": 1.0, "dist_52w_high": 1.0, "overnight_ret_252": 1.0},
26 "price_reversal": {"ret_1": -1.0, "ret_5": -1.0, "ret_20": -1.0, "resrev_5": 1.0, "overnight_ret_20": -1.0, "intraday_ret_20": -1.0},
27 "volatility_beta": {"vol_20": -1.0, "vol_60": -1.0, "beta_252": -1.0, "idio_vol_60": -1.0, "max_ret_20": -1.0, "range_20": -1.0},
28 "liquidity": {"amihud_20": 1.0, "log_dollar_volume_20": -1.0, "volume_z_20": -1.0},
29 "fundamental_level": {"gp_assets": 1.0, "roe": 1.0, "cfo_assets": 1.0, "accruals": -1.0, "leverage": -1.0, "book_to_market": 1.0, "earnings_yield": 1.0},
30 "fundamental_growth": {"asset_growth": -1.0, "net_issuance": -1.0, "sue": 1.0, "days_since_filing": -1.0},
31}
32HORIZONS = (5, 21, 63)
33COVERAGE_FIELDS = ("gp_assets", "accruals", "asset_growth", "net_issuance", "book_to_market", "earnings_yield", "leverage", "cfo_assets", "accruals_ttm", "noa", "capex_growth")
36def group_table(features: Mapping[str, pd.DataFrame], group: str, member: pd.DataFrame | None = None) -> pd.DataFrame | None:
37 """The group's fixed composite, from whichever of its features this cell holds. None if it holds none."""
38 present = [features[name] * sign for name, sign in FEATURE_GROUPS[group].items() if name in features]
39 if not present:
40 return None
41 table = rank_mean(present, minimum=1)
42 if member is None:
43 return table
44 return table.where(member.reindex(index=table.index, columns=table.columns, fill_value=False))
47def fundamental_coverage(features: Mapping[str, pd.DataFrame], member: pd.DataFrame) -> dict[str, Any]:
48 """{field: {year: share of member rows with a value}}, on member rows only. The early years of training windows read this."""
49 report: dict[str, dict[str, float]] = {}
50 for name in COVERAGE_FIELDS:
51 if name not in features:
52 continue
53 mask = member.reindex(index=features[name].index, columns=features[name].columns, fill_value=False)
54 known = features[name].notna() & mask
55 years = pd.Index(features[name].index).str[:4]
56 report[name] = {
57 str(year): round(float(known[years == year].to_numpy().sum() / max(1, mask[years == year].to_numpy().sum())), 4)
58 for year in sorted(set(years))
59 }
60 return report
63def feature_group_ic(cell: WideCell, *, horizons: tuple[int, ...] = HORIZONS, ic_fn: Callable[..., Any] | None=None) -> dict[str, Any]:
64 """{group: {horizon: mean IC, non-overlapping t, IC by year}} on the cell's own dates. Refuses a cell outside the free ones: this is a report,
65 and no freeze stands behind it."""
66 if cell.cell.name not in FREE_CELLS or CELLS[cell.cell.name] != cell.cell:
67 raise PermissionError(f"the model audit reads free cells only, not {cell.cell.name}")
68 if ic_fn is None:
69 from evaluation.wide_context import signal_ic_t as ic_fn
70 report: dict[str, dict] = {}
71 labels = {horizon: (cell.label if horizon == 21 and cell.label is not None else wide_label(cell.bars, cell.sectors, horizon=horizon)) for horizon in horizons}
72 for group in FEATURE_GROUPS:
73 table = group_table(cell.features, group, cell.member)
74 if table is None:
75 report[group] = {str(horizon): None for horizon in horizons}
76 continue
77 report[group] = {
78 str(horizon): ic_fn(table, labels[horizon], start=cell.cell.start, end=cell.cell.end, horizon=horizon, min_names=20)
79 for horizon in horizons
80 }
81 return report
84def audit_trial_ids() -> list[str]:
85 """The 18 looks, as the trial ledger counts them."""
86 return [f"audit:{group}:{horizon}" for group in FEATURE_GROUPS for horizon in HORIZONS]