Coverage for evaluation/lean_statistics.py: 100%

102 statements  

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

1"""Lean's portfolio statistics, reproduced from a backtest result (V6.2.0). 

2 

3Lean's Sharpe ratio is (AnnualPerformance - average risk-free rate) / AnnualStandardDeviation, where (Lean source, 

4Common/Statistics/Statistics.cs, StatisticsBuilder.cs, PortfolioStatistics.cs, Common/Data/InterestRateProvider.cs): 

5 

6 * the daily performance list is the result's "Strategy Equity / Return" series in percent, first two points dropped, 

7 every calendar day it holds (a portfolio with crypto has weekend points); 

8 * AnnualPerformance = (1 + mean)^N - 1 and AnnualVariance = sample variance x N, N = `tradingDaysPerYear`; 

9 * the risk-free rate is the mean of the filled-forward primary credit rate 

10 (data/alternative/interest-rate/usa/interest-rate.csv, percent) over every equity-curve sample (several a day); 

11 * Sortino uses the annual variance of the returns below 0; PSR the observed (daily) Sharpe with skew / kurtosis. 

12 

13This reproduces Lean's printed statistics exactly (V6.1 BT1: -1.673), so a counterfactual - a refreshed risk-free 

14file, another day count, extra daily returns such as a T-bill sweep's - can be priced before a Lean run is spent. 

15Stdlib + math only. 

16""" 

17 

18from __future__ import annotations 

19 

20import bisect 

21import json 

22import math 

23from collections.abc import Iterable, Sequence 

24from datetime import date, datetime, timezone 

25from pathlib import Path 

26from typing import Any 

27 

28DEFAULT_RISK_FREE_RATE = 0.01 # InterestRateProvider.DefaultRiskFreeRate, used before the file's first row 

29 

30 

31def load_backtest_series(result_path: str | Path) -> dict[str, Any]: 

32 """The daily performance list (fractions, Lean's own preprocessing) and the equity dates of one Lean result JSON.""" 

33 result = json.loads(Path(result_path).read_text(encoding="utf-8")) 

34 series = result["charts"]["Strategy Equity"]["series"] 

35 returns = [(_utc_date(point[0]), float(point[1]) / 100.0) for point in series["Return"]["values"] if point[1] is not None] 

36 # every equity sample, duplicates included: Lean averages the rate over the equity curve's points, not its days 

37 equity_dates = [_utc_date(point[0]) for point in series["Equity"]["values"]] 

38 configuration = result.get("algorithmConfiguration") or {} 

39 return { 

40 "performance": [value for _day, value in returns[2:]], 

41 "performance_dates": [day for day, _value in returns[2:]], 

42 "equity_dates": equity_dates, 

43 "trading_days_per_year": int(configuration.get("tradingDaysPerYear") or 252), 

44 "statistics": result.get("statistics", {}), 

45 } 

46 

47 

48def _utc_date(timestamp: float) -> date: 

49 return datetime.fromtimestamp(float(timestamp), timezone.utc).date() 

50 

51 

52def load_interest_rate_changes(path: str | Path) -> list[tuple[date, float]]: 

53 """(date, rate as a fraction) rows of Lean's interest-rate file, sorted; a header or malformed row is skipped.""" 

54 changes = [] 

55 for line in Path(path).read_text(encoding="utf-8").splitlines(): 

56 parts = line.strip().split(",") 

57 if len(parts) < 2: 

58 continue 

59 try: 

60 changes.append((date.fromisoformat(parts[0].strip()), float(parts[1]) / 100.0)) 

61 except ValueError: 

62 continue 

63 return sorted(changes) 

64 

65 

66def rate_on(day: date, changes: Sequence[tuple[date, float]]) -> float: 

67 """The rate in force on `day`: the last change on or before it (filled forward past the file's end).""" 

68 position = bisect.bisect_right([change_day for change_day, _rate in changes], day) - 1 

69 if position < 0: 

70 return changes[0][1] if changes else DEFAULT_RISK_FREE_RATE 

71 return changes[position][1] 

72 

73 

74def average_risk_free_rate(days: Iterable[date], changes: Sequence[tuple[date, float]]) -> float: 

75 days = list(days) 

76 if not days: 

77 return 0.0 

78 keys = [change_day for change_day, _rate in changes] 

79 total = 0.0 

80 for day in days: 

81 position = bisect.bisect_right(keys, day) - 1 

82 total += changes[max(position, 0)][1] if changes else DEFAULT_RISK_FREE_RATE 

83 return total / len(days) 

84 

85 

86def _mean(values: Sequence[float]) -> float: 

87 return sum(values) / len(values) if values else 0.0 

88 

89 

90def _sample_variance(values: Sequence[float]) -> float: 

91 if len(values) < 2: 

92 return float("nan") 

93 mean = _mean(values) 

94 return sum((value - mean) ** 2 for value in values) / (len(values) - 1) 

95 

96 

97def _annual_variance(values: Sequence[float], days: int) -> float: 

98 variance = _sample_variance(values) 

99 return 0.0 if not math.isfinite(variance) or variance == 0.0 else variance * days 

100 

101 

102def _skewness(values: Sequence[float]) -> float: 

103 n = len(values) 

104 if n < 3: 

105 return float("nan") 

106 mean, sd = _mean(values), math.sqrt(_sample_variance(values)) 

107 if sd == 0.0: 

108 return float("nan") 

109 return n / ((n - 1) * (n - 2)) * sum(((value - mean) / sd) ** 3 for value in values) 

110 

111 

112def _excess_kurtosis(values: Sequence[float]) -> float: 

113 n = len(values) 

114 if n < 4: 

115 return float("nan") 

116 mean, sd = _mean(values), math.sqrt(_sample_variance(values)) 

117 if sd == 0.0: 

118 return float("nan") 

119 fourth = sum(((value - mean) / sd) ** 4 for value in values) 

120 return (n + 1) * n / ((n - 1) * (n - 2) * (n - 3)) * fourth - 3 * (n - 1) ** 2 / ((n - 2) * (n - 3)) 

121 

122 

123def _normal_cdf(value: float) -> float: 

124 return 0.5 * (1.0 + math.erf(value / math.sqrt(2.0))) 

125 

126 

127def lean_statistics( 

128 performance: Sequence[float], equity_dates: Iterable[date], *, trading_days_per_year: int, 

129 rate_changes: Sequence[tuple[date, float]], 

130) -> dict[str, Any]: 

131 """Sharpe, Sortino, PSR and their inputs exactly as Lean computes them; non-finite inputs give 0 like Lean's guards.""" 

132 values = [float(value) for value in performance if value is not None and math.isfinite(float(value))] 

133 days = int(trading_days_per_year) 

134 risk_free = average_risk_free_rate(equity_dates, rate_changes) 

135 annual_return = (1.0 + _mean(values)) ** days - 1.0 if values else 0.0 

136 annual_std = math.sqrt(_annual_variance(values, days)) 

137 downside_std = math.sqrt(_annual_variance([value for value in values if value < 0.0], days)) 

138 sharpe = 0.0 if annual_std == 0.0 else (annual_return - risk_free) / annual_std 

139 sortino = 0.0 if downside_std == 0.0 else (annual_return - risk_free) / downside_std 

140 daily_sd = math.sqrt(_sample_variance(values)) if len(values) > 1 else float("nan") 

141 observed = 0.0 if not math.isfinite(daily_sd) or daily_sd == 0.0 else (_mean(values) - risk_free / days) / daily_sd 

142 skew, kurtosis = _skewness(values), _excess_kurtosis(values) 

143 psr = 0.0 

144 if len(values) > 1 and math.isfinite(skew) and math.isfinite(kurtosis): 

145 estimate = (1 - skew * observed + (kurtosis - 1) / 4 * observed**2) / (len(values) - 1) 

146 if estimate > 0.0: 

147 psr = _normal_cdf((observed - 1.0 / math.sqrt(days)) / math.sqrt(estimate)) 

148 return { 

149 "sharpe_ratio": sharpe, "sortino_ratio": sortino, "probabilistic_sharpe_ratio": psr, 

150 "annual_return": annual_return, "annual_standard_deviation": annual_std, "risk_free_rate": risk_free, 

151 "trading_days_per_year": days, "observations": len(values), 

152 } 

153 

154 

155def with_extra_daily_returns( 

156 performance: Sequence[float], performance_dates: Sequence[date], extra_by_date: dict[date, float], 

157) -> list[float]: 

158 """Counterfactual daily performance: each day's return plus `extra_by_date[day]` (e.g. a sweep's weight x its 

159 T-bill return, as a fraction of NAV). Additive in return space, which is exact to first order for a small sleeve.""" 

160 return [value + float(extra_by_date.get(day, 0.0)) for value, day in zip(performance, performance_dates, strict=False)] 

161 

162 

163def statistics_table(result_path: str | Path, rate_files: dict[str, str | Path], day_counts: Sequence[int] = (252, 365)) -> dict[str, Any]: 

164 """Lean's printed statistics next to the replica on every (rate file, day count): `aq evaluate --lean-stats`.""" 

165 series = load_backtest_series(result_path) 

166 rows = {} 

167 for label, path in rate_files.items(): 

168 changes = load_interest_rate_changes(path) 

169 for days in day_counts: 

170 rows[f"{label}/{days}"] = lean_statistics( 

171 series["performance"], series["equity_dates"], trading_days_per_year=days, rate_changes=changes 

172 ) 

173 printed = series["statistics"] 

174 return { 

175 "lean_printed": {key: printed.get(key) for key in ("Sharpe Ratio", "Sortino Ratio", "Probabilistic Sharpe Ratio", 

176 "Annual Standard Deviation", "Compounding Annual Return")}, 

177 "run_trading_days_per_year": series["trading_days_per_year"], 

178 "replica": rows, 

179 }