Coverage for evaluation/lean_benchmarks.py: 100%

33 statements  

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

1"""What a finished Lean run earned against what a reader could have held instead: the README's Benchmarks table. 

2 

3Every series is compounded onto the US equity session calendar and scored by one formula (no risk-free rate), so a book 

4that also trades at weekends is compared on the same intervals as SPY.""" 

5 

6from __future__ import annotations 

7 

8import math 

9 

10import numpy as np 

11import pandas as pd 

12 

13PERIODS_PER_YEAR = 252.0 

14STOCK_WEIGHT = 0.6 

15 

16 

17def series_row(name: str, returns: pd.Series, *, periods_per_year: float = PERIODS_PER_YEAR) -> dict: 

18 """Total and annual return, volatility, Sharpe and maximum drawdown of one return series.""" 

19 values = np.asarray(returns.dropna(), dtype=float) 

20 if values.size < 2: 

21 return {"series": name, "total_return": None, "annual_return": None, "volatility": None, "sharpe": None, "max_drawdown": None} 

22 equity = np.cumprod(1.0 + values) 

23 peaks = np.maximum.accumulate(np.concatenate(([1.0], equity)))[1:] 

24 deviation = float(values.std(ddof=1)) 

25 total = float(equity[-1] - 1.0) 

26 return { 

27 "series": name, 

28 "total_return": total, 

29 "annual_return": float((1.0 + total) ** (periods_per_year / values.size) - 1.0) if total > -1.0 else None, 

30 "volatility": deviation * math.sqrt(periods_per_year), 

31 "sharpe": float(values.mean()) / deviation * math.sqrt(periods_per_year) if deviation > 0 else None, 

32 "max_drawdown": float(np.max(1.0 - equity / peaks)), 

33 } 

34 

35 

36def benchmark_rows(portfolio: pd.Series, strategy: pd.Series, benchmarks: pd.DataFrame, crypto: list[str]) -> list[dict]: 

37 """The run and its alternatives over the same sessions. `benchmarks` holds session returns; `crypto` names the coins the 

38 run traded, held equally weighted and rebalanced daily with no fees.""" 

39 sessions = portfolio.index.intersection(benchmarks.index) 

40 if not len(sessions): 

41 return [] 

42 table = benchmarks.loc[sessions] 

43 rows = [series_row("**Portfolio** (with the T-bill sweep)", portfolio.loc[sessions])] 

44 if not strategy.empty: 

45 rows.append(series_row("**Strategy** (without the sweep)", strategy.reindex(sessions).fillna(0.0))) 

46 if "SPY" in table: 

47 rows.append(series_row("SPY", table["SPY"])) 

48 if "SPY" in table and "AGG" in table: 

49 rows.append(series_row("60/40 SPY/AGG, rebalanced daily", STOCK_WEIGHT * table["SPY"] + (1.0 - STOCK_WEIGHT) * table["AGG"])) 

50 if "BTCUSD" in table: 

51 rows.append(series_row("Bitcoin, buy and hold", table["BTCUSD"])) 

52 coins = [coin for coin in crypto if coin in table] 

53 if len(coins) > 1: 

54 rows.append(series_row(f"The book's {len(coins)} coins, equal weight", table[coins].mean(axis=1))) 

55 return rows