quantlite 1.12.0__tar.gz → 1.13.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 (248) hide show
  1. {quantlite-1.12.0/src/quantlite.egg-info → quantlite-1.13.0}/PKG-INFO +5 -4
  2. {quantlite-1.12.0 → quantlite-1.13.0}/README.md +3 -3
  3. {quantlite-1.12.0 → quantlite-1.13.0}/pyproject.toml +7 -1
  4. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/__init__.py +1 -1
  5. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/_doctor.py +21 -3
  6. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/alerts/__init__.py +36 -8
  7. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/antifragile/__init__.py +25 -7
  8. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/backtesting/analysis.py +80 -29
  9. quantlite-1.13.0/src/quantlite/backtesting/engine.py +566 -0
  10. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/backtesting/legacy.py +16 -1
  11. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/backtesting/signals.py +12 -3
  12. quantlite-1.13.0/src/quantlite/benchmark/compare.py +594 -0
  13. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/benchmark/runner.py +57 -15
  14. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/benchmark/speed.py +53 -15
  15. quantlite-1.13.0/src/quantlite/benchmark/tail_events.py +691 -0
  16. quantlite-1.13.0/src/quantlite/contagion/__init__.py +444 -0
  17. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/core/types.py +32 -4
  18. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/crypto/exchange.py +45 -8
  19. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/crypto/funding.py +16 -3
  20. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/crypto/onchain.py +86 -33
  21. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/crypto/stablecoin.py +82 -21
  22. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/data/__init__.py +23 -6
  23. quantlite-1.13.0/src/quantlite/data/base.py +307 -0
  24. quantlite-1.13.0/src/quantlite/data/cache.py +368 -0
  25. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/data/crypto.py +55 -3
  26. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/data/fred.py +22 -3
  27. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/data/funding.py +4 -1
  28. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/data/local.py +42 -8
  29. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/data/registry.py +26 -2
  30. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/data/stream.py +37 -7
  31. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/data_generation.py +23 -2
  32. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/datasets/__init__.py +50 -17
  33. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/dependency/clustering.py +43 -5
  34. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/dependency/copulas.py +151 -66
  35. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/dependency/correlation.py +14 -0
  36. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/distributions/fat_tails.py +50 -10
  37. quantlite-1.13.0/src/quantlite/diversification/__init__.py +284 -0
  38. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/ergodicity/__init__.py +31 -28
  39. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/explain/attribution.py +44 -25
  40. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/explain/audit.py +20 -7
  41. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/explain/narratives.py +29 -4
  42. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/explain/whatif.py +104 -53
  43. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/factors/classical.py +6 -4
  44. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/factors/custom.py +11 -0
  45. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/factors/tail_risk.py +66 -44
  46. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/honesty.py +38 -5
  47. quantlite-1.13.0/src/quantlite/instruments/bond_pricing.py +169 -0
  48. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/instruments/exotic_options.py +54 -8
  49. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/instruments/option_pricing.py +31 -4
  50. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/metrics.py +25 -7
  51. quantlite-1.13.0/src/quantlite/monte_carlo.py +140 -0
  52. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/network/__init__.py +75 -20
  53. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/overfit/__init__.py +61 -19
  54. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/pipeline.py +17 -16
  55. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/portfolio/dynamic_kelly.py +41 -16
  56. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/portfolio/ensemble.py +58 -8
  57. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/portfolio/optimisation.py +209 -32
  58. quantlite-1.13.0/src/quantlite/portfolio/rebalancing.py +373 -0
  59. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/portfolio/regime_bl.py +15 -1
  60. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/portfolio/walkforward.py +40 -14
  61. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/reference.py +68 -0
  62. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/regime_integration/portfolio.py +69 -42
  63. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/regime_integration/reporting.py +35 -8
  64. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/regime_integration/risk.py +48 -24
  65. quantlite-1.13.0/src/quantlite/regimes/changepoint.py +421 -0
  66. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/regimes/conditional.py +80 -21
  67. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/regimes/hmm.py +76 -15
  68. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/regimes/online.py +57 -15
  69. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/report/html_renderer.py +11 -2
  70. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/report/pdf_renderer.py +26 -9
  71. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/report/sections.py +125 -28
  72. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/report/tearsheet.py +22 -4
  73. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/resample/__init__.py +7 -0
  74. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/risk/evt.py +44 -6
  75. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/risk/gaussian.py +6 -3
  76. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/risk/metrics.py +129 -38
  77. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/scenarios/__init__.py +75 -30
  78. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/scenarios/historical.py +62 -8
  79. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/score/__init__.py +6 -3
  80. quantlite-1.13.0/src/quantlite/score/_methodology.py +55 -0
  81. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/score/_qls1.py +17 -11
  82. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/score/artifact.py +7 -5
  83. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/score/engine.py +183 -36
  84. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/score/integrity.py +92 -12
  85. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/score/monitoring.py +207 -36
  86. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/score/provenance.py +5 -3
  87. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/simulation/evt_simulation.py +106 -49
  88. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/simulation/regime_mc.py +33 -10
  89. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/visualisation.py +44 -6
  90. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/alerts.py +13 -2
  91. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/allocation.py +85 -13
  92. quantlite-1.13.0/src/quantlite/viz/benchmark.py +927 -0
  93. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/dependency.py +29 -15
  94. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/explain.py +58 -5
  95. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/gaussian.py +6 -1
  96. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/portfolio.py +71 -9
  97. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/regimes.py +7 -6
  98. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/risk.py +107 -15
  99. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/streaming.py +9 -5
  100. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/volatility.py +10 -3
  101. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/volatility/dcc.py +13 -0
  102. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/volatility/garch.py +158 -13
  103. {quantlite-1.12.0 → quantlite-1.13.0/src/quantlite.egg-info}/PKG-INFO +5 -4
  104. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite.egg-info/SOURCES.txt +15 -0
  105. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite.egg-info/requires.txt +1 -0
  106. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_backtesting.py +2 -1
  107. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_benchmarks.py +40 -21
  108. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_changepoint.py +3 -1
  109. quantlite-1.13.0/tests/test_data_connectors.py +598 -0
  110. quantlite-1.13.0/tests/test_definition_ledger.py +131 -0
  111. quantlite-1.13.0/tests/test_definitions_backtesting_overfit.py +2029 -0
  112. quantlite-1.13.0/tests/test_definitions_charts_a.py +1833 -0
  113. quantlite-1.13.0/tests/test_definitions_charts_b.py +2092 -0
  114. quantlite-1.13.0/tests/test_definitions_crypto.py +1058 -0
  115. quantlite-1.13.0/tests/test_definitions_data_core_score.py +2918 -0
  116. quantlite-1.13.0/tests/test_definitions_factors_explain_benchmark.py +2329 -0
  117. quantlite-1.13.0/tests/test_definitions_known_six.py +623 -0
  118. quantlite-1.13.0/tests/test_definitions_portfolio.py +1699 -0
  119. quantlite-1.13.0/tests/test_definitions_regimes.py +1383 -0
  120. quantlite-1.13.0/tests/test_definitions_review_fixes.py +383 -0
  121. quantlite-1.13.0/tests/test_definitions_risk_and_processes.py +1652 -0
  122. quantlite-1.13.0/tests/test_definitions_simulation_scenarios.py +1672 -0
  123. quantlite-1.13.0/tests/test_definitions_volatility_dependence.py +2617 -0
  124. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_monitoring.py +20 -2
  125. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_rebalancing.py +2 -1
  126. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_reference.py +2 -2
  127. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_scenarios_historical.py +4 -0
  128. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_viz_ported_from_plotly.py +17 -2
  129. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_viz_untested_modules.py +2 -2
  130. quantlite-1.12.0/src/quantlite/backtesting/engine.py +0 -401
  131. quantlite-1.12.0/src/quantlite/benchmark/compare.py +0 -483
  132. quantlite-1.12.0/src/quantlite/benchmark/tail_events.py +0 -314
  133. quantlite-1.12.0/src/quantlite/contagion/__init__.py +0 -295
  134. quantlite-1.12.0/src/quantlite/data/base.py +0 -106
  135. quantlite-1.12.0/src/quantlite/data/cache.py +0 -155
  136. quantlite-1.12.0/src/quantlite/diversification/__init__.py +0 -222
  137. quantlite-1.12.0/src/quantlite/instruments/bond_pricing.py +0 -108
  138. quantlite-1.12.0/src/quantlite/monte_carlo.py +0 -88
  139. quantlite-1.12.0/src/quantlite/portfolio/rebalancing.py +0 -247
  140. quantlite-1.12.0/src/quantlite/regimes/changepoint.py +0 -249
  141. quantlite-1.12.0/src/quantlite/viz/benchmark.py +0 -622
  142. quantlite-1.12.0/tests/test_data_connectors.py +0 -343
  143. {quantlite-1.12.0 → quantlite-1.13.0}/LICENSE +0 -0
  144. {quantlite-1.12.0 → quantlite-1.13.0}/setup.cfg +0 -0
  145. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/accessor.py +0 -0
  146. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/backtesting/__init__.py +0 -0
  147. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/benchmark/__init__.py +0 -0
  148. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/core/__init__.py +0 -0
  149. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/crypto/__init__.py +0 -0
  150. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/data/yahoo.py +0 -0
  151. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/datasets/data/dff.csv +0 -0
  152. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/datasets/data/dgs10.csv +0 -0
  153. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/datasets/data/dgs2.csv +0 -0
  154. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/datasets/data/dtwexbgs.csv +0 -0
  155. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/datasets/data/four_assets_prices.csv +0 -0
  156. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/dependency/__init__.py +0 -0
  157. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/distributions/__init__.py +0 -0
  158. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/ergodicity/ruin.py +0 -0
  159. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/explain/__init__.py +0 -0
  160. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/factors/__init__.py +0 -0
  161. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/forensics/__init__.py +0 -0
  162. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/instruments/__init__.py +0 -0
  163. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/portfolio/__init__.py +0 -0
  164. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/portfolio/tail_risk_parity.py +0 -0
  165. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/py.typed +0 -0
  166. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/regime_integration/__init__.py +0 -0
  167. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/regimes/__init__.py +0 -0
  168. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/report/__init__.py +0 -0
  169. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/risk/__init__.py +0 -0
  170. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/simulation/__init__.py +0 -0
  171. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/simulation/copula_mc.py +0 -0
  172. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/__init__.py +0 -0
  173. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/funding.py +0 -0
  174. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/online_regimes.py +0 -0
  175. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/scenarios.py +0 -0
  176. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/viz/theme.py +0 -0
  177. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/volatility/__init__.py +0 -0
  178. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite/volatility/realised.py +0 -0
  179. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite.egg-info/dependency_links.txt +0 -0
  180. {quantlite-1.12.0 → quantlite-1.13.0}/src/quantlite.egg-info/top_level.txt +0 -0
  181. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_accessor.py +0 -0
  182. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_alerts.py +0 -0
  183. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_allocation_engine.py +0 -0
  184. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_analysis.py +0 -0
  185. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_antifragile.py +0 -0
  186. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_clustering.py +0 -0
  187. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_conditional.py +0 -0
  188. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_contagion.py +0 -0
  189. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_copulas.py +0 -0
  190. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_correlation.py +0 -0
  191. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_crypto_exchange.py +0 -0
  192. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_crypto_funding.py +0 -0
  193. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_crypto_onchain.py +0 -0
  194. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_crypto_stablecoin.py +0 -0
  195. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_data_funding.py +0 -0
  196. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_data_generation.py +0 -0
  197. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_datasets.py +0 -0
  198. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_diversification.py +0 -0
  199. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_doctor.py +0 -0
  200. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_drawdown_from_the_start.py +0 -0
  201. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_engine.py +0 -0
  202. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_ergodicity.py +0 -0
  203. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_ergodicity_ruin.py +0 -0
  204. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_evt.py +0 -0
  205. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_explainability.py +0 -0
  206. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_explainable_html.py +0 -0
  207. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_factors_classical.py +0 -0
  208. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_factors_custom.py +0 -0
  209. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_factors_tail_risk.py +0 -0
  210. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_fat_tails.py +0 -0
  211. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_forensics.py +0 -0
  212. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_front_door.py +0 -0
  213. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_hmm.py +0 -0
  214. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_honesty.py +0 -0
  215. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_instruments.py +0 -0
  216. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_metrics.py +0 -0
  217. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_monte_carlo.py +0 -0
  218. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_network.py +0 -0
  219. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_online_regime.py +0 -0
  220. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_optimisation.py +0 -0
  221. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_overfit.py +0 -0
  222. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_pipeline.py +0 -0
  223. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_provenance.py +0 -0
  224. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_regime_integration.py +0 -0
  225. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_regime_integration_risk_first_passage.py +0 -0
  226. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_report.py +0 -0
  227. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_resample.py +0 -0
  228. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_risk_gaussian.py +0 -0
  229. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_risk_metrics.py +0 -0
  230. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_scenarios.py +0 -0
  231. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_score.py +0 -0
  232. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_signals.py +0 -0
  233. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_sim_copula.py +0 -0
  234. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_sim_evt.py +0 -0
  235. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_sim_regime.py +0 -0
  236. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_stream.py +0 -0
  237. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_visualisation.py +0 -0
  238. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_viz.py +0 -0
  239. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_viz_dependency.py +0 -0
  240. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_viz_funding.py +0 -0
  241. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_viz_gaussian.py +0 -0
  242. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_viz_portfolio.py +0 -0
  243. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_viz_regimes.py +0 -0
  244. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_viz_volatility.py +0 -0
  245. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_volatility_arch_crosscheck.py +0 -0
  246. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_volatility_dcc.py +0 -0
  247. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_volatility_garch.py +0 -0
  248. {quantlite-1.12.0 → quantlite-1.13.0}/tests/test_volatility_realised.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantlite
3
- Version: 1.12.0
3
+ Version: 1.13.0
4
4
  Summary: A fat-tail-native quantitative finance toolkit: EVT, risk metrics, and honest modelling for markets that bite.
5
5
  Author-email: Prasant Sudhakaran <code@prasant.net>
6
6
  License-Expression: MIT
@@ -27,6 +27,7 @@ Requires-Dist: pandas>=2.0
27
27
  Requires-Dist: scipy>=1.10
28
28
  Requires-Dist: matplotlib>=3.7
29
29
  Requires-Dist: mplfinance
30
+ Requires-Dist: six
30
31
  Provides-Extra: yahoo
31
32
  Requires-Dist: yfinance>=0.2; extra == "yahoo"
32
33
  Provides-Extra: crypto
@@ -97,7 +98,7 @@ ql.ruin_check(returns, leverage=3).explain() # what leverage does to the p
97
98
  ql.replay_all(prices, weights, prices=True).explain() # every historical crisis your data covers, replayed
98
99
  ```
99
100
 
100
- And one to check the library itself: `ql.reference_check()` reproduces 19 published results, from the deflated Sharpe ratio to the Kelly fraction, and shows any difference.
101
+ And one to check the library itself: `ql.reference_check()` reproduces 29 published results, from the deflated Sharpe ratio to the Kelly fraction, and shows any difference.
101
102
 
102
103
  ---
103
104
 
@@ -125,7 +126,7 @@ payload = result.artifact.to_json() # publish or store this
125
126
  assert verify_artifact(payload, returns) # anyone can reproduce it bit for bit
126
127
  ```
127
128
 
128
- Every score ships as a portable artifact with a SHA-256 content hash. Same returns, same parameters, same library version: same score, bit for bit. The methodology (QLS-1.0) is open and frozen per version; see [the specification](docs/score.md).
129
+ Every score ships as a portable artifact with a SHA-256 content hash. Same returns, same parameters, same methodology version: same score, bit for bit, in every library version. The methodology (QLS-1.1 is current; QLS-1.0 scores still verify) is open and frozen per version; see [the specification](docs/score.md).
129
130
 
130
131
  ---
131
132
 
@@ -319,7 +320,7 @@ print(f"95% CI: [{result['ci_lower']:.2f}, {result['ci_upper']:.2f}]")
319
320
  |--------|-------------|
320
321
  | `quantlite.forensics` | Deflated Sharpe Ratio, Probabilistic Sharpe, haircut adjustments, minimum track record |
321
322
  | `quantlite.honesty_check` | One call, one verdict: PSR, deflated Sharpe with the luck benchmark, minimum track record, bootstrap interval, and PBO when the trials are supplied |
322
- | `quantlite.reference_check` | Reproduces 19 published results (deflated and probabilistic Sharpe, minimum track record, normal tail constants, Kelly, Parkinson) and shows the differences; `python -m quantlite.reference` for CI |
323
+ | `quantlite.reference_check` | Reproduces 29 published results (deflated and probabilistic Sharpe, minimum track record, normal tail constants, Kelly, Parkinson, Sharpe and Sortino, Black-Scholes, effective bets, copula tail dependence) and shows the differences; `python -m quantlite.reference` for CI |
323
324
  | `quantlite.overfit` | CSCV/PBO, TrialTracker, multiple testing correction, walk-forward validation |
324
325
  | `quantlite.resample` | Block and stationary bootstrap, confidence intervals for Sharpe and drawdown |
325
326
 
@@ -32,7 +32,7 @@ ql.ruin_check(returns, leverage=3).explain() # what leverage does to the p
32
32
  ql.replay_all(prices, weights, prices=True).explain() # every historical crisis your data covers, replayed
33
33
  ```
34
34
 
35
- And one to check the library itself: `ql.reference_check()` reproduces 19 published results, from the deflated Sharpe ratio to the Kelly fraction, and shows any difference.
35
+ And one to check the library itself: `ql.reference_check()` reproduces 29 published results, from the deflated Sharpe ratio to the Kelly fraction, and shows any difference.
36
36
 
37
37
  ---
38
38
 
@@ -60,7 +60,7 @@ payload = result.artifact.to_json() # publish or store this
60
60
  assert verify_artifact(payload, returns) # anyone can reproduce it bit for bit
61
61
  ```
62
62
 
63
- Every score ships as a portable artifact with a SHA-256 content hash. Same returns, same parameters, same library version: same score, bit for bit. The methodology (QLS-1.0) is open and frozen per version; see [the specification](docs/score.md).
63
+ Every score ships as a portable artifact with a SHA-256 content hash. Same returns, same parameters, same methodology version: same score, bit for bit, in every library version. The methodology (QLS-1.1 is current; QLS-1.0 scores still verify) is open and frozen per version; see [the specification](docs/score.md).
64
64
 
65
65
  ---
66
66
 
@@ -254,7 +254,7 @@ print(f"95% CI: [{result['ci_lower']:.2f}, {result['ci_upper']:.2f}]")
254
254
  |--------|-------------|
255
255
  | `quantlite.forensics` | Deflated Sharpe Ratio, Probabilistic Sharpe, haircut adjustments, minimum track record |
256
256
  | `quantlite.honesty_check` | One call, one verdict: PSR, deflated Sharpe with the luck benchmark, minimum track record, bootstrap interval, and PBO when the trials are supplied |
257
- | `quantlite.reference_check` | Reproduces 19 published results (deflated and probabilistic Sharpe, minimum track record, normal tail constants, Kelly, Parkinson) and shows the differences; `python -m quantlite.reference` for CI |
257
+ | `quantlite.reference_check` | Reproduces 29 published results (deflated and probabilistic Sharpe, minimum track record, normal tail constants, Kelly, Parkinson, Sharpe and Sortino, Black-Scholes, effective bets, copula tail dependence) and shows the differences; `python -m quantlite.reference` for CI |
258
258
  | `quantlite.overfit` | CSCV/PBO, TrialTracker, multiple testing correction, walk-forward validation |
259
259
  | `quantlite.resample` | Block and stationary bootstrap, confidence intervals for Sharpe and drawdown |
260
260
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "quantlite"
7
- version = "1.12.0"
7
+ version = "1.13.0"
8
8
  description = "A fat-tail-native quantitative finance toolkit: EVT, risk metrics, and honest modelling for markets that bite."
9
9
  requires-python = ">=3.10"
10
10
  license = "MIT"
@@ -43,6 +43,9 @@ dependencies = [
43
43
  "scipy>=1.10",
44
44
  "matplotlib>=3.7",
45
45
  "mplfinance",
46
+ # mplfinance imports six without declaring it. It used to arrive with
47
+ # python-dateutil, which dropped it in 4.0.
48
+ "six",
46
49
  ]
47
50
 
48
51
  [project.optional-dependencies]
@@ -98,3 +101,6 @@ disallow_untyped_defs = false
98
101
  [tool.pytest.ini_options]
99
102
  testpaths = ["tests"]
100
103
  asyncio_mode = "auto"
104
+ markers = [
105
+ "checks(name): the public function or method this test checks against its definition",
106
+ ]
@@ -17,7 +17,7 @@ from __future__ import annotations
17
17
  import importlib
18
18
  from typing import Any
19
19
 
20
- __version__ = "1.12.0"
20
+ __version__ = "1.13.0"
21
21
 
22
22
  # Public names mapped to the module that defines them, for lazy loading.
23
23
  _ATTR_SOURCES = {
@@ -21,13 +21,20 @@ import sys
21
21
 
22
22
  __all__ = ["doctor"]
23
23
 
24
+ # The packages of the [all] extra, as listed under ``all`` in pyproject.toml
25
+ # ([project.optional-dependencies]). Keep the two in step.
26
+ _ALL_EXTRA: tuple[str, ...] = ("yfinance", "ccxt", "fredapi", "weasyprint", "hmmlearn")
27
+
24
28
  # extra name -> (packages that must be importable, what it unlocks)
25
29
  _EXTRAS: dict[str, tuple[tuple[str, ...], str]] = {
26
30
  "yahoo": (("yfinance",), "Yahoo Finance connector: fetch(..., source='yahoo')"),
27
31
  "crypto": (("ccxt",), "Exchange OHLCV, order books, funding history: fetch(..., source='ccxt'), data.funding"),
28
32
  "fred": (("fredapi",), "FRED macro series by API key: fetch(..., source='fred')"),
29
33
  "pdf": (("weasyprint",), "PDF tearsheets (also needs the pango and cairo system libraries)"),
30
- "all": (("hmmlearn",), "HMM regime detection: detect_regimes(method='hmm'); part of the [all] extra"),
34
+ "all": (
35
+ _ALL_EXTRA,
36
+ "Every optional package above plus hmmlearn (HMM regimes: detect_regimes(method='hmm'))",
37
+ ),
31
38
  }
32
39
 
33
40
  _CORE = ("numpy", "scipy", "pandas", "matplotlib")
@@ -52,7 +59,14 @@ def doctor(*, echo: bool = True) -> dict[str, bool]:
52
59
  -------
53
60
  dict
54
61
  Extra name to installed flag. Bundled datasets and everything in
55
- the core need no extra and are not listed.
62
+ the core need no extra and are not listed. ``"all"`` is true only
63
+ when every package of the ``[all]`` extra is findable.
64
+
65
+ Notes
66
+ -----
67
+ Before QuantLite 1.13 ``"all"`` tested hmmlearn alone, so a machine
68
+ with hmmlearn and none of yfinance, ccxt, fredapi or weasyprint was
69
+ reported as ``all: installed``.
56
70
  """
57
71
  from . import __version__
58
72
 
@@ -73,7 +87,11 @@ def doctor(*, echo: bool = True) -> dict[str, bool]:
73
87
  mark = "installed" if status[name] else "missing "
74
88
  lines.append(f" {name:<{width}} {mark} {unlocks}")
75
89
  if not status[name]:
76
- lines.append(f" {'':<{width}} pip install quantlite[{name}] (needs {', '.join(packages)})")
90
+ absent = [p for p in packages if not _present(p)]
91
+ lines.append(
92
+ f" {'':<{width}} pip install quantlite[{name}]"
93
+ f" (needs {', '.join(absent)})"
94
+ )
77
95
  lines.append("")
78
96
  lines.append("Bundled datasets need no extra: quantlite.datasets.available()")
79
97
  print("\n".join(lines))
@@ -22,6 +22,7 @@ Example::
22
22
  from __future__ import annotations
23
23
 
24
24
  import logging
25
+ import math
25
26
  import time
26
27
  from collections.abc import Callable, Sequence
27
28
  from dataclasses import dataclass, field
@@ -115,10 +116,21 @@ class AlertManager:
115
116
 
116
117
  Args:
117
118
  max_history: Maximum number of alerts to keep in the
118
- history log. Defaults to 1000.
119
+ history log. Defaults to 1000. Zero keeps no history.
120
+
121
+ Raises:
122
+ ValueError: If ``max_history`` is negative.
119
123
  """
120
124
 
125
+ _RULE_CONDITIONS = ("regime_change",)
126
+
121
127
  def __init__(self, max_history: int = 1000) -> None:
128
+ if max_history < 0:
129
+ raise ValueError(
130
+ f"max_history must be zero or more, got {max_history}. "
131
+ "Use 0 to keep no history."
132
+ )
133
+ self._name_counter = 0
122
134
  self._rules: dict[str, AlertRule] = {}
123
135
  self._history: list[Alert] = []
124
136
  self._max_history = max_history
@@ -162,9 +174,17 @@ class AlertManager:
162
174
 
163
175
  Returns:
164
176
  The created ``AlertRule``.
177
+
178
+ Raises:
179
+ ValueError: If ``condition`` is not a supported condition.
165
180
  """
181
+ if condition not in self._RULE_CONDITIONS:
182
+ raise ValueError(
183
+ f"Unknown condition '{condition}'. Supported: {list(self._RULE_CONDITIONS)}. "
184
+ "Use add_threshold() for threshold alerts."
185
+ )
166
186
  if name is None:
167
- name = f"{metric}_{condition}_{len(self._rules)}"
187
+ name = self._next_name(f"{metric}_{condition}")
168
188
 
169
189
  rule = AlertRule(
170
190
  name=name,
@@ -200,7 +220,7 @@ class AlertManager:
200
220
  The created ``AlertRule``.
201
221
  """
202
222
  if name is None:
203
- name = f"{metric}_threshold_{len(self._rules)}"
223
+ name = self._next_name(f"{metric}_threshold")
204
224
 
205
225
  dir_enum = ThresholdDirection(direction.lower())
206
226
 
@@ -216,6 +236,14 @@ class AlertManager:
216
236
  self._rules[name] = rule
217
237
  return rule
218
238
 
239
+ def _next_name(self, prefix: str) -> str:
240
+ """Return an auto-generated rule name that no earlier rule has used."""
241
+ while True:
242
+ name = f"{prefix}_{self._name_counter}"
243
+ self._name_counter += 1
244
+ if name not in self._rules:
245
+ return name
246
+
219
247
  def remove_rule(self, name: str) -> None:
220
248
  """Remove an alert rule by name.
221
249
 
@@ -273,15 +301,14 @@ class AlertManager:
273
301
  continue
274
302
  if rule.metric != metric:
275
303
  continue
276
- if now - rule._last_fired < rule.cooldown_s:
277
- continue
278
304
 
305
+ # Evaluate even during cooldown so a cross rule keeps its previous
306
+ # value up to date; the alert is only dropped, never fired late.
279
307
  alert = self._evaluate_rule(
280
308
  rule, value, regime, previous_regime, metadata
281
309
  )
282
- if alert is not None:
310
+ if alert is not None and now - rule._last_fired >= rule.cooldown_s:
283
311
  rule._last_fired = now
284
- rule._last_value = value
285
312
  self._record_alert(alert)
286
313
  fired.append(alert)
287
314
 
@@ -353,6 +380,7 @@ class AlertManager:
353
380
  elif (
354
381
  rule.condition == "threshold"
355
382
  and value is not None
383
+ and not math.isnan(value)
356
384
  and rule.threshold is not None
357
385
  ):
358
386
  triggered = False
@@ -395,7 +423,7 @@ class AlertManager:
395
423
  """
396
424
  self._history.append(alert)
397
425
  if len(self._history) > self._max_history:
398
- self._history = self._history[-self._max_history:]
426
+ self._history = self._history[len(self._history) - self._max_history:]
399
427
 
400
428
  # Fire rule-specific callback
401
429
  rule = self._rules.get(alert.rule_name)
@@ -144,14 +144,18 @@ def fourth_quadrant(returns: ArrayLike) -> FourthQuadrantResult:
144
144
  'payoff_nonlinearity' above 2, which normal returns exceed threefold,
145
145
  so the test was on kurtosis alone. It now compares the ratio with its
146
146
  value for normal returns.
147
+
148
+ Before QuantLite 1.13 'kurtosis' scaled by the sample standard deviation
149
+ (ddof=1) but averaged the fourth power with divisor n, so it matched
150
+ neither the population nor the bias-corrected convention: for 40 points
151
+ it ran about 0.2 below the population excess kurtosis. It is now the
152
+ population excess kurtosis, ``scipy.stats.kurtosis`` with its defaults.
147
153
  """
148
154
  r = _to_array(returns)
149
155
 
150
- # Excess kurtosis (normal = 0)
156
+ # Population excess kurtosis, m4 / m2^2 - 3 (normal = 0); 0 for a constant series.
151
157
  n = r.size
152
- mean = np.mean(r)
153
- std = np.std(r, ddof=1) if n > 1 else 1.0
154
- kurt = 0.0 if std == 0 else float(np.mean(((r - mean) / std) ** 4) - 3.0)
158
+ kurt = 0.0 if np.ptp(r) == 0 else float(stats.kurtosis(r))
155
159
 
156
160
  fat_tailed = kurt > 1.0
157
161
 
@@ -406,12 +410,26 @@ def skin_in_game_score(
406
410
  Keys: 'alignment' (correlation), 'downside_sharing' (ratio of
407
411
  manager downside to fund downside), 'upside_asymmetry',
408
412
  'score' (composite: 1.0 = perfect alignment).
413
+
414
+ Raises
415
+ ------
416
+ ValueError
417
+ If the two series differ in length, or either is empty.
418
+
419
+ Notes
420
+ -----
421
+ Before QuantLite 1.13 unequal series were cut to the shorter length
422
+ without warning, which pairs each manager return with the wrong fund
423
+ period. A series of 12 months against one of 10 silently dropped the
424
+ last two months of the longer one.
409
425
  """
410
426
  m = _to_array(manager_returns)
411
427
  f = _to_array(fund_returns)
412
- min_len = min(m.size, f.size)
413
- m = m[:min_len]
414
- f = f[:min_len]
428
+ if m.size != f.size:
429
+ raise ValueError(
430
+ f"manager_returns has {m.size} observations and fund_returns has {f.size}; "
431
+ "they must cover the same periods. Align the two series before scoring."
432
+ )
415
433
 
416
434
  # Correlation as alignment measure
417
435
  alignment = 0.0 if np.std(m) == 0 or np.std(f) == 0 else float(np.corrcoef(m, f)[0, 1])
@@ -31,27 +31,33 @@ def performance_summary(result: Any) -> pd.DataFrame:
31
31
  result: A ``BacktestResult`` from the backtesting engine.
32
32
 
33
33
  Returns:
34
- Single-column DataFrame with metric names as the index.
34
+ Single-column DataFrame with metric names as the index. A metric
35
+ the backtest did not compute is NaN, not 0.
36
+
37
+ Notes:
38
+ Before QuantLite 1.13 a missing metric showed as 0: a 4-bar backtest
39
+ with a 10% drawdown reported Max Drawdown 0.0.
35
40
  """
36
41
  m = result.metrics
42
+ nan = float("nan")
37
43
  rows = {
38
- "Initial Capital": m.get("initial_capital", 0),
39
- "Final Value": m.get("final_value", 0),
40
- "Total Return": m.get("total_return", 0),
41
- "Annualised Return": m.get("annualised_return", 0),
42
- "Annualised Volatility": m.get("annualised_volatility", 0),
43
- "Sharpe Ratio": m.get("sharpe_ratio", 0),
44
- "Sortino Ratio": m.get("sortino_ratio", 0),
45
- "Calmar Ratio": m.get("calmar_ratio", 0),
46
- "Max Drawdown": m.get("max_drawdown", 0),
47
- "Max DD Duration": m.get("max_drawdown_duration", 0),
48
- "VaR (95%)": m.get("var_95", 0),
49
- "CVaR (95%)": m.get("cvar_95", 0),
50
- "Omega Ratio": m.get("omega_ratio", 0),
51
- "Tail Ratio": m.get("tail_ratio", 0),
52
- "Skewness": m.get("skewness", 0),
53
- "Kurtosis": m.get("kurtosis", 0),
54
- "Total Trades": m.get("n_trades", 0),
44
+ "Initial Capital": m.get("initial_capital", nan),
45
+ "Final Value": m.get("final_value", nan),
46
+ "Total Return": m.get("total_return", nan),
47
+ "Annualised Return": m.get("annualised_return", nan),
48
+ "Annualised Volatility": m.get("annualised_volatility", nan),
49
+ "Sharpe Ratio": m.get("sharpe_ratio", nan),
50
+ "Sortino Ratio": m.get("sortino_ratio", nan),
51
+ "Calmar Ratio": m.get("calmar_ratio", nan),
52
+ "Max Drawdown": m.get("max_drawdown", nan),
53
+ "Max DD Duration": m.get("max_drawdown_duration", nan),
54
+ "VaR (95%)": m.get("var_95", nan),
55
+ "CVaR (95%)": m.get("cvar_95", nan),
56
+ "Omega Ratio": m.get("omega_ratio", nan),
57
+ "Tail Ratio": m.get("tail_ratio", nan),
58
+ "Skewness": m.get("skewness", nan),
59
+ "Kurtosis": m.get("kurtosis", nan),
60
+ "Total Trades": m.get("n_trades", nan),
55
61
  }
56
62
  return pd.DataFrame({"Value": rows})
57
63
 
@@ -65,11 +71,20 @@ def monthly_returns_table(result: Any) -> pd.DataFrame:
65
71
  Returns:
66
72
  DataFrame with years as rows (index) and months 1-12 as columns.
67
73
  Values are total returns for each month. Missing months are NaN.
74
+ The first month runs from the first value of the series.
75
+
76
+ Notes:
77
+ Before QuantLite 1.13 the first month was always NaN, because month
78
+ returns were changes between month-end values and the starting value
79
+ was ignored: a series from 100 to 130.5 over January showed NaN
80
+ where the return is 0.305.
68
81
  """
69
82
  pv = result.portfolio_value
70
83
  # Compute monthly returns from portfolio value
71
84
  monthly_pv = pv.resample("ME").last()
72
85
  monthly_rets = monthly_pv.pct_change()
86
+ if len(monthly_pv) > 0:
87
+ monthly_rets.iloc[0] = float(monthly_pv.iloc[0] / pv.iloc[0] - 1.0)
73
88
 
74
89
  # Build year x month table
75
90
  if len(monthly_rets) == 0:
@@ -109,16 +124,24 @@ def rolling_metrics(
109
124
 
110
125
  Returns:
111
126
  DataFrame with columns: rolling_sharpe, rolling_vol, rolling_drawdown.
127
+ Every column is NaN until a full window of real returns exists, which
128
+ is at position ``window``.
129
+
130
+ Notes:
131
+ Before QuantLite 1.13 the first observation's return was filled in as
132
+ 0.0 and used, so with a window of 5 the volatility at position 4 came
133
+ from one invented zero and four real returns, and the rolling
134
+ drawdown read 0.0 before the first full window.
112
135
  """
113
136
  pv = result.portfolio_value
114
- rets = pv.pct_change().fillna(0.0)
137
+ rets = pv.pct_change()
115
138
 
116
139
  rolling_vol = rets.rolling(window).std() * np.sqrt(freq)
117
140
  rolling_mean = rets.rolling(window).mean() * freq
118
141
  rolling_sharpe = rolling_mean / rolling_vol.replace(0, np.nan)
119
142
 
120
143
  # Rolling drawdown
121
- rolling_dd = pd.Series(0.0, index=pv.index)
144
+ rolling_dd = pd.Series(np.nan, index=pv.index)
122
145
  for i in range(window, len(pv)):
123
146
  window_pv = pv.iloc[i - window:i + 1]
124
147
  peak = window_pv.cummax()
@@ -167,7 +190,8 @@ def trade_analysis(result: Any, prices: pd.DataFrame | None = None) -> TradeAnal
167
190
  Each trade that leaves a non-zero weight opens a position, held until
168
191
  the next trade in the same asset (or the end). Its profit is what that
169
192
  weight earned in the meantime, in the backtest's own accounting,
170
- less the trade's cost. A position wins if that is positive.
193
+ less the cost of the trade that opened it and the cost of the trade
194
+ that closed it to zero weight. A position wins if that is positive.
171
195
 
172
196
  Args:
173
197
  result: A ``BacktestResult`` from the backtesting engine.
@@ -192,6 +216,11 @@ def trade_analysis(result: Any, prices: pd.DataFrame | None = None) -> TradeAnal
192
216
  sale as a loss: ``win_rate`` was the share of trades that bought.
193
217
  Without ``prices`` those numbers are still returned, with a
194
218
  warning, and will be removed.
219
+
220
+ Before QuantLite 1.13 the cost of a trade that closed a position was
221
+ charged to no position, so "net of costs" was wrong for round trips:
222
+ with a 1% fee and a 1.5% price rise, a round trip that lost 5.20
223
+ (1000 to 994.80) reported a win of 4.85.
195
224
  """
196
225
  trades = result.trades
197
226
  base: dict[str, Any] = {
@@ -256,11 +285,20 @@ def trade_analysis(result: Any, prices: pd.DataFrame | None = None) -> TradeAnal
256
285
  pnls: list[float] = []
257
286
  for asset, events in by_asset.items():
258
287
  events.sort()
288
+ open_pnl: float | None = None # the position still open in this asset
259
289
  for idx, (i, k) in enumerate(events):
260
290
  if abs(float(trades[k]["new_weight"])) < 1e-12:
291
+ # A closing trade: its cost belongs to the position it closes.
292
+ if open_pnl is not None:
293
+ pnls.append(open_pnl - costs[k])
294
+ open_pnl = None
261
295
  continue
296
+ if open_pnl is not None:
297
+ pnls.append(open_pnl)
262
298
  end = events[idx + 1][0] if idx + 1 < len(events) else len(value) - 1
263
- pnls.append(float(earned[i + 1 : end + 1, col[asset]].sum()) - costs[k])
299
+ open_pnl = float(earned[i + 1 : end + 1, col[asset]].sum()) - costs[k]
300
+ if open_pnl is not None:
301
+ pnls.append(open_pnl)
264
302
 
265
303
  arr = np.asarray(pnls)
266
304
  wins, losses = arr[arr > 0], arr[arr < 0]
@@ -283,20 +321,33 @@ def regime_attribution(result: Any) -> pd.DataFrame:
283
321
 
284
322
  Returns:
285
323
  DataFrame indexed by regime label with columns: total_return,
286
- mean_return, volatility, n_periods, pct_time.
324
+ mean_return, volatility, n_periods, pct_time. Only real returns are
325
+ used: the return of period ``t`` is attributed to the label of
326
+ period ``t``, so the first label, which has no return, is dropped
327
+ and ``pct_time`` is a share of the returns.
328
+
329
+ Raises:
330
+ ValueError: If the number of labels differs from the number of
331
+ portfolio values.
332
+
333
+ Notes:
334
+ Before QuantLite 1.13 the first period's return was invented as 0 and
335
+ counted: 8 values reported 8 periods where there are 7 returns. A
336
+ label array of the wrong length was trimmed silently.
287
337
  """
288
338
  if result.regime_labels is None:
289
339
  return pd.DataFrame()
290
340
 
291
341
  pv = result.portfolio_value
292
- rets = pv.pct_change().fillna(0.0)
293
342
  labels = np.asarray(result.regime_labels)
294
343
 
295
- if len(labels) != len(rets):
296
- # Trim to match
297
- min_len = min(len(labels), len(rets))
298
- labels = labels[:min_len]
299
- rets = rets.iloc[:min_len]
344
+ if len(labels) != len(pv):
345
+ raise ValueError(
346
+ f"regime_labels has {len(labels)} labels but the backtest has {len(pv)} values; "
347
+ "supply one label per period."
348
+ )
349
+ rets = pv.pct_change().iloc[1:]
350
+ labels = labels[1:]
300
351
 
301
352
  unique_regimes = sorted(set(labels))
302
353
  rows: list[dict[str, float]] = []