Coverage for risk/kelly.py: 100%
30 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Kelly sizing (V6.6.5, #345): the growth-optimal fraction, shrunk by `fraction` (half Kelly by default) and capped.
3Full Kelly is `mean / variance` for one bet and `inv(cov) @ mu` for many. Estimation error makes full Kelly far too large in
4practice, so the default is half Kelly with a cap; a non-finite or degenerate input sizes to zero, never to a guess.
5"""
7from __future__ import annotations
9import math
11import numpy as np
13__all__ = ["kelly_fraction", "kelly_weights"]
16def kelly_fraction(mean: float, variance: float, *, fraction: float = 0.5, cap: float = 1.0) -> float:
17 """`fraction * mean / variance`, clipped to [-cap, cap]. Zero for a non-positive or non-finite variance or input."""
18 try:
19 mu, var, share, limit = float(mean), float(variance), float(fraction), abs(float(cap))
20 except (TypeError, ValueError):
21 return 0.0
22 if not all(math.isfinite(value) for value in (mu, var, share, limit)) or var <= 0.0 or share <= 0.0:
23 return 0.0
24 return float(min(max(share * mu / var, -limit), limit))
27def kelly_weights(mu: np.ndarray, cov: np.ndarray, *, fraction: float = 0.5, gross_cap: float = 1.0, ridge: float = 1e-8) -> np.ndarray:
28 """`fraction * solve(cov + ridge*I, mu)`, scaled down (never up) so that `sum(|w|) <= gross_cap`. Zeros when an input
29 is non-finite, the shapes disagree, or the system is singular."""
30 mean = np.asarray(mu, dtype=float).ravel()
31 matrix = np.asarray(cov, dtype=float)
32 zeros = np.zeros_like(mean)
33 if matrix.shape != (mean.size, mean.size) or not np.all(np.isfinite(mean)) or not np.all(np.isfinite(matrix)):
34 return zeros
35 share, cap = float(fraction), abs(float(gross_cap))
36 if not math.isfinite(share) or share <= 0.0 or not math.isfinite(cap):
37 return zeros
38 try:
39 raw = np.linalg.solve(matrix + max(float(ridge), 0.0) * np.eye(mean.size), mean)
40 except np.linalg.LinAlgError:
41 return zeros
42 weights = share * raw
43 if not np.all(np.isfinite(weights)):
44 return zeros
45 gross = float(np.abs(weights).sum())
46 return weights * (cap / gross) if gross > cap and gross > 0.0 else weights