Coverage for evaluation/research_cells.py: 100%
91 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"""Which data a V6.6.0 research step may read: a split by name and by time, enforced in code.
3Every earlier phase read the project's own 104 assets over 2013-2026, so time alone holds nothing unread. Names outside that universe
4have never been scored by any rule, so half of them stay out of selection altogether:
6 TA side A, 2004-2018 ML training rows only
7 S side A, 2011-2018 selection; SV (short volume, from 2018-08) and CS (crypto) are its siblings
8 V1 side A, 2019-2026 later time on the read names
9 V2 side B, 2011-2018 never-read names, same time
10 V3 side B, 2019-2026 never-read names, later time: the cleanest cell
11 P both, 2004-2010 before XBRL fundamentals, price families only. ML training read side A here: disclosed
12 CV crypto holdout side B coins on all dates, side A coins from 2023-01
14`open_cell` is the only way in, and it refuses any cell outside `FREE_CELLS` unless given the digest recorded at the freeze. A panel
15holds only its cell's names, so a rank, a label, a covariance or a history count can't see the other side.
16"""
18from __future__ import annotations
20import hashlib
21import json
22from collections.abc import Iterable, Mapping
23from dataclasses import dataclass
24from pathlib import Path
25from typing import Any
27import pandas as pd
29from data_pipeline.sp500_membership import canonical_issuer
31SALT = "aq-v660-names"
32BENCHMARK_TICKERS = ("SPY", "AGG")
33SWEEP_TICKER = "BIL"
34WARMUP_SESSIONS = 300
35STALE_ROWS = 5
38@dataclass(frozen=True)
39class Cell:
40 """One research cell: a universe side and a date window, holdout or free, that trials are scored on."""
41 name: str
42 side: str
43 start: str
44 end: str
45 split: str | None = None
46 universe: str = "equity"
49CELLS = {
50 "TA": Cell("TA", "A", "2004-01-01", "2018-12-31"),
51 "S": Cell("S", "A", "2011-01-01", "2018-12-31", "2015-01-01"),
52 "SV": Cell("SV", "A", "2018-08-01", "2022-12-31", "2020-10-01"),
53 "CS": Cell("CS", "A", "2018-01-01", "2022-12-31", "2020-07-01", "crypto"),
54 "V1": Cell("V1", "A", "2019-01-01", "2026-11-02"),
55 "V2": Cell("V2", "B", "2011-01-01", "2018-12-31"),
56 "V3": Cell("V3", "B", "2019-01-01", "2026-11-02"),
57 "CV": Cell("CV", "AB", "2018-01-01", "2026-11-02", None, "crypto"),
58 "P": Cell("P", "AB", "2004-01-01", "2010-12-31"),
59}
60FREE_CELLS = frozenset({"TA", "S", "SV", "CS"})
63def name_side(ticker: str, project_issuers: Iterable[str] = ()) -> str:
64 """A or B, fixed by a hash of the issuer: share classes and renames share a side, and it can't be tuned. A name any earlier phase
65 has read is always A."""
66 issuer = canonical_issuer(str(ticker))
67 if issuer in {canonical_issuer(str(name)) for name in project_issuers}:
68 return "A"
69 return "A" if hashlib.sha256((SALT + issuer).encode("utf-8")).digest()[0] % 2 == 0 else "B"
72def coin_side(ticker: str, project_coins: Iterable[str] = ()) -> str:
73 """The same split for coins, by base asset: BTCUSD and BTCUSDT are one coin."""
74 base = str(ticker).upper()
75 for quote in ("USDT", "USD"):
76 if base.endswith(quote):
77 base = base[: -len(quote)]
78 break
79 known = {str(name).upper().removesuffix("USD") for name in project_coins}
80 if base in known:
81 return "A"
82 return "A" if hashlib.sha256((SALT + "coin" + base).encode("utf-8")).digest()[0] % 2 == 0 else "B"
85def names_in_cell(cell: Cell, tickers: Iterable[str], project: Iterable[str]) -> list[str]:
86 """The tickers a cell may trade: all of them for side AB, else those on the cell's side of the split."""
87 project = list(project)
88 side_of = coin_side if cell.universe == "crypto" else name_side
89 return sorted(ticker for ticker in tickers if cell.side == "AB" or side_of(ticker, project) == cell.side)
92def freeze_digest_of(path: Path) -> str:
93 """SHA-256 of a freeze file's bytes, the digest a holdout read must quote."""
94 return hashlib.sha256(Path(path).read_bytes()).hexdigest()
97def assert_cell_open(cell_name: str, freeze_path: Path | None, freeze_digest: str | None) -> Cell:
98 """The gate itself. A later cell needs the digest of the freeze file, and that file must be the one on disk."""
99 if cell_name not in CELLS:
100 raise ValueError(f"unknown cell {cell_name!r}; expected one of {sorted(CELLS)}")
101 if cell_name in FREE_CELLS:
102 return CELLS[cell_name]
103 if not freeze_digest:
104 raise PermissionError(f"cell {cell_name} is held out: it opens only with the digest of the recorded freeze")
105 if freeze_path is None or not Path(freeze_path).exists():
106 raise PermissionError(f"cell {cell_name}: no recorded freeze")
107 actual = freeze_digest_of(Path(freeze_path))
108 if actual != freeze_digest:
109 raise PermissionError(f"cell {cell_name}: digest {freeze_digest} is not the recorded freeze {actual}")
110 return CELLS[cell_name]
113def window_rows(index: Iterable[str], cell: Cell, *, warmup: int = WARMUP_SESSIONS) -> list[str]:
114 """The cell's sessions plus the `warmup` before them, which give a signal its history. A warm-up row can never hold a position:
115 weights start at `cell.start`. Nothing after `cell.end` exists in the panel at all."""
116 dates = sorted(str(day) for day in index if str(day) <= cell.end)
117 first = next((position for position, day in enumerate(dates) if day >= cell.start), len(dates))
118 return dates[max(0, first - warmup):]
121def blank_stale(known: pd.DataFrame, closes: pd.DataFrame, *, rows: int = STALE_ROWS) -> pd.DataFrame:
122 """`known_closes` carries the last price forward, so a name whose bars stopped would keep a signal forever. A cell with no bar over
123 the last `rows` rows goes NaN. Looks backward only, and it never reads why the bars stopped."""
124 recent = closes.reindex(index=known.index, columns=known.columns).notna().rolling(rows, min_periods=1).sum() > 0
125 return known.where(recent)
128def membership_mask(table: Mapping[str, list[tuple[str, str]]], sessions: list[str], columns: list[str]) -> pd.DataFrame:
129 """Session x ticker, True while a member. Names outside the membership table are False."""
130 mask = pd.DataFrame(False, index=sessions, columns=columns)
131 for ticker in columns:
132 for start, end in table.get(ticker, ()):
133 mask[ticker] |= (mask.index >= start) & (mask.index < end)
134 return mask
137def record_holdout_read(path: Path, *, candidate: str, cells: tuple[str, ...], digest: str, created_at: str) -> None:
138 """The once-only ledger of holdout reads. `write_freeze` only refuses its own path, so a second freeze file would otherwise reopen a cell.
139 Written before the read: a crash after it still counts as spent."""
140 path = Path(path)
141 held = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] if path.exists() else []
142 # fail closed on a malformed entry: a string `cells` used to iterate into characters, so "V1" never read as spent (#363)
143 for number, entry in enumerate(held, start=1):
144 if not isinstance(entry, dict) or not isinstance(entry.get("cells", []), list) or not all(isinstance(cell, str) for cell in entry.get("cells", [])):
145 raise ValueError(f"{path}: entry {number} is not a holdout record; refusing every read until it is repaired")
146 spent = {cell for entry in held for cell in entry.get("cells", ())}
147 again = sorted(spent & set(cells))
148 if again:
149 raise PermissionError(f"cells {again} have already been read: a holdout is read once")
150 path.parent.mkdir(parents=True, exist_ok=True)
151 with path.open("a", encoding="utf-8", newline="\n") as handle:
152 handle.write(json.dumps({"candidate": candidate, "cells": list(cells), "digest": digest, "created_at": created_at}, sort_keys=True) + "\n")
155def write_freeze(path: Path, payload: Mapping[str, Any]) -> str:
156 """Writes the freeze file once and returns its digest. Refuses to overwrite: a second freeze would be a second look."""
157 path = Path(path)
158 if path.exists():
159 raise FileExistsError(f"{path} exists: a candidate is frozen once")
160 path.parent.mkdir(parents=True, exist_ok=True)
161 path.write_text(json.dumps(payload, indent=1, sort_keys=True), encoding="utf-8", newline="\n")
162 return freeze_digest_of(path)