riskvalidation 0.8.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 (193) hide show
  1. riskvalidation-0.8.0/LICENSE +21 -0
  2. riskvalidation-0.8.0/PKG-INFO +136 -0
  3. riskvalidation-0.8.0/README.md +99 -0
  4. riskvalidation-0.8.0/pyproject.toml +74 -0
  5. riskvalidation-0.8.0/setup.cfg +4 -0
  6. riskvalidation-0.8.0/src/riskvalidation/__init__.py +30 -0
  7. riskvalidation-0.8.0/src/riskvalidation/aggregation/__init__.py +11 -0
  8. riskvalidation-0.8.0/src/riskvalidation/aggregation/band.py +151 -0
  9. riskvalidation-0.8.0/src/riskvalidation/aggregation/bounds.py +191 -0
  10. riskvalidation-0.8.0/src/riskvalidation/aggregation/copulas.py +241 -0
  11. riskvalidation-0.8.0/src/riskvalidation/aggregation/model_risk.py +133 -0
  12. riskvalidation-0.8.0/src/riskvalidation/aggregation/simple.py +147 -0
  13. riskvalidation-0.8.0/src/riskvalidation/ccr/__init__.py +13 -0
  14. riskvalidation-0.8.0/src/riskvalidation/ccr/collateral.py +175 -0
  15. riskvalidation-0.8.0/src/riskvalidation/ccr/cva.py +193 -0
  16. riskvalidation-0.8.0/src/riskvalidation/ccr/exposure.py +192 -0
  17. riskvalidation-0.8.0/src/riskvalidation/ccr/hw1f.py +426 -0
  18. riskvalidation-0.8.0/src/riskvalidation/ccr/swaps.py +172 -0
  19. riskvalidation-0.8.0/src/riskvalidation/core/__init__.py +1 -0
  20. riskvalidation-0.8.0/src/riskvalidation/core/build.py +57 -0
  21. riskvalidation-0.8.0/src/riskvalidation/core/hashing.py +48 -0
  22. riskvalidation-0.8.0/src/riskvalidation/core/policy.py +130 -0
  23. riskvalidation-0.8.0/src/riskvalidation/core/registry.py +65 -0
  24. riskvalidation-0.8.0/src/riskvalidation/core/result.py +117 -0
  25. riskvalidation-0.8.0/src/riskvalidation/core/suite.py +78 -0
  26. riskvalidation-0.8.0/src/riskvalidation/engines/__init__.py +2 -0
  27. riskvalidation-0.8.0/src/riskvalidation/engines/low_default.py +170 -0
  28. riskvalidation-0.8.0/src/riskvalidation/engines/pd_curve.py +529 -0
  29. riskvalidation-0.8.0/src/riskvalidation/engines/vasicek.py +72 -0
  30. riskvalidation-0.8.0/src/riskvalidation/fairness/__init__.py +10 -0
  31. riskvalidation-0.8.0/src/riskvalidation/fairness/_checks.py +115 -0
  32. riskvalidation-0.8.0/src/riskvalidation/fairness/conditional.py +201 -0
  33. riskvalidation-0.8.0/src/riskvalidation/fairness/inference.py +64 -0
  34. riskvalidation-0.8.0/src/riskvalidation/fairness/metrics.py +261 -0
  35. riskvalidation-0.8.0/src/riskvalidation/fairness/plants.py +240 -0
  36. riskvalidation-0.8.0/src/riskvalidation/fairness/policy.py +97 -0
  37. riskvalidation-0.8.0/src/riskvalidation/fairness/replication.py +39 -0
  38. riskvalidation-0.8.0/src/riskvalidation/fairness/situation.py +307 -0
  39. riskvalidation-0.8.0/src/riskvalidation/generators/__init__.py +68 -0
  40. riskvalidation-0.8.0/src/riskvalidation/generators/_base.py +145 -0
  41. riskvalidation-0.8.0/src/riskvalidation/generators/counts.py +232 -0
  42. riskvalidation-0.8.0/src/riskvalidation/generators/drift.py +107 -0
  43. riskvalidation-0.8.0/src/riskvalidation/generators/framingham.py +124 -0
  44. riskvalidation-0.8.0/src/riskvalidation/generators/paths.py +349 -0
  45. riskvalidation-0.8.0/src/riskvalidation/generators/ratings.py +186 -0
  46. riskvalidation-0.8.0/src/riskvalidation/generators/scores.py +347 -0
  47. riskvalidation-0.8.0/src/riskvalidation/harness/__init__.py +46 -0
  48. riskvalidation-0.8.0/src/riskvalidation/harness/exact.py +137 -0
  49. riskvalidation-0.8.0/src/riskvalidation/harness/performance.py +74 -0
  50. riskvalidation-0.8.0/src/riskvalidation/harness/rates.py +103 -0
  51. riskvalidation-0.8.0/src/riskvalidation/harness/run.py +197 -0
  52. riskvalidation-0.8.0/src/riskvalidation/irrbb/__init__.py +9 -0
  53. riskvalidation-0.8.0/src/riskvalidation/irrbb/behavioural.py +206 -0
  54. riskvalidation-0.8.0/src/riskvalidation/irrbb/curves.py +286 -0
  55. riskvalidation-0.8.0/src/riskvalidation/irrbb/eve_nii.py +245 -0
  56. riskvalidation-0.8.0/src/riskvalidation/irrbb/shocks.py +171 -0
  57. riskvalidation-0.8.0/src/riskvalidation/irrbb/simulation.py +203 -0
  58. riskvalidation-0.8.0/src/riskvalidation/irrbb/slotting.py +184 -0
  59. riskvalidation-0.8.0/src/riskvalidation/lgd_ead/__init__.py +8 -0
  60. riskvalidation-0.8.0/src/riskvalidation/lgd_ead/_checks.py +50 -0
  61. riskvalidation-0.8.0/src/riskvalidation/lgd_ead/ccf.py +228 -0
  62. riskvalidation-0.8.0/src/riskvalidation/lgd_ead/downturn.py +64 -0
  63. riskvalidation-0.8.0/src/riskvalidation/lgd_ead/floors.py +114 -0
  64. riskvalidation-0.8.0/src/riskvalidation/lgd_ead/lgd_models.py +297 -0
  65. riskvalidation-0.8.0/src/riskvalidation/lgd_ead/workout.py +162 -0
  66. riskvalidation-0.8.0/src/riskvalidation/liquidity/__init__.py +9 -0
  67. riskvalidation-0.8.0/src/riskvalidation/liquidity/_checks.py +78 -0
  68. riskvalidation-0.8.0/src/riskvalidation/liquidity/cbc.py +158 -0
  69. riskvalidation-0.8.0/src/riskvalidation/liquidity/deposits.py +151 -0
  70. riskvalidation-0.8.0/src/riskvalidation/liquidity/ladder.py +119 -0
  71. riskvalidation-0.8.0/src/riskvalidation/liquidity/reverse.py +141 -0
  72. riskvalidation-0.8.0/src/riskvalidation/liquidity/runoff.py +220 -0
  73. riskvalidation-0.8.0/src/riskvalidation/liquidity/scenarios.py +272 -0
  74. riskvalidation-0.8.0/src/riskvalidation/market/__init__.py +8 -0
  75. riskvalidation-0.8.0/src/riskvalidation/market/caviar.py +239 -0
  76. riskvalidation-0.8.0/src/riskvalidation/market/conventions.py +83 -0
  77. riskvalidation-0.8.0/src/riskvalidation/market/evt.py +111 -0
  78. riskvalidation-0.8.0/src/riskvalidation/market/frtb.py +175 -0
  79. riskvalidation-0.8.0/src/riskvalidation/market/garch.py +204 -0
  80. riskvalidation-0.8.0/src/riskvalidation/market/gas_fz.py +219 -0
  81. riskvalidation-0.8.0/src/riskvalidation/market/historical.py +96 -0
  82. riskvalidation-0.8.0/src/riskvalidation/market/parametric.py +78 -0
  83. riskvalidation-0.8.0/src/riskvalidation/market/scoring.py +145 -0
  84. riskvalidation-0.8.0/src/riskvalidation/ml/__init__.py +11 -0
  85. riskvalidation-0.8.0/src/riskvalidation/ml/_checks.py +67 -0
  86. riskvalidation-0.8.0/src/riskvalidation/ml/_logistic.py +82 -0
  87. riskvalidation-0.8.0/src/riskvalidation/ml/cbpe.py +91 -0
  88. riskvalidation-0.8.0/src/riskvalidation/ml/challenger.py +73 -0
  89. riskvalidation-0.8.0/src/riskvalidation/ml/conformal.py +116 -0
  90. riskvalidation-0.8.0/src/riskvalidation/ml/dataquality.py +130 -0
  91. riskvalidation-0.8.0/src/riskvalidation/ml/effects.py +67 -0
  92. riskvalidation-0.8.0/src/riskvalidation/ml/explanations.py +125 -0
  93. riskvalidation-0.8.0/src/riskvalidation/ml/generalisation.py +79 -0
  94. riskvalidation-0.8.0/src/riskvalidation/ml/leakage.py +99 -0
  95. riskvalidation-0.8.0/src/riskvalidation/ml/plants.py +425 -0
  96. riskvalidation-0.8.0/src/riskvalidation/ml/policy.py +182 -0
  97. riskvalidation-0.8.0/src/riskvalidation/ml/robustness.py +286 -0
  98. riskvalidation-0.8.0/src/riskvalidation/ml/seeds.py +106 -0
  99. riskvalidation-0.8.0/src/riskvalidation/oprisk/__init__.py +18 -0
  100. riskvalidation-0.8.0/src/riskvalidation/oprisk/_checks.py +60 -0
  101. riskvalidation-0.8.0/src/riskvalidation/oprisk/aggregate.py +375 -0
  102. riskvalidation-0.8.0/src/riskvalidation/oprisk/distributions.py +758 -0
  103. riskvalidation-0.8.0/src/riskvalidation/oprisk/scenarios.py +342 -0
  104. riskvalidation-0.8.0/src/riskvalidation/oprisk/sla.py +80 -0
  105. riskvalidation-0.8.0/src/riskvalidation/oprisk/sma.py +169 -0
  106. riskvalidation-0.8.0/src/riskvalidation/policies/__init__.py +4 -0
  107. riskvalidation-0.8.0/src/riskvalidation/policies/default.json +273 -0
  108. riskvalidation-0.8.0/src/riskvalidation/portfolio/__init__.py +16 -0
  109. riskvalidation-0.8.0/src/riskvalidation/portfolio/asrf_fit.py +283 -0
  110. riskvalidation-0.8.0/src/riskvalidation/portfolio/copula.py +129 -0
  111. riskvalidation-0.8.0/src/riskvalidation/portfolio/creditrisk_plus.py +232 -0
  112. riskvalidation-0.8.0/src/riskvalidation/portfolio/euler.py +126 -0
  113. riskvalidation-0.8.0/src/riskvalidation/portfolio/granularity.py +135 -0
  114. riskvalidation-0.8.0/src/riskvalidation/portfolio/importance.py +277 -0
  115. riskvalidation-0.8.0/src/riskvalidation/portfolio/portfolio.py +309 -0
  116. riskvalidation-0.8.0/src/riskvalidation/provisions/__init__.py +8 -0
  117. riskvalidation-0.8.0/src/riskvalidation/provisions/_checks.py +100 -0
  118. riskvalidation-0.8.0/src/riskvalidation/provisions/ecl.py +233 -0
  119. riskvalidation-0.8.0/src/riskvalidation/provisions/local_cl.py +360 -0
  120. riskvalidation-0.8.0/src/riskvalidation/provisions/local_es.py +157 -0
  121. riskvalidation-0.8.0/src/riskvalidation/provisions/overlays.py +102 -0
  122. riskvalidation-0.8.0/src/riskvalidation/provisions/reconciliation.py +157 -0
  123. riskvalidation-0.8.0/src/riskvalidation/provisions/staging.py +211 -0
  124. riskvalidation-0.8.0/src/riskvalidation/provisions/term_structure.py +199 -0
  125. riskvalidation-0.8.0/src/riskvalidation/regulatory/__init__.py +14 -0
  126. riskvalidation-0.8.0/src/riskvalidation/regulatory/ba_cva.py +138 -0
  127. riskvalidation-0.8.0/src/riskvalidation/regulatory/frtb.py +345 -0
  128. riskvalidation-0.8.0/src/riskvalidation/regulatory/irb.py +314 -0
  129. riskvalidation-0.8.0/src/riskvalidation/regulatory/lcr_nsfr.py +369 -0
  130. riskvalidation-0.8.0/src/riskvalidation/regulatory/output_floor.py +45 -0
  131. riskvalidation-0.8.0/src/riskvalidation/regulatory/sa_ccr.py +486 -0
  132. riskvalidation-0.8.0/src/riskvalidation/regulatory/standardised.py +348 -0
  133. riskvalidation-0.8.0/src/riskvalidation/stress/__init__.py +9 -0
  134. riskvalidation-0.8.0/src/riskvalidation/stress/capital.py +476 -0
  135. riskvalidation-0.8.0/src/riskvalidation/stress/paths.py +108 -0
  136. riskvalidation-0.8.0/src/riskvalidation/stress/reverse.py +179 -0
  137. riskvalidation-0.8.0/src/riskvalidation/stress/satellites.py +268 -0
  138. riskvalidation-0.8.0/src/riskvalidation/stress/scenario_models.py +274 -0
  139. riskvalidation-0.8.0/src/riskvalidation/transitions/__init__.py +0 -0
  140. riskvalidation-0.8.0/src/riskvalidation/transitions/em.py +120 -0
  141. riskvalidation-0.8.0/src/riskvalidation/transitions/embedding.py +221 -0
  142. riskvalidation-0.8.0/src/riskvalidation/transitions/estimators.py +213 -0
  143. riskvalidation-0.8.0/src/riskvalidation/transitions/intervals.py +306 -0
  144. riskvalidation-0.8.0/src/riskvalidation/transitions/mobility.py +57 -0
  145. riskvalidation-0.8.0/src/riskvalidation/transitions/ttc.py +171 -0
  146. riskvalidation-0.8.0/src/riskvalidation/validation/__init__.py +103 -0
  147. riskvalidation-0.8.0/src/riskvalidation/validation/_common.py +57 -0
  148. riskvalidation-0.8.0/src/riskvalidation/validation/aggregation.py +425 -0
  149. riskvalidation-0.8.0/src/riskvalidation/validation/calibration.py +757 -0
  150. riskvalidation-0.8.0/src/riskvalidation/validation/ccr.py +530 -0
  151. riskvalidation-0.8.0/src/riskvalidation/validation/discrimination.py +314 -0
  152. riskvalidation-0.8.0/src/riskvalidation/validation/fairness.py +632 -0
  153. riskvalidation-0.8.0/src/riskvalidation/validation/ifrs9.py +693 -0
  154. riskvalidation-0.8.0/src/riskvalidation/validation/irrbb.py +389 -0
  155. riskvalidation-0.8.0/src/riskvalidation/validation/lgd_ead.py +469 -0
  156. riskvalidation-0.8.0/src/riskvalidation/validation/liquidity.py +647 -0
  157. riskvalidation-0.8.0/src/riskvalidation/validation/market.py +807 -0
  158. riskvalidation-0.8.0/src/riskvalidation/validation/ml.py +958 -0
  159. riskvalidation-0.8.0/src/riskvalidation/validation/oprisk.py +357 -0
  160. riskvalidation-0.8.0/src/riskvalidation/validation/portfolio.py +353 -0
  161. riskvalidation-0.8.0/src/riskvalidation/validation/rating_system.py +245 -0
  162. riskvalidation-0.8.0/src/riskvalidation/validation/stability.py +256 -0
  163. riskvalidation-0.8.0/src/riskvalidation/validation/stress.py +552 -0
  164. riskvalidation-0.8.0/src/riskvalidation/validation/transitions.py +386 -0
  165. riskvalidation-0.8.0/src/riskvalidation.egg-info/PKG-INFO +136 -0
  166. riskvalidation-0.8.0/src/riskvalidation.egg-info/SOURCES.txt +191 -0
  167. riskvalidation-0.8.0/src/riskvalidation.egg-info/dependency_links.txt +1 -0
  168. riskvalidation-0.8.0/src/riskvalidation.egg-info/requires.txt +21 -0
  169. riskvalidation-0.8.0/src/riskvalidation.egg-info/top_level.txt +1 -0
  170. riskvalidation-0.8.0/tests/test_catalogue.py +36 -0
  171. riskvalidation-0.8.0/tests/test_default_policy_batch3.py +20 -0
  172. riskvalidation-0.8.0/tests/test_discrimination.py +106 -0
  173. riskvalidation-0.8.0/tests/test_docs.py +65 -0
  174. riskvalidation-0.8.0/tests/test_examples.py +39 -0
  175. riskvalidation-0.8.0/tests/test_generators.py +276 -0
  176. riskvalidation-0.8.0/tests/test_harness.py +180 -0
  177. riskvalidation-0.8.0/tests/test_hashing.py +20 -0
  178. riskvalidation-0.8.0/tests/test_imports.py +44 -0
  179. riskvalidation-0.8.0/tests/test_irb.py +116 -0
  180. riskvalidation-0.8.0/tests/test_low_default.py +188 -0
  181. riskvalidation-0.8.0/tests/test_pd_calibration.py +174 -0
  182. riskvalidation-0.8.0/tests/test_pd_curve.py +293 -0
  183. riskvalidation-0.8.0/tests/test_policy.py +66 -0
  184. riskvalidation-0.8.0/tests/test_rating_system.py +60 -0
  185. riskvalidation-0.8.0/tests/test_registry_complete.py +314 -0
  186. riskvalidation-0.8.0/tests/test_reproductions.py +240 -0
  187. riskvalidation-0.8.0/tests/test_result_schema.py +42 -0
  188. riskvalidation-0.8.0/tests/test_size.py +234 -0
  189. riskvalidation-0.8.0/tests/test_stability.py +52 -0
  190. riskvalidation-0.8.0/tests/test_suite.py +29 -0
  191. riskvalidation-0.8.0/tests/test_transitions.py +366 -0
  192. riskvalidation-0.8.0/tests/test_transitions_reconciliation.py +263 -0
  193. riskvalidation-0.8.0/tests/test_vasicek.py +31 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Felipe Santibáñez-Leal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: riskvalidation
3
+ Version: 0.8.0
4
+ Summary: Validation tests, regulatory calculators and reference engines for financial risk models: the toolkit of an independent model validator.
5
+ Author: Felipe Santibáñez-Leal
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/fsantibanezleal/CAOS_RiskValidation
8
+ Project-URL: Repository, https://github.com/fsantibanezleal/CAOS_RiskValidation
9
+ Project-URL: Changelog, https://github.com/fsantibanezleal/CAOS_RiskValidation/blob/main/CHANGELOG.md
10
+ Keywords: model-validation,model-risk-management,credit-risk,market-risk,basel,ifrs9,probability-of-default,backtesting,irrbb,liquidity-risk,operational-risk
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Financial and Insurance Industry
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Office/Business :: Financial
16
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: numpy>=1.24
21
+ Requires-Dist: scipy>=1.10
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=8; extra == "dev"
24
+ Requires-Dist: ruff<0.17,>=0.6; extra == "dev"
25
+ Requires-Dist: build>=1.2; extra == "dev"
26
+ Requires-Dist: pypdf>=4; extra == "dev"
27
+ Provides-Extra: market
28
+ Requires-Dist: arch<9,>=8.0; extra == "market"
29
+ Provides-Extra: ml
30
+ Requires-Dist: fairlearn<0.16,>=0.15; extra == "ml"
31
+ Requires-Dist: mapie<2,>=1.5; extra == "ml"
32
+ Provides-Extra: stress
33
+ Requires-Dist: statsmodels<0.16,>=0.15; extra == "stress"
34
+ Provides-Extra: transitions
35
+ Requires-Dist: transitionMatrix==0.5.1; extra == "transitions"
36
+ Dynamic: license-file
37
+
38
+ # riskvalidation
39
+
40
+ [![CI](https://github.com/fsantibanezleal/CAOS_RiskValidation/actions/workflows/ci.yml/badge.svg)](https://github.com/fsantibanezleal/CAOS_RiskValidation/actions/workflows/ci.yml)
41
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
42
+
43
+ Validation tests, regulatory calculators and reference engines for financial risk models: the toolkit of an
44
+ independent model validator.
45
+
46
+ Every test returns one `TestResult` that carries the statistic, the null hypothesis, the primary source that
47
+ defines the test, the policy that classified it and a fingerprint of the inputs. Thresholds live in versioned
48
+ policy files and are presented as policy, never as regulation. The core depends only on NumPy and SciPy, so the
49
+ same wheel runs in a Python pipeline and in the browser under Pyodide.
50
+
51
+ ## Status
52
+
53
+ Version 0.08.000: liquidity (run-off, deposits, the counterbalancing capacity, the maturity ladder and reverse liquidity stress), aggregation (simple sum and variance-covariance, copulas, bounds and the dependence band, aggregation model risk), stress testing (satellites, scenario models, path transposition, the capital path, reverse stress), the regulatory calculators (the standardised approach, IRB, the output floor, SA-CCR, BA-CVA, the FRTB sensitivities-based method and liquidity-horizon cascade, LCR and NSFR), counterparty credit risk (Hull-White one-factor exposure, swaps, collateral, CVA), machine-learning model validation and fair lending, each with its validation tests; 0.07.000: portfolio credit capital (copula Monte Carlo, CreditRisk+, the granularity adjustment, importance sampling, Euler contributions, the Vasicek fit), market risk (VaR and ES estimators, scoring, the model confidence set, the FRTB back-tests and PLA), interest rate risk in the banking book (SRP31 and RAN 21-13 Annex 1 EVE and NII, behavioural models, EaR and EVaR) and operational risk (LDA by Monte Carlo, Panjer and FFT, the SMA), each with its validation tests; 0.06.000: loss given default and exposure at default (workout LGD, the LGD rungs, downturn LGD, CCF and EAD, the IRB floors, and their validation tests); 0.05.000: provisions (the IFRS 9 expected credit loss engine with its validation battery, and the CMF B-1 and BdE Annex 9 statutory provisions); before it, the core contracts (result record, policy, registry, suite runner); 27 validation tests for
54
+ PD calibration, discrimination, rating-system stability, population stability and rating transitions; the IRB
55
+ risk-weight functions under four regimes; three reference engines (the one-factor model with its large homogeneous
56
+ portfolio, most prudent estimation for low-default portfolios, PD curve calibration after Tasche 2013); rating
57
+ transitions (cohort, duration, Aalen-Johansen and EM estimators, the embedding problem, intervals for PDs by grade,
58
+ mobility, the through-the-cycle portfolio a migration matrix implies); and known-truth generators, among them rating
59
+ paths with planted momentum, regimes and withdrawals, with a size and power harness that measures how often each test
60
+ rejects a right model and catches a wrong one, with the Monte Carlo error of every rate. Each reproduces its primary
61
+ source's own tables, worked examples or published simulations. Further calculators and engines arrive unit by unit; the
62
+ [CHANGELOG](CHANGELOG.md) lists exactly what each release contains. Not yet published on PyPI.
63
+
64
+ ## Install (from source, until the first PyPI release)
65
+
66
+ ```bash
67
+ git clone https://github.com/fsantibanezleal/CAOS_RiskValidation.git
68
+ cd CAOS_RiskValidation
69
+ python -m venv .venv
70
+ .venv/bin/pip install -e ".[dev]" # Windows: .venv\Scripts\pip install -e ".[dev]"
71
+ .venv/bin/pytest -q
72
+ ```
73
+
74
+ ## Use
75
+
76
+ [`examples/quickstart.py`](examples/quickstart.py), run by the test suite:
77
+
78
+ ```python
79
+ import numpy as np
80
+
81
+ from riskvalidation import default_policy, run_suite
82
+ from riskvalidation.validation import (
83
+ bin_counts,
84
+ disc_auc_vs_initial,
85
+ pd_jeffreys_grades,
86
+ quantile_edges,
87
+ stability_psi,
88
+ )
89
+
90
+ rng = np.random.default_rng(2026)
91
+
92
+ # Jeffreys test per grade and for the portfolio (ECB 2019, section 2.5.3.1)
93
+ for r in pd_jeffreys_grades(n=[400, 900, 300], d=[2, 14, 19], pd=[0.004, 0.012, 0.05], grades=["A", "B", "C"]):
94
+ print(f"{r.segment:>9} p = {r.p_value:.4f} {r.light.value}")
95
+
96
+ # a scored sample: PDs and observed defaults, plus a development-period score sample
97
+ pd_scores = rng.beta(1.2, 40.0, 5000)
98
+ defaults = (rng.uniform(size=5000) < pd_scores).astype(int)
99
+ development = rng.beta(1.2, 45.0, 8000)
100
+ edges = quantile_edges(development, 10)
101
+
102
+ # a battery under one policy; a failing test is recorded and the rest still run
103
+ run = run_suite(
104
+ [
105
+ (disc_auc_vs_initial, {"auc_initial": 0.78, "risk": pd_scores, "defaults": defaults}),
106
+ (stability_psi, {"expected_counts": bin_counts(development, edges),
107
+ "actual_counts": bin_counts(pd_scores, edges)}),
108
+ ],
109
+ policy=default_policy(),
110
+ model_id="retail-pd-v3",
111
+ )
112
+ for r in run.results:
113
+ print(f"{r.test_id:>22} statistic = {r.statistic:.4f} p = {r.p_value:.4f} {r.light.value}")
114
+ print("lights:", run.counts(), "worst:", run.worst().value)
115
+ ```
116
+
117
+ ## Documentation
118
+
119
+ The [`docs/`](docs/README.md) wiki: the software design document, the architecture (result contract, policies
120
+ and lights, suites and reproducibility), one page per test family with its formula, null hypothesis, decision rule
121
+ and primary source, the [regulatory calculators](docs/regulatory.md), the [reference engines](docs/engines.md),
122
+ [rating transitions](docs/transitions.md) and the [generators and the size and power harness](docs/generators.md). [`examples/size_power.py`](examples/size_power.py)
123
+ measures the size and power of a few tests in seconds.
124
+ [`examples/credit_math.py`](examples/credit_math.py) runs the credit mathematics end to end: IRB capital under two
125
+ regimes, the large homogeneous portfolio behind it, most prudent PDs, and a PD curve calibrated to a new year and
126
+ tested for fit. [`examples/rating_transitions.py`](examples/rating_transitions.py) estimates, embeds, tests, bounds
127
+ and projects a migration matrix on a known generator, then plants rating momentum and shows which tests see it.
128
+
129
+ ## What this is not
130
+
131
+ A compliance verdict on any model, a training framework for heavy learners, or a data service. A green light
132
+ means a statistic fell inside a policy band.
133
+
134
+ ## License
135
+
136
+ MIT, see [LICENSE](LICENSE). Developed by Felipe Santibáñez-Leal.
@@ -0,0 +1,99 @@
1
+ # riskvalidation
2
+
3
+ [![CI](https://github.com/fsantibanezleal/CAOS_RiskValidation/actions/workflows/ci.yml/badge.svg)](https://github.com/fsantibanezleal/CAOS_RiskValidation/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
+
6
+ Validation tests, regulatory calculators and reference engines for financial risk models: the toolkit of an
7
+ independent model validator.
8
+
9
+ Every test returns one `TestResult` that carries the statistic, the null hypothesis, the primary source that
10
+ defines the test, the policy that classified it and a fingerprint of the inputs. Thresholds live in versioned
11
+ policy files and are presented as policy, never as regulation. The core depends only on NumPy and SciPy, so the
12
+ same wheel runs in a Python pipeline and in the browser under Pyodide.
13
+
14
+ ## Status
15
+
16
+ Version 0.08.000: liquidity (run-off, deposits, the counterbalancing capacity, the maturity ladder and reverse liquidity stress), aggregation (simple sum and variance-covariance, copulas, bounds and the dependence band, aggregation model risk), stress testing (satellites, scenario models, path transposition, the capital path, reverse stress), the regulatory calculators (the standardised approach, IRB, the output floor, SA-CCR, BA-CVA, the FRTB sensitivities-based method and liquidity-horizon cascade, LCR and NSFR), counterparty credit risk (Hull-White one-factor exposure, swaps, collateral, CVA), machine-learning model validation and fair lending, each with its validation tests; 0.07.000: portfolio credit capital (copula Monte Carlo, CreditRisk+, the granularity adjustment, importance sampling, Euler contributions, the Vasicek fit), market risk (VaR and ES estimators, scoring, the model confidence set, the FRTB back-tests and PLA), interest rate risk in the banking book (SRP31 and RAN 21-13 Annex 1 EVE and NII, behavioural models, EaR and EVaR) and operational risk (LDA by Monte Carlo, Panjer and FFT, the SMA), each with its validation tests; 0.06.000: loss given default and exposure at default (workout LGD, the LGD rungs, downturn LGD, CCF and EAD, the IRB floors, and their validation tests); 0.05.000: provisions (the IFRS 9 expected credit loss engine with its validation battery, and the CMF B-1 and BdE Annex 9 statutory provisions); before it, the core contracts (result record, policy, registry, suite runner); 27 validation tests for
17
+ PD calibration, discrimination, rating-system stability, population stability and rating transitions; the IRB
18
+ risk-weight functions under four regimes; three reference engines (the one-factor model with its large homogeneous
19
+ portfolio, most prudent estimation for low-default portfolios, PD curve calibration after Tasche 2013); rating
20
+ transitions (cohort, duration, Aalen-Johansen and EM estimators, the embedding problem, intervals for PDs by grade,
21
+ mobility, the through-the-cycle portfolio a migration matrix implies); and known-truth generators, among them rating
22
+ paths with planted momentum, regimes and withdrawals, with a size and power harness that measures how often each test
23
+ rejects a right model and catches a wrong one, with the Monte Carlo error of every rate. Each reproduces its primary
24
+ source's own tables, worked examples or published simulations. Further calculators and engines arrive unit by unit; the
25
+ [CHANGELOG](CHANGELOG.md) lists exactly what each release contains. Not yet published on PyPI.
26
+
27
+ ## Install (from source, until the first PyPI release)
28
+
29
+ ```bash
30
+ git clone https://github.com/fsantibanezleal/CAOS_RiskValidation.git
31
+ cd CAOS_RiskValidation
32
+ python -m venv .venv
33
+ .venv/bin/pip install -e ".[dev]" # Windows: .venv\Scripts\pip install -e ".[dev]"
34
+ .venv/bin/pytest -q
35
+ ```
36
+
37
+ ## Use
38
+
39
+ [`examples/quickstart.py`](examples/quickstart.py), run by the test suite:
40
+
41
+ ```python
42
+ import numpy as np
43
+
44
+ from riskvalidation import default_policy, run_suite
45
+ from riskvalidation.validation import (
46
+ bin_counts,
47
+ disc_auc_vs_initial,
48
+ pd_jeffreys_grades,
49
+ quantile_edges,
50
+ stability_psi,
51
+ )
52
+
53
+ rng = np.random.default_rng(2026)
54
+
55
+ # Jeffreys test per grade and for the portfolio (ECB 2019, section 2.5.3.1)
56
+ for r in pd_jeffreys_grades(n=[400, 900, 300], d=[2, 14, 19], pd=[0.004, 0.012, 0.05], grades=["A", "B", "C"]):
57
+ print(f"{r.segment:>9} p = {r.p_value:.4f} {r.light.value}")
58
+
59
+ # a scored sample: PDs and observed defaults, plus a development-period score sample
60
+ pd_scores = rng.beta(1.2, 40.0, 5000)
61
+ defaults = (rng.uniform(size=5000) < pd_scores).astype(int)
62
+ development = rng.beta(1.2, 45.0, 8000)
63
+ edges = quantile_edges(development, 10)
64
+
65
+ # a battery under one policy; a failing test is recorded and the rest still run
66
+ run = run_suite(
67
+ [
68
+ (disc_auc_vs_initial, {"auc_initial": 0.78, "risk": pd_scores, "defaults": defaults}),
69
+ (stability_psi, {"expected_counts": bin_counts(development, edges),
70
+ "actual_counts": bin_counts(pd_scores, edges)}),
71
+ ],
72
+ policy=default_policy(),
73
+ model_id="retail-pd-v3",
74
+ )
75
+ for r in run.results:
76
+ print(f"{r.test_id:>22} statistic = {r.statistic:.4f} p = {r.p_value:.4f} {r.light.value}")
77
+ print("lights:", run.counts(), "worst:", run.worst().value)
78
+ ```
79
+
80
+ ## Documentation
81
+
82
+ The [`docs/`](docs/README.md) wiki: the software design document, the architecture (result contract, policies
83
+ and lights, suites and reproducibility), one page per test family with its formula, null hypothesis, decision rule
84
+ and primary source, the [regulatory calculators](docs/regulatory.md), the [reference engines](docs/engines.md),
85
+ [rating transitions](docs/transitions.md) and the [generators and the size and power harness](docs/generators.md). [`examples/size_power.py`](examples/size_power.py)
86
+ measures the size and power of a few tests in seconds.
87
+ [`examples/credit_math.py`](examples/credit_math.py) runs the credit mathematics end to end: IRB capital under two
88
+ regimes, the large homogeneous portfolio behind it, most prudent PDs, and a PD curve calibrated to a new year and
89
+ tested for fit. [`examples/rating_transitions.py`](examples/rating_transitions.py) estimates, embeds, tests, bounds
90
+ and projects a migration matrix on a known generator, then plants rating momentum and shows which tests see it.
91
+
92
+ ## What this is not
93
+
94
+ A compliance verdict on any model, a training framework for heavy learners, or a data service. A green light
95
+ means a statistic fell inside a policy band.
96
+
97
+ ## License
98
+
99
+ MIT, see [LICENSE](LICENSE). Developed by Felipe Santibáñez-Leal.
@@ -0,0 +1,74 @@
1
+ # riskvalidation: validation tests, regulatory calculators and reference engines for financial risk models.
2
+ # Distribution name == import name (`riskvalidation`), verified free on PyPI 2026-10-04 (ADR-0061).
3
+ # The core depends on NumPy and SciPy only, so it runs in the browser under Pyodide.
4
+ [build-system]
5
+ requires = ["setuptools>=77"]
6
+ build-backend = "setuptools.build_meta"
7
+
8
+ [project]
9
+ name = "riskvalidation"
10
+ # PEP 440 form of the display version X.XX.XXX in VERSION (see CHANGELOG.md and riskvalidation.__version__).
11
+ version = "0.8.0"
12
+ description = "Validation tests, regulatory calculators and reference engines for financial risk models: the toolkit of an independent model validator."
13
+ readme = "README.md"
14
+ requires-python = ">=3.10"
15
+ license = "MIT"
16
+ license-files = ["LICENSE"]
17
+ authors = [{ name = "Felipe Santibáñez-Leal" }]
18
+ keywords = [
19
+ "model-validation", "model-risk-management", "credit-risk", "market-risk", "basel", "ifrs9",
20
+ "probability-of-default", "backtesting", "irrbb", "liquidity-risk", "operational-risk",
21
+ ]
22
+ classifiers = [
23
+ "Development Status :: 3 - Alpha",
24
+ "Intended Audience :: Financial and Insurance Industry",
25
+ "Intended Audience :: Science/Research",
26
+ "Programming Language :: Python :: 3",
27
+ "Topic :: Office/Business :: Financial",
28
+ "Topic :: Scientific/Engineering :: Mathematics",
29
+ ]
30
+ dependencies = ["numpy>=1.24", "scipy>=1.10"]
31
+
32
+ [project.optional-dependencies]
33
+ dev = ["pytest>=8", "ruff>=0.6,<0.17", "build>=1.2", "pypdf>=4"]
34
+ # U8 market: arch (GARCH family, the Model Confidence Set) is optional; its own bounds (numpy<3,>=1.22.3, scipy>=1.8, Python >=3.10) sit
35
+ # inside the engine pins above, and it brings pandas and statsmodels, which the engine core never imports.
36
+ market = ["arch>=8.0,<9"]
37
+ # U14 ml: fairlearn and MAPIE reconcile the fairness metrics and the split-conformal quantile, in the tests only (U14 sizing Q11);
38
+ # the engine core never imports them.
39
+ ml = ["fairlearn>=0.15,<0.16", "mapie>=1.5,<2"]
40
+ # U13 stress: statsmodels is the independent reference of the VAR and the growth-at-risk regressions, in the tests only (U13 sizing R2).
41
+ stress = ["statsmodels>=0.15,<0.16"]
42
+ # BL-083 transitions: Open Risk's transitionMatrix (Apache-2.0) is the independent reference of the cohort estimator, in the tests only;
43
+ # the engine core never imports it. Pinned to the version the reconciliation was measured against.
44
+ transitions = ["transitionMatrix==0.5.1"]
45
+
46
+ [project.urls]
47
+ Homepage = "https://github.com/fsantibanezleal/CAOS_RiskValidation"
48
+ Repository = "https://github.com/fsantibanezleal/CAOS_RiskValidation"
49
+ Changelog = "https://github.com/fsantibanezleal/CAOS_RiskValidation/blob/main/CHANGELOG.md"
50
+
51
+ [tool.setuptools.packages.find]
52
+ where = ["src"]
53
+
54
+ [tool.setuptools.package-data]
55
+ riskvalidation = ["policies/*.json"]
56
+
57
+ [tool.pytest.ini_options]
58
+ testpaths = ["tests"]
59
+ addopts = "-q"
60
+ markers = [
61
+ "sizepower: a size and power study at 4,000 repetitions or more; deselected in CI, run locally as the release gate (ADR-0074, U14 decision G7)",
62
+ ]
63
+
64
+ [tool.ruff]
65
+ line-length = 120
66
+ target-version = "py310"
67
+ src = ["src", "tests"]
68
+
69
+ [tool.ruff.lint]
70
+ select = ["E", "F", "W", "I", "B", "UP"]
71
+
72
+ [tool.ruff.lint.per-file-ignores]
73
+ # Shared guard copied verbatim from the product line (OreFlow's check_sdd.py); kept identical across repos.
74
+ "scripts/check_sdd.py" = ["E501"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,30 @@
1
+ """riskvalidation: validation tests, regulatory calculators and reference engines for financial risk models.
2
+
3
+ Every validation test returns one :class:`TestResult`; a versioned :class:`Policy` turns its statistic into a
4
+ traffic light; :func:`run_suite` runs a battery without stopping at the first failure. The core depends
5
+ only on NumPy and SciPy, so it also runs in the browser under Pyodide.
6
+ """
7
+
8
+ from riskvalidation import validation # noqa: E402,F401 (registers the test catalogue)
9
+ from riskvalidation.core.policy import Policy, Threshold, default_policy, load_policy
10
+ from riskvalidation.core.registry import TestSpec, catalogue
11
+ from riskvalidation.core.result import Light, TestResult
12
+ from riskvalidation.core.suite import SuiteRun, run_suite
13
+
14
+ __version__ = "0.8.0"
15
+ """PEP 440 form of the display version in ``VERSION``."""
16
+
17
+ __all__ = [
18
+ "Light",
19
+ "Policy",
20
+ "SuiteRun",
21
+ "TestResult",
22
+ "TestSpec",
23
+ "Threshold",
24
+ "__version__",
25
+ "catalogue",
26
+ "default_policy",
27
+ "load_policy",
28
+ "run_suite",
29
+ "validation",
30
+ ]
@@ -0,0 +1,11 @@
1
+ """Risk aggregation: the ladder from the simple sum to the worst-case bounds, the dependence band, model risk and the
2
+ validation tests.
3
+
4
+ Modules are imported by path (for example ``from riskvalidation.aggregation import simple``); nothing is re-exported
5
+ here.
6
+ Capital is economic capital on the unexpected-loss basis, ``EC = VaR - EL``. The simple sum is the headline capital of
7
+ the
8
+ case; every other figure of the band is information, not capital. The engine computes and states no compliance claim:
9
+ thresholds and light parameters are supplied by the caller or are Contraste internal gates, not regulatory requirements.
10
+ The validation tests are in ``riskvalidation.validation.aggregation``. Contract: ``engine-aggregation-api`` 1.0.0.
11
+ """
@@ -0,0 +1,151 @@
1
+ """The dependence-uncertainty band every aggregate is shown with (dossier 05 G.3, l.366; the SDD): the lower bound,
2
+ the simple
3
+ sum, the variance-covariance, the Gaussian copula, one Student t copula per degrees-of-freedom value and the worst
4
+ case, on
5
+ the same marginals. The band is returned whole, never one diversified number.
6
+
7
+ Every row is economic capital on the unexpected-loss basis, `EC = VaR - EL` (dossier 04 l.652-653); the expected loss is
8
+ additive, so the simple sum of the marginal EC equals the comonotonic EC of the total. The simple sum is the headline
9
+ capital
10
+ (`status = "headline-capital"`); every other row is information, not capital (`"information-not-capital"`, dossier 05
11
+ l.519). A row above the headline is a true result (VaR is not subadditive, dossier 05 l.366): it is reported by
12
+ `validation.aggregation.diversification_sign`, never repaired and never refused here. The lower-bound row is signed:
13
+ the best
14
+ VaR less the sum of the expected losses may be negative and is reported as computed.
15
+
16
+ A marginal with an infinite-mean severity has no expected loss: the caller passes it as `ec = VaR` and `el = 0.0`, so
17
+ that
18
+ every row is built on the EC the document carries. The caller converts a marginal read at another level or horizon,
19
+ never the
20
+ engine. Contract: `engine-aggregation-api` 1.0.0, module aggregation.band.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import math
26
+ from collections.abc import Callable, Sequence
27
+ from dataclasses import dataclass
28
+
29
+ import numpy as np
30
+
31
+ from riskvalidation.aggregation.bounds import worst_var_bounds
32
+ from riskvalidation.aggregation.copulas import DEFAULT_CHUNK, copula_aggregate
33
+ from riskvalidation.aggregation.simple import _matrix, check_correlation, simple_sum, variance_covariance
34
+ from riskvalidation.portfolio.portfolio import check_level, float_vector
35
+
36
+ Ppf = Callable[[np.ndarray], np.ndarray]
37
+ METHODS = ("lower-bound", "simple-sum", "variance-covariance", "gaussian-copula", "t-copula", "worst-case")
38
+ HEADLINE = "headline-capital"
39
+ INFORMATION = "information-not-capital"
40
+ CAPITAL_BASIS = "economic-capital-var-less-el"
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class BandRow:
45
+ """One row of the band; maps onto the document row `outputs.aggregation.band[*]` (`method`, `nu`, `capital_clp_m`,
46
+ `diversification_factor`, `status`, `mc_se_clp_m`). `capital` is money (EC), `diversification_factor` is
47
+ capital / simple sum, `mc_se` the Monte Carlo standard error where the row is simulated."""
48
+
49
+ method: str
50
+ nu: float | None
51
+ capital: float
52
+ diversification_factor: float
53
+ status: str
54
+ mc_se: float | None
55
+
56
+ def __post_init__(self) -> None:
57
+ if self.method not in METHODS:
58
+ raise ValueError(f"method must be one of {METHODS}, got {self.method!r}")
59
+ if self.status != (HEADLINE if self.method == "simple-sum" else INFORMATION):
60
+ raise ValueError(f"status {self.status!r} does not follow method {self.method!r}")
61
+ if (self.nu is not None) != (self.method == "t-copula"):
62
+ raise ValueError("nu must be set exactly for the t-copula row")
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Band:
67
+ """The rows (lower bound, simple sum, variance-covariance, Gaussian, one t row per nu, worst case), the `headline`
68
+ (the
69
+ capital of the single simple-sum row), the horizon in years, the confidence level and the capital basis."""
70
+
71
+ rows: tuple[BandRow, ...]
72
+ headline: float
73
+ horizon_years: int
74
+ confidence_level: float
75
+ capital_basis: str
76
+
77
+
78
+ def _check_nu_set(nu_set: Sequence[float]) -> tuple[float, ...]:
79
+ nus = tuple(float(v) for v in nu_set)
80
+ if not nus:
81
+ raise ValueError("nu_set is empty")
82
+ if not all(math.isfinite(v) and v > 2.0 for v in nus):
83
+ raise ValueError(f"nu_set values must be finite and above 2, got {list(nu_set)}")
84
+ if any(b <= a for a, b in zip(nus, nus[1:], strict=False)):
85
+ raise ValueError(f"nu_set must be ascending and distinct, got {list(nu_set)}")
86
+ return nus
87
+
88
+
89
+ # A convention, not a derived constant: `marginal_ppf_sample` interpolates while `var_from_sample` takes the order
90
+ # statistic, so ec and ppf(level) - el agree only to sampling resolution; 1 % relative (absolute below 1).
91
+ EC_CONSISTENCY_TOLERANCE = 0.01
92
+
93
+
94
+ def dependence_band(ppfs: Sequence[Ppf], ec: np.ndarray, el: np.ndarray, corr: np.ndarray, nu_set: Sequence[float],
95
+ level: float = 0.999, horizon_years: int = 1, n_draws: int = 1_000_000, seed: int = 0,
96
+ chunk_size: int = DEFAULT_CHUNK, bounds_n: int = 100_000, bounds_epsilon: float = 1e-3,
97
+ ec_consistency_tolerance: float = EC_CONSISTENCY_TOLERANCE) -> Band:
98
+ """The band on the marginals `ppfs` (money quantile functions), their economic capital `ec` and expected loss `el`
99
+ (K,), the correlation `corr` of the copulas and the t degrees of freedom `nu_set` (above 2, ascending, distinct).
100
+
101
+ The rows: `simple_sum`, `variance_covariance`, `copula_aggregate` for the Gaussian copula and for each nu (the same
102
+ `seed` on every row), and `worst_var_bounds` (its `lower_range[0]` and `upper_range[1]` less the sum of `el`) for
103
+ the
104
+ lower and the worst case. One horizon and one confidence level apply to every row: `level` lies in (0, 1) and
105
+ `horizon_years` is a positive integer. Golden: ec (3, 4), el (0, 0), R = [[1, 0.5], [0.5, 1]] gives the simple-sum
106
+ row 7.0
107
+ and the variance-covariance row 6.0828, with lower <= 6.0828 <= worst."""
108
+ lv = check_level(level, "level")
109
+ if isinstance(horizon_years, bool) or not isinstance(horizon_years, (int, np.integer)) or horizon_years < 1:
110
+ raise ValueError(f"horizon_years must be a positive integer, got {horizon_years}")
111
+ nus = _check_nu_set(nu_set)
112
+ capital_ec = float_vector(ec, "ec")
113
+ if np.any(capital_ec < 0.0):
114
+ raise ValueError("ec must not contain a negative element")
115
+ losses = float_vector(el, "el")
116
+ if np.any(losses < 0.0):
117
+ raise ValueError("el must not contain a negative element")
118
+ r = _matrix(corr, "corr")
119
+ check_correlation(r)
120
+ k = capital_ec.size
121
+ if not (len(ppfs) == losses.size == r.shape[0] == k):
122
+ raise ValueError(f"ppfs, ec, el and corr must have the same length, got {len(ppfs)}, {k}, {losses.size} and "
123
+ f"{r.shape[0]}")
124
+ headline = simple_sum(capital_ec)
125
+ if not headline > 0.0:
126
+ raise ValueError("ec must have a positive sum: the diversification factors are undefined")
127
+ tol = float(ec_consistency_tolerance)
128
+ if not (math.isfinite(tol) and tol >= 0.0):
129
+ raise ValueError(f"ec_consistency_tolerance must be a nonnegative number, got {ec_consistency_tolerance}")
130
+ for idx, ppf in enumerate(ppfs):
131
+ implied = float(np.ravel(ppf(np.array([lv])))[0]) - float(losses[idx])
132
+ if not abs(float(capital_ec[idx]) - implied) <= tol * max(1.0, abs(float(capital_ec[idx]))):
133
+ raise ValueError(f"ec does not match the marginals: marginal {idx} has ec {float(capital_ec[idx])} but "
134
+ f"ppf(level) - el is {implied} (tolerance {tol})")
135
+ el_total = float(losses.sum())
136
+ bounds = worst_var_bounds(ppfs, lv, bounds_n, bounds_epsilon, seed=seed)
137
+ rows: list[tuple[str, float | None, float, float | None]] = [
138
+ ("lower-bound", None, bounds.lower_range[0] - el_total, None),
139
+ ("simple-sum", None, headline, None),
140
+ ("variance-covariance", None, variance_covariance(capital_ec, r), None),
141
+ ]
142
+ for family, nu in (("gaussian", None), *(("t", v) for v in nus)):
143
+ agg = copula_aggregate(ppfs, r, family, nu, el_total, lv, n_draws, seed, chunk_size)
144
+ rows.append(("gaussian-copula" if family == "gaussian" else "t-copula", nu, agg.ec, agg.var_se))
145
+ rows.append(("worst-case", None, bounds.upper_range[1] - el_total, None))
146
+ band_rows = tuple(
147
+ BandRow(method=method, nu=nu, capital=float(capital), diversification_factor=float(capital) / headline,
148
+ status=HEADLINE if method == "simple-sum" else INFORMATION, mc_se=se)
149
+ for method, nu, capital, se in rows)
150
+ return Band(rows=band_rows, headline=headline, horizon_years=int(horizon_years), confidence_level=lv,
151
+ capital_basis=CAPITAL_BASIS)