Coverage for notebooks/src/02_book_construction.py: 100%

50 statements  

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

1# %% [markdown] 

2# # Book construction: from scores to a tradable, costed book 

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/02_book_construction.ipynb) 

5# 

6# One signal, the 20-day momentum of 11 coins, taken through each step a book goes through: 

7# 

8# 1. **A rank book.** Long the top names and short the bottom ones, with `build_rank_based_book`, the function the live algorithm calls. 

9# 2. **Neutrality.** Dollar neutrality with per-name caps (`apply_book_neutrality`), then beta neutrality against BTC. 

10# 3. **Allocation and sizing.** Hierarchical risk parity, volatility targeting and fractional Kelly. 

11# 4. **Costs.** Composable cost models, and `backtest()` with and without them. 

12 

13# %% 

14import sys 

15from pathlib import Path 

16 

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

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

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

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

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

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

23 break 

24 

25# %% 

26import pandas as pd 

27 

28from aether_quant import backtest, costs, neutrality, portfolio, samples, sizing 

29 

30closes = samples.load_sample_prices().loc["2023-07-13":] 

31opens = samples.load_sample_prices("open").loc[closes.index] 

32returns = closes.pct_change(fill_method=None) 

33momentum = closes / closes.shift(20) - 1 

34 

35# %% [markdown] 

36# ## 1. A rank book on one day 

37# 

38# `build_rank_based_book` takes each name's predicted rank, here the momentum percentile, and returns the long and short slots with the reason for each. 

39 

40# %% 

41day = "2025-03-03" 

42ranks = momentum.loc[day].rank(pct=True) 

43candidates = {ticker: {"predicted_rank_20d": float(rank), "trading_eligible": True, "asset_class": "crypto"} for ticker, rank in ranks.items()} 

44book = portfolio.build_rank_based_book(candidates, top_n=3, bottom_n=3) 

45pd.DataFrame({ticker: {"role": alloc.role, "rank": round(alloc.predicted_rank_20d, 2), "reason": alloc.book_reason} for ticker, alloc in book.items()}).T 

46 

47# %% [markdown] 

48# ## 2. Neutrality: dollars, then beta 

49# 

50# Equal raw weights become a dollar-neutral book with a 20% per-name cap. Crypto names have very different betas to BTC, so a dollar-neutral book can still carry a market bet. `beta_neutralize` removes it with the smallest change to the weights. 

51 

52# %% 

53raw = {ticker: (0.3 if alloc.role == "long" else -0.3) for ticker, alloc in book.items()} 

54dollar_neutral, steps = neutrality.apply_book_neutrality( 

55 raw, sector_by_symbol=dict.fromkeys(raw, "crypto"), dollar_neutral=True, sector_neutral=False, gross_exposure_cap=1.0, 

56 max_weight_per_name=0.2, sector_max_net_weight=1.0, 

57) 

58betas = neutrality.estimate_betas(returns.loc[:day], returns["BTCUSD"].loc[:day], window=120).to_dict() 

59beta_neutral = neutrality.beta_neutralize(dollar_neutral, betas) 

60print(f"net beta to BTC: dollar neutral {neutrality.net_beta(dollar_neutral, betas):+.3f}, beta neutral {neutrality.net_beta(beta_neutral, betas):+.6f}") 

61print("neutrality steps:", steps["steps_applied"]) 

62pd.DataFrame({"raw": raw, "dollar neutral": dollar_neutral, "beta neutral": beta_neutral, "beta to BTC": betas}).loc[list(raw)].round(3) 

63 

64# %% [markdown] 

65# ## 3. Allocation and sizing 

66# 

67# These three answer different questions: 

68# 

69# - **HRP:** how to split risk across correlated names without inverting a noisy covariance matrix. 

70# - **Volatility targeting:** how big the whole book should be. 

71# - **Kelly:** the growth-optimal size if the expected returns were known. They never are, so the default is half Kelly with a cap. 

72 

73# %% 

74history = returns.loc["2024-03-01":day].dropna(axis=1) 

75hrp = portfolio.compute_hrp_weights(history) 

76scaled = sizing.volatility_target_weights(hrp.to_dict(), history.cov(), target_annual_vol=0.10, max_leverage=1.0, annualization=365) 

77mu = history.mean().to_numpy() * 0.25 # a shrunk view of expected returns; the raw sample mean is far too noisy for Kelly 

78half_kelly = sizing.kelly_weights(mu, history.cov().to_numpy(), fraction=0.5, gross_cap=1.0) 

79pd.DataFrame({"HRP": hrp, "HRP at 10% vol": pd.Series(scaled), "half Kelly (capped)": pd.Series(half_kelly, index=history.columns)}).round(3) 

80 

81# %% [markdown] 

82# ## 4. Costs, and a backtest with and without them 

83# 

84# A cost model answers one question: what does one trade cost, in basis points? Models add up. The presets are the fees the live path charges, so a research cost and a live cost are the same numbers. 

85 

86# %% 

87coinbase = costs.coinbase_model() 

88impact = costs.CompositeCostModel((costs.LinearCostModel(commission_bps=5.0, half_spread_bps=2.0), costs.SquareRootImpactModel(eta=1.0))) 

89print("Coinbase market order:", coinbase.cost_bps(10_000.0), "bps") 

90print("5 bps + 2 bps spread + impact, $1M into $50M ADV at 3% daily vol:", round(impact.cost_bps(1e6, adv_usd=5e7, daily_vol=0.03), 1), "bps") 

91 

92# %% 

93rank = momentum.rank(axis=1, pct=True) 

94signal_weights = rank.sub(rank.mean(axis=1), axis=0) 

95signal_weights = signal_weights.div(signal_weights.abs().sum(axis=1), axis=0) # dollar neutral, gross 1 

96weekly = signal_weights.where(pd.Series(range(len(signal_weights)), index=signal_weights.index) % 7 == 0) # decide once a week 

97start = "2023-09-01" 

98runs = { 

99 "no costs": backtest.backtest(weekly.loc[start:], closes.loc[start:], opens=opens.loc[start:], periods_per_year=365), 

100 "Coinbase costs": backtest.backtest(weekly.loc[start:], closes.loc[start:], opens=opens.loc[start:], cost_model=coinbase, periods_per_year=365), 

101} 

102pd.DataFrame({name: run.stats() for name, run in runs.items()}).loc[["cagr", "sharpe_ratio", "max_drawdown", "turnover_annual", "cost_drag_bps_annual"]].round(3) 

103 

104# %% [markdown] 

105# ## Turnover against cost 

106# 

107# The same book at rising cost levels. A signal that only works below the venue's real cost is not a signal you can trade. 

108 

109# %% 

110import matplotlib.pyplot as plt 

111 

112levels = [0, 10, 25, 50, 90, 150] 

113sweep = pd.Series({bps: backtest.backtest(weekly.loc[start:], closes.loc[start:], opens=opens.loc[start:], cost_model=costs.LinearCostModel(commission_bps=bps), 

114 periods_per_year=365).stats()["sharpe_ratio"] for bps in levels}) 

115axes = sweep.plot(marker="o", figsize=(7, 3.2), title="Sharpe of the weekly momentum book by cost per trade (bps)") 

116axes.axvline(90, color="#d97706", linestyle="--", linewidth=0.8) 

117axes.axhline(0, color="#9ca3af", linewidth=0.8) 

118plt.show() 

119 

120# %% [markdown] 

121# **Next:** [03 overfitting tests](03_overfitting_tests.ipynb). How much of a backtest's Sharpe survives the search that found it?