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 ADDED
@@ -0,0 +1,536 @@
1
+ """
2
+ StratStat — Quantitative strategy evaluation statistics.
3
+ """
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ from typing import Any
8
+
9
+ # Import the metric implementation modules so their @register_metric
10
+ # decorators populate the registry at import time. Without these side-effect
11
+ # imports ``list_metrics()`` is empty and ``compute()`` raises
12
+ # ``UnknownMetricError``.
13
+ import stratstat.core.benchmark # noqa: F401
14
+ import stratstat.core.compare # noqa: F401
15
+ import stratstat.core.exposure # noqa: F401
16
+ import stratstat.core.returns.descriptive # noqa: F401
17
+ import stratstat.core.returns.inference # noqa: F401
18
+ import stratstat.core.returns.risk # noqa: F401
19
+ import stratstat.core.returns.risk_adjusted # noqa: F401
20
+ import stratstat.core.trades # noqa: F401
21
+ from stratstat.container import Comparison, Strategy
22
+ from stratstat.conventions import get_default, set_default
23
+ from stratstat.core.returns.wrappers import by_regime, rolling
24
+ from stratstat.inputs import BenchmarkInput, CompareInput, ExposureInput, ReturnsInput, TradeInput
25
+ from stratstat.registry import get_metric, list_metrics, register_metric
26
+ from stratstat.results import MetricResult, MetricSet
27
+ from stratstat.schema import Schema, clear_schema, describe_columns, get_schema, set_schema
28
+
29
+ __all__ = [
30
+ "__version__",
31
+ "register_metric",
32
+ "list_metrics",
33
+ "get_metric",
34
+ "compute",
35
+ "compute_all",
36
+ "compute_returns",
37
+ "compute_trades",
38
+ "compute_benchmark",
39
+ "compute_exposure",
40
+ "compute_compare",
41
+ "MetricResult",
42
+ "MetricSet",
43
+ "ReturnsInput",
44
+ "ExposureInput",
45
+ "TradeInput",
46
+ "BenchmarkInput",
47
+ "CompareInput",
48
+ "Strategy",
49
+ "Comparison",
50
+ "get_default",
51
+ "set_default",
52
+ "Schema",
53
+ "set_schema",
54
+ "get_schema",
55
+ "clear_schema",
56
+ "describe_columns",
57
+ "rolling",
58
+ "by_regime",
59
+ ]
60
+
61
+
62
+ # compute() and compute_all() are defined here for convenient top-level access.
63
+ # They accept raw data (numpy, pandas, polars) or pre-built Input objects.
64
+ def compute(
65
+ input_data: Any,
66
+ metric_name: str,
67
+ *,
68
+ periods_per_year: int | None = None,
69
+ rf: float = 0.0,
70
+ **kwargs: Any,
71
+ ) -> MetricResult:
72
+ """Compute a single metric on the given data.
73
+
74
+ Parameters
75
+ ----------
76
+ input_data:
77
+ Raw returns (numpy array, pandas Series/DataFrame, polars
78
+ Series/DataFrame) or a pre-built :class:`ReturnsInput` /
79
+ :class:`BenchmarkInput` / etc.
80
+ metric_name:
81
+ Registered metric name (e.g. ``"sharpe_ratio"``).
82
+ periods_per_year:
83
+ Annualisation factor (252 for daily, 12 for monthly, etc.).
84
+ Only needed when passing raw data; ignored if *input_data* is
85
+ already an Input object.
86
+ rf:
87
+ Annual risk-free rate (default 0.0). Used by benchmark-tier,
88
+ compare-tier, and the risk-adjusted returns metrics.
89
+ **kwargs:
90
+ Forwarded to the metric function (e.g. ``return_type="log"``).
91
+
92
+ Returns
93
+ -------
94
+ MetricResult
95
+ The computed value with metadata (name, category, ref, etc.).
96
+ """
97
+ from stratstat.registry import _compute_one
98
+
99
+ return _compute_one(
100
+ input_data,
101
+ metric_name,
102
+ periods_per_year=periods_per_year,
103
+ rf=rf,
104
+ **kwargs,
105
+ )
106
+
107
+
108
+ def compute_all(
109
+ returns: Any = None,
110
+ trades: Any = None,
111
+ benchmark: Any = None,
112
+ exposure: Any = None,
113
+ compare: Any = None,
114
+ *,
115
+ periods_per_year: int | None = None,
116
+ rf: float = 0.0,
117
+ schema: Any = None,
118
+ columns: Any = None,
119
+ include_returns: bool = True,
120
+ include_trades: bool = True,
121
+ include_benchmark: bool = True,
122
+ include_exposure: bool = True,
123
+ include_compare: bool = True,
124
+ deduplicate: bool = True,
125
+ category: str | None = None,
126
+ tiers: list[str] | None = None,
127
+ **kwargs: Any,
128
+ ) -> MetricSet:
129
+ """Compute every metric across all five input tiers in one call.
130
+
131
+ Provide the data you have; each tier runs only when its data is present
132
+ (and its ``include_*`` flag is ``True``). The mapping is:
133
+
134
+ * ``returns`` → returns-tier metrics (strategy returns).
135
+ * ``trades`` → trade-tier metrics (a trade log with a ``pnl`` column).
136
+ * ``benchmark`` → benchmark-tier metrics (strategy returns +
137
+ benchmark returns).
138
+ * ``exposure`` → exposure-tier metrics (positions / weights).
139
+ * ``compare`` → compare-tier metrics (multi-strategy returns); this tier
140
+ runs only when ``compare`` is explicitly provided.
141
+
142
+ Parameters
143
+ ----------
144
+ returns:
145
+ Strategy returns (numpy, pandas, polars, or a :class:`ReturnsInput`).
146
+ trades:
147
+ Trade log (dict, pandas/polars DataFrame, or a :class:`TradeInput`).
148
+ benchmark:
149
+ Benchmark returns (numpy, pandas, polars).
150
+ exposure:
151
+ Positions / weights (numpy, pandas, polars, or an
152
+ :class:`ExposureInput`).
153
+ compare:
154
+ Multi-strategy returns for compare-tier metrics. The compare tier
155
+ runs only when this is provided.
156
+ periods_per_year:
157
+ Annualisation factor (252 for daily, 12 for monthly, etc.).
158
+ rf:
159
+ Annual risk-free rate (default 0.0). Used by benchmark-tier,
160
+ compare-tier, and the risk-adjusted returns metrics.
161
+ include_returns, include_trades, include_benchmark, include_exposure, include_compare:
162
+ Per-tier switches (all default ``True``).
163
+ deduplicate:
164
+ Drop period-level "twin" metrics when their trade-level canonical
165
+ (e.g. ``avg_up_period`` vs ``avg_win``) also runs (default ``True``).
166
+ category:
167
+ Primary statistical tag to filter by (e.g. ``"risk"``,
168
+ ``"descriptive"``). ``None`` computes all matching metrics.
169
+ tiers:
170
+ Optional explicit list of tiers to run (e.g. ``["returns"]``).
171
+ **kwargs:
172
+ Forwarded to metric functions (e.g. ``confidence=0.95``).
173
+
174
+ Returns
175
+ -------
176
+ MetricSet
177
+ Ordered collection of :class:`MetricResult` objects. Its ``meta``
178
+ records ``"skipped"``, ``"excluded_resampling"``,
179
+ ``"excluded_tiers"``, and ``"deduplicated"`` names so nothing is
180
+ dropped silently.
181
+ """
182
+ from stratstat.registry import _compute_all
183
+ from stratstat.schema import Schema
184
+
185
+ if schema is not None and columns is not None:
186
+ raise TypeError("Pass either schema= or columns=, not both.")
187
+ if columns is not None:
188
+ schema = Schema(**dict(columns))
189
+
190
+ return _compute_all(
191
+ returns=returns,
192
+ trades=trades,
193
+ benchmark=benchmark,
194
+ exposure=exposure,
195
+ compare=compare,
196
+ periods_per_year=periods_per_year,
197
+ rf=rf,
198
+ schema=schema,
199
+ include_returns=include_returns,
200
+ include_trades=include_trades,
201
+ include_benchmark=include_benchmark,
202
+ include_exposure=include_exposure,
203
+ include_compare=include_compare,
204
+ deduplicate=deduplicate,
205
+ category=category,
206
+ tiers=tiers,
207
+ **kwargs,
208
+ )
209
+
210
+
211
+ def compute_returns(
212
+ data: Any,
213
+ *,
214
+ periods_per_year: int | None = None,
215
+ rf: float = 0.0,
216
+ category: str | None = None,
217
+ schema: Any = None,
218
+ columns: Any = None,
219
+ **kwargs: Any,
220
+ ) -> MetricSet:
221
+ """Compute every returns-tier metric on strategy returns.
222
+
223
+ Parameters
224
+ ----------
225
+ data:
226
+ Strategy returns (numpy, pandas, polars, or a :class:`ReturnsInput`).
227
+ periods_per_year:
228
+ Annualisation factor (252 for daily, etc.).
229
+ rf:
230
+ Annual risk-free rate (default 0.0). Used by the risk-adjusted
231
+ returns metrics.
232
+ category:
233
+ Primary statistical tag to filter by (e.g. ``"risk"``).
234
+ schema:
235
+ A :class:`Schema` mapping canonical names to your columns.
236
+ columns:
237
+ Inline shorthand for ``schema``. On this single-tier entry point it
238
+ names the returns column directly, e.g. ``columns={"returns": "pct"}``.
239
+ **kwargs:
240
+ Forwarded to metric functions.
241
+
242
+ Returns
243
+ -------
244
+ MetricSet
245
+ All returns-tier metrics (resampling metrics excluded).
246
+ """
247
+ from stratstat.registry import _compute_all
248
+ from stratstat.schema import Schema
249
+
250
+ if schema is not None and columns is not None:
251
+ raise TypeError("Pass either schema= or columns=, not both.")
252
+ if columns is not None:
253
+ schema = Schema(**dict(columns))
254
+
255
+ return _compute_all(
256
+ returns=data,
257
+ periods_per_year=periods_per_year,
258
+ rf=rf,
259
+ category=category,
260
+ tiers=["returns"],
261
+ schema=schema,
262
+ **kwargs,
263
+ )
264
+
265
+
266
+ def compute_trades(
267
+ trades: Any,
268
+ *,
269
+ periods_per_year: int | None = None,
270
+ category: str | None = None,
271
+ columns: Any = None,
272
+ pnl_basis: str = "trade",
273
+ pnl_unit: str = "fraction",
274
+ prices: Any = None,
275
+ **kwargs: Any,
276
+ ) -> MetricSet:
277
+ """Compute every trade-tier metric on a trade log.
278
+
279
+ Parameters
280
+ ----------
281
+ trades:
282
+ Trade log (dict with a ``pnl`` column, pandas/polars DataFrame, or a
283
+ :class:`TradeInput`).
284
+ periods_per_year:
285
+ Annualisation factor (required by holding-period metrics).
286
+ category:
287
+ Primary statistical tag to filter by (trade-tier metrics use
288
+ ``"trades"``).
289
+ columns:
290
+ Inline column mapping, canonical name to the name in your trade log,
291
+ e.g. ``{"side": "direction"}``. This entry point covers one tier, so
292
+ the mapping is written flat rather than nested under ``trades``.
293
+ Shorthand for ``schema=Schema(trades=...)``; pass one or the other.
294
+ pnl_basis:
295
+ Whether the ``pnl`` column is per trade (``"trade"``) or per account
296
+ (``"account"``). Default ``"trade"``.
297
+ pnl_unit:
298
+ Whether pnl is a fraction of entry (``"fraction"``) or a currency
299
+ amount (``"currency"``). Default ``"fraction"``. Metrics that need a
300
+ fractional pnl (Kelly criterion, geometric mean) refuse to run when
301
+ ``"currency"``.
302
+ prices:
303
+ Price bars used to derive maximum favorable/adverse excursion when no
304
+ excursion column is present. A mapping of ``time``, ``close``, and
305
+ optional ``high``/``low`` arrays, or a DataFrame with a datetime index.
306
+ **kwargs:
307
+ Forwarded to metric functions.
308
+
309
+ Returns
310
+ -------
311
+ MetricSet
312
+ All trade-tier metrics.
313
+ """
314
+ from stratstat.registry import _compute_all
315
+
316
+ schema_arg = kwargs.pop("schema", None)
317
+ if columns is not None:
318
+ # The tier is unambiguous here, so a flat mapping is what a caller
319
+ # would naturally write. Normalise it to the nested form before
320
+ # handing off, so downstream sees exactly one shape.
321
+ from stratstat.schema import Schema
322
+
323
+ if schema_arg is not None:
324
+ raise TypeError(
325
+ "Pass either schema= or columns=, not both. "
326
+ "columns= is shorthand that builds a Schema."
327
+ )
328
+ schema_arg = Schema(trades=dict(columns))
329
+
330
+ return _compute_all(
331
+ trades=trades,
332
+ periods_per_year=periods_per_year,
333
+ category=category,
334
+ tiers=["trades"],
335
+ schema=schema_arg,
336
+ pnl_basis=pnl_basis,
337
+ pnl_unit=pnl_unit,
338
+ prices=prices,
339
+ **kwargs,
340
+ )
341
+
342
+
343
+ def compute_benchmark(
344
+ returns: Any,
345
+ benchmark: Any,
346
+ *,
347
+ periods_per_year: int | None = None,
348
+ rf: float = 0.0,
349
+ category: str | None = None,
350
+ schema: Any = None,
351
+ columns: Any = None,
352
+ **kwargs: Any,
353
+ ) -> MetricSet:
354
+ """Compute every benchmark-tier metric on strategy + benchmark returns.
355
+
356
+ Parameters
357
+ ----------
358
+ returns:
359
+ Strategy returns (numpy, pandas, polars, or a :class:`ReturnsInput`).
360
+ benchmark:
361
+ Benchmark returns (numpy, pandas, polars).
362
+ periods_per_year:
363
+ Annualisation factor.
364
+ rf:
365
+ Annual risk-free rate (default 0.0).
366
+ category:
367
+ Primary statistical tag to filter by (benchmark-tier metrics use
368
+ ``"benchmark"``).
369
+ **kwargs:
370
+ Forwarded to metric functions.
371
+
372
+ Returns
373
+ -------
374
+ MetricSet
375
+ All benchmark-tier metrics.
376
+ """
377
+ from stratstat.registry import _compute_all
378
+ from stratstat.schema import Schema
379
+
380
+ if schema is not None and columns is not None:
381
+ raise TypeError("Pass either schema= or columns=, not both.")
382
+ if columns is not None:
383
+ schema = Schema(**dict(columns))
384
+
385
+ return _compute_all(
386
+ returns=returns,
387
+ benchmark=benchmark,
388
+ periods_per_year=periods_per_year,
389
+ rf=rf,
390
+ category=category,
391
+ tiers=["benchmark"],
392
+ schema=schema,
393
+ **kwargs,
394
+ )
395
+
396
+
397
+ def compute_exposure(
398
+ positions: Any,
399
+ *,
400
+ returns: Any = None,
401
+ asset_returns: Any = None,
402
+ benchmark: Any = None,
403
+ benchmark_weights: Any = None,
404
+ equity: Any = None,
405
+ periods_per_year: int | None = None,
406
+ category: str | None = None,
407
+ schema: Any = None,
408
+ columns: Any = None,
409
+ **kwargs: Any,
410
+ ) -> MetricSet:
411
+ """Compute every exposure-tier metric on a positions/weights matrix.
412
+
413
+ Parameters
414
+ ----------
415
+ positions:
416
+ Position weights of shape ``(n_periods, n_assets)``.
417
+ returns:
418
+ Strategy-level returns of shape ``(n_periods,)`` (optional). Used only
419
+ to derive the equity curve for leverage.
420
+ asset_returns:
421
+ Asset-level returns of shape ``(n_periods, n_assets)`` (optional).
422
+ benchmark:
423
+ Benchmark returns (optional, for long/short beta metrics).
424
+ benchmark_weights:
425
+ Benchmark constituent weights (optional, for active share).
426
+ equity:
427
+ Portfolio equity curve (optional; derived from strategy returns, or
428
+ from positions + asset_returns, if omitted).
429
+ periods_per_year:
430
+ Annualisation factor (required by turnover).
431
+ category:
432
+ Primary statistical tag to filter by (exposure-tier metrics use
433
+ ``"exposure"``).
434
+ **kwargs:
435
+ Forwarded to metric functions.
436
+
437
+ Returns
438
+ -------
439
+ MetricSet
440
+ All exposure-tier metrics.
441
+ """
442
+ from stratstat.inputs import ExposureInput
443
+ from stratstat.registry import _compute_all
444
+ from stratstat.schema import Schema
445
+
446
+ if schema is not None and columns is not None:
447
+ raise TypeError("Pass either schema= or columns=, not both.")
448
+ if columns is not None:
449
+ schema = Schema(**dict(columns))
450
+
451
+ if isinstance(positions, ExposureInput):
452
+ inp = positions
453
+ else:
454
+ inp = ExposureInput(
455
+ positions,
456
+ returns=returns,
457
+ asset_returns=asset_returns,
458
+ benchmark=benchmark,
459
+ benchmark_weights=benchmark_weights,
460
+ equity=equity,
461
+ periods_per_year=periods_per_year,
462
+ schema=schema,
463
+ )
464
+ return _compute_all(
465
+ exposure=inp,
466
+ category=category,
467
+ tiers=["exposure"],
468
+ **kwargs,
469
+ )
470
+
471
+
472
+ def compute_compare(
473
+ returns: Any,
474
+ *,
475
+ weights: Any = None,
476
+ benchmark: Any = None,
477
+ periods_per_year: int | None = None,
478
+ rf: float = 0.0,
479
+ category: str | None = None,
480
+ schema: Any = None,
481
+ columns: Any = None,
482
+ **kwargs: Any,
483
+ ) -> MetricSet:
484
+ """Compute every compare-tier metric on multi-strategy returns.
485
+
486
+ Parameters
487
+ ----------
488
+ returns:
489
+ Strategy returns of shape ``(n_periods, n_strategies)`` (at least two
490
+ strategies for most metrics).
491
+ weights:
492
+ Strategy weights of shape ``(n_strategies,)`` (defaults to equal
493
+ weight where needed).
494
+ benchmark:
495
+ Benchmark returns (required only by White's Reality Check).
496
+ periods_per_year:
497
+ Annualisation factor (required by JK test and PBO).
498
+ rf:
499
+ Annual risk-free rate (default 0.0).
500
+ category:
501
+ Primary statistical tag to filter by (compare-tier metrics use
502
+ ``"relative"``).
503
+ **kwargs:
504
+ Forwarded to metric functions.
505
+
506
+ Returns
507
+ -------
508
+ MetricSet
509
+ All compare-tier metrics (resampling metrics excluded).
510
+ """
511
+ from stratstat.inputs import CompareInput
512
+ from stratstat.registry import _compute_all
513
+ from stratstat.schema import Schema
514
+
515
+ if schema is not None and columns is not None:
516
+ raise TypeError("Pass either schema= or columns=, not both.")
517
+ if columns is not None:
518
+ schema = Schema(**dict(columns))
519
+
520
+ if isinstance(returns, CompareInput):
521
+ inp = returns
522
+ else:
523
+ inp = CompareInput(
524
+ returns,
525
+ weights=weights,
526
+ benchmark=benchmark,
527
+ periods_per_year=periods_per_year,
528
+ rf=rf,
529
+ schema=schema,
530
+ )
531
+ return _compute_all(
532
+ compare=inp,
533
+ category=category,
534
+ tiers=["compare"],
535
+ **kwargs,
536
+ )