riskvalidation 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. riskvalidation/__init__.py +30 -0
  2. riskvalidation/aggregation/__init__.py +11 -0
  3. riskvalidation/aggregation/band.py +151 -0
  4. riskvalidation/aggregation/bounds.py +191 -0
  5. riskvalidation/aggregation/copulas.py +241 -0
  6. riskvalidation/aggregation/model_risk.py +133 -0
  7. riskvalidation/aggregation/simple.py +147 -0
  8. riskvalidation/ccr/__init__.py +13 -0
  9. riskvalidation/ccr/collateral.py +175 -0
  10. riskvalidation/ccr/cva.py +193 -0
  11. riskvalidation/ccr/exposure.py +192 -0
  12. riskvalidation/ccr/hw1f.py +426 -0
  13. riskvalidation/ccr/swaps.py +172 -0
  14. riskvalidation/core/__init__.py +1 -0
  15. riskvalidation/core/build.py +57 -0
  16. riskvalidation/core/hashing.py +48 -0
  17. riskvalidation/core/policy.py +130 -0
  18. riskvalidation/core/registry.py +65 -0
  19. riskvalidation/core/result.py +117 -0
  20. riskvalidation/core/suite.py +78 -0
  21. riskvalidation/engines/__init__.py +2 -0
  22. riskvalidation/engines/low_default.py +170 -0
  23. riskvalidation/engines/pd_curve.py +529 -0
  24. riskvalidation/engines/vasicek.py +72 -0
  25. riskvalidation/fairness/__init__.py +10 -0
  26. riskvalidation/fairness/_checks.py +115 -0
  27. riskvalidation/fairness/conditional.py +201 -0
  28. riskvalidation/fairness/inference.py +64 -0
  29. riskvalidation/fairness/metrics.py +261 -0
  30. riskvalidation/fairness/plants.py +240 -0
  31. riskvalidation/fairness/policy.py +97 -0
  32. riskvalidation/fairness/replication.py +39 -0
  33. riskvalidation/fairness/situation.py +307 -0
  34. riskvalidation/generators/__init__.py +68 -0
  35. riskvalidation/generators/_base.py +145 -0
  36. riskvalidation/generators/counts.py +232 -0
  37. riskvalidation/generators/drift.py +107 -0
  38. riskvalidation/generators/framingham.py +124 -0
  39. riskvalidation/generators/paths.py +349 -0
  40. riskvalidation/generators/ratings.py +186 -0
  41. riskvalidation/generators/scores.py +347 -0
  42. riskvalidation/harness/__init__.py +46 -0
  43. riskvalidation/harness/exact.py +137 -0
  44. riskvalidation/harness/performance.py +74 -0
  45. riskvalidation/harness/rates.py +103 -0
  46. riskvalidation/harness/run.py +197 -0
  47. riskvalidation/irrbb/__init__.py +9 -0
  48. riskvalidation/irrbb/behavioural.py +206 -0
  49. riskvalidation/irrbb/curves.py +286 -0
  50. riskvalidation/irrbb/eve_nii.py +245 -0
  51. riskvalidation/irrbb/shocks.py +171 -0
  52. riskvalidation/irrbb/simulation.py +203 -0
  53. riskvalidation/irrbb/slotting.py +184 -0
  54. riskvalidation/lgd_ead/__init__.py +8 -0
  55. riskvalidation/lgd_ead/_checks.py +50 -0
  56. riskvalidation/lgd_ead/ccf.py +228 -0
  57. riskvalidation/lgd_ead/downturn.py +64 -0
  58. riskvalidation/lgd_ead/floors.py +114 -0
  59. riskvalidation/lgd_ead/lgd_models.py +297 -0
  60. riskvalidation/lgd_ead/workout.py +162 -0
  61. riskvalidation/liquidity/__init__.py +9 -0
  62. riskvalidation/liquidity/_checks.py +78 -0
  63. riskvalidation/liquidity/cbc.py +158 -0
  64. riskvalidation/liquidity/deposits.py +151 -0
  65. riskvalidation/liquidity/ladder.py +119 -0
  66. riskvalidation/liquidity/reverse.py +141 -0
  67. riskvalidation/liquidity/runoff.py +220 -0
  68. riskvalidation/liquidity/scenarios.py +272 -0
  69. riskvalidation/market/__init__.py +8 -0
  70. riskvalidation/market/caviar.py +239 -0
  71. riskvalidation/market/conventions.py +83 -0
  72. riskvalidation/market/evt.py +111 -0
  73. riskvalidation/market/frtb.py +175 -0
  74. riskvalidation/market/garch.py +204 -0
  75. riskvalidation/market/gas_fz.py +219 -0
  76. riskvalidation/market/historical.py +96 -0
  77. riskvalidation/market/parametric.py +78 -0
  78. riskvalidation/market/scoring.py +145 -0
  79. riskvalidation/ml/__init__.py +11 -0
  80. riskvalidation/ml/_checks.py +67 -0
  81. riskvalidation/ml/_logistic.py +82 -0
  82. riskvalidation/ml/cbpe.py +91 -0
  83. riskvalidation/ml/challenger.py +73 -0
  84. riskvalidation/ml/conformal.py +116 -0
  85. riskvalidation/ml/dataquality.py +130 -0
  86. riskvalidation/ml/effects.py +67 -0
  87. riskvalidation/ml/explanations.py +125 -0
  88. riskvalidation/ml/generalisation.py +79 -0
  89. riskvalidation/ml/leakage.py +99 -0
  90. riskvalidation/ml/plants.py +425 -0
  91. riskvalidation/ml/policy.py +182 -0
  92. riskvalidation/ml/robustness.py +286 -0
  93. riskvalidation/ml/seeds.py +106 -0
  94. riskvalidation/oprisk/__init__.py +18 -0
  95. riskvalidation/oprisk/_checks.py +60 -0
  96. riskvalidation/oprisk/aggregate.py +375 -0
  97. riskvalidation/oprisk/distributions.py +758 -0
  98. riskvalidation/oprisk/scenarios.py +342 -0
  99. riskvalidation/oprisk/sla.py +80 -0
  100. riskvalidation/oprisk/sma.py +169 -0
  101. riskvalidation/policies/__init__.py +4 -0
  102. riskvalidation/policies/default.json +273 -0
  103. riskvalidation/portfolio/__init__.py +16 -0
  104. riskvalidation/portfolio/asrf_fit.py +283 -0
  105. riskvalidation/portfolio/copula.py +129 -0
  106. riskvalidation/portfolio/creditrisk_plus.py +232 -0
  107. riskvalidation/portfolio/euler.py +126 -0
  108. riskvalidation/portfolio/granularity.py +135 -0
  109. riskvalidation/portfolio/importance.py +277 -0
  110. riskvalidation/portfolio/portfolio.py +309 -0
  111. riskvalidation/provisions/__init__.py +8 -0
  112. riskvalidation/provisions/_checks.py +100 -0
  113. riskvalidation/provisions/ecl.py +233 -0
  114. riskvalidation/provisions/local_cl.py +360 -0
  115. riskvalidation/provisions/local_es.py +157 -0
  116. riskvalidation/provisions/overlays.py +102 -0
  117. riskvalidation/provisions/reconciliation.py +157 -0
  118. riskvalidation/provisions/staging.py +211 -0
  119. riskvalidation/provisions/term_structure.py +199 -0
  120. riskvalidation/regulatory/__init__.py +14 -0
  121. riskvalidation/regulatory/ba_cva.py +138 -0
  122. riskvalidation/regulatory/frtb.py +345 -0
  123. riskvalidation/regulatory/irb.py +314 -0
  124. riskvalidation/regulatory/lcr_nsfr.py +369 -0
  125. riskvalidation/regulatory/output_floor.py +45 -0
  126. riskvalidation/regulatory/sa_ccr.py +486 -0
  127. riskvalidation/regulatory/standardised.py +348 -0
  128. riskvalidation/stress/__init__.py +9 -0
  129. riskvalidation/stress/capital.py +476 -0
  130. riskvalidation/stress/paths.py +108 -0
  131. riskvalidation/stress/reverse.py +179 -0
  132. riskvalidation/stress/satellites.py +268 -0
  133. riskvalidation/stress/scenario_models.py +274 -0
  134. riskvalidation/transitions/__init__.py +0 -0
  135. riskvalidation/transitions/em.py +120 -0
  136. riskvalidation/transitions/embedding.py +221 -0
  137. riskvalidation/transitions/estimators.py +213 -0
  138. riskvalidation/transitions/intervals.py +306 -0
  139. riskvalidation/transitions/mobility.py +57 -0
  140. riskvalidation/transitions/ttc.py +171 -0
  141. riskvalidation/validation/__init__.py +103 -0
  142. riskvalidation/validation/_common.py +57 -0
  143. riskvalidation/validation/aggregation.py +425 -0
  144. riskvalidation/validation/calibration.py +757 -0
  145. riskvalidation/validation/ccr.py +530 -0
  146. riskvalidation/validation/discrimination.py +314 -0
  147. riskvalidation/validation/fairness.py +632 -0
  148. riskvalidation/validation/ifrs9.py +693 -0
  149. riskvalidation/validation/irrbb.py +389 -0
  150. riskvalidation/validation/lgd_ead.py +469 -0
  151. riskvalidation/validation/liquidity.py +647 -0
  152. riskvalidation/validation/market.py +807 -0
  153. riskvalidation/validation/ml.py +958 -0
  154. riskvalidation/validation/oprisk.py +357 -0
  155. riskvalidation/validation/portfolio.py +353 -0
  156. riskvalidation/validation/rating_system.py +245 -0
  157. riskvalidation/validation/stability.py +256 -0
  158. riskvalidation/validation/stress.py +552 -0
  159. riskvalidation/validation/transitions.py +386 -0
  160. riskvalidation-0.8.0.dist-info/METADATA +136 -0
  161. riskvalidation-0.8.0.dist-info/RECORD +164 -0
  162. riskvalidation-0.8.0.dist-info/WHEEL +5 -0
  163. riskvalidation-0.8.0.dist-info/licenses/LICENSE +21 -0
  164. riskvalidation-0.8.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,425 @@
1
+ """The aggregation validation tests (dossier 05 G.5): each returns one `TestResult` that validates against
2
+ `common/test-result`.
3
+
4
+ Acceptance gates are Contraste internal gates, stated as such, not regulatory thresholds. Each function states its light
5
+ rule in its docstring and records its parameters in `policy_version` and in `extras["thresholds"]`, so that a view can
6
+ explain a light (`alpha_amber` and `alpha_red` are null: these tests are not hypothesis tests). A test that cannot be
7
+ evaluated returns the light `not_evaluated` with its reason in `notes` and a null statistic, metric and p-value once
8
+ serialised, never a fabricated number; a non-finite input raises `ValueError` naming the field. The tests are plain
9
+ functions that do not read the registry or the default policy: their rules are the contract's (`engine-aggregation-api`,
10
+ module validation.aggregation). They state no compliance claim. The Euler additivity test of the band is the reused
11
+ `riskvalidation.validation.portfolio.euler_additivity`.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Mapping, Sequence
17
+ from typing import Any
18
+
19
+ import numpy as np
20
+
21
+ from riskvalidation.aggregation import simple as _simple
22
+ from riskvalidation.core.hashing import inputs_hash
23
+ from riskvalidation.core.registry import register
24
+ from riskvalidation.core.result import Light, TestResult
25
+ from riskvalidation.lgd_ead._checks import scalar, vec
26
+
27
+ POLICY_LABEL = "contraste-aggregation-battery-1.0.0"
28
+ NAN = float("nan")
29
+ EPS = 1e-12 # tolerance on a gate comparison, so that a value exactly on a gate is not moved by rounding
30
+
31
+ G5 = ("dossier 05 G.5 (validation tests of an economic capital model: benchmark the aggregation against the simple sum "
32
+ "and the variance-covariance formula, the copula-choice sensitivity, worst-case bounds, the correlation "
33
+ "stress, the sign of every diversification benefit, one horizon and confidence level)")
34
+ G1 = "dossier 05 G.1 (the aggregation ladder: simple sum, variance-covariance, copulas)"
35
+ G3 = ("dossier 05 G.3 (VaR is not subadditive; worst-case VaR bounds by the rearrangement algorithm of Embrechts, "
36
+ "Puccetti and Ruschendorf 2013, doi:10.1016/j.jbankfin.2013.03.014)")
37
+ G2 = ("Rosenberg and Schuermann (2006), A general approach to integrated risk management with skewed, "
38
+ "fat-tailed risks, J. Financial Economics 79(3):569-614, doi:10.1016/j.jfineco.2005.03.001 (dossier 05 G.2)")
39
+
40
+
41
+ def _version(**params: Any) -> str:
42
+ return "; ".join([POLICY_LABEL, *(f"{k}={v}" for k, v in params.items())])
43
+
44
+
45
+ def _not_evaluated(test_id: str, h0: str, alternative: str, reference: str, version: str, reason: str, *,
46
+ thresholds: Mapping[str, Any], model_id: str | None = None, segment: str | None = None,
47
+ n: int | None = None, extras: Mapping[str, Any] | None = None) -> TestResult:
48
+ """No number is carried: the statistic is NaN (null once serialised), the metric and the p-value are None."""
49
+ return TestResult(
50
+ test_id=test_id, h0=h0, alternative=alternative, reference=reference, policy_version=version,
51
+ light=Light.NOT_EVALUATED, statistic=NAN, notes=f"not evaluated: {reason}", model_id=model_id, segment=segment,
52
+ n=n, extras={**(extras or {}), "thresholds": dict(thresholds)})
53
+
54
+
55
+ def _gate(value: float, name: str) -> float:
56
+ v = scalar(value, name)
57
+ if v < 0.0:
58
+ raise ValueError(f"{name} must be nonnegative, got {value}")
59
+ return v
60
+
61
+
62
+ def _three_light(value: float, green: float, amber: float) -> Light:
63
+ """Green at or below `green`, amber at or below `amber`, red above (with a rounding tolerance)."""
64
+ if value <= green + EPS:
65
+ return Light.GREEN
66
+ return Light.AMBER if value <= amber + EPS else Light.RED
67
+
68
+
69
+ @register(
70
+ "aggregation.simple_sum_and_variance_covariance",
71
+ family="aggregation",
72
+ name="Simple sum and variance covariance",
73
+ h0="the aggregate is not above the simple sum and agrees with the variance-covariance formula",
74
+ reference=f"{G5}; {G1}",
75
+ decision="metric",
76
+ )
77
+ def simple_sum_and_variance_covariance(ec: np.ndarray, corr: np.ndarray, aggregate: float, amber: float = 0.10,
78
+ tolerance: float = 1e-9, model_id: str | None = None,
79
+ segment: str | None = None) -> TestResult:
80
+ """The aggregate against the simple sum and the variance-covariance formula (dossier 05 G.5).
81
+
82
+ h0: the aggregate is not above the simple sum and agrees with the variance-covariance formula. statistic =
83
+ aggregate /
84
+ variance_covariance(ec, corr), metric = aggregate / simple_sum(ec), p_value null; extras carry `simple_sum`,
85
+ `variance_covariance` and thresholds = {"amber": amber, "tolerance": tolerance}. Light (a Contraste internal gate):
86
+ red when aggregate > simple_sum (1 + tolerance) (a diversified figure above the sum), amber when |statistic - 1| >
87
+ amber, green otherwise. not_evaluated when the simple sum or the variance-covariance anchor is zero.
88
+ """
89
+ test_id = "aggregation.simple_sum_and_variance_covariance"
90
+ h0 = "the aggregate is not above the simple sum and agrees with the variance-covariance formula"
91
+ alt = "the aggregate is above the simple sum or departs from the variance-covariance formula"
92
+ reference = f"{G5}; {G1}"
93
+ agg = scalar(aggregate, "aggregate")
94
+ am, tol = _gate(amber, "amber"), _gate(tolerance, "tolerance")
95
+ capital = vec(ec, "ec")
96
+ ss = _simple.simple_sum(capital)
97
+ vc = _simple.variance_covariance(capital, corr)
98
+ thresholds = {"amber": am, "tolerance": tol}
99
+ version = _version(amber=am, tolerance=tol)
100
+ extras = {"simple_sum": ss, "variance_covariance": vc}
101
+ kw = dict(model_id=model_id, segment=segment, n=int(capital.size))
102
+ if not (ss > 0.0 and vc > 0.0):
103
+ return _not_evaluated(test_id, h0, alt, reference, version, "the simple sum or the "
104
+ "variance-covariance anchor is zero: no ratio", thresholds=thresholds,
105
+ extras=extras, **kw)
106
+ statistic = agg / vc
107
+ if agg > ss * (1.0 + tol):
108
+ light = Light.RED
109
+ elif abs(statistic - 1.0) > am + EPS:
110
+ light = Light.AMBER
111
+ else:
112
+ light = Light.GREEN
113
+ return TestResult(test_id=test_id, h0=h0, alternative=alt, reference=reference, policy_version=version, light=light,
114
+ statistic=statistic, metric=agg / ss, inputs_hash=inputs_hash(capital, np.asarray(corr), agg),
115
+ extras={**extras, "thresholds": thresholds}, **kw)
116
+
117
+
118
+ @register(
119
+ "aggregation.copula_choice_sensitivity",
120
+ family="aggregation",
121
+ name="Copula choice sensitivity",
122
+ h0=(
123
+ "the choice between the Gaussian and the t copula over the stated nu set moves the capital by less than the "
124
+ "thresholds"),
125
+ reference=f"{G5}; {G2}",
126
+ decision="metric",
127
+ )
128
+ def copula_choice_sensitivity(gaussian: float, t_capitals: Sequence[tuple[float, float]], amber: float = 0.05,
129
+ red: float = 0.15, model_id: str | None = None,
130
+ segment: str | None = None) -> TestResult:
131
+ """The sensitivity of the capital to the choice between the Gaussian and the t copula (dossier 05 G.5; Rosenberg and
132
+ Schuermann find the choice has "a more modest effect on risk", G.2).
133
+
134
+ h0: the choice over the stated nu set moves the capital by less than the thresholds. `t_capitals` are pairs (nu,
135
+ capital). statistic = max over nu of |t / gaussian - 1|, metric = the signed value at the smallest nu, p_value null;
136
+ extras carry the per-nu differences (`differences`, keyed by nu) and thresholds = {"amber": amber, "red": red}.
137
+ Light (a
138
+ Contraste internal gate): green when statistic <= amber, amber when <= red, red above. not_evaluated for no pair
139
+ or a
140
+ nonpositive Gaussian capital.
141
+ """
142
+ test_id = "aggregation.copula_choice_sensitivity"
143
+ h0 = ("the choice between the Gaussian and the t copula over the stated nu set moves the capital by less than the "
144
+ "thresholds")
145
+ alt = "the copula choice moves the capital by more than the thresholds"
146
+ reference = f"{G5}; {G2}"
147
+ g = scalar(gaussian, "gaussian")
148
+ am, rd = _gate(amber, "amber"), _gate(red, "red")
149
+ if am > rd:
150
+ raise ValueError(f"amber and red must satisfy 0 <= amber <= red, got {amber} and {red}")
151
+ thresholds = {"amber": am, "red": rd}
152
+ version = _version(amber=am, red=rd)
153
+ kw = dict(model_id=model_id, segment=segment)
154
+ pairs = np.array(t_capitals, dtype=float).reshape(-1, 2) if len(t_capitals) else np.empty((0, 2))
155
+ if not np.all(np.isfinite(pairs)):
156
+ raise ValueError("t_capitals contains non-finite values")
157
+ if pairs.shape[0] == 0:
158
+ return _not_evaluated(test_id, h0, alt, reference, version, "t_capitals holds no (nu, capital) pair",
159
+ thresholds=thresholds, n=0, **kw)
160
+ if not g > 0.0:
161
+ return _not_evaluated(test_id, h0, alt, reference, version, "the Gaussian capital is not positive: no ratio",
162
+ thresholds=thresholds, n=int(pairs.shape[0]), **kw)
163
+ diff = pairs[:, 1] / g - 1.0
164
+ statistic = float(np.max(np.abs(diff)))
165
+ first = int(np.argmin(pairs[:, 0]))
166
+ return TestResult(
167
+ test_id=test_id, h0=h0, alternative=alt, reference=reference, policy_version=version,
168
+ light=_three_light(statistic, am, rd), statistic=statistic, metric=float(diff[first]), n=int(pairs.shape[0]),
169
+ inputs_hash=inputs_hash(pairs, g),
170
+ extras={"differences": {f"{nu:g}": float(d) for nu, d in zip(pairs[:, 0], diff, strict=True)},
171
+ "thresholds": thresholds}, **kw)
172
+
173
+
174
+ @register(
175
+ "aggregation.worst_case_bracket",
176
+ family="aggregation",
177
+ name="Worst case bracket",
178
+ h0="every row of the band lies between the lower bound and the worst case",
179
+ reference=f"{G5}; {G3}",
180
+ decision="metric",
181
+ )
182
+ def worst_case_bracket(lower: float, rows: Sequence[float], worst: float, tolerance: float = 1e-9,
183
+ model_id: str | None = None, segment: str | None = None) -> TestResult:
184
+ """Every row of the band lies between the lower bound and the worst case (dossier 05 G.3 and G.5: report worst-case
185
+ bounds).
186
+
187
+ statistic = worst - lower, metric = (worst - lower) / max(rows) (null when no row is positive), p_value null; extras
188
+ carry thresholds = {"tolerance": tolerance}. Light (a Contraste internal gate, no amber: a bracket holds or it does
189
+ not): red when any row is outside [lower - tolerance, worst + tolerance] or lower > worst, green otherwise.
190
+ not_evaluated for no row.
191
+ """
192
+ test_id = "aggregation.worst_case_bracket"
193
+ h0 = "every row of the band lies between the lower bound and the worst case"
194
+ alt = "a row of the band lies outside the bracket of the lower bound and the worst case"
195
+ reference = f"{G5}; {G3}"
196
+ lo, hi = scalar(lower, "lower"), scalar(worst, "worst")
197
+ tol = _gate(tolerance, "tolerance")
198
+ r = vec(rows, "rows", allow_empty=True)
199
+ thresholds = {"tolerance": tol}
200
+ version = _version(tolerance=tol)
201
+ kw = dict(model_id=model_id, segment=segment)
202
+ if r.size == 0:
203
+ return _not_evaluated(test_id, h0, alt, reference, version, "rows holds no row", thresholds=thresholds, n=0,
204
+ **kw)
205
+ outside = int(np.sum((r < lo - tol) | (r > hi + tol)))
206
+ red = lo > hi or outside > 0
207
+ top = float(r.max())
208
+ return TestResult(
209
+ test_id=test_id, h0=h0, alternative=alt, reference=reference, policy_version=version,
210
+ light=Light.RED if red else Light.GREEN, statistic=hi - lo, metric=(hi - lo) / top if top > 0.0 else None,
211
+ n=int(r.size), inputs_hash=inputs_hash(r, lo, hi),
212
+ extras={"rows_outside": outside, "thresholds": thresholds},
213
+ notes="" if not red else "a row lies outside the bracket, or the lower bound is above the worst case", **kw)
214
+
215
+
216
+ @register(
217
+ "aggregation.correlation_stress",
218
+ family="aggregation",
219
+ name="Correlation stress",
220
+ h0="raising the market-credit correlation does not lower the capital and raises it by less than the amber gate",
221
+ reference=G5,
222
+ decision="metric",
223
+ )
224
+ def correlation_stress(base: float, stressed: float, amber: float = 0.10, tolerance: float = 1e-9,
225
+ model_id: str | None = None, segment: str | None = None) -> TestResult:
226
+ """Raising the market-credit correlation to 0.8 (dossier 05 G.5) does not lower the capital and raises it by less
227
+ than
228
+ `amber`.
229
+
230
+ statistic = stressed / base - 1, metric = statistic, p_value null; extras carry thresholds = {"amber": amber,
231
+ "tolerance": tolerance}. Light (a Contraste internal gate): red when statistic < -tolerance (the capital falls
232
+ when a
233
+ correlation rises), amber when statistic > amber, green otherwise. not_evaluated for a nonpositive base capital.
234
+ """
235
+ test_id = "aggregation.correlation_stress"
236
+ h0 = "raising the market-credit correlation does not lower the capital and raises it by less than the amber gate"
237
+ alt = "the capital falls when the correlation rises, or rises by more than the amber gate"
238
+ reference = G5
239
+ b, s = scalar(base, "base"), scalar(stressed, "stressed")
240
+ am, tol = _gate(amber, "amber"), _gate(tolerance, "tolerance")
241
+ thresholds = {"amber": am, "tolerance": tol}
242
+ version = _version(amber=am, tolerance=tol)
243
+ kw = dict(model_id=model_id, segment=segment)
244
+ if not b > 0.0:
245
+ return _not_evaluated(test_id, h0, alt, reference, version, "the base capital is not positive: "
246
+ "no relative change", thresholds=thresholds, **kw)
247
+ statistic = s / b - 1.0
248
+ if statistic < -tol:
249
+ light = Light.RED
250
+ elif statistic > am + EPS:
251
+ light = Light.AMBER
252
+ else:
253
+ light = Light.GREEN
254
+ return TestResult(test_id=test_id, h0=h0, alternative=alt, reference=reference, policy_version=version, light=light,
255
+ statistic=statistic, metric=statistic, inputs_hash=inputs_hash(np.array([b, s])),
256
+ extras={"thresholds": thresholds}, **kw)
257
+
258
+
259
+ @register(
260
+ "aggregation.diversification_sign",
261
+ family="aggregation",
262
+ name="Diversification sign",
263
+ h0="every diversification benefit has the right sign (DF <= 1)",
264
+ reference=f"{G5}; {G3}",
265
+ decision="metric",
266
+ )
267
+ def diversification_sign(factors: Sequence[float], tolerance: float = 1e-9, model_id: str | None = None,
268
+ segment: str | None = None) -> TestResult:
269
+ """Every diversification benefit has the right sign, DF <= 1 (dossier 05 G.5: "the sign of every diversification
270
+ benefit"). `factors` are the DF of each diversified row.
271
+
272
+ statistic = max(factors), metric = 1 - min(factors), p_value null; extras carry `count_above_one` (the rows above
273
+ 1 +
274
+ tolerance) and thresholds = {"tolerance": tolerance}. Light (a Contraste internal gate): red when max(factors) > 1 +
275
+ tolerance, green otherwise. not_evaluated for no factor.
276
+ """
277
+ test_id = "aggregation.diversification_sign"
278
+ h0 = "every diversification benefit has the right sign (DF <= 1)"
279
+ alt = "a diversified row is above the simple sum (DF > 1)"
280
+ reference = f"{G5}; {G3}"
281
+ f = vec(factors, "factors", allow_empty=True)
282
+ tol = _gate(tolerance, "tolerance")
283
+ thresholds = {"tolerance": tol}
284
+ version = _version(tolerance=tol)
285
+ kw = dict(model_id=model_id, segment=segment)
286
+ if f.size == 0:
287
+ return _not_evaluated(test_id, h0, alt, reference, version, "factors holds no row", thresholds=thresholds,
288
+ n=0, **kw)
289
+ top = float(f.max())
290
+ return TestResult(
291
+ test_id=test_id, h0=h0, alternative=alt, reference=reference, policy_version=version,
292
+ light=Light.RED if top > 1.0 + tol else Light.GREEN, statistic=top, metric=1.0 - float(f.min()), n=int(f.size),
293
+ inputs_hash=inputs_hash(f), extras={"count_above_one": int(np.sum(f > 1.0 + tol)), "thresholds": thresholds},
294
+ **kw)
295
+
296
+
297
+ @register(
298
+ "aggregation.horizon_confidence_consistency",
299
+ family="aggregation",
300
+ name="Horizon confidence consistency",
301
+ h0="one risk horizon and one confidence level apply across the marginals",
302
+ reference=f"{G5}; dossier 01 l.837-839 (one horizon and one confidence level for the aggregation)",
303
+ decision="metric",
304
+ )
305
+ def horizon_confidence_consistency(horizons: Sequence[float], levels: Sequence[float], expected_horizon: float = 1.0,
306
+ expected_level: float = 0.999, model_id: str | None = None,
307
+ segment: str | None = None) -> TestResult:
308
+ """One risk horizon and one confidence level across the marginals (dossier 05 G.5; dossier 01 l.837-839).
309
+
310
+ statistic = the number of marginals that differ from the expected horizon or level, metric null, p_value null;
311
+ extras
312
+ carry `offending_indices` and thresholds = {"expected_horizon": ..., "expected_level": ...}. Light (a Contraste
313
+ internal
314
+ gate): red when statistic > 0, green otherwise. not_evaluated for no marginal. Unequal lengths raise.
315
+ """
316
+ test_id = "aggregation.horizon_confidence_consistency"
317
+ h0 = "one risk horizon and one confidence level apply across the marginals"
318
+ alt = "a marginal is at another horizon or confidence level"
319
+ reference = f"{G5}; dossier 01 l.837-839 (one horizon and one confidence level for the aggregation)"
320
+ h = vec(horizons, "horizons", allow_empty=True)
321
+ lv = vec(levels, "levels", allow_empty=True)
322
+ if h.size != lv.size:
323
+ raise ValueError(f"horizons and levels must have the same length, got {h.size} and {lv.size}")
324
+ eh, el = scalar(expected_horizon, "expected_horizon"), scalar(expected_level, "expected_level")
325
+ thresholds = {"expected_horizon": eh, "expected_level": el}
326
+ version = _version(expected_horizon=eh, expected_level=el)
327
+ kw = dict(model_id=model_id, segment=segment)
328
+ if h.size == 0:
329
+ return _not_evaluated(test_id, h0, alt, reference, version, "no marginal to compare", thresholds=thresholds,
330
+ n=0, **kw)
331
+ bad = np.flatnonzero((np.abs(h - eh) > EPS) | (np.abs(lv - el) > EPS))
332
+ return TestResult(
333
+ test_id=test_id, h0=h0, alternative=alt, reference=reference, policy_version=version,
334
+ light=Light.RED if bad.size else Light.GREEN, statistic=float(bad.size), n=int(h.size),
335
+ inputs_hash=inputs_hash(h, lv), extras={"offending_indices": [int(i) for i in bad], "thresholds": thresholds},
336
+ **kw)
337
+
338
+
339
+ @register(
340
+ "aggregation.elliptical_mc_agreement",
341
+ family="aggregation",
342
+ name="Elliptical MC agreement",
343
+ h0=(
344
+ "the Monte Carlo capital agrees with the variance-covariance anchor within z standard errors in the "
345
+ "elliptical case"),
346
+ reference=f"{G5}; {G1}",
347
+ decision="metric",
348
+ )
349
+ def elliptical_mc_agreement(mc_capital: float, mc_se: float, vc_capital: float, z: float = 3.0,
350
+ model_id: str | None = None, segment: str | None = None) -> TestResult:
351
+ """In the elliptical case (normal marginals, Gaussian copula) the Monte Carlo capital agrees with the
352
+ variance-covariance anchor within `z` standard errors (exact there for a common quantile scaling: dossier 05 G.1).
353
+
354
+ statistic = (mc_capital - vc_capital) / mc_se, metric = mc_capital / vc_capital - 1, p_value null; extras carry
355
+ thresholds = {"z": z}. Light (a Contraste internal gate): green when |statistic| <= z, red above. not_evaluated when
356
+ mc_se or vc_capital is not positive.
357
+ """
358
+ test_id = "aggregation.elliptical_mc_agreement"
359
+ h0 = ("the Monte Carlo capital agrees with the variance-covariance anchor within z standard errors in the "
360
+ "elliptical case")
361
+ alt = "the Monte Carlo capital departs from the variance-covariance anchor by more than z standard errors"
362
+ reference = f"{G5}; {G1}"
363
+ mc, se, vc = scalar(mc_capital, "mc_capital"), scalar(mc_se, "mc_se"), scalar(vc_capital, "vc_capital")
364
+ zz = scalar(z, "z")
365
+ if not zz > 0.0:
366
+ raise ValueError(f"z must be positive, got {z}")
367
+ thresholds = {"z": zz}
368
+ version = _version(z=zz)
369
+ kw = dict(model_id=model_id, segment=segment)
370
+ if not se > 0.0:
371
+ return _not_evaluated(test_id, h0, alt, reference, version, "the Monte Carlo standard error is not positive",
372
+ thresholds=thresholds, **kw)
373
+ if not vc > 0.0:
374
+ return _not_evaluated(test_id, h0, alt, reference, version, "the variance-covariance capital is not positive",
375
+ thresholds=thresholds, **kw)
376
+ statistic = (mc - vc) / se
377
+ return TestResult(
378
+ test_id=test_id, h0=h0, alternative=alt, reference=reference, policy_version=version,
379
+ light=Light.GREEN if abs(statistic) <= zz + EPS else Light.RED, statistic=statistic, metric=mc / vc - 1.0,
380
+ inputs_hash=inputs_hash(np.array([mc, se, vc])), extras={"thresholds": thresholds}, **kw)
381
+
382
+
383
+ @register(
384
+ "aggregation.rosenberg_schuermann_reference",
385
+ family="aggregation",
386
+ name="Rosenberg schuermann reference",
387
+ h0="none to reject: the additive approximation typically overestimates risk by about 30 to 40 percent",
388
+ reference=f"{G2}; the figure is a reference beside the result, never a gate",
389
+ decision="metric",
390
+ )
391
+ def rosenberg_schuermann_reference(simple_sum: float, gaussian: float, low: float = 0.30, high: float = 0.40,
392
+ model_id: str | None = None, segment: str | None = None) -> TestResult:
393
+ """The additive approximation overestimates risk by about 30 to 40 percent (Rosenberg and Schuermann 2006; dossier
394
+ 05
395
+ G.2), reported beside the result as a reference, never a gate.
396
+
397
+ h0: none to reject. statistic = simple_sum / gaussian - 1, metric = statistic, p_value null; the light is always
398
+ green
399
+ (the row exists to be shown) and `notes` states whether the figure lies inside or outside [low, high]; extras carry
400
+ `role = "reference-not-a-gate"` and thresholds = {"low": low, "high": high}. not_evaluated for a nonpositive
401
+ Gaussian
402
+ capital. The published range itself is UNVERIFIED in its original (dossier 05 G.2).
403
+ """
404
+ test_id = "aggregation.rosenberg_schuermann_reference"
405
+ h0 = "none to reject: the additive approximation typically overestimates risk by about 30 to 40 percent"
406
+ alt = "a reference, not a hypothesis test"
407
+ reference = f"{G2}; the figure is a reference beside the result, never a gate"
408
+ ss, g = scalar(simple_sum, "simple_sum"), scalar(gaussian, "gaussian")
409
+ lo, hi = scalar(low, "low"), scalar(high, "high")
410
+ if not 0.0 <= lo <= hi:
411
+ raise ValueError(f"low and high must satisfy 0 <= low <= high, got {low} and {high}")
412
+ thresholds = {"low": lo, "high": hi}
413
+ version = _version(low=lo, high=hi)
414
+ kw = dict(model_id=model_id, segment=segment)
415
+ role = {"role": "reference-not-a-gate"}
416
+ if not g > 0.0:
417
+ return _not_evaluated(test_id, h0, alt, reference, version, "the Gaussian capital is not positive: no ratio",
418
+ thresholds=thresholds, extras=role, **kw)
419
+ statistic = ss / g - 1.0
420
+ where = "inside" if lo - EPS <= statistic <= hi + EPS else "outside"
421
+ return TestResult(
422
+ test_id=test_id, h0=h0, alternative=alt, reference=reference, policy_version=version, light=Light.GREEN,
423
+ statistic=statistic, metric=statistic, inputs_hash=inputs_hash(np.array([ss, g])),
424
+ extras={**role, "thresholds": thresholds},
425
+ notes=f"the additive overestimate {statistic:.4f} lies {where} the published range [{lo}, {hi}]", **kw)