quantstats-pro 0.4.4__tar.gz → 0.5.0__tar.gz

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.
Files changed (55) hide show
  1. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/.gitignore +4 -0
  2. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/CHANGELOG.md +287 -0
  3. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/PKG-INFO +83 -8
  4. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/README.md +80 -5
  5. quantstats_pro-0.5.0/llms.txt +17 -0
  6. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/pyproject.toml +17 -7
  7. quantstats_pro-0.5.0/quantstats/AGENT_GUIDE.md +167 -0
  8. quantstats_pro-0.5.0/quantstats/__main__.py +5 -0
  9. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/_compat.py +81 -27
  10. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/_montecarlo.py +1 -3
  11. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/_plotting/core.py +17 -10
  12. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/_plotting/wrappers.py +13 -3
  13. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/alphadecay/core.py +115 -19
  14. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/alphadecay/plotting.py +4 -0
  15. quantstats_pro-0.5.0/quantstats/cli.py +437 -0
  16. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/core.py +1 -1
  17. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/plotting.py +2 -2
  18. quantstats_pro-0.5.0/quantstats/report_validity.html +55 -0
  19. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/reports.py +288 -72
  20. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/stats.py +467 -171
  21. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/utils.py +158 -68
  22. quantstats_pro-0.5.0/quantstats/validity/__init__.py +42 -0
  23. quantstats_pro-0.5.0/quantstats/validity/core.py +1068 -0
  24. quantstats_pro-0.5.0/quantstats/validity/plotting.py +172 -0
  25. quantstats_pro-0.5.0/quantstats/validity/report.py +350 -0
  26. quantstats_pro-0.5.0/quantstats/version.py +1 -0
  27. quantstats_pro-0.4.4/quantstats/version.py +0 -1
  28. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/LICENSE.txt +0 -0
  29. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/__init__.py +0 -0
  30. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/_numpy_compat.py +0 -0
  31. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/_plotting/__init__.py +0 -0
  32. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/_reporting/__init__.py +0 -0
  33. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/_reporting/engine.py +0 -0
  34. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/_reporting/sections.py +0 -0
  35. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/alphadecay/__init__.py +0 -0
  36. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/__init__.py +0 -0
  37. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/analytics.py +0 -0
  38. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/base.py +0 -0
  39. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/models/__init__.py +0 -0
  40. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/models/bayesian.py +0 -0
  41. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/models/block_bootstrap.py +0 -0
  42. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/models/bootstrap.py +0 -0
  43. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/models/garch.py +0 -0
  44. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/models/gbm.py +0 -0
  45. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/models/heston.py +0 -0
  46. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/models/jump_diffusion.py +0 -0
  47. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/models/shuffle.py +0 -0
  48. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/models/trimmed.py +0 -0
  49. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/montecarlo/registry.py +0 -0
  50. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/plots.py +0 -0
  51. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/py.typed +0 -0
  52. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/report.html +0 -0
  53. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/report_alpha_decay.html +0 -0
  54. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/report_montecarlo.html +0 -0
  55. {quantstats_pro-0.4.4 → quantstats_pro-0.5.0}/quantstats/report_simple.html +0 -0
@@ -29,3 +29,7 @@ CONTEXT.md
29
29
  .sandbox/
30
30
  san_alpha_decay.ipynb
31
31
  san_alpha_decay.html
32
+ .claude/settings.local.json
33
+
34
+ # Environment files (may contain secrets)
35
+ .env
@@ -1,6 +1,79 @@
1
1
  Changelog
2
2
  ===========
3
3
 
4
+ 0.5.0
5
+ -----
6
+
7
+ **Backtest validity (new)**
8
+
9
+ - New ``quantstats.validity`` module and ``reports.html_validity()`` tearsheet:
10
+ how much of a backtest's performance is statistically credible.
11
+
12
+ - Probabilistic and **deflated Sharpe ratio** (``n_trials`` / ``trials``),
13
+ selection hurdle and **minimum track record length**.
14
+ - **Stationary-bootstrap confidence intervals** for Sharpe, CAGR, volatility
15
+ and max drawdown.
16
+ - **In-sample vs out-of-sample** comparison with a test for Sharpe degradation
17
+ (``split`` as a date or out-of-sample fraction).
18
+ - **Alpha and alpha-decay trend** against a benchmark, with Newey–West
19
+ standard errors (mean-return trend when no benchmark is given).
20
+ - **Probability of backtest overfitting** (CSCV) from the returns of every
21
+ variant tried.
22
+ - ``validate()`` returns a ``ValidityResult`` with ``findings`` (stable codes
23
+ with ``info`` / ``caution`` / ``warning`` severity), ``summary()`` and a
24
+ strict-JSON ``to_dict()``.
25
+
26
+ **Agent-first interface (new)**
27
+
28
+ - ``quantstats`` command-line tool (also ``python -m quantstats``) with
29
+ ``validate``, ``metrics``, ``decay``, ``montecarlo`` and ``report``
30
+ subcommands. Analysis commands read CSV/Parquet and print one JSON object;
31
+ errors are JSON on stderr; nothing opens a browser or downloads data.
32
+ - ``quantstats guide`` prints ``AGENT_GUIDE.md``, a usage guide for AI agents
33
+ that ships inside the package (input contract, which call answers which
34
+ question, how to read and report results). ``llms.txt`` added at the repo root.
35
+ - ``alphadecay.DecayResult.to_dict()`` for structured output.
36
+
37
+ **Alpha decay — behaviour changes**
38
+
39
+ - The CUSUM target mean and σ are now estimated on a **reference period** (the
40
+ first 50% of the sample by default, ``baseline=0.5``) instead of the full
41
+ sample, where a decayed strategy lowered its own target. Pass
42
+ ``baseline=None`` for the previous behaviour.
43
+ - Z-scores, percentiles and the reported mean now use a reference distribution
44
+ that **excludes the rolling values overlapping the current window**, so the
45
+ latest reading is no longer part of the history it is compared with.
46
+ - New ``benchmark=`` argument in ``alphadecay.analyze()`` and
47
+ ``reports.html_alpha_decay()``: the monitor runs on ``r − β·benchmark``
48
+ (alpha) instead of total returns.
49
+ - Expected Shortfall in the monitor now uses the same Gaussian estimator as
50
+ ``stats.cvar()`` (see upstream sync below).
51
+
52
+ **Upstream sync (QuantStats 0.0.82 – 0.0.86)**
53
+
54
+ - Merged upstream's statistical corrections. Numbers that change:
55
+
56
+ - ``probabilistic_sharpe_ratio`` and related: excess kurtosis was reduced by
57
+ 3 a second time, ``rf`` was subtracted in the wrong units, and
58
+ ``annualize=True`` multiplied a probability by √252 (now ignored).
59
+ - ``cvar`` / ``expected_shortfall``: consistent parametric (default) and
60
+ ``method="historical"`` estimators; no longer falls back to VaR.
61
+ - ``rar``: ``rf`` is de-annualised (any non-zero ``rf`` used to return −100%).
62
+ - Benchmark statistics on gapped series, rolling alpha, time-varying ``rf``
63
+ cache key, Series/DataFrame cache collision.
64
+
65
+ - **Minimum pandas is now 2.0** (was 1.5), following upstream.
66
+ - ``rar`` keeps Pro's ``periods``-aware CAGR alongside upstream's ``compounded``.
67
+
68
+ 0.4.5
69
+ -----
70
+
71
+ **Bug Fixes**
72
+
73
+ - Fixed ``html_montecarlo`` Max Drawdown boxplot crashing on matplotlib 3.7–3.9
74
+ (``TypeError`` from ``orientation=`` / ``tick_labels=``). Uses a signature-based
75
+ compatibility shim so the plot works from matplotlib 3.7 through 3.11+.
76
+
4
77
  0.4.4
5
78
  -----
6
79
 
@@ -233,6 +306,220 @@ QuantStats Pro is an enhanced, actively maintained drop-in replacement:
233
306
  - Import unchanged: `import quantstats as qs`
234
307
  - 125 tests passing
235
308
  - Apache 2.0 license with attribution to original author
309
+ 0.0.86
310
+ ------
311
+
312
+ **Statistical corrections** - these change reported numbers.
313
+
314
+ - Fixed trade statistics on a DataFrame depending on the *other* columns in
315
+ the frame (#556). `avg_return()`, `avg_win()` and `avg_loss()` masked the
316
+ unselected cells to `NaN` and then called `.dropna()`, which drops whole
317
+ **rows** on a DataFrame. Each column's average was therefore computed only
318
+ over rows where every other column also qualified, so a strategy's average
319
+ win was measured only on days the benchmark also rose. Anyone calling
320
+ `reports.metrics()` with a benchmark on a DataFrame got affected figures
321
+ for Average Win/Loss, Payoff Ratio, Win/Loss Ratio, CPC Index and Kelly
322
+ Criterion. `.mean()` already skips `NaN` column-wise, so the `.dropna()`
323
+ is gone.
324
+ - Fixed `rolling_greeks()` computing alpha from the full-sample means rather
325
+ than each window's own means (#554, reported with a fix by @WatchTree-19).
326
+ Every window shared one baseline, so rolling alpha only moved when rolling
327
+ beta did: on a strategy that starts earning an extra 10bp a day halfway
328
+ through, alpha read 0.00057 before and 0.00056 after, where a regression
329
+ on those windows gives 0.00035 and 0.00198. Rolling beta, and the
330
+ beta-only rolling plots, are unchanged.
331
+ - Fixed a time-varying `rf` Series colliding in the `_prepare_returns()`
332
+ cache (#555, reported with a fix by @WatchTree-19). The key formatted `rf`
333
+ with its repr, which pandas truncates to the first and last few rows, so
334
+ two rate series of the same length differing only in between shared an
335
+ entry and the second caller was handed the first one's excess returns.
336
+ The result depended on call order. A Series `rf` is now hashed like the
337
+ data.
338
+
339
+ 0.0.85
340
+ ------
341
+
342
+ - Fixed `rar()` charging the **annual** risk-free rate once per period
343
+ (#552). It passed `rf` to `_prepare_returns()` without `periods`, so at a
344
+ daily frequency a 5% rate was subtracted from every single day: the series
345
+ was wiped out and the Risk-Adjusted Return pinned to -100% for any
346
+ non-zero `rf`. `rar()` now takes a `periods` argument (default 252) and
347
+ de-annualizes the rate, and `reports.metrics()` passes the report's own
348
+ `periods_per_year` through.
349
+
350
+ This was the second half of #552, which 0.0.84 did not address. 0.0.81
351
+ reported a plausible number here only because `metrics()` never passed
352
+ `rf` into `rar()` at all; the standalone `stats.rar(returns, rf=0.05)`
353
+ call has been wrong in every release that had it. On a sample series the
354
+ row now reads 0.37 against 0.44 gross, where 0.0.82-0.0.84 read -1.00.
355
+
356
+ 0.0.84
357
+ ------
358
+
359
+ **Fixes a regression introduced in 0.0.83.**
360
+
361
+ - Fixed `greeks()`, `r_squared()`/`r2()` and `treynor_ratio()` collapsing to
362
+ zero or `NaN` when the strategy or benchmark had even one missing
363
+ observation (#553, reported with a fix by @WatchTree-19). 0.0.83 stopped
364
+ filling gaps with 0, and `np.cov`/`linregress` propagate `NaN` through the
365
+ whole estimate, so a single absent day reduced beta and alpha to 0 and
366
+ R-squared to `NaN` — and `greeks()` reported that zero without complaint.
367
+ These are now estimated over the dates on which both series were observed.
368
+ `reports.metrics()` was not affected, as it fills the frame beforehand.
369
+
370
+ **Reverted**
371
+
372
+ - `kelly_criterion()` returns the classic fixed-odds fraction `p - q/b`
373
+ again, as it did up to 0.0.81 (#552). 0.0.82 divided it by the average-loss
374
+ magnitude, on the argument that a fraction which does not move when the
375
+ series is rescaled must be wrong. That quantity is the growth-optimal
376
+ *leverage* for a per-period P&L, not the Kelly fraction: on daily returns
377
+ it reaches double and triple digits, and reports showed figures like
378
+ 10792% where the fraction reads 21%. The fixed-odds fraction depends only
379
+ on the odds by construction, so its scale-invariance is a property rather
380
+ than a defect.
381
+
382
+ 0.0.83
383
+ ------
384
+
385
+ **Statistical corrections** - these change reported numbers.
386
+
387
+ - Fixed `rolling_sharpe()` and `rolling_sortino()` de-annualizing the
388
+ risk-free rate over the rolling window instead of the year (#549). They
389
+ passed `rolling_period` where `_prepare_returns()` expects
390
+ `periods_per_year`, so at the defaults they subtracted **exactly twice**
391
+ the correct risk-free rate. Any call with a non-zero `rf` was affected.
392
+ - **Missing observations are no longer treated as 0.0 returns** (#546).
393
+ `_prepare_returns()` filled gaps with zero, asserting the strategy was flat
394
+ on days it had no data for, which understated volatility, softened
395
+ drawdowns and inflated every ratio built on them. Gaps now stay `NaN` and
396
+ are skipped by the statistics; equity curves still carry through a gap as
397
+ flat, because a curve has to have a value there.
398
+
399
+ Metrics that counted periods were corrected to count *observed* periods:
400
+ `cagr()`, `win_rate()`, `sortino()`, `ghpr()`, `exposure()`,
401
+ `risk_of_ruin()` and `autocorr_penalty()`. `win_rate()` was the worst of
402
+ these, since `NaN != 0` is true and gaps were landing in its denominator.
403
+ - Fixed `conditional_value_at_risk()` mixing estimators (#547). It took a
404
+ *parametric* VaR threshold and then averaged the observations below it, and
405
+ returned the VaR itself when none fell below - which overstates CVaR, since
406
+ CVaR is by definition at least as severe as VaR. Small samples also emitted
407
+ `RuntimeWarning: Mean of empty slice`.
408
+
409
+ The default is now the closed-form normal expected shortfall, consistent
410
+ with `value_at_risk()`. Pass `method="historical"` for the empirical tail,
411
+ which captures fat tails but needs enough data to mean anything. An
412
+ undefined tail returns `NaN` rather than the VaR.
413
+
414
+ **Documentation**
415
+
416
+ - The trade-derived metrics (`win_rate`, `payoff_ratio`, `profit_factor`,
417
+ `consecutive_wins`/`losses`, `common_sense_ratio`, `cpc_index`,
418
+ `gain_to_pain_ratio`, `outliers` and friends) now carry the period-based
419
+ caveat in their docstrings, so it is visible from `help()` and in editors
420
+ rather than only in the README (#493).
421
+ - Corrected the stale `help()` example in the README.
422
+
423
+ 0.0.82
424
+ ------
425
+
426
+ **Correctness fixes**
427
+
428
+ - Fixed `max_drawdown()` and `to_drawdown_series()` returning drawdowns that
429
+ depended on the price level of the input (#541). The baseline is now taken
430
+ from whether the series was rebuilt from returns or was a real price series,
431
+ instead of guessing from magnitude thresholds. A price series scaled by any
432
+ constant now reports the same drawdown.
433
+ - Fixed `_prepare_prices()` filling a missing price with `0`, which reported a
434
+ spurious -100% drawdown for any gapped price series (#545). Gaps now carry
435
+ the last known price forward.
436
+ - Fixed weekly aggregation raising `AttributeError: 'DatetimeIndex' object has
437
+ no attribute 'week'` on pandas >= 2.0 (#533). `aggregate_returns()` now uses
438
+ `isocalendar().week` for the `"week"`, `"eow"` and `"W"` periods.
439
+ - Fixed `cagr(compounded=False)` turning a loss worse than -100% into a
440
+ positive return (#548). Terminal wealth at or below zero now yields `NaN`
441
+ rather than a value produced by taking a root of a negative number.
442
+ - Fixed the prepared-returns cache returning a DataFrame to a caller that
443
+ passed a Series (#544). Container type, column names, dtypes and the
444
+ risk-free flag are now part of the cache key.
445
+ - Fixed `information_ratio()` preparing the benchmark twice, which re-ran
446
+ price/return detection on already-normalized data.
447
+ - Fixed `rolling_volatility()` passing its rolling period into the risk-free
448
+ rate argument.
449
+
450
+ **Statistical corrections**
451
+
452
+ - Fixed `probabilistic_sharpe_ratio()` / `probabilistic_ratio()` (#551):
453
+ the raw-kurtosis formula was being fed excess kurtosis, the estimator
454
+ standard error now follows Bailey & Lopez de Prado, and `rf` is routed into
455
+ the underlying Sharpe/Sortino rather than dropped. The `annualize` argument
456
+ is documented as inert; it never affected the result.
457
+ - **Behavior change:** `kelly_criterion()` now divides by the average loss,
458
+ giving the position size the Kelly formula actually defines. The previous
459
+ result was scale-invariant and therefore dimensionally wrong; returned
460
+ values will differ in magnitude from 0.0.81 and earlier.
461
+ - `autocorr_penalty()` now guards against series shorter than two
462
+ observations and zero-variance input instead of emitting a numpy
463
+ `RuntimeWarning` and propagating `NaN` (#525).
464
+
465
+ **API**
466
+
467
+ - `calmar()` and `rar()` accept a `compounded` flag (#512), and
468
+ `reports.metrics()` threads its own `compounded` setting into both.
469
+ - Report risk-free rates may now be a `pd.Series` of time-varying rates
470
+ (#524). Rates are aligned onto the return dates, carried forward across
471
+ gaps, and subtracted row-wise for DataFrame input. The reported
472
+ "Risk-Free Rate" row shows the average over the period.
473
+ - `reports.html()`, `reports.full()` and `reports.basic()` now forward
474
+ `match_dates` to `metrics()` (#536), so the table and the plots describe
475
+ the same date range.
476
+
477
+ **Crash fixes**
478
+
479
+ - Fixed `reports.metrics()` raising `UnboundLocalError` for a single-column
480
+ DataFrame.
481
+ - Fixed `reports.html()` and `reports.full()` raising `TypeError` when given a
482
+ DataFrame together with a string `strategy_title`.
483
+ - Fixed a `KeyError` in the drawdown table when the metrics frame came back
484
+ with a single-level MultiIndex.
485
+ - `sharpe()`, `sortino()`, `rolling_sharpe()` and `rolling_sortino()` no
486
+ longer raise "truth value of a Series is ambiguous" when `rf` is a Series.
487
+
488
+ **Compatibility**
489
+
490
+ - Fixed `ValueError: Invalid frequency: ME` on pandas 2.0 and 2.1. The
491
+ codebase spells frequencies the pandas 2.2 way (`ME`/`QE`/`YE`), which
492
+ older versions reject; the compatibility layer now translates aliases in
493
+ both directions. Reports and plots were unusable on those versions.
494
+ - Raised the declared pandas floor from `>=1.5.0` to `>=2.0.0` to match what
495
+ is actually supported and tested. pandas 1.5 never worked with recent
496
+ releases.
497
+
498
+ **Reports**
499
+
500
+ - Fixed the "10Y (ann.)" column covering eleven calendar years (#523).
501
+
502
+ **Internals**
503
+
504
+ - `_prepare_returns()` no longer inspects the call stack (`inspect.stack()`)
505
+ to decide whether to apply the risk-free rate; callers pass an explicit
506
+ `apply_rf` argument.
507
+
508
+ **CI**
509
+
510
+ - Repaired the test workflow, which was disabled and pointed at
511
+ `test_fixes.py` and `tests/test_compatibility.py` (#540) - neither file has
512
+ existed for several releases. It now runs `pytest tests/` across a
513
+ Python 3.10-3.13 x pandas x numpy matrix, plus a latest-versions job and a
514
+ ruff lint job.
515
+ - Repaired the publish workflow, which still called `python setup.py`;
516
+ `setup.py` was removed in 0.0.78 in favour of pyproject.toml + hatchling.
517
+ - Bumped `actions/checkout` and `actions/setup-python` to v7 (#526, #534).
518
+ - Removed the abandoned `.travis.yml` (Python 3.6-3.9, `nosetests`).
519
+ - Added a regression test module covering every fix above.
520
+ - Applied `ruff` autofixes and formatting across the codebase, and
521
+ grandfathered the remaining violations per file so lint is enforced on new
522
+ code.
236
523
 
237
524
  0.0.81
238
525
  ------
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: quantstats-pro
3
- Version: 0.4.4
3
+ Version: 0.5.0
4
4
  Summary: Drop-in replacement for QuantStats — advanced risk engines, institutional HTML tearsheets, and actionable portfolio analytics for quants
5
5
  Project-URL: Homepage, https://github.com/diegoalvarezmgl/quantstats-pro
6
6
  Project-URL: Documentation, https://github.com/diegoalvarezmgl/quantstats-pro
@@ -33,7 +33,7 @@ Requires-Python: >=3.10
33
33
  Requires-Dist: arch>=6.0
34
34
  Requires-Dist: matplotlib>=3.7.0
35
35
  Requires-Dist: numpy>=1.24.0
36
- Requires-Dist: pandas>=1.5.0
36
+ Requires-Dist: pandas>=2.0.0
37
37
  Requires-Dist: python-dateutil>=2.8.0
38
38
  Requires-Dist: scipy>=1.11.0
39
39
  Requires-Dist: seaborn>=0.13.0
@@ -90,6 +90,9 @@ Same API surface, stronger foundation — bugfixes, reliability, and a growing a
90
90
  | `html_simple` | Lean equity-curve tearsheet — fast read on performance vs benchmark |
91
91
  | `html_montecarlo` | Multi-model forward risk report (GBM, GARCH, Heston, bootstraps, Bayesian, …) with bust/goal probabilities and cross-model consensus |
92
92
  | `html_alpha_decay` | Rolling alpha-decay monitor — z-score traffic lights, CUSUM, time-underwater, per-metric distribution charts |
93
+ | `html_validity` | **New in 0.5** — is the backtest real? Deflated Sharpe, minimum track record, bootstrap intervals, in/out-of-sample, alpha decay, PBO |
94
+ | `quantstats.validity` | Programmatic backtest-validity engine with structured findings and JSON output |
95
+ | `quantstats` CLI | **New in 0.5** — JSON-first command line and a packaged guide so AI agents use the library correctly |
93
96
  | `quantstats.montecarlo` | Programmatic multi-model simulation engine behind the Montecarlo tearsheet |
94
97
  | `quantstats.alphadecay` | Short-horizon rolling diagnostics engine behind the Alpha Decay tearsheet |
95
98
  | Classic `html` | Full tearsheet — metrics + all charts, visually redesigned (v0.2.0+) |
@@ -105,6 +108,8 @@ Same API surface, stronger foundation — bugfixes, reliability, and a growing a
105
108
  | `quantstats.reports` | HTML tearsheets and metrics tables |
106
109
  | `quantstats.montecarlo` | Multi-model forward simulation engine and analytics |
107
110
  | `quantstats.alphadecay` | Short-horizon rolling risk analysis and decay detection |
111
+ | `quantstats.validity` | Backtest validity: overfitting, selection bias, out-of-sample, alpha decay |
112
+ | `quantstats.cli` | `quantstats` command line (JSON output) and the agent guide |
108
113
  | `quantstats.utils` | Data prep, `download_returns`, pandas helpers |
109
114
 
110
115
 
@@ -114,7 +119,7 @@ Legacy shuffle-based Montecarlo remains at `qs.stats.montecarlo()` for backward
114
119
 
115
120
  ## HTML Tearsheets
116
121
 
117
- The main product surface in QuantStats Pro is its **reporting layer**: four HTML tearsheet types that turn a returns series into shareable, browser-ready analytics. All open in the browser by default, or save to disk with `output="path.html"`.
122
+ The main product surface in QuantStats Pro is its **reporting layer**: five HTML tearsheet types that turn a returns series into shareable, browser-ready analytics. All open in the browser by default, or save to disk with `output="path.html"`.
118
123
 
119
124
 
120
125
  | Function | Use case |
@@ -123,8 +128,28 @@ The main product surface in QuantStats Pro is its **reporting layer**: four HTML
123
128
  | `qs.reports.html_simple(...)` | **Pro-only** — lean equity-curve tearsheet for quick strategy review |
124
129
  | `qs.reports.html_montecarlo(...)` | **Pro-only** — multi-model forward risk analysis (1y horizon by default) |
125
130
  | `qs.reports.html_alpha_decay(...)` | **Pro-only** — short-window alpha-decay health monitor (7/15/30d) |
131
+ | `qs.reports.html_validity(...)` | **Pro-only** — backtest validity: selection bias, overfitting, decay |
126
132
 
127
133
 
134
+ ### Backtest validity tearsheet — `html_validity`
135
+
136
+ A Sharpe ratio from a backtest is an estimate, and usually the best of many attempts. This report measures how much of it survives: the **deflated Sharpe ratio** (discounted for the number of variants tried), the **minimum track record** needed, **bootstrap confidence intervals**, an **in-sample vs out-of-sample** comparison, an **alpha-decay** trend test and the **probability of backtest overfitting**.
137
+
138
+ ```python
139
+ result = qs.reports.html_validity(
140
+ returns,
141
+ benchmark, # returns Series (optional)
142
+ n_trials=50, # strategy variants tried before choosing this one
143
+ split="2023-01-01", # first out-of-sample date
144
+ output="validity.html",
145
+ )
146
+ print(result.summary())
147
+ ```
148
+
149
+ ![Backtest validity tearsheet — an overfit moving-average crossover](https://raw.githubusercontent.com/diegoalvarezmgl/quantstats-pro/main/docs/report_validity.webp)
150
+
151
+ [View interactive validity sample](https://htmlpreview.github.io/?https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/docs/tearsheet_validity.html) · [Backtest validity docs](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/docs/validity.md)
152
+
128
153
  ### Simple tearsheet — `html_simple`
129
154
 
130
155
  Focused equity-curve view with core metrics and charts. Ideal when you need a clean performance read without the full classic layout.
@@ -216,6 +241,54 @@ qs.stats.sharpe(returns, periods=365)
216
241
 
217
242
  ---
218
243
 
244
+ ## Backtest Validity
245
+
246
+ `quantstats.validity` returns structured results instead of a picture: numbers, the assumptions used, and a list of findings with stable codes.
247
+
248
+ ```python
249
+ from quantstats import validity
250
+
251
+ res = validity.validate(returns, benchmark, n_trials=50, split="2023-01-01")
252
+
253
+ res.sharpe["dsr"] # deflated Sharpe ratio
254
+ res.bootstrap["sharpe"] # {'observed': …, 'low': …, 'median': …, 'high': …}
255
+ res.split["degradation_p_value"]
256
+ for f in res.findings:
257
+ print(f.severity, f.code, f.message)
258
+ # warning OUT_OF_SAMPLE_DEGRADATION Sharpe fell from 0.74 in-sample to -0.45 out-of-sample (p=0.042).
259
+
260
+ res.to_json() # strict JSON
261
+ ```
262
+
263
+ Pass `trials=` (a DataFrame with the returns of every variant you tried) to measure the real dispersion between variants and get the probability of backtest overfitting.
264
+
265
+ [Backtest validity documentation »](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/docs/validity.md)
266
+
267
+ ---
268
+
269
+ ## For AI agents
270
+
271
+ QuantStats Pro is built to be driven by coding agents as well as by people. Charts are for humans; agents get JSON, explicit input checks and a usage guide that ships inside the package.
272
+
273
+ ```bash
274
+ python -m quantstats guide # input contract, which call answers what, how to report results
275
+ quantstats validate returns.csv --benchmark spy.csv --n-trials 50 --split 2023-01-01
276
+ quantstats metrics returns.csv --benchmark spy.csv
277
+ quantstats decay returns.csv --windows 21,63,126
278
+ quantstats montecarlo returns.csv --sims 1000 --bust -0.25
279
+ quantstats report returns.csv --kind validity --output validity.html
280
+ ```
281
+
282
+ - Every analysis command prints **one JSON object** to stdout; errors are JSON on stderr with exit code 2.
283
+ - **No side effects**: nothing opens a browser or downloads data. Benchmarks come from a file.
284
+ - **Explicit inputs**: prices are rejected with a message that says how to convert them; ambiguous columns must be named.
285
+ - **Reproducible**: bootstraps and simulations are seeded by default.
286
+ - [`AGENT_GUIDE.md`](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/quantstats/AGENT_GUIDE.md) and [`llms.txt`](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/llms.txt) tell an agent how to use the library and how not to overstate a result.
287
+
288
+ Point your agent at the guide with one line in your project instructions: *"Before using quantstats, run `python -m quantstats guide`."*
289
+
290
+ ---
291
+
219
292
  ## Montecarlo Engine
220
293
 
221
294
  `quantstats.montecarlo` characterises an asset with several stochastic models, simulates forward paths from each, and compares the distribution of outcomes (CAGR, max drawdown, bust/goal probabilities, CVaR).
@@ -291,7 +364,7 @@ CAGR · Volatility · Downside Vol · Max Drawdown · Mean Drawdown · Win Rate
291
364
  Each metric-window cell gets a **traffic-light status** (Excellent / Good / Warning / Critical) based on z-scores computed on a per-metric analysis scale (log transforms for skewed metrics). The tearsheet also includes:
292
365
 
293
366
  - **Health score** — count of Good/Excellent cells
294
- - **CUSUM** return-decay detector
367
+ - **CUSUM** return-decay detector, with its target estimated on a reference period (first half of the sample by default) rather than on the data being judged
295
368
  - **Time underwater** duration analysis
296
369
  - Per-metric distribution charts with current observation vs historical mean
297
370
 
@@ -305,9 +378,11 @@ print(available_metrics())
305
378
 
306
379
  result = analyze(
307
380
  returns,
308
- windows=(7, 15, 30),
381
+ windows=(7, 15, 30), # (21, 63, 126) is less noisy for daily data
309
382
  rf=0.0,
310
383
  periods=252,
384
+ benchmark=None, # pass benchmark returns to monitor alpha (r − β·b)
385
+ baseline=0.5, # leading fraction of the sample used as reference
311
386
  )
312
387
 
313
388
  print(f"Health: {result.score}/{result.total} ({result.score_pct:.0f}%)")
@@ -325,7 +400,7 @@ Generate the full HTML tearsheet with `qs.reports.html_alpha_decay(returns)`.
325
400
 
326
401
  ## API reference
327
402
 
328
- QuantStats Pro exposes **50+ stats**, **15+ plot types**, and **4 HTML report generators**. Explore the full API interactively:
403
+ QuantStats Pro exposes **50+ stats**, **15+ plot types**, and **5 HTML report generators**. Explore the full API interactively:
329
404
 
330
405
  ```python
331
406
  [f for f in dir(qs.stats) if not f.startswith("_")]
@@ -366,7 +441,7 @@ pip install quantstats-pro --upgrade
366
441
  ## Requirements
367
442
 
368
443
  - [Python](https://www.python.org) >= 3.10
369
- - [pandas](https://github.com/pydata/pandas) >= 1.5.0
444
+ - [pandas](https://github.com/pydata/pandas) >= 2.0.0
370
445
  - [numpy](http://www.numpy.org) >= 1.24.0
371
446
  - [scipy](https://www.scipy.org) >= 1.11.0
372
447
  - [matplotlib](https://matplotlib.org) >= 3.7.0
@@ -38,6 +38,9 @@ Same API surface, stronger foundation — bugfixes, reliability, and a growing a
38
38
  | `html_simple` | Lean equity-curve tearsheet — fast read on performance vs benchmark |
39
39
  | `html_montecarlo` | Multi-model forward risk report (GBM, GARCH, Heston, bootstraps, Bayesian, …) with bust/goal probabilities and cross-model consensus |
40
40
  | `html_alpha_decay` | Rolling alpha-decay monitor — z-score traffic lights, CUSUM, time-underwater, per-metric distribution charts |
41
+ | `html_validity` | **New in 0.5** — is the backtest real? Deflated Sharpe, minimum track record, bootstrap intervals, in/out-of-sample, alpha decay, PBO |
42
+ | `quantstats.validity` | Programmatic backtest-validity engine with structured findings and JSON output |
43
+ | `quantstats` CLI | **New in 0.5** — JSON-first command line and a packaged guide so AI agents use the library correctly |
41
44
  | `quantstats.montecarlo` | Programmatic multi-model simulation engine behind the Montecarlo tearsheet |
42
45
  | `quantstats.alphadecay` | Short-horizon rolling diagnostics engine behind the Alpha Decay tearsheet |
43
46
  | Classic `html` | Full tearsheet — metrics + all charts, visually redesigned (v0.2.0+) |
@@ -53,6 +56,8 @@ Same API surface, stronger foundation — bugfixes, reliability, and a growing a
53
56
  | `quantstats.reports` | HTML tearsheets and metrics tables |
54
57
  | `quantstats.montecarlo` | Multi-model forward simulation engine and analytics |
55
58
  | `quantstats.alphadecay` | Short-horizon rolling risk analysis and decay detection |
59
+ | `quantstats.validity` | Backtest validity: overfitting, selection bias, out-of-sample, alpha decay |
60
+ | `quantstats.cli` | `quantstats` command line (JSON output) and the agent guide |
56
61
  | `quantstats.utils` | Data prep, `download_returns`, pandas helpers |
57
62
 
58
63
 
@@ -62,7 +67,7 @@ Legacy shuffle-based Montecarlo remains at `qs.stats.montecarlo()` for backward
62
67
 
63
68
  ## HTML Tearsheets
64
69
 
65
- The main product surface in QuantStats Pro is its **reporting layer**: four HTML tearsheet types that turn a returns series into shareable, browser-ready analytics. All open in the browser by default, or save to disk with `output="path.html"`.
70
+ The main product surface in QuantStats Pro is its **reporting layer**: five HTML tearsheet types that turn a returns series into shareable, browser-ready analytics. All open in the browser by default, or save to disk with `output="path.html"`.
66
71
 
67
72
 
68
73
  | Function | Use case |
@@ -71,8 +76,28 @@ The main product surface in QuantStats Pro is its **reporting layer**: four HTML
71
76
  | `qs.reports.html_simple(...)` | **Pro-only** — lean equity-curve tearsheet for quick strategy review |
72
77
  | `qs.reports.html_montecarlo(...)` | **Pro-only** — multi-model forward risk analysis (1y horizon by default) |
73
78
  | `qs.reports.html_alpha_decay(...)` | **Pro-only** — short-window alpha-decay health monitor (7/15/30d) |
79
+ | `qs.reports.html_validity(...)` | **Pro-only** — backtest validity: selection bias, overfitting, decay |
74
80
 
75
81
 
82
+ ### Backtest validity tearsheet — `html_validity`
83
+
84
+ A Sharpe ratio from a backtest is an estimate, and usually the best of many attempts. This report measures how much of it survives: the **deflated Sharpe ratio** (discounted for the number of variants tried), the **minimum track record** needed, **bootstrap confidence intervals**, an **in-sample vs out-of-sample** comparison, an **alpha-decay** trend test and the **probability of backtest overfitting**.
85
+
86
+ ```python
87
+ result = qs.reports.html_validity(
88
+ returns,
89
+ benchmark, # returns Series (optional)
90
+ n_trials=50, # strategy variants tried before choosing this one
91
+ split="2023-01-01", # first out-of-sample date
92
+ output="validity.html",
93
+ )
94
+ print(result.summary())
95
+ ```
96
+
97
+ ![Backtest validity tearsheet — an overfit moving-average crossover](https://raw.githubusercontent.com/diegoalvarezmgl/quantstats-pro/main/docs/report_validity.webp)
98
+
99
+ [View interactive validity sample](https://htmlpreview.github.io/?https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/docs/tearsheet_validity.html) · [Backtest validity docs](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/docs/validity.md)
100
+
76
101
  ### Simple tearsheet — `html_simple`
77
102
 
78
103
  Focused equity-curve view with core metrics and charts. Ideal when you need a clean performance read without the full classic layout.
@@ -164,6 +189,54 @@ qs.stats.sharpe(returns, periods=365)
164
189
 
165
190
  ---
166
191
 
192
+ ## Backtest Validity
193
+
194
+ `quantstats.validity` returns structured results instead of a picture: numbers, the assumptions used, and a list of findings with stable codes.
195
+
196
+ ```python
197
+ from quantstats import validity
198
+
199
+ res = validity.validate(returns, benchmark, n_trials=50, split="2023-01-01")
200
+
201
+ res.sharpe["dsr"] # deflated Sharpe ratio
202
+ res.bootstrap["sharpe"] # {'observed': …, 'low': …, 'median': …, 'high': …}
203
+ res.split["degradation_p_value"]
204
+ for f in res.findings:
205
+ print(f.severity, f.code, f.message)
206
+ # warning OUT_OF_SAMPLE_DEGRADATION Sharpe fell from 0.74 in-sample to -0.45 out-of-sample (p=0.042).
207
+
208
+ res.to_json() # strict JSON
209
+ ```
210
+
211
+ Pass `trials=` (a DataFrame with the returns of every variant you tried) to measure the real dispersion between variants and get the probability of backtest overfitting.
212
+
213
+ [Backtest validity documentation »](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/docs/validity.md)
214
+
215
+ ---
216
+
217
+ ## For AI agents
218
+
219
+ QuantStats Pro is built to be driven by coding agents as well as by people. Charts are for humans; agents get JSON, explicit input checks and a usage guide that ships inside the package.
220
+
221
+ ```bash
222
+ python -m quantstats guide # input contract, which call answers what, how to report results
223
+ quantstats validate returns.csv --benchmark spy.csv --n-trials 50 --split 2023-01-01
224
+ quantstats metrics returns.csv --benchmark spy.csv
225
+ quantstats decay returns.csv --windows 21,63,126
226
+ quantstats montecarlo returns.csv --sims 1000 --bust -0.25
227
+ quantstats report returns.csv --kind validity --output validity.html
228
+ ```
229
+
230
+ - Every analysis command prints **one JSON object** to stdout; errors are JSON on stderr with exit code 2.
231
+ - **No side effects**: nothing opens a browser or downloads data. Benchmarks come from a file.
232
+ - **Explicit inputs**: prices are rejected with a message that says how to convert them; ambiguous columns must be named.
233
+ - **Reproducible**: bootstraps and simulations are seeded by default.
234
+ - [`AGENT_GUIDE.md`](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/quantstats/AGENT_GUIDE.md) and [`llms.txt`](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/llms.txt) tell an agent how to use the library and how not to overstate a result.
235
+
236
+ Point your agent at the guide with one line in your project instructions: *"Before using quantstats, run `python -m quantstats guide`."*
237
+
238
+ ---
239
+
167
240
  ## Montecarlo Engine
168
241
 
169
242
  `quantstats.montecarlo` characterises an asset with several stochastic models, simulates forward paths from each, and compares the distribution of outcomes (CAGR, max drawdown, bust/goal probabilities, CVaR).
@@ -239,7 +312,7 @@ CAGR · Volatility · Downside Vol · Max Drawdown · Mean Drawdown · Win Rate
239
312
  Each metric-window cell gets a **traffic-light status** (Excellent / Good / Warning / Critical) based on z-scores computed on a per-metric analysis scale (log transforms for skewed metrics). The tearsheet also includes:
240
313
 
241
314
  - **Health score** — count of Good/Excellent cells
242
- - **CUSUM** return-decay detector
315
+ - **CUSUM** return-decay detector, with its target estimated on a reference period (first half of the sample by default) rather than on the data being judged
243
316
  - **Time underwater** duration analysis
244
317
  - Per-metric distribution charts with current observation vs historical mean
245
318
 
@@ -253,9 +326,11 @@ print(available_metrics())
253
326
 
254
327
  result = analyze(
255
328
  returns,
256
- windows=(7, 15, 30),
329
+ windows=(7, 15, 30), # (21, 63, 126) is less noisy for daily data
257
330
  rf=0.0,
258
331
  periods=252,
332
+ benchmark=None, # pass benchmark returns to monitor alpha (r − β·b)
333
+ baseline=0.5, # leading fraction of the sample used as reference
259
334
  )
260
335
 
261
336
  print(f"Health: {result.score}/{result.total} ({result.score_pct:.0f}%)")
@@ -273,7 +348,7 @@ Generate the full HTML tearsheet with `qs.reports.html_alpha_decay(returns)`.
273
348
 
274
349
  ## API reference
275
350
 
276
- QuantStats Pro exposes **50+ stats**, **15+ plot types**, and **4 HTML report generators**. Explore the full API interactively:
351
+ QuantStats Pro exposes **50+ stats**, **15+ plot types**, and **5 HTML report generators**. Explore the full API interactively:
277
352
 
278
353
  ```python
279
354
  [f for f in dir(qs.stats) if not f.startswith("_")]
@@ -314,7 +389,7 @@ pip install quantstats-pro --upgrade
314
389
  ## Requirements
315
390
 
316
391
  - [Python](https://www.python.org) >= 3.10
317
- - [pandas](https://github.com/pydata/pandas) >= 1.5.0
392
+ - [pandas](https://github.com/pydata/pandas) >= 2.0.0
318
393
  - [numpy](http://www.numpy.org) >= 1.24.0
319
394
  - [scipy](https://www.scipy.org) >= 1.11.0
320
395
  - [matplotlib](https://matplotlib.org) >= 3.7.0
@@ -0,0 +1,17 @@
1
+ # QuantStats Pro
2
+
3
+ > Python library for portfolio analytics and backtest validation. Drop-in replacement for QuantStats (`pip install quantstats-pro`, `import quantstats as qs`). Takes a series of simple per-period returns and produces performance metrics, HTML tearsheets, forward simulations, drift monitoring and statistical tests of whether a backtest is overfit. Structured JSON output and a CLI are provided for AI agents.
4
+
5
+ Inputs are simple returns as fractions (0.01 = +1%) in a pandas Series with a DatetimeIndex, not prices. The agent guide below is also available offline with `python -m quantstats guide`.
6
+
7
+ ## Docs
8
+
9
+ - [Agent guide](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/quantstats/AGENT_GUIDE.md): input contract, which call answers which question, how to read and report results, CLI reference
10
+ - [README](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/README.md): overview, install, tearsheet gallery
11
+ - [Backtest validity](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/docs/validity.md): deflated Sharpe, minimum track record, bootstrap intervals, in/out-of-sample, alpha decay, probability of backtest overfitting
12
+ - [Montecarlo engine](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/docs/montecarlo.md): multi-model forward simulation
13
+ - [Alpha decay monitor](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/docs/alphadecay.md): rolling drift diagnostics and CUSUM
14
+
15
+ ## Optional
16
+
17
+ - [Changelog](https://github.com/diegoalvarezmgl/quantstats-pro/blob/main/CHANGELOG.md)