Coverage for portfolio/wide_signals.py: 100%
46 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"""Signal tables of V6.6.0's wide trials: session x ticker, higher is better, each known at that session's close.
3They reach `portfolio.premia_signals` through its `external_score` family, so they run the same weight pipeline, placebos and engine as
4every earlier sleeve. A signal is masked to members, and a name with no sector is never ranked.
5"""
7from __future__ import annotations
9from collections.abc import Mapping
11import numpy as np
12import pandas as pd
14# Signal per trial, a feature's name with its sign. Composites are the equal mean of cross-sectional ranks; nothing here is fitted.
15SINGLE = {
16 "w01": ("gp_assets", 1.0), "w02": ("net_issuance", -1.0), "w03": ("asset_growth", -1.0), "w04": ("accruals", -1.0), "w07": ("sue", 1.0),
17 "w08": ("insider_net_180", 1.0), "w09": ("resmom_252", 1.0), "w10": ("overnight_ret_252", 1.0), "w11": ("dist_52w_high", 1.0), "w12": ("beta_252", -1.0),
18 "w13": ("short_ratio_20", -1.0), "w14": ("resrev_5", 1.0),
19}
20COMPOSITES = {
21 "w05": (("earnings_yield", 1.0), ("book_to_market", 1.0)),
22 "w06": (("gp_assets", 1.0), ("leverage", -1.0), ("accruals", -1.0), ("cfo_assets", 1.0)),
23}
24W15_PARTS = ("w01", "w02", "w04", "w05", "w07", "w09")
25MIN_COMPOSITE_PARTS = {"w05": 1, "w06": 2, "w15": 3}
28def cross_sectional_rank(table: pd.DataFrame) -> pd.DataFrame:
29 """Each row's percentile ranks across the columns."""
30 return table.rank(axis=1, pct=True)
33def rank_mean(tables: list[pd.DataFrame], *, minimum: int) -> pd.DataFrame:
34 """The mean of each table's cross-sectional rank, where at least `minimum` of them have a value."""
35 ranks = [cross_sectional_rank(table) for table in tables]
36 total = sum(rank.fillna(0.0) for rank in ranks)
37 count = sum(rank.notna().astype(float) for rank in ranks)
38 return (total / count.where(count > 0.0)).where(count >= float(minimum))
41def wide_tables(features: Mapping[str, pd.DataFrame], member: pd.DataFrame) -> dict[str, pd.DataFrame]:
42 """Every w-trial's table that its features allow. A feature all NaN (no data for this window) leaves its trial with an empty book,
43 which the minimum-names check reports rather than reading as no skill."""
44 tables: dict[str, pd.DataFrame] = {}
45 for trial, (name, sign) in SINGLE.items():
46 if name in features:
47 tables[trial] = features[name] * sign
48 for trial, parts in COMPOSITES.items():
49 present = [features[name] * sign for name, sign in parts if name in features]
50 if present:
51 tables[trial] = rank_mean(present, minimum=MIN_COMPOSITE_PARTS[trial])
52 parts = [tables[trial] for trial in W15_PARTS if trial in tables]
53 if parts:
54 tables["w15"] = rank_mean(parts, minimum=MIN_COMPOSITE_PARTS["w15"])
55 return {trial: table.where(member.reindex(index=table.index, columns=table.columns, fill_value=False)) for trial, table in tables.items()}
58def crypto_tables(known: pd.DataFrame, funding: pd.DataFrame | None, liquid: pd.DataFrame, btc: str = "BTCUSD") -> dict[str, pd.DataFrame]:
59 """c1-c4, session x coin, masked to the liquid set. `known` already holds each coin's bar from before the session, and funding is
60 shifted the same way: a day's settlements aren't all known at that day's equity close."""
61 daily = known.pct_change(fill_method=None)
62 bench = daily[btc]
63 beta = daily.rolling(60, min_periods=60).cov(bench).div(bench.rolling(60, min_periods=60).var(), axis=0).shift(1)
64 residual = daily.sub(beta.mul(bench, axis=0))
65 tables = {"c1": known / known.shift(28) - 1.0, "c2": residual.rolling(60, min_periods=60).sum()}
66 if funding is not None and not funding.empty:
67 cost = funding.reindex(columns=known.columns).sort_index()
68 seven_days = cost.rolling(7, min_periods=3).mean().shift(1)
69 crowding = -seven_days.reindex(seven_days.index.union(known.index)).ffill().reindex(known.index)
70 tables["c3"] = crowding
71 tables["c4"] = rank_mean([tables["c1"], crowding], minimum=2)
72 return {trial: table.where(liquid.reindex(index=table.index, columns=table.columns, fill_value=False)) for trial, table in tables.items()}
75def live_names_per_rebalance(table: pd.DataFrame, rebalance_every: int) -> dict[str, float]:
76 """How many names a signal can rank, on the days it decides: an empty book must not read as a sleeve with no skill."""
77 counts = table.notna().sum(axis=1).to_numpy(dtype=float)[::max(1, rebalance_every)]
78 if counts.size == 0:
79 return {"median": 0.0, "minimum": 0.0}
80 return {"median": float(np.median(counts)), "minimum": float(counts.min())}