stratstat 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stratstat/__init__.py +536 -0
- stratstat/container.py +466 -0
- stratstat/conventions.py +189 -0
- stratstat/core/__init__.py +6 -0
- stratstat/core/_utils.py +155 -0
- stratstat/core/benchmark.py +934 -0
- stratstat/core/compare.py +1026 -0
- stratstat/core/exposure.py +1120 -0
- stratstat/core/returns/__init__.py +16 -0
- stratstat/core/returns/descriptive.py +1812 -0
- stratstat/core/returns/inference.py +1711 -0
- stratstat/core/returns/risk.py +1971 -0
- stratstat/core/returns/risk_adjusted.py +1644 -0
- stratstat/core/returns/wrappers.py +196 -0
- stratstat/core/trades.py +1587 -0
- stratstat/exceptions.py +36 -0
- stratstat/inputs.py +1349 -0
- stratstat/py.typed +0 -0
- stratstat/registry.py +594 -0
- stratstat/report/__init__.py +64 -0
- stratstat/report/_charts.py +1040 -0
- stratstat/report/_common.py +115 -0
- stratstat/report/_dashboard.py +228 -0
- stratstat/report/_export.py +136 -0
- stratstat/report/_report.py +1169 -0
- stratstat/report/_tearsheet.py +214 -0
- stratstat/results.py +460 -0
- stratstat/schema.py +356 -0
- stratstat-0.1.0.dist-info/METADATA +439 -0
- stratstat-0.1.0.dist-info/RECORD +33 -0
- stratstat-0.1.0.dist-info/WHEEL +5 -0
- stratstat-0.1.0.dist-info/licenses/LICENSE +21 -0
- stratstat-0.1.0.dist-info/top_level.txt +1 -0
stratstat/container.py
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
"""Strategy and Comparison containers.
|
|
2
|
+
|
|
3
|
+
A :class:`Strategy` holds one strategy's inputs once and caches the derived
|
|
4
|
+
quantities that several metrics would otherwise recompute: the equity curve,
|
|
5
|
+
the running maximum, the drawdown series, and the drawdown episodes. A
|
|
6
|
+
:class:`Comparison` stacks several strategies' period aligned returns into a
|
|
7
|
+
single ``(n_periods, n_strategies)`` matrix and runs the vectorized engine
|
|
8
|
+
once, then slices per strategy.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import warnings
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, cast
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
from numpy.typing import NDArray
|
|
19
|
+
|
|
20
|
+
from stratstat.inputs import CompareInput, ExposureInput, ReturnsInput, TradeInput
|
|
21
|
+
from stratstat.results import MetricSet
|
|
22
|
+
from stratstat.schema import _coerce
|
|
23
|
+
|
|
24
|
+
# (equity, running_max, drawdown_series, episodes) produced by the risk module.
|
|
25
|
+
_Drawdowns = tuple[
|
|
26
|
+
NDArray[np.floating],
|
|
27
|
+
NDArray[np.floating],
|
|
28
|
+
NDArray[np.floating],
|
|
29
|
+
list[list[dict[str, Any]]],
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _read_position_size(trades: Any) -> NDArray[np.floating] | None:
|
|
34
|
+
"""Read an optional ``position_size`` column from a raw trade log.
|
|
35
|
+
|
|
36
|
+
``position_size`` is not yet a formal contract column (it lands with
|
|
37
|
+
Package B); read it opportunistically here so the reconciliation uses
|
|
38
|
+
account basis whenever the caller happens to supply it, and falls back to
|
|
39
|
+
full account (1.0) otherwise.
|
|
40
|
+
"""
|
|
41
|
+
if isinstance(trades, dict):
|
|
42
|
+
col = trades.get("position_size")
|
|
43
|
+
if col is None:
|
|
44
|
+
return None
|
|
45
|
+
return np.asarray(col, dtype=np.float64).ravel()
|
|
46
|
+
|
|
47
|
+
columns = getattr(trades, "columns", None)
|
|
48
|
+
if columns is not None and "position_size" in columns:
|
|
49
|
+
return np.asarray(trades["position_size"], dtype=np.float64).ravel()
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ---------------------------------------------------------------------------
|
|
54
|
+
# Strategy
|
|
55
|
+
# ---------------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Strategy:
|
|
59
|
+
"""One strategy: inputs built once, derived quantities cached once.
|
|
60
|
+
|
|
61
|
+
Parameters mirror the container input contract. ``returns``, ``equity``,
|
|
62
|
+
``trades``, ``positions``, ``asset_returns``, ``prices``, ``benchmark``,
|
|
63
|
+
``periods_per_year``, ``rf``, and ``schema`` are all optional. Each
|
|
64
|
+
provided input is turned into its :mod:`stratstat.inputs` container once
|
|
65
|
+
at construction and reused by every ``compute`` call. The equity curve,
|
|
66
|
+
running maximum, drawdown series, and drawdown episodes are derived once
|
|
67
|
+
from the strategy returns and cached, so a report or a later computation
|
|
68
|
+
never redoes that work.
|
|
69
|
+
|
|
70
|
+
When both ``returns`` and ``trades`` are present, construction also runs a
|
|
71
|
+
reconciliation check: each trade's pnl is converted to account basis with
|
|
72
|
+
``position_size`` (full account when absent), compounded, and compared with
|
|
73
|
+
the equity curve's total return. A disagreement raises a warning and the
|
|
74
|
+
figures are recorded on :attr:`reconciliation`.
|
|
75
|
+
|
|
76
|
+
The container is treated as immutable after construction; its inputs and
|
|
77
|
+
cached quantities are not reassigned.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
returns: Any = None,
|
|
83
|
+
*,
|
|
84
|
+
equity: Any = None,
|
|
85
|
+
trades: Any = None,
|
|
86
|
+
positions: Any = None,
|
|
87
|
+
asset_returns: Any = None,
|
|
88
|
+
prices: Any = None,
|
|
89
|
+
benchmark: Any = None,
|
|
90
|
+
periods_per_year: int | None = None,
|
|
91
|
+
rf: float = 0.0,
|
|
92
|
+
schema: Any = None,
|
|
93
|
+
columns: Any = None,
|
|
94
|
+
pnl_basis: str = "trade",
|
|
95
|
+
pnl_unit: str = "fraction",
|
|
96
|
+
) -> None:
|
|
97
|
+
self.schema = _coerce(schema, columns, tier=None)
|
|
98
|
+
self.periods_per_year: int | None = periods_per_year
|
|
99
|
+
self.rf: float = rf
|
|
100
|
+
|
|
101
|
+
# Raw inputs, kept so report() and the benchmark tier can rebuild
|
|
102
|
+
# exactly what was handed in.
|
|
103
|
+
self.returns: Any = returns
|
|
104
|
+
self.trades: Any = trades
|
|
105
|
+
self.positions: Any = positions
|
|
106
|
+
self.asset_returns: Any = asset_returns
|
|
107
|
+
self.equity: Any = equity
|
|
108
|
+
self.benchmark: Any = benchmark
|
|
109
|
+
self.prices: Any = prices
|
|
110
|
+
|
|
111
|
+
# Input containers, built once.
|
|
112
|
+
self.returns_input: ReturnsInput | None = (
|
|
113
|
+
ReturnsInput(returns, periods_per_year=periods_per_year, schema=self.schema)
|
|
114
|
+
if returns is not None
|
|
115
|
+
else None
|
|
116
|
+
)
|
|
117
|
+
self.trades_input: TradeInput | None = (
|
|
118
|
+
TradeInput(
|
|
119
|
+
trades=trades,
|
|
120
|
+
periods_per_year=periods_per_year,
|
|
121
|
+
schema=self.schema,
|
|
122
|
+
pnl_basis=pnl_basis,
|
|
123
|
+
pnl_unit=pnl_unit,
|
|
124
|
+
prices=prices,
|
|
125
|
+
)
|
|
126
|
+
if trades is not None
|
|
127
|
+
else None
|
|
128
|
+
)
|
|
129
|
+
self.exposure_input: ExposureInput | None = (
|
|
130
|
+
ExposureInput(
|
|
131
|
+
positions,
|
|
132
|
+
returns=returns,
|
|
133
|
+
asset_returns=asset_returns,
|
|
134
|
+
benchmark=benchmark,
|
|
135
|
+
equity=equity,
|
|
136
|
+
periods_per_year=periods_per_year,
|
|
137
|
+
schema=self.schema,
|
|
138
|
+
)
|
|
139
|
+
if positions is not None
|
|
140
|
+
else None
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
self._drawdowns: _Drawdowns | None = None
|
|
144
|
+
|
|
145
|
+
# Reconciliation of the trade log against the equity curve, run only
|
|
146
|
+
# when both inputs are present. Recorded even when the figures agree
|
|
147
|
+
# so the check is observable.
|
|
148
|
+
self.reconciliation: dict[str, Any] | None = (
|
|
149
|
+
self._reconcile_trades()
|
|
150
|
+
if returns is not None and trades is not None
|
|
151
|
+
else None
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
def _reconcile_trades(self) -> dict[str, Any] | None:
|
|
155
|
+
"""Reconcile the trade log against the equity curve.
|
|
156
|
+
|
|
157
|
+
With both strategy returns and a trade log present, compounding each
|
|
158
|
+
trade's account basis pnl should reproduce the equity curve's total
|
|
159
|
+
return. Returns a small dict recording the two figures and whether
|
|
160
|
+
``position_size`` was applied, so the check is observable even when the
|
|
161
|
+
numbers agree; warns when they do not.
|
|
162
|
+
"""
|
|
163
|
+
assert self.returns_input is not None and self.trades_input is not None
|
|
164
|
+
|
|
165
|
+
returns = self.returns_input.values
|
|
166
|
+
if returns.shape[1] != 1:
|
|
167
|
+
return None # no single equity curve to reconcile a matrix against
|
|
168
|
+
|
|
169
|
+
strat_returns = returns[:, 0]
|
|
170
|
+
pnl = np.asarray(self.trades_input.pnl, dtype=np.float64)
|
|
171
|
+
if np.any(np.isnan(strat_returns)) or np.any(np.isnan(pnl)):
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
size = _read_position_size(self.trades)
|
|
175
|
+
if size is not None and size.shape[0] == pnl.shape[0]:
|
|
176
|
+
converted = True
|
|
177
|
+
else:
|
|
178
|
+
size = np.ones_like(pnl)
|
|
179
|
+
converted = False
|
|
180
|
+
account_pnl = pnl * size
|
|
181
|
+
if np.any(account_pnl <= -1.0):
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
compounded_pnl = float(np.prod(1.0 + account_pnl) - 1.0)
|
|
185
|
+
equity_total = float(np.prod(1.0 + strat_returns) - 1.0)
|
|
186
|
+
|
|
187
|
+
info: dict[str, Any] = {
|
|
188
|
+
"compounded_account_pnl": compounded_pnl,
|
|
189
|
+
"equity_total_return": equity_total,
|
|
190
|
+
"converted_to_account_basis": converted,
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
close = bool(np.isclose(compounded_pnl, equity_total, rtol=1e-2, atol=1e-4))
|
|
194
|
+
if not close:
|
|
195
|
+
warnings.warn(
|
|
196
|
+
"Trade pnl does not reconcile with the equity curve: compounded "
|
|
197
|
+
f"account pnl is {compounded_pnl:.2%} but strategy returns "
|
|
198
|
+
f"compound to {equity_total:.2%}. This usually means the trade "
|
|
199
|
+
"log omits trades, or the returns include components outside "
|
|
200
|
+
"the trades such as fees, dividends, or cash drag.",
|
|
201
|
+
UserWarning,
|
|
202
|
+
stacklevel=2,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
return info
|
|
206
|
+
|
|
207
|
+
# -- derived quantities (cached) -------------------------------------
|
|
208
|
+
|
|
209
|
+
def _ensure_drawdowns(self) -> _Drawdowns:
|
|
210
|
+
"""Compute the cached drawdown analysis once."""
|
|
211
|
+
if self._drawdowns is None:
|
|
212
|
+
if self.returns_input is None:
|
|
213
|
+
raise ValueError("drawdown quantities require strategy returns")
|
|
214
|
+
from stratstat.core.returns.risk import _analyse_drawdowns
|
|
215
|
+
|
|
216
|
+
self._drawdowns = cast(_Drawdowns, _analyse_drawdowns(self.returns_input.values))
|
|
217
|
+
return self._drawdowns
|
|
218
|
+
|
|
219
|
+
@property
|
|
220
|
+
def equity_curve(self) -> NDArray[np.floating]:
|
|
221
|
+
"""Equity curve derived from returns, cached.
|
|
222
|
+
|
|
223
|
+
Shape ``(n_periods + 1, n_strategies)`` with a prepended 1.0 row so
|
|
224
|
+
the drawdown from start is measured.
|
|
225
|
+
"""
|
|
226
|
+
return self._ensure_drawdowns()[0]
|
|
227
|
+
|
|
228
|
+
@property
|
|
229
|
+
def running_max(self) -> NDArray[np.floating]:
|
|
230
|
+
"""Running maximum of the equity curve, cached."""
|
|
231
|
+
return self._ensure_drawdowns()[1]
|
|
232
|
+
|
|
233
|
+
@property
|
|
234
|
+
def drawdown_series(self) -> NDArray[np.floating]:
|
|
235
|
+
"""Drawdown series (values at or below zero), cached."""
|
|
236
|
+
return self._ensure_drawdowns()[2]
|
|
237
|
+
|
|
238
|
+
@property
|
|
239
|
+
def drawdown_episodes(self) -> list[list[dict[str, Any]]]:
|
|
240
|
+
"""Drawdown episodes per strategy column, cached."""
|
|
241
|
+
return self._ensure_drawdowns()[3]
|
|
242
|
+
|
|
243
|
+
# -- computation ------------------------------------------------------
|
|
244
|
+
|
|
245
|
+
def compute_all(self, **kwargs: Any) -> MetricSet:
|
|
246
|
+
"""Compute every metric for which this strategy has data.
|
|
247
|
+
|
|
248
|
+
Forwards to :func:`stratstat.compute_all` with the containers built at
|
|
249
|
+
construction, so inputs are never rebuilt. Keyword arguments pass
|
|
250
|
+
through to the metric functions (for example ``confidence=0.95``).
|
|
251
|
+
"""
|
|
252
|
+
from stratstat.registry import _compute_all
|
|
253
|
+
|
|
254
|
+
return _compute_all(
|
|
255
|
+
returns=self.returns_input,
|
|
256
|
+
trades=self.trades_input,
|
|
257
|
+
benchmark=self.benchmark,
|
|
258
|
+
exposure=self.exposure_input,
|
|
259
|
+
periods_per_year=self.periods_per_year,
|
|
260
|
+
rf=self.rf,
|
|
261
|
+
schema=self.schema,
|
|
262
|
+
**kwargs,
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
def compute(self, category: str, **kwargs: Any) -> MetricSet:
|
|
266
|
+
"""Compute metrics in one primary statistical category.
|
|
267
|
+
|
|
268
|
+
*category* is a primary tag such as ``"risk"``, ``"descriptive"``, or
|
|
269
|
+
``"trades"``. Keyword arguments pass through to the metric functions.
|
|
270
|
+
"""
|
|
271
|
+
return self.compute_all(category=category, **kwargs)
|
|
272
|
+
|
|
273
|
+
def report(
|
|
274
|
+
self,
|
|
275
|
+
output_path: str | Path,
|
|
276
|
+
*,
|
|
277
|
+
metrics: MetricSet | None = None,
|
|
278
|
+
**kwargs: Any,
|
|
279
|
+
) -> None:
|
|
280
|
+
"""Generate an HTML (or PDF) report for this strategy.
|
|
281
|
+
|
|
282
|
+
Requires ``plotly``. *metrics* lets you hand in a precomputed
|
|
283
|
+
:class:`MetricSet`; otherwise one is computed with :meth:`compute_all`.
|
|
284
|
+
Keyword arguments pass through to
|
|
285
|
+
:func:`stratstat.report.generate_report`.
|
|
286
|
+
"""
|
|
287
|
+
from stratstat.report import generate_report
|
|
288
|
+
|
|
289
|
+
if self.returns is None:
|
|
290
|
+
raise ValueError("Strategy.report() requires strategy returns")
|
|
291
|
+
ms = metrics if metrics is not None else self.compute_all()
|
|
292
|
+
generate_report(
|
|
293
|
+
self.returns,
|
|
294
|
+
output_path,
|
|
295
|
+
benchmark=self.benchmark,
|
|
296
|
+
positions=self.positions,
|
|
297
|
+
asset_returns=self.asset_returns,
|
|
298
|
+
trades=self.trades,
|
|
299
|
+
periods_per_year=self.periods_per_year,
|
|
300
|
+
metrics=ms,
|
|
301
|
+
**kwargs,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
def __repr__(self) -> str:
|
|
305
|
+
n = self.returns_input.n_periods if self.returns_input is not None else 0
|
|
306
|
+
return f"Strategy(n_periods={n}, periods_per_year={self.periods_per_year})"
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
# ---------------------------------------------------------------------------
|
|
310
|
+
# Comparison
|
|
311
|
+
# ---------------------------------------------------------------------------
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
class Comparison:
|
|
315
|
+
"""Several strategies, stacked and run through the vectorized engine once.
|
|
316
|
+
|
|
317
|
+
*strategies* is either a ``{name: returns}`` mapping or a 2-D array-like
|
|
318
|
+
whose columns are strategies. Every series must be period aligned (the
|
|
319
|
+
same length). The container stacks them into one
|
|
320
|
+
``(n_periods, n_strategies)`` matrix, builds a :class:`CompareInput` and a
|
|
321
|
+
:class:`ReturnsInput` once, and runs the returns, benchmark, and compare
|
|
322
|
+
tiers in a single vectorized pass. Use :attr:`strategies` or
|
|
323
|
+
``comparison[name]`` to slice one strategy out for per-strategy work.
|
|
324
|
+
|
|
325
|
+
The container is treated as immutable after construction.
|
|
326
|
+
"""
|
|
327
|
+
|
|
328
|
+
def __init__(
|
|
329
|
+
self,
|
|
330
|
+
strategies: Any,
|
|
331
|
+
*,
|
|
332
|
+
weights: Any = None,
|
|
333
|
+
benchmark: Any = None,
|
|
334
|
+
periods_per_year: int | None = None,
|
|
335
|
+
rf: float = 0.0,
|
|
336
|
+
schema: Any = None,
|
|
337
|
+
columns: Any = None,
|
|
338
|
+
) -> None:
|
|
339
|
+
from stratstat.inputs import _column_labels, _to_numpy
|
|
340
|
+
|
|
341
|
+
self.schema = _coerce(schema, columns, tier=None)
|
|
342
|
+
self.periods_per_year: int | None = periods_per_year
|
|
343
|
+
self.rf: float = rf
|
|
344
|
+
self.benchmark: Any = benchmark
|
|
345
|
+
self.weights: Any = weights
|
|
346
|
+
|
|
347
|
+
matrix: NDArray[np.floating]
|
|
348
|
+
if isinstance(strategies, dict):
|
|
349
|
+
self.names = [str(k) for k in strategies]
|
|
350
|
+
cols = [np.asarray(v, dtype=np.float64).ravel() for v in strategies.values()]
|
|
351
|
+
if not cols:
|
|
352
|
+
raise ValueError("Comparison requires at least one strategy")
|
|
353
|
+
n_periods = cols[0].shape[0]
|
|
354
|
+
for col in cols[1:]:
|
|
355
|
+
if col.shape[0] != n_periods:
|
|
356
|
+
raise ValueError(
|
|
357
|
+
"all strategy return series must be period aligned (the same length)"
|
|
358
|
+
)
|
|
359
|
+
matrix = np.column_stack(cols) if len(cols) > 1 else cols[0].reshape(-1, 1)
|
|
360
|
+
else:
|
|
361
|
+
labels = _column_labels(strategies)
|
|
362
|
+
matrix = _to_numpy(strategies)
|
|
363
|
+
if matrix.ndim == 1:
|
|
364
|
+
matrix = matrix.reshape(-1, 1)
|
|
365
|
+
self.names = (
|
|
366
|
+
[str(x) for x in labels]
|
|
367
|
+
if labels is not None and len(labels) == matrix.shape[1]
|
|
368
|
+
else [f"s{i}" for i in range(matrix.shape[1])]
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
self.returns: NDArray[np.floating] = matrix # (n_periods, n_strategies)
|
|
372
|
+
self.compare_input = CompareInput(
|
|
373
|
+
matrix,
|
|
374
|
+
weights=weights,
|
|
375
|
+
benchmark=benchmark,
|
|
376
|
+
periods_per_year=periods_per_year,
|
|
377
|
+
rf=rf,
|
|
378
|
+
schema=self.schema,
|
|
379
|
+
)
|
|
380
|
+
self.returns_input = ReturnsInput(
|
|
381
|
+
matrix, periods_per_year=periods_per_year, schema=self.schema
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
# -- slicing ----------------------------------------------------------
|
|
385
|
+
|
|
386
|
+
@property
|
|
387
|
+
def labels(self) -> list[str]:
|
|
388
|
+
"""Strategy names, in column order."""
|
|
389
|
+
return list(self.names)
|
|
390
|
+
|
|
391
|
+
@property
|
|
392
|
+
def strategies(self) -> dict[str, Strategy]:
|
|
393
|
+
"""Slice the stacked matrix into one :class:`Strategy` per column.
|
|
394
|
+
|
|
395
|
+
Each :class:`Strategy` carries that column's returns plus the shared
|
|
396
|
+
benchmark, so ``comparison[name].compute_all()`` yields that
|
|
397
|
+
strategy's returns and benchmark metrics without redoing the
|
|
398
|
+
cross-strategy work.
|
|
399
|
+
"""
|
|
400
|
+
return {
|
|
401
|
+
name: Strategy(
|
|
402
|
+
self.returns[:, i],
|
|
403
|
+
benchmark=self.benchmark,
|
|
404
|
+
periods_per_year=self.periods_per_year,
|
|
405
|
+
rf=self.rf,
|
|
406
|
+
schema=self.schema,
|
|
407
|
+
)
|
|
408
|
+
for i, name in enumerate(self.names)
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
def __getitem__(self, key: int | str) -> Strategy:
|
|
412
|
+
if isinstance(key, str):
|
|
413
|
+
if key not in self.names:
|
|
414
|
+
raise KeyError(key)
|
|
415
|
+
i = self.names.index(key)
|
|
416
|
+
else:
|
|
417
|
+
i = key
|
|
418
|
+
return Strategy(
|
|
419
|
+
self.returns[:, i],
|
|
420
|
+
benchmark=self.benchmark,
|
|
421
|
+
periods_per_year=self.periods_per_year,
|
|
422
|
+
rf=self.rf,
|
|
423
|
+
schema=self.schema,
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
def __len__(self) -> int:
|
|
427
|
+
return int(self.returns.shape[1])
|
|
428
|
+
|
|
429
|
+
def __iter__(self) -> Any:
|
|
430
|
+
return iter(self.strategies)
|
|
431
|
+
|
|
432
|
+
# -- computation ------------------------------------------------------
|
|
433
|
+
|
|
434
|
+
def compute_all(self, **kwargs: Any) -> MetricSet:
|
|
435
|
+
"""Run the returns, benchmark, and compare tiers once on the stack.
|
|
436
|
+
|
|
437
|
+
Returns-tier metrics are computed vectorized across all strategies and
|
|
438
|
+
come back as per-strategy array values. Keyword arguments pass through
|
|
439
|
+
to the metric functions.
|
|
440
|
+
"""
|
|
441
|
+
from stratstat.registry import _compute_all
|
|
442
|
+
|
|
443
|
+
return _compute_all(
|
|
444
|
+
returns=self.returns_input,
|
|
445
|
+
benchmark=self.benchmark,
|
|
446
|
+
compare=self.compare_input,
|
|
447
|
+
periods_per_year=self.periods_per_year,
|
|
448
|
+
rf=self.rf,
|
|
449
|
+
schema=self.schema,
|
|
450
|
+
**kwargs,
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
def compute(self, category: str, **kwargs: Any) -> MetricSet:
|
|
454
|
+
"""Compute metrics in one primary statistical category.
|
|
455
|
+
|
|
456
|
+
*category* is a primary tag such as ``"risk"`` or ``"relative"``.
|
|
457
|
+
Keyword arguments pass through to the metric functions.
|
|
458
|
+
"""
|
|
459
|
+
return self.compute_all(category=category, **kwargs)
|
|
460
|
+
|
|
461
|
+
def __repr__(self) -> str:
|
|
462
|
+
return (
|
|
463
|
+
f"Comparison(n_strategies={self.returns.shape[1]}, "
|
|
464
|
+
f"n_periods={self.returns.shape[0]}, "
|
|
465
|
+
f"names={self.names})"
|
|
466
|
+
)
|
stratstat/conventions.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Session-level metric convention overrides.
|
|
2
|
+
|
|
3
|
+
For metrics with genuinely competing real-world definitions (Sharpe ddof,
|
|
4
|
+
Sortino denominator, max drawdown return type, VaR/CVaR estimator choice,
|
|
5
|
+
beta variant, drawdown duration units, tail cutoffs), this module provides
|
|
6
|
+
``set_default()`` / ``get_default()`` so users can set session-wide
|
|
7
|
+
preferences that every metric call consults as a fallback for its convention
|
|
8
|
+
parameter.
|
|
9
|
+
|
|
10
|
+
Conventions are expressed in ``"param=value"`` form (e.g. ``"ddof=0"``),
|
|
11
|
+
which is unambiguous even for metrics that expose more than one convention
|
|
12
|
+
parameter (VaR/CVaR expose both ``method`` and ``confidence``).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from typing import Any, TypeVar
|
|
20
|
+
|
|
21
|
+
from stratstat.exceptions import ConventionError
|
|
22
|
+
|
|
23
|
+
_T = TypeVar("_T")
|
|
24
|
+
|
|
25
|
+
_defaults: dict[str, str] = {}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class _ParamSpec:
|
|
30
|
+
"""Validation + coercion rules for a single convention parameter."""
|
|
31
|
+
|
|
32
|
+
validate: Callable[[str], bool]
|
|
33
|
+
coerce: Callable[[str], Any]
|
|
34
|
+
description: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _choice(*options: str) -> _ParamSpec:
|
|
38
|
+
"""A categorical parameter whose value must be one of *options*."""
|
|
39
|
+
return _ParamSpec(
|
|
40
|
+
validate=lambda v: v in options,
|
|
41
|
+
coerce=lambda v: v,
|
|
42
|
+
description="/".join(repr(o) for o in options),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _int_choice(*options: str) -> _ParamSpec:
|
|
47
|
+
"""A categorical parameter whose value must be one of *options*, coerced to int."""
|
|
48
|
+
return _ParamSpec(
|
|
49
|
+
validate=lambda v: v in options,
|
|
50
|
+
coerce=int,
|
|
51
|
+
description="/".join(repr(o) for o in options),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _float_range(low: float, high: float, *, inclusive_high: bool = False) -> _ParamSpec:
|
|
56
|
+
"""A numeric parameter that must lie within (low, high)."""
|
|
57
|
+
|
|
58
|
+
def validate(value: str) -> bool:
|
|
59
|
+
try:
|
|
60
|
+
f = float(value)
|
|
61
|
+
except ValueError:
|
|
62
|
+
return False
|
|
63
|
+
return (low < f <= high) if inclusive_high else (low < f < high)
|
|
64
|
+
|
|
65
|
+
end = "]" if inclusive_high else ")"
|
|
66
|
+
return _ParamSpec(
|
|
67
|
+
validate=validate,
|
|
68
|
+
coerce=float,
|
|
69
|
+
description=f"float in ({low}, {high}{end}",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
#: Convention vocabulary, mirroring the table in docs/formula-reference.md.
|
|
74
|
+
#: Only metrics with genuinely competing definitions are listed (build
|
|
75
|
+
#: instructions §3.6 — do not add configuration surface to metrics with a
|
|
76
|
+
#: single legitimate definition).
|
|
77
|
+
_CONVENTIONS: dict[str, dict[str, _ParamSpec]] = {
|
|
78
|
+
"sharpe_ratio": {"ddof": _int_choice("0", "1")},
|
|
79
|
+
"sortino_ratio": {"denominator": _choice("full_downside", "downside_only")},
|
|
80
|
+
"exposure_time": {"rounding": _choice("raw", "percent_ceil")},
|
|
81
|
+
"rar": {"rounding": _choice("raw", "percent_ceil")},
|
|
82
|
+
"annualized_volatility": {"return_type": _choice("simple", "log")},
|
|
83
|
+
"max_drawdown": {"return_type": _choice("simple", "log")},
|
|
84
|
+
"longest_drawdown_duration": {"units": _choice("periods", "years")},
|
|
85
|
+
"psr": {"se_formula": _choice("blp", "lo")},
|
|
86
|
+
"probabilistic_sortino_ratio": {"se_formula": _choice("blp", "lo")},
|
|
87
|
+
"probabilistic_adjusted_sortino_ratio": {"se_formula": _choice("blp", "lo")},
|
|
88
|
+
"var": {
|
|
89
|
+
"method": _choice("historical", "parametric", "cornish_fisher"),
|
|
90
|
+
"confidence": _float_range(0.0, 1.0),
|
|
91
|
+
},
|
|
92
|
+
"cvar": {
|
|
93
|
+
"method": _choice("historical", "parametric"),
|
|
94
|
+
"confidence": _float_range(0.0, 1.0),
|
|
95
|
+
},
|
|
96
|
+
"tail_ratio": {"tail_cutoff": _float_range(0.0, 0.5)},
|
|
97
|
+
"hill_tail_index": {"tail_fraction": _float_range(0.0, 0.5, inclusive_high=True)},
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def set_default(metric: str, convention: str) -> None:
|
|
102
|
+
"""Set the default convention for a metric session-wide.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
metric: Metric name (e.g. ``"sharpe_ratio"``).
|
|
106
|
+
convention: Convention in ``"param=value"`` form (e.g. ``"ddof=0"``).
|
|
107
|
+
|
|
108
|
+
Raises:
|
|
109
|
+
ConventionError: If the metric, parameter, or value is not recognized.
|
|
110
|
+
"""
|
|
111
|
+
params = _CONVENTIONS.get(metric)
|
|
112
|
+
if params is None:
|
|
113
|
+
raise ConventionError(
|
|
114
|
+
f"Unknown convention-bearing metric: {metric!r}. Supported metrics: "
|
|
115
|
+
f"{', '.join(sorted(_CONVENTIONS))}."
|
|
116
|
+
)
|
|
117
|
+
param, sep, value = convention.partition("=")
|
|
118
|
+
if not sep:
|
|
119
|
+
raise ConventionError(
|
|
120
|
+
f"Convention for {metric!r} must be 'param=value', got {convention!r}"
|
|
121
|
+
)
|
|
122
|
+
spec = params.get(param)
|
|
123
|
+
if spec is None:
|
|
124
|
+
raise ConventionError(
|
|
125
|
+
f"Unknown parameter {param!r} for {metric!r}. Valid parameters: "
|
|
126
|
+
f"{', '.join(sorted(params))}."
|
|
127
|
+
)
|
|
128
|
+
if not spec.validate(value):
|
|
129
|
+
raise ConventionError(
|
|
130
|
+
f"Invalid value {value!r} for {metric!r}.{param} (expected {spec.description})."
|
|
131
|
+
)
|
|
132
|
+
_defaults[metric] = f"{param}={value}"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def get_default(metric: str) -> str | None:
|
|
136
|
+
"""Get the session-wide default convention for a metric, if set.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
metric: Metric name.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
The canonical ``"param=value"`` convention string, or None if no
|
|
143
|
+
override is set.
|
|
144
|
+
"""
|
|
145
|
+
return _defaults.get(metric)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def resolve_default(metric: str, param: str) -> Any | None:
|
|
149
|
+
"""Coerce and return the session override for a metric's parameter.
|
|
150
|
+
|
|
151
|
+
Used internally by convention-bearing metrics to consult the session
|
|
152
|
+
default as a fallback for their explicit parameter.
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
metric: Metric name (e.g. ``"sharpe_ratio"``).
|
|
156
|
+
param: Parameter name (e.g. ``"ddof"``).
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
The coerced override value (typed: int/float/str as appropriate), or
|
|
160
|
+
``None`` if no override is set for that metric's parameter.
|
|
161
|
+
"""
|
|
162
|
+
convention = _defaults.get(metric)
|
|
163
|
+
if convention is None:
|
|
164
|
+
return None
|
|
165
|
+
p, sep, value = convention.partition("=")
|
|
166
|
+
if not sep or p != param:
|
|
167
|
+
return None
|
|
168
|
+
return _CONVENTIONS[metric][param].coerce(value)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def resolve_convention(value: _T | None, metric: str, param: str, builtin: _T) -> _T:
|
|
172
|
+
"""Resolve a convention parameter to its effective value.
|
|
173
|
+
|
|
174
|
+
Precedence: an explicit *value* (not ``None``) wins; otherwise the
|
|
175
|
+
session default set via :func:`set_default` is used; otherwise *builtin*
|
|
176
|
+
(the cited default).
|
|
177
|
+
|
|
178
|
+
Convention-bearing metrics accept ``None`` for their convention parameter
|
|
179
|
+
and call this helper at the top of their body.
|
|
180
|
+
"""
|
|
181
|
+
if value is not None:
|
|
182
|
+
return value
|
|
183
|
+
override = resolve_default(metric, param)
|
|
184
|
+
return builtin if override is None else override
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def clear_defaults() -> None:
|
|
188
|
+
"""Reset all session-wide convention overrides."""
|
|
189
|
+
_defaults.clear()
|