Coverage for notebooks/src/04_models.py: 100%

30 statements  

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

1# %% [markdown] 

2# # Models: load an exported model and score with numpy 

3# 

4# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/leon1706-lol/Aether-quant/blob/main/notebooks/04_models.ipynb) 

5# 

6# `aether_quant.models` loads any folder that holds an exported model and its feature schema, and scores a close table with the library's numpy forward pass: no torch. Each GitHub release publishes two small example models trained on the bundled sample (`aq models install example-crypto-mlp`); the project's own trading models are not published. 

7# 

8# This notebook stays offline. It writes a hand-made one-layer model in the export format, so the steps are the same as for a trained example or your own retrain's `ml/versions/<id>/`. 

9 

10# %% 

11import sys 

12from pathlib import Path 

13 

14if "google.colab" in sys.modules: # Colab: install the library (numpy and pandas come with it) 

15 get_ipython().run_line_magic("pip", 'install -q "aether-quant[notebooks]"') # noqa: F821 

16else: # a clone: run against the checkout's code 

17 for parent in (Path.cwd(), *Path.cwd().parents): 

18 if (parent / "aether_quant" / "__init__.py").is_file(): 

19 sys.path.insert(0, str(parent)) 

20 break 

21 

22# %% [markdown] 

23# ## The catalog 

24# 

25# The examples each release carries. `models.install(name)` downloads one, checks its sha256 against the release's manifest and unpacks it into `~/.cache/aether-quant/models`; `models.load(name)` then opens it. 

26 

27# %% 

28import pandas as pd 

29 

30from aether_quant import models, samples 

31 

32pd.DataFrame(models.catalog())[["name", "kind", "summary"]] 

33 

34# %% [markdown] 

35# ## The features 

36# 

37# Six features per coin and session, each from closes up to that session only, z-scored across the coins of the date: returns over 1, 5, 20 and 60 sessions and volatility over 20 and 60. 

38 

39# %% 

40closes = samples.load_sample_prices() 

41features = models.example_features(closes) 

42names = [column for column in features.columns if column not in ("date", "ticker")] 

43features.dropna().tail() 

44 

45# %% [markdown] 

46# ## A model folder 

47# 

48# The export format is a list of layers and a state dict. This one is linear: 20-session momentum minus half the 20-session volatility, read through one `rank_20d` head. 

49 

50# %% 

51import json 

52import tempfile 

53 

54folder = Path(tempfile.mkdtemp()) / "momentum-minus-volatility" 

55folder.mkdir(parents=True) 

56export = {"trunk": [{"type": "linear", "weight_key": "w", "bias_key": "b"}], "heads": {"rank_20d": [{"type": "linear", "weight_key": "h", "bias_key": "hb"}]}, 

57 "state_dict": {"w": [[0.0, 0.0, 1.0, 0.0, -0.5, 0.0]], "b": [0.0], "h": [[1.0]], "hb": [0.0]}} 

58(folder / "multitask_model.json").write_text(json.dumps({"export": export}), encoding="utf-8") 

59(folder / "multitask_feature_schema.json").write_text(json.dumps({"model_input_names": names}), encoding="utf-8") 

60model = models.load(folder) 

61print(model["name"], model["kind"], model["schema"]["model_input_names"]) 

62 

63# %% [markdown] 

64# ## Score and look at the ranking 

65# 

66# `models.score` returns long rows (date, ticker, score) for every session the features exist. A trained example scores the same way. 

67 

68# %% 

69import matplotlib.pyplot as plt 

70 

71scores = models.score(model, closes) 

72last = scores[scores["date"] == scores["date"].max()].set_index("ticker")["score"].sort_values() 

73axes = last.plot.barh(figsize=(7, 3.2), title=f"Scores on {scores['date'].max()}") 

74plt.show() 

75print(f"{len(scores)} rows, {scores['ticker'].nunique()} coins, {scores['date'].min()} to {scores['date'].max()}") 

76 

77# %% [markdown] 

78# *A score is not a result. Judge one with the IC report and the overfitting tests of the first notebooks before any book trades on it.*