Coverage for retraining/model_catalog.py: 100%

148 statements  

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

1"""Example models anyone can install (V6.6.10): small networks trained on the library's bundled public sample, published as 

2GitHub release assets, installed into a local cache and scored with the numpy forward pass (no torch). 

3 

4The project's own trading models are never among them: they stay on the owner's machine. `scripts/build_example_models.py` 

5trains the examples from `aether_quant/_sample/` alone, and a test checks that no example file shares a name or a hash with 

6an installed model (`ml/artifact_pins.json`). 

7 

8Trust: the release job builds the zips and a manifest of their sha256 in one run and signs the release's files (Sigstore). 

9`install` downloads the manifest over HTTPS, refuses a zip whose hash differs, and checks every file inside against the zip's 

10own manifest before anything is read. 

11""" 

12 

13from __future__ import annotations 

14 

15import hashlib 

16import json 

17import shutil 

18import urllib.request 

19import zipfile 

20from collections.abc import Callable, Mapping, Sequence 

21from pathlib import Path 

22from typing import Any 

23 

24import numpy as np 

25import pandas as pd 

26 

27REPOSITORY = "leon1706-lol/Aether-quant" 

28MANIFEST_ASSET = "example_models_manifest.json" 

29DEFAULT_ROOT = Path.home() / ".cache" / "aether-quant" / "models" 

30FEATURES = ("ret_1", "ret_5", "ret_20", "ret_60", "vol_20", "vol_60") 

31SPLITS = {"train_end": "2023-12-31", "validation_end": "2024-12-31", "backtest_end": "2025-12-31"} 

32EXAMPLES: dict[str, dict[str, str]] = { 

33 "example-crypto-mlp": { 

34 "kind": "multitask", "model": "multitask_model.json", "schema": "multitask_feature_schema.json", 

35 "summary": "A small multitask network on six return and volatility features of the 11 sample coins.", 

36 }, 

37 "example-crypto-seq": { 

38 "kind": "sequence", "model": "sequence_model.json", "schema": "sequence_feature_schema.json", 

39 "summary": "A small causal convolutional network over 20 sessions of the same six features.", 

40 }, 

41} 

42 

43 

44def catalog() -> list[dict[str, str]]: 

45 """The example models, by name: what each is and which file holds it.""" 

46 return [{"name": name, **entry} for name, entry in EXAMPLES.items()] 

47 

48 

49def example_features(closes: pd.DataFrame) -> pd.DataFrame: 

50 """Long rows (date, ticker, features) from a dates x tickers close table. Each feature uses closes up to its own date only, and is 

51 z-scored across the tickers of that date (a date with fewer than two names, or no spread, is NaN).""" 

52 returns = closes.pct_change(fill_method=None) 

53 raw = { 

54 "ret_1": returns, "ret_5": closes.pct_change(5, fill_method=None), "ret_20": closes.pct_change(20, fill_method=None), 

55 "ret_60": closes.pct_change(60, fill_method=None), "vol_20": returns.rolling(20, min_periods=20).std(), "vol_60": returns.rolling(60, min_periods=60).std(), 

56 } 

57 columns = {} 

58 for name, table in raw.items(): 

59 spread = table.std(axis=1, ddof=0) 

60 columns[name] = table.sub(table.mean(axis=1), axis=0).div(spread.where(spread > 0), axis=0).where(table.notna().sum(axis=1) >= 2, axis=0) 

61 long = pd.concat({name: table.stack(future_stack=True) for name, table in columns.items()}, axis=1) 

62 long.index.names = ["date", "ticker"] 

63 return long.reset_index().astype({"date": str, "ticker": str}) 

64 

65 

66def example_dataset(closes: pd.DataFrame, *, splits: Mapping[str, str] = SPLITS) -> pd.DataFrame: 

67 """The trainers' dataset format from a close table: the features, every target the heads read (forward returns and their daily 

68 ranks), a split by date and the bookkeeping columns. Rows without every feature are dropped; the last rows keep NaN targets.""" 

69 frame = example_features(closes) 

70 forward = {h: (closes.shift(-h) / closes - 1.0) for h in (1, 5, 20)} 

71 ranks = {h: forward[h].rank(axis=1, pct=True) for h in (5, 20)} 

72 volatility = forward[1].abs() 

73 

74 def column(table: pd.DataFrame) -> np.ndarray: 

75 return table.stack(future_stack=True).reindex(pd.MultiIndex.from_frame(frame[["date", "ticker"]])).to_numpy(dtype=float) 

76 

77 frame["target_return_1d"] = column(forward[1]) 

78 frame["target_direction"] = (frame["target_return_1d"] > 0).astype(float).where(frame["target_return_1d"].notna()) 

79 frame["target_volatility_next_day"] = column(volatility) 

80 frame["target_return_5d"], frame["target_return_20d"] = column(forward[5]), column(forward[20]) 

81 frame["target_direction_5d"] = (frame["target_return_5d"] > 0).astype(float).where(frame["target_return_5d"].notna()) 

82 frame["target_direction_20d"] = (frame["target_return_20d"] > 0).astype(float).where(frame["target_return_20d"].notna()) 

83 frame["target_rank_5d"], frame["target_rank_20d"] = column(ranks[5]), column(ranks[20]) 

84 for name in ("target_sector_neutral_rank_20d", "target_beta_neutral_rank_20d", "target_residual_rank_20d"): 

85 frame[name] = frame["target_rank_20d"] 

86 frame["target_residual_rank_5d"] = frame["target_rank_5d"] 

87 frame = frame.dropna(subset=list(FEATURES) + ["target_return_1d", "target_volatility_next_day"]).reset_index(drop=True) 

88 frame["split"] = np.select( 

89 [frame["date"] <= splits["train_end"], frame["date"] <= splits["validation_end"], frame["date"] <= splits["backtest_end"]], 

90 ["train", "validation", "backtest"], "holdout", 

91 ) 

92 frame["training_eligible"] = True 

93 frame["security_type"] = "crypto" 

94 return frame.sort_values(["ticker", "date"]).reset_index(drop=True) 

95 

96 

97def production_collisions(files: Mapping[str, bytes], pinned: Mapping[str, str]) -> list[str]: 

98 """The example files whose sha256 is one of the installed models' pinned hashes (`ml/artifact_pins.json` "files"): a production model 

99 must never be published as an example, so the build refuses any.""" 

100 hashes = set(pinned.values()) 

101 return sorted(name for name, data in files.items() if hashlib.sha256(data).hexdigest() in hashes) 

102 

103 

104def release_url(asset: str, *, version: str | None = None) -> str: 

105 """The download URL of a release asset: the latest release, or the tag `v<version>`.""" 

106 base = f"https://github.com/{REPOSITORY}/releases" 

107 return f"{base}/latest/download/{asset}" if version is None else f"{base}/download/v{version}/{asset}" 

108 

109 

110def sha256_file(path: Path) -> str: 

111 """The file's sha256, read in chunks: what a release manifest lists for each published file.""" 

112 digest = hashlib.sha256() 

113 with Path(path).open("rb") as handle: 

114 for block in iter(lambda: handle.read(1 << 20), b""): 

115 digest.update(block) 

116 return digest.hexdigest() 

117 

118 

119def zip_problems(path: Path) -> list[str]: 

120 """What is wrong inside an example zip: a missing manifest, a file the manifest does not list, or a file whose hash differs.""" 

121 problems = [] 

122 with zipfile.ZipFile(path) as archive: 

123 names = set(archive.namelist()) 

124 if "manifest.json" not in names: 

125 return ["no manifest.json"] 

126 listed = json.loads(archive.read("manifest.json")).get("files", {}) 

127 for name in sorted(names - {"manifest.json"}): 

128 if name not in listed: 

129 problems.append(f"{name}: not in the manifest") 

130 elif hashlib.sha256(archive.read(name)).hexdigest() != listed[name]: 

131 problems.append(f"{name}: sha256 differs from the manifest") 

132 problems.extend(f"{name}: listed but missing" for name in sorted(set(listed) - names)) 

133 return problems 

134 

135 

136def install_zip(path: Path, *, name: str, expected_sha256: str | None = None, root: Path | None = None, allow_unlisted: bool = False) -> Path: 

137 """Checks a downloaded (or local) example zip and unpacks it into `root/<name>/`. Refuses an unknown name (unless 

138 `allow_unlisted`: a zip `aq lab export` wrote), a hash that differs from `expected_sha256`, or any problem inside; a 

139 refusal leaves the cache as it was.""" 

140 if not allow_unlisted and name not in EXAMPLES: 

141 raise ValueError(f"unknown example model {name!r}; expected one of {sorted(EXAMPLES)}") 

142 if expected_sha256 is not None and sha256_file(path) != expected_sha256: 

143 raise ValueError(f"{Path(path).name}: sha256 differs from the release manifest; refusing it") 

144 problems = zip_problems(path) 

145 if problems: 

146 raise ValueError(f"{Path(path).name}: {'; '.join(problems)}") 

147 target = Path(root or DEFAULT_ROOT) / name 

148 staging = target.with_name(f".{name}.partial") 

149 shutil.rmtree(staging, ignore_errors=True) 

150 with zipfile.ZipFile(path) as archive: 

151 archive.extractall(staging) 

152 shutil.rmtree(target, ignore_errors=True) 

153 staging.rename(target) 

154 return target 

155 

156 

157def _download(url: str, destination: Path, *, opener: Callable[..., Any] = urllib.request.urlopen) -> Path: 

158 destination.parent.mkdir(parents=True, exist_ok=True) 

159 with opener(url, timeout=60) as response, destination.open("wb") as handle: 

160 shutil.copyfileobj(response, handle) 

161 return destination 

162 

163 

164def install(name: str, *, version: str | None = None, root: Path | None = None, opener: Callable[..., Any] = urllib.request.urlopen) -> Path: 

165 """Downloads `name` from the release (the latest, or `v<version>`), checks it against the release manifest and unpacks it. 

166 Returns the model's folder.""" 

167 if name not in EXAMPLES: 

168 raise ValueError(f"unknown example model {name!r}; expected one of {sorted(EXAMPLES)}") 

169 folder = Path(root or DEFAULT_ROOT) 

170 manifest = json.loads(_download(release_url(MANIFEST_ASSET, version=version), folder / ".downloads" / MANIFEST_ASSET, opener=opener).read_text(encoding="utf-8")) 

171 entry = manifest.get("models", {}).get(name) 

172 if not entry: 

173 raise ValueError(f"the release manifest lists no {name!r}") 

174 zip_path = _download(release_url(f"{name}.zip", version=version), folder / ".downloads" / f"{name}.zip", opener=opener) 

175 return install_zip(zip_path, name=name, expected_sha256=entry["sha256"], root=folder) 

176 

177 

178def load(name_or_path: str | Path, *, root: Path | None = None) -> dict[str, Any]: 

179 """An installed example (by name) or any folder holding one exported model and its schema (your own `ml/versions/<id>/`, say): 

180 {"name", "kind", "export", "schema", "card"}.""" 

181 folder = Path(name_or_path) 

182 cached = Path(root or DEFAULT_ROOT) / str(name_or_path) 

183 if str(name_or_path) in EXAMPLES or (not folder.is_dir() and cached.is_dir()): 

184 folder = cached 

185 lab_features = folder / "lab_features.json" 

186 kinds = (("sequence", "sequence_model.json", "sequence_feature_schema.json"), ("multitask", "multitask_model.json", "multitask_feature_schema.json"), 

187 ("baseline", "baseline_model.json", "baseline_feature_schema.json"), ("linear", "linear_model.json", "linear_feature_schema.json")) 

188 for kind, model_file, schema_file in kinds: 

189 if (folder / model_file).exists(): 

190 card = folder / "card.md" 

191 return { 

192 "name": folder.name, "kind": kind, "export": json.loads((folder / model_file).read_text(encoding="utf-8")), 

193 "schema": json.loads((folder / schema_file).read_text(encoding="utf-8")), "card": card.read_text(encoding="utf-8") if card.exists() else "", 

194 "lab_features": json.loads(lab_features.read_text(encoding="utf-8")) if lab_features.exists() else None, 

195 } 

196 raise FileNotFoundError(f"no exported model in {folder} (install it first: aq models install <name>)") 

197 

198 

199def score(model: Mapping[str, Any], closes: pd.DataFrame, *, head: str = "rank_20d") -> pd.DataFrame: 

200 """One model's `head` for every (date, ticker) the close table has every feature for, as long rows (date, ticker, score). The inputs 

201 are `example_features(closes)` in the schema's order; a sequence model reads each ticker's last `window_size` rows, zero-padded.""" 

202 from inference import run_exported_model, run_exported_multitask_model, run_exported_sequence_multitask_model_batched 

203 from retraining.slicing import gather_windows, sequence_window_index 

204 

205 names = list(model["schema"]["model_input_names"]) 

206 if model.get("lab_features"): 

207 frame = lab_features_frame(closes, names) 

208 else: 

209 frame = example_features(closes).dropna(subset=names).sort_values(["ticker", "date"]).reset_index(drop=True) 

210 matrix = frame[names].to_numpy(dtype=np.float64) 

211 if model["kind"] == "linear": 

212 coefficients = np.asarray(model["export"]["coefficients"], dtype=float) 

213 frame["score"] = coefficients[0] + matrix @ coefficients[1:] 

214 return frame[["date", "ticker", "score"]].sort_values(["date", "ticker"]).reset_index(drop=True) 

215 if model["kind"] == "baseline": 

216 frame["score"] = [run_exported_model(model["export"], list(row)) for row in matrix] 

217 return frame[["date", "ticker", "score"]].sort_values(["date", "ticker"]).reset_index(drop=True) 

218 if model["kind"] == "sequence": 

219 window = int(model["schema"].get("window_size") or model["export"]["model"]["window_size"]) 

220 sequences = gather_windows(matrix, sequence_window_index(frame["ticker"].to_numpy(), window)).tolist() 

221 outputs = run_exported_sequence_multitask_model_batched(model["export"], sequences) 

222 else: 

223 outputs = [run_exported_multitask_model(model["export"], list(row)) for row in matrix] 

224 frame["score"] = [None if output is None else output.get(head) for output in outputs] 

225 return frame[["date", "ticker", "score"]].sort_values(["date", "ticker"]).reset_index(drop=True) 

226 

227 

228def lab_features_frame(closes: pd.DataFrame, names: Sequence[str]) -> pd.DataFrame: 

229 """A lab model's inputs: the registry features it was trained on, each as its within-date percentile rank minus one half 

230 (missing = 0), sorted by ticker and date as the sequence windows need.""" 

231 from features.feature_registry import build_long 

232 

233 frame = build_long(closes, list(names)) 

234 ranked = frame.groupby("date", sort=False)[list(names)].rank(pct=True) - 0.5 

235 frame[list(names)] = ranked.fillna(0.0) 

236 return frame.sort_values(["ticker", "date"]).reset_index(drop=True) 

237