Coverage for scripts/v664_register_observers.py: 100%

91 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Registers the forward observers of V6.6.4's pre-registered rule (`ml/evaluation/v664/observers.json`), at zero capital. 

2 

3Time is the only evidence that can't be overfit and a missed session can't be backfilled, so the three highest-Sharpe trials of round 4C on cell CS (by that rule alone, a tie to the lower trial 

4number) are recorded forward from the first session, beside k09, which needs a host that has fundamentals. Each enters the registry as tier `none`, stage `shadow`: it is marked every session and 

5holds nothing, whatever its record (`share_cap`), and counts in N when it is judged. The universe is the USD coins Coinbase lists as trading today with a full 300-bar history, the most traded 

6first: a universe stated as such, not the cell's, so the forward record is of the trial as a live feed can compute it (marks only: no volume, no funding). 

7 

8 python scripts/v664_register_observers.py # prints what it would register 

9 python scripts/v664_register_observers.py --apply # writes ml/generations/registry.json and lifecycle.jsonl 

10""" 

11 

12from __future__ import annotations 

13 

14import argparse 

15import datetime 

16import json 

17import sys 

18import time 

19from collections.abc import Callable, Mapping 

20from pathlib import Path 

21 

22ROOT = Path(__file__).resolve().parents[1] 

23sys.path.insert(0, str(ROOT)) 

24sys.path.insert(0, str(ROOT / "scripts")) 

25 

26from evaluation.forward_ledger import definition_sha256 # noqa: E402 

27from evaluation.generation_registry import Generation, append_lifecycle, load_registry, save_registry # noqa: E402 

28 

29SCORES = ROOT / "ml" / "evaluation" / "v664" / "selection_scores_round4c.json" 

30OBSERVERS_RULE = ROOT / "ml" / "evaluation" / "v664" / "observers.json" 

31PRODUCTS_URL = "https://api.exchange.coinbase.com/products" 

32CANDLES_URL = "https://api.exchange.coinbase.com/products/{product}/candles?granularity=86400" 

33UNIVERSE_SIZE = 25 

34MIN_BARS = 295 

35STABLE_BASES = frozenset({"USDT", "USDC", "DAI", "PYUSD", "EURC", "GUSD", "PAX", "USDP", "TUSD", "USDS", "FDUSD", "BUSD", "UST", "LUSD", "FRAX", "RLUSD", "USD1", "USDG"}) 

36CRYPTO_SETTINGS = {"target_vol": 0.07, "gross_cap": 1.4, "name_cap": 0.03, "class_caps": {"crypto": 0.15}, "name_cap_by_class": {"crypto": 0.05}} 

37# round 4C's trials as the forward feed can compute them: from marks alone 

38SIGNALS = { 

39 "x10": ("time_series", 5, {"builder": "breadth_timing", "params": {"window": 50, "floor": 0.5}}, None), 

40 "x12": ("cross_sectional", 20, {"builder": "low_vol", "params": {"window": 60}, "gate": "regime"}, 10), 

41 "x14": ("cross_sectional", 20, {"rank_mean": [{"builder": "low_vol", "params": {"window": 60}}, {"builder": "lottery_max", "params": {"window": 30}}, 

42 {"builder": "high_proximity", "params": {"window": 365, "min_periods": 180}}], "minimum": 3, "gate": "regime"}, 10), 

43 "x01": ("cross_sectional", 20, {"builder": "low_vol", "params": {"window": 60}}, 10), 

44 "x02": ("cross_sectional", 20, {"builder": "lottery_max", "params": {"window": 30}}, 10), 

45 "x05": ("cross_sectional", 20, {"builder": "high_proximity", "params": {"window": 365, "min_periods": 180}}, 10), 

46 "x06": ("cross_sectional", 5, {"builder": "short_reversal", "params": {"window": 7}}, 10), 

47 "x07": ("cross_sectional", 20, {"builder": "low_beta", "params": {"window": 60}}, 10), 

48 "x08": ("cross_sectional", 20, {"builder": "idio_vol", "params": {"window": 60}}, 10), 

49 "x11": ("time_series", 5, {"builder": "core_constant", "params": {}}, None), 

50} 

51# a trial the forward feed cannot compute from marks: volume, funding or a fitted model 

52NOT_FROM_MARKS = {"x03": "needs volume", "x04": "needs volume", "x09": "needs funding", "x13": "a fitted model needs its own host"} 

53 

54 

55def select_observers(scores: Mapping[str, Mapping], count: int = 3) -> list[str]: 

56 """The `count` x-trials with the highest pooled Sharpe, a tie to the lower trial number, skipping any the feed cannot compute (the next-highest takes its place).""" 

57 ranked = sorted((trial for trial, score in scores.items() if trial.startswith("x") and score.get("sharpe") is not None), key=lambda trial: (-float(scores[trial]["sharpe"]), trial)) 

58 return [trial for trial in ranked if trial in SIGNALS][:count] 

59 

60 

61def looks_like_a_stablecoin(product_id: str, closes: list[float]) -> bool: 

62 """A stablecoin has no trend to rank: by name, or by a price that stayed within 2% of one dollar for the whole window.""" 

63 if product_id.split("-")[0] in STABLE_BASES: 

64 return True 

65 values = sorted(float(close) for close in closes if close) 

66 return bool(values) and 0.97 <= values[len(values) // 2] <= 1.03 and (values[-1] - values[0]) < 0.02 * values[len(values) // 2] 

67 

68 

69def rank_coins( 

70 products: list[dict], volume_by_product: Mapping[str, float], bars_by_product: Mapping[str, int], size: int = UNIVERSE_SIZE, *, stable: frozenset[str] | set[str] = frozenset(), 

71) -> list[str]: 

72 """USD products that are online and tradeable, with a full history and not a stablecoin, the most traded (30-day quote volume) first. Tickers in the project's own form (`BTCUSD`).""" 

73 eligible = [ 

74 product["id"] for product in products 

75 if product.get("quote_currency") == "USD" and product.get("status") == "online" and not product.get("trading_disabled") and bars_by_product.get(product["id"], 0) >= MIN_BARS 

76 and product["id"] not in stable 

77 ] 

78 eligible.sort(key=lambda name: (-float(volume_by_product.get(name, 0.0)), name)) 

79 return [name.replace("-", "") for name in eligible[:size]] 

80 

81 

82def build_definition(trial: str, tickers: list[str], anchor: str) -> dict: 

83 kind, every, signal, top_k = SIGNALS[trial] 

84 params: dict = {"signal": signal} 

85 if top_k: 

86 params["top_k"] = top_k 

87 return { 

88 "id": f"obs_{trial}", "kind": kind, "family": "crypto_signal", "universe": ["crypto"], "rebalance_every": every, "params": params, "tickers": list(tickers), 

89 "asset_class": dict.fromkeys(tickers, "crypto"), "anchor_date": anchor, "cost_class": "crypto", "initial_weights": {}, "settings": dict(CRYPTO_SETTINGS), 

90 "data_sources": ["Coinbase public candles", "Yahoo chart API"], 

91 } 

92 

93 

94def k09_definition(anchor: str) -> dict: 

95 """k09 (quarterly accruals, IC t 2.60 in round 3) needs fundamentals, so a host dates its decisions (`aq cycle decide`); the runner only marks it.""" 

96 from evaluation.wide_context import SECTORS 

97 

98 return { 

99 "id": "obs_k09", "kind": "pooled", "family": "external_score", "universe": list(SECTORS), "rebalance_every": 20, "params": {"table": "k09", "top_k": None}, "tickers": [], "asset_class": {}, 

100 "anchor_date": anchor, "cost_class": "equity", "initial_weights": {}, "settings": {"target_vol": 0.07, "gross_cap": 1.4, "name_cap": 0.03, "class_caps": {"crypto": 0.15}, "name_cap_by_class": {"crypto": 0.05}}, 

101 "data_sources": ["SEC EDGAR (host-computed decisions)", "Yahoo chart API"], 

102 } 

103 

104 

105def fetch_universe(get_json: Callable[[str], object], pause: float = 0.35) -> tuple[list[str], dict]: 

106 products = [item for item in get_json(PRODUCTS_URL) if item.get("quote_currency") == "USD" and item.get("status") == "online" and not item.get("trading_disabled")] 

107 volume, bars, stable = {}, {}, set() 

108 for product in products: 

109 rows = get_json(CANDLES_URL.format(product=product["id"])) 

110 time.sleep(pause) 

111 bars[product["id"]] = len(rows) 

112 recent = rows[:30] # newest first: [time, low, high, open, close, volume] 

113 volume[product["id"]] = sum(float(row[4]) * float(row[5]) for row in recent) 

114 if looks_like_a_stablecoin(product["id"], [row[4] for row in recent]): 

115 stable.add(product["id"]) 

116 return rank_coins(products, volume, bars, stable=stable), { 

117 "products_online_usd": len(products), "with_full_history": sum(1 for count in bars.values() if count >= MIN_BARS), "stablecoins_left_out": sorted(stable), 

118 } 

119 

120 

121def main(argv: list[str] | None = None) -> int: 

122 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

123 parser.add_argument("--apply", action="store_true") 

124 parser.add_argument("--anchor", default=None, help="the last session before the first decision (default: the newest weekday)") 

125 args = parser.parse_args(argv) 

126 import forward_ledger 

127 

128 scores = json.loads(SCORES.read_text(encoding="utf-8")) 

129 chosen = select_observers(scores) 

130 rule_sha = OBSERVERS_RULE.with_suffix(".sha256").read_text(encoding="utf-8").strip() 

131 today = datetime.datetime.now(datetime.timezone.utc) 

132 anchor = args.anchor or forward_ledger.session_for_outage(today) 

133 tickers, universe_note = fetch_universe(forward_ledger._get_json) 

134 definitions = {f"obs_{trial}": build_definition(trial, tickers, anchor) for trial in chosen} 

135 definitions["obs_k09"] = k09_definition(anchor) 

136 summary = {"chosen_x_trials": chosen, "rule_sha256": rule_sha, "anchor": anchor, "universe": tickers, "universe_note": universe_note, "ids": list(definitions)} 

137 print(json.dumps(summary, indent=1)) 

138 if not args.apply: 

139 return 0 

140 registry_path = ROOT / "ml" / "generations" / "registry.json" 

141 registry = load_registry(registry_path) 

142 number = max(int(name[1:]) for name in registry) + 1 

143 lifecycle = ROOT / "ml" / "generations" / "lifecycle.jsonl" 

144 created = today.replace(microsecond=0).isoformat() 

145 for observer_id, definition in definitions.items(): 

146 generation_id = f"g{number:04d}" 

147 number += 1 

148 needs = "fundamentals" if observer_id == "obs_k09" else None 

149 note = f"{observer_id}: a forward observer under observers.json (sha256 {rule_sha[:12]}), tier none, shadow, holds nothing; not verified." 

150 registry[generation_id] = Generation( 

151 id=generation_id, kind="rule", tier="none", stage="shadow", born=created[:10], procedure_sha256=definition_sha256(definition), definition=definition, needs=needs, 

152 expected_sharpe=0.0, note=note, admission={}, 

153 ) 

154 append_lifecycle(lifecycle, event="observer_registered", created_at=created, payload={"generation": generation_id, "observer": observer_id, "definition_sha256": definition_sha256(definition), "rule_sha256": rule_sha}) 

155 save_registry(registry_path, registry) 

156 print(f"registered {len(definitions)} observers") 

157 return 0 

158 

159 

160if __name__ == "__main__": 

161 raise SystemExit(main())