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,647 @@
1
+ """The liquidity validation tests (dossier 05 E.1 to E.5 and its acceptance rows; dossier 08 G.2 and G.4): each
2
+ returns one
3
+ `TestResult` that validates against `common/test-result`.
4
+
5
+ Acceptance gates are Contraste internal gates, stated as such, never regulatory thresholds (decision Q14: the named
6
+ parameters of the case documents). Each function states its light rule in its docstring and records its parameters in
7
+ `policy_version` and in `extras["thresholds"]`, so that a view can explain a light. A test that cannot be evaluated
8
+ returns
9
+ the light `not_evaluated` with its reason in `notes` and a null statistic, metric and p-value once serialised, never a
10
+ fabricated number. The tests are plain functions that do not read the registry or the default policy: their rules are
11
+ the
12
+ contract's (`engine-liquidity-api` 1.2.0, module validation.liquidity). They state no compliance claim. The tests of
13
+ `regulatory.lcr_nsfr` are constructed tests and invariants (`tests/liquidity/test_lcr_nsfr.py`), not `TestResult`
14
+ functions.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import math
20
+ from collections.abc import Mapping, Sequence
21
+ from typing import Any
22
+
23
+ import numpy as np
24
+
25
+ from riskvalidation.core.hashing import inputs_hash
26
+ from riskvalidation.core.registry import register
27
+ from riskvalidation.core.result import Light, TestResult
28
+ from riskvalidation.liquidity import cbc as _cbc
29
+ from riskvalidation.liquidity import ladder as _ladder
30
+ from riskvalidation.liquidity import runoff as _runoff
31
+ from riskvalidation.liquidity._checks import check_increasing_grid, check_unit_share
32
+ from riskvalidation.liquidity.ladder import SurvivalResult
33
+
34
+ POLICY_LABEL = "contraste-liquidity-battery-1.0.0"
35
+ NAN = float("nan")
36
+ EPS = 1e-12 # tolerance on a gate comparison, so that a value exactly on a gate is not moved by rounding
37
+
38
+ LIST_NOTE = ("ECB Banking Supervision, Sensitivity analysis of liquidity risk, stress test 2019, methodological note "
39
+ "(2019-02-06) and results annex (2019-10-07), https://www.bankingsupervision.europa.eu/")
40
+ REF_COMPOUNDING = (
41
+ "dossier 05 E.1 line 237 (constant daily compounding on relevant days, Table 3.3 and para 107 of the LiST note) "
42
+ f"and the SDD acceptance row of the unit sizing; {LIST_NOTE}")
43
+ REF_MONOTONE = (
44
+ "dossier 05 E.1 line 240 (median survival periods 176 and 122 days) and line 480, SDD line 329: the survival "
45
+ f"period does not lengthen as the severity rises; {LIST_NOTE}")
46
+ REF_HAIRCUTS = (
47
+ "dossier 05 E.1 line 238 and line 480 (LiST note para 74, Table 2.1: the haircut order, the equity table, "
48
+ f"30 and 50 percent); {LIST_NOTE}")
49
+ REF_NLP = ("dossier 05 E.1 line 234: NLP(t) = CBC(t) - sum over s <= t of (O(s) - I(s)), "
50
+ "checked on hand-computed ladders")
51
+ REF_ADEQUACY = (
52
+ "dossier 08 lines 566 to 568 and dossier 06 lines 971 to 973: a Basel outflow assumption back-tested against "
53
+ "the observed run rate (BCBS d555 Box A, Table A.1, https://www.bis.org/bcbs/publ/d555.htm); "
54
+ "a descriptive score on the real event, one observation, no p-value (decision Q5)")
55
+ REF_GENERATOR = (
56
+ "dossier 08 line 698 and G.4 lines 739 to 742: the run-off estimate against the depositor generator's exact "
57
+ "truth, in Monte Carlo standard errors (the generator test of decision Q5)")
58
+ REF_CLIFF = (
59
+ "dossier 05 E.1 line 236 defines the cliff effect (NLP(35) - NLP(30)) / TA as a diagnostic of LCR window "
60
+ f"optimisation and no limit, so the lights are conventions (decision Q14); {LIST_NOTE}")
61
+ REF_HTM = (
62
+ "dossier 05 lines 263, 278 and 480: the CBC and the survival period with and without held-to-maturity "
63
+ "unrealised losses (Jiang, Matvos, Piskorski and Seru, doi:10.1016/j.jfineco.2024.103899)")
64
+ REF_UNINSURED = ("dossier 05 line 278: the survival period does not lengthen as the uninsured share of deposits "
65
+ "rises")
66
+ REF_REVERSE = ("dossier 05 E.5 rung 5, line 279: the reverse liquidity stress round trip (the survival period at "
67
+ "the solved multiplier equals the target)")
68
+ REF_REVALUATION = (
69
+ "dossier 05 line 263 and decision Q11: the HTM book revalued from its maturity profile under the Treasury "
70
+ "curve through the engine's irrbb curves against the reported fair value SCHF (FDIC BankFind fields, "
71
+ "addendum L3)")
72
+
73
+
74
+ def _version(**params: Any) -> str:
75
+ return "; ".join([POLICY_LABEL, *(f"{k}={v}" for k, v in params.items())])
76
+
77
+
78
+ def _not_evaluated(test_id: str, h0: str, alternative: str, reference: str, version: str, reason: str, *,
79
+ n: int | None = None, segment: str | None = None,
80
+ extras: Mapping[str, Any] | None = None) -> TestResult:
81
+ """No number is carried: the statistic is NaN (null once serialised), the metric and the p-value are None."""
82
+ return TestResult(test_id=test_id, h0=h0, alternative=alternative, reference=reference, policy_version=version,
83
+ light=Light.NOT_EVALUATED, statistic=NAN, notes=f"not evaluated: {reason}", n=n, segment=segment,
84
+ extras=dict(extras or {}))
85
+
86
+
87
+ def _scalar(x: Any, name: str) -> float:
88
+ try:
89
+ v = float(x)
90
+ except (TypeError, ValueError) as exc:
91
+ raise ValueError(f"{name}: must be numeric, got {x!r}") from exc
92
+ if not math.isfinite(v):
93
+ raise ValueError(f"{name}: must be finite, got {x!r}")
94
+ return v
95
+
96
+
97
+ def _nonneg_tol(x: Any, name: str) -> float:
98
+ """A tolerance: finite and not negative (a negative tolerance would turn a shortening into a failure)."""
99
+ v = _scalar(x, name)
100
+ if v < 0.0:
101
+ raise ValueError(f"{name}: must be non-negative, got {x!r}")
102
+ return v
103
+
104
+
105
+ def _vec(x: Any, name: str) -> np.ndarray:
106
+ a = np.array(x, dtype=float)
107
+ if a.ndim != 1 or a.size == 0 or not np.all(np.isfinite(a)):
108
+ raise ValueError(f"{name}: must be a non-empty one-dimensional array of finite values, got shape {a.shape}")
109
+ return a
110
+
111
+
112
+ def _same_length(**arrays: np.ndarray) -> None:
113
+ sizes = {k: v.shape[0] for k, v in arrays.items()}
114
+ if len(set(sizes.values())) > 1:
115
+ raise ValueError(f"{', '.join(sizes)} must have the same length, got {sizes}")
116
+
117
+
118
+ def _days(values: Sequence[float | None], name: str) -> np.ndarray:
119
+ """Survival periods in days with `None` ("survives the horizon") as infinity, longer than any day."""
120
+ out = []
121
+ for v in values:
122
+ out.append(math.inf if v is None else _scalar(v, name))
123
+ return np.array(out, dtype=float)
124
+
125
+
126
+ def _largest_increase(days: np.ndarray) -> float:
127
+ """The largest lengthening of the survival period along the order, in days, at least 0; a finite period followed by
128
+ "survives the horizon" is an unbounded lengthening (infinity)."""
129
+ worst = 0.0
130
+ for a, b in zip(days[:-1], days[1:], strict=True):
131
+ if math.isinf(b) and not math.isinf(a):
132
+ return math.inf
133
+ if math.isinf(a):
134
+ continue
135
+ worst = max(worst, float(b - a))
136
+ return worst
137
+
138
+
139
+ def _three_light_high(value: float, green: float, amber: float) -> Light:
140
+ """Green at or above `green`, amber at or above `amber`, red below (with a rounding tolerance)."""
141
+ if value >= green - EPS:
142
+ return Light.GREEN
143
+ return Light.AMBER if value >= amber - EPS else Light.RED
144
+
145
+
146
+ def _three_light_low(value: float, green: float, amber: float) -> Light:
147
+ """Green at or below `green`, amber at or below `amber`, red above (with a rounding tolerance)."""
148
+ if value <= green + EPS:
149
+ return Light.GREEN
150
+ return Light.AMBER if value <= amber + EPS else Light.RED
151
+
152
+
153
+ # ----------------------------------------------------------------------------------------------------------------
154
+ # The goldens and identities
155
+
156
+
157
+ @register(
158
+ "liq.list_compounding_golden",
159
+ family="liquidity",
160
+ name="LiST compounding golden",
161
+ h0="the engine reproduces the LiST compounding golden of dossier 05 line 237 within the printed precision",
162
+ reference=REF_COMPOUNDING,
163
+ decision="metric",
164
+ )
165
+ def list_compounding_golden(q: float = 0.00103258, n: int = 125, expected: float = 0.121148,
166
+ tol: float = 5e-7) -> TestResult:
167
+ """Reproduces the LiST compounding of dossier 05 line 237: stable retail sight deposits at `q = 0.103258`
168
+ percent per
169
+ relevant day for `n = 125` relevant days give a cumulative outflow of 12.11 percent.
170
+
171
+ statistic = `abs(1 - (1 - q)^n - expected)`, metric = the computed cumulative outflow, p_value None. Light (a
172
+ Contraste internal gate): green when the statistic is at most `tol` (the named parameter
173
+ `list_compounding_tolerance`), red otherwise; `extras["thresholds"]` holds the tolerance. At the defaults the metric
174
+ is
175
+ `0.1211484` (`0.12114837`) and the statistic `3.7e-7`."""
176
+ test_id = "liq.list_compounding_golden"
177
+ h0 = "the engine reproduces the LiST compounding golden of dossier 05 line 237 within the printed precision"
178
+ alt = "the engine departs from the printed cumulative outflow"
179
+ rate = float(check_unit_share(q, "q")[0])
180
+ days = int(_scalar(n, "n"))
181
+ exp, tolerance = _scalar(expected, "expected"), _scalar(tol, "tol")
182
+ if tolerance < 0.0:
183
+ raise ValueError(f"tol: must be non-negative, got {tol}")
184
+ value = float(_runoff.cumulative_outflow_constant(rate, days))
185
+ stat = abs(value - exp)
186
+ return TestResult(
187
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_COMPOUNDING,
188
+ policy_version=_version(tolerance=tolerance),
189
+ light=Light.GREEN if stat <= tolerance + EPS else Light.RED, statistic=stat, metric=value, n=days,
190
+ inputs_hash=inputs_hash(np.array([rate, days, exp])), extras={"thresholds": {"tolerance": tolerance}})
191
+
192
+
193
+ @register(
194
+ "liq.survival_monotone_in_severity",
195
+ family="liquidity",
196
+ name="Survival monotone in severity",
197
+ h0="the survival period does not lengthen as the scenario severity rises",
198
+ reference=REF_MONOTONE,
199
+ decision="metric",
200
+ )
201
+ def survival_monotone_in_severity(survival_days: Sequence[float | None], tol_days: float = 0.0) -> TestResult:
202
+ """The survival period does not lengthen as the severity rises (dossier 05 line 480; SDD l.329).
203
+
204
+ `survival_days` is ordered from the mildest to the most severe scenario, in relevant days; `None` is "survives the
205
+ horizon" and counts as longer than any day. statistic = the largest increase of the survival period along the order,
206
+ in days (at least 0; a finite period followed by "survives the horizon" is an unbounded increase, null once
207
+ serialised). Light (a Contraste internal gate): green when no step lengthens the survival period by more than
208
+ `tol_days` (the named parameter `monotonicity_tolerance_days`), red otherwise; fewer than two scenarios:
209
+ not_evaluated. Golden: `[None, 176, 122]` (the LiST 2019 median survival periods, 05 line 240) is green with
210
+ statistic 0; `[100, 120]` is red with statistic 20."""
211
+ test_id = "liq.survival_monotone_in_severity"
212
+ h0 = "the survival period does not lengthen as the scenario severity rises"
213
+ alt = "a more severe scenario survives longer than a milder one"
214
+ tol = _nonneg_tol(tol_days, "tol_days")
215
+ days = _days(survival_days, "survival_days")
216
+ version = _version(tolerance_days=tol)
217
+ thresholds = {"tolerance_days": tol}
218
+ if days.size < 2:
219
+ return _not_evaluated(test_id, h0, alt, REF_MONOTONE, version, "fewer than 2 scenarios", n=int(days.size),
220
+ extras={"thresholds": thresholds})
221
+ stat = _largest_increase(days)
222
+ return TestResult(
223
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_MONOTONE, policy_version=version,
224
+ light=Light.GREEN if stat <= tol + EPS else Light.RED, statistic=stat, n=int(days.size),
225
+ inputs_hash=inputs_hash(np.where(np.isinf(days), -1.0, days)),
226
+ extras={"thresholds": thresholds, "survives_horizon": [bool(math.isinf(d)) for d in days]},
227
+ notes="a finite survival period is followed by 'survives the horizon': an unbounded lengthening"
228
+ if math.isinf(stat) else "")
229
+
230
+
231
+ _HAIRCUT_CASES: tuple[tuple[str, dict[str, Any], float, str], ...] = (
232
+ ("equity", {"equity_rating": "AAA-A-"}, 0.20, "ecb-equity-table"),
233
+ ("equity", {"equity_rating": "BBB+-BBB-"}, 0.35, "ecb-equity-table"),
234
+ ("equity", {"equity_rating": "lower-or-unrated"}, 0.50, "ecb-equity-table"),
235
+ ("non-equity", {"hqla_level": "level_1"}, 0.30, "ecb-non-equity-hqla"),
236
+ ("non-equity", {}, 0.50, "fifty-percent-fallback"),
237
+ ("non-equity", {"central_bank_eligible": True, "central_bank_haircut": 0.04}, 0.04, "central-bank-framework"),
238
+ ("non-equity", {"central_bank_eligible": True, "hqla_level": "level_2a"}, 0.15, "lcr-haircut-hqla"),
239
+ ("non-equity", {"central_bank_eligible": True}, 0.50, "fifty-percent-fallback"),
240
+ ("cash", {}, 0.0, "nominal-value"),
241
+ )
242
+
243
+
244
+ @register(
245
+ "liq.cbc_haircut_rules",
246
+ family="liquidity",
247
+ name="CBC haircut rules",
248
+ h0="the engine's haircut rules reproduce the order and values of LiST note para 74 on the nine printed cases",
249
+ reference=REF_HAIRCUTS,
250
+ decision="metric",
251
+ )
252
+ def cbc_haircut_rules(tol: float = 1e-12) -> TestResult:
253
+ """Runs `cbc.haircut_rule` on the nine cases of dossier 05 line 238 (the three equity bands, non-equity HQLA
254
+ and not,
255
+ central bank given, eligible and undetermined HQLA and not, cash) and compares the haircut and the rule label with
256
+ the
257
+ printed ones.
258
+
259
+ statistic = the largest absolute haircut deviation, n = 9. Light (a Contraste internal gate): green when every
260
+ haircut
261
+ and label equals the expected one (deviation at most `tol`), red otherwise (a wrong label alone is red; a case that
262
+ raises counts as failed with an infinite deviation, null once serialised); `extras["thresholds"]` holds the
263
+ tolerance."""
264
+ test_id = "liq.cbc_haircut_rules"
265
+ h0 = "the engine's haircut rules reproduce the order and values of LiST note para 74 on the nine printed cases"
266
+ alt = "a haircut or a rule label departs from the note"
267
+ tolerance = _scalar(tol, "tol")
268
+ if tolerance < 0.0:
269
+ raise ValueError(f"tol: must be non-negative, got {tol}")
270
+ deviations, wrong_labels, cases = [], 0, []
271
+ for kind, kwargs, haircut, label in _HAIRCUT_CASES:
272
+ try:
273
+ got_h, got_label = _cbc.haircut_rule(kind, **kwargs)
274
+ except ValueError as exc:
275
+ got_h, got_label = math.inf, f"raised: {exc}"
276
+ deviations.append(abs(got_h - haircut))
277
+ wrong_labels += int(got_label != label)
278
+ cases.append({"kind": kind, "expected": [haircut, label], "got": [got_h, got_label]})
279
+ stat = max(deviations)
280
+ ok = stat <= tolerance + EPS and wrong_labels == 0
281
+ return TestResult(
282
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_HAIRCUTS, policy_version=_version(tolerance=tolerance),
283
+ light=Light.GREEN if ok else Light.RED, statistic=stat, n=len(_HAIRCUT_CASES),
284
+ inputs_hash=inputs_hash(np.array(deviations)), extras={"thresholds": {"tolerance": tolerance}, "cases": cases,
285
+ "wrong_labels": wrong_labels},
286
+ notes="" if ok else f"{wrong_labels} wrong label(s); the largest haircut deviation is {stat}")
287
+
288
+
289
+ @register(
290
+ "liq.nlp_identity",
291
+ family="liquidity",
292
+ name="NLP identity",
293
+ h0="the net liquidity position equals the CBC less the cumulated net outflows on every day",
294
+ reference=REF_NLP,
295
+ decision="metric",
296
+ )
297
+ def nlp_identity(cbc: np.ndarray, outflows: np.ndarray, inflows: np.ndarray, nlp: np.ndarray,
298
+ tol: float = 1e-6) -> TestResult:
299
+ """The net liquidity position identity of dossier 05 E.1 line 234 on a ladder: `NLP(t) = CBC(t) - sum over s <= t of
300
+ (O(s) - I(s))`. Money (H,) arrays in USD thousands.
301
+
302
+ statistic = the largest absolute residual of `nlp - (cbc - cumsum(outflows - inflows))`. Light (a Contraste internal
303
+ gate): green when the statistic is at most `tol` (the named parameter `nlp_identity_tolerance`), red otherwise;
304
+ `extras["thresholds"]` holds the tolerance. Golden: the hand ladder `cbc = [100]*4`, outflows `[30, 40, 50, 60]`,
305
+ inflows `[0, 10, 0, 0]`, `nlp = [70, 40, -10, -70]` gives statistic 0 and green."""
306
+ test_id = "liq.nlp_identity"
307
+ h0 = "the net liquidity position equals the CBC less the cumulated net outflows on every day"
308
+ alt = "the net liquidity position departs from the identity"
309
+ c, o, i, p = _vec(cbc, "cbc"), _vec(outflows, "outflows"), _vec(inflows, "inflows"), _vec(nlp, "nlp")
310
+ _same_length(cbc=c, outflows=o, inflows=i, nlp=p)
311
+ tolerance = _scalar(tol, "tol")
312
+ residual = p - (c - np.cumsum(o - i))
313
+ stat = float(np.max(np.abs(residual)))
314
+ return TestResult(
315
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_NLP, policy_version=_version(tolerance=tolerance),
316
+ light=Light.GREEN if stat <= tolerance + EPS else Light.RED, statistic=stat, n=int(c.size),
317
+ inputs_hash=inputs_hash(c, o, i, p), extras={"thresholds": {"tolerance": tolerance}})
318
+
319
+
320
+ @register(
321
+ "liq.runoff_adequacy_back_test",
322
+ family="liquidity",
323
+ name="Runoff adequacy back test",
324
+ h0="the modelled outflow share is at least as large as the realised one",
325
+ reference=REF_ADEQUACY,
326
+ decision="metric",
327
+ )
328
+ def runoff_adequacy_back_test(modelled_share: float, realised_share: float, ratio_green: float = 0.8,
329
+ ratio_amber: float = 0.5, compared_at: str = "event-horizon",
330
+ denominator: str | None = None) -> TestResult:
331
+ """A Basel outflow assumption back-tested against the observed rate (dossier 08 lines 566 to 568; 06 lines 971
332
+ to 973):
333
+ a descriptive score on the real event, one observation, no p-value (decision Q5). Shares of the deposit base.
334
+
335
+ statistic = the ratio `modelled_share / realised_share`, metric = the shortfall `realised_share - modelled_share`,
336
+ `segment` = the denominator id. Light (a Contraste internal gate): green when the ratio is at least `ratio_green`,
337
+ amber when at least `ratio_amber`, red below (the named parameters `scoring_ratio_green` and `scoring_ratio_amber`);
338
+ not_evaluated when `realised_share` is 0. `compared_at` is `"event-horizon"` or `"model-horizon"`;
339
+ `extras["thresholds"]` holds both ratios and `compared_at`. Golden: modelled 0.013723 against 0.85 gives ratio
340
+ 0.016145, shortfall 0.836277 and red."""
341
+ test_id = "liq.runoff_adequacy_back_test"
342
+ h0 = "the modelled outflow share is at least as large as the realised one"
343
+ alt = "the modelled outflow share falls short of the realised one"
344
+ modelled = float(check_unit_share(modelled_share, "modelled_share")[0])
345
+ realised = float(check_unit_share(realised_share, "realised_share")[0])
346
+ green, amber = _scalar(ratio_green, "ratio_green"), _scalar(ratio_amber, "ratio_amber")
347
+ if not 0.0 <= amber <= green:
348
+ raise ValueError(f"ratio_amber and ratio_green: must satisfy 0 <= ratio_amber <= ratio_green, got {amber} and "
349
+ f"{green}")
350
+ if compared_at not in ("event-horizon", "model-horizon"):
351
+ raise ValueError(f"compared_at: must be 'event-horizon' or 'model-horizon', got {compared_at!r}")
352
+ thresholds = {"ratio_green": green, "ratio_amber": amber, "compared_at": compared_at}
353
+ version = _version(ratio_green=green, ratio_amber=amber, compared_at=compared_at)
354
+ if realised == 0.0:
355
+ return _not_evaluated(test_id, h0, alt, REF_ADEQUACY, version,
356
+ "realised_share is 0, so the ratio is undefined", n=1, segment=denominator,
357
+ extras={"thresholds": thresholds})
358
+ ratio = modelled / realised
359
+ return TestResult(
360
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_ADEQUACY, policy_version=version,
361
+ light=_three_light_high(ratio, green, amber), statistic=ratio, metric=realised - modelled, n=1,
362
+ segment=denominator, inputs_hash=inputs_hash(np.array([modelled, realised])),
363
+ extras={"thresholds": thresholds})
364
+
365
+
366
+ @register(
367
+ "liq.runoff_vs_generator_truth",
368
+ family="liquidity",
369
+ name="Runoff vs generator truth",
370
+ h0="the run-off estimate reproduces the generator's exact truth within Monte Carlo error",
371
+ reference=REF_GENERATOR,
372
+ decision="metric",
373
+ )
374
+ def runoff_vs_generator_truth(estimated: np.ndarray, truth: np.ndarray, mc_se: np.ndarray, se_green: float = 2.0,
375
+ se_red: float = 3.0) -> TestResult:
376
+ """The run-off estimate against the depositor generator's exact truth (dossier 08 line 698, G.4 lines 739 to 742).
377
+ `estimated`, `truth` and `mc_se` are `(K,)` by segment and horizon; `mc_se` is the Monte Carlo standard error of the
378
+ generator's verification.
379
+
380
+ statistic = the largest `abs(estimated - truth) / mc_se`, in standard errors, `n = K`. Light (a Contraste internal
381
+ gate): green when the statistic is at most `se_green`, amber when at most `se_red`, red above (the named parameters
382
+ `generator_truth_se_green` and `generator_truth_se_red`); a zero or negative `mc_se` raises `ValueError`;
383
+ `extras["thresholds"]` holds both. Golden: `estimated = truth` gives 0 and green; an entry off by `2.5 x mc_se`
384
+ gives
385
+ 2.5 and amber; by `3.5 x mc_se` gives 3.5 and red."""
386
+ test_id = "liq.runoff_vs_generator_truth"
387
+ h0 = "the run-off estimate reproduces the generator's exact truth within Monte Carlo error"
388
+ alt = "the run-off estimate departs from the generator's truth by more than Monte Carlo error"
389
+ est, tru, se = _vec(estimated, "estimated"), _vec(truth, "truth"), _vec(mc_se, "mc_se")
390
+ _same_length(estimated=est, truth=tru, mc_se=se)
391
+ if np.any(se <= 0.0):
392
+ raise ValueError(f"mc_se: every standard error must be positive, got {float(se.min())}")
393
+ green, red = _scalar(se_green, "se_green"), _scalar(se_red, "se_red")
394
+ if not 0.0 <= green <= red:
395
+ raise ValueError(f"se_green and se_red: must satisfy 0 <= se_green <= se_red, got {green} and {red}")
396
+ z = np.abs(est - tru) / se
397
+ stat = float(z.max())
398
+ return TestResult(
399
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_GENERATOR,
400
+ policy_version=_version(se_green=green, se_red=red),
401
+ light=_three_light_low(stat, green, red), statistic=stat, n=int(est.size),
402
+ inputs_hash=inputs_hash(est, tru, se),
403
+ extras={"thresholds": {"se_green": green, "se_red": red}, "z": z.tolist()})
404
+
405
+
406
+ @register(
407
+ "liq.cliff_effect_diagnostic",
408
+ family="liquidity",
409
+ name="Cliff effect diagnostic",
410
+ h0="the net liquidity position does not drop between the near and far day by more than the convention allows",
411
+ reference=REF_CLIFF,
412
+ decision="metric",
413
+ )
414
+ def cliff_effect_diagnostic(nlp: np.ndarray, total_assets: float, near: int = 30, far: int = 35, amber: float = -0.01,
415
+ red: float = -0.03) -> TestResult:
416
+ """The cliff effect of dossier 05 E.1 line 236: a diagnostic of LCR window optimisation. `nlp` is `(H,)` money, the
417
+ cliff a share of total assets.
418
+
419
+ statistic = `ladder.cliff_effect(nlp, total_assets, near, far)`, metric = `NLP(far) - NLP(near)` in money. Light (a
420
+ convention, decision Q14, as 05 E.1 line 236 defines no limit): green when the statistic is at least `amber`, amber
421
+ when at least `red`, red below (the named parameters `cliff_amber_threshold` and `cliff_red_threshold`);
422
+ not_evaluated with the reason in `notes` when the horizon is shorter than `far`; `extras["thresholds"]` holds both.
423
+ Golden: `NLP(30) = 100`, `NLP(35) = 40`, `TA = 1000` gives `-0.06` and red."""
424
+ test_id = "liq.cliff_effect_diagnostic"
425
+ h0 = "the net liquidity position does not drop between the near and far day by more than the convention allows"
426
+ alt = "the net liquidity position drops between the near and far day (an LCR window effect)"
427
+ x = _vec(nlp, "nlp")
428
+ ta = _scalar(total_assets, "total_assets")
429
+ a, r = _scalar(amber, "amber"), _scalar(red, "red")
430
+ if r > a:
431
+ raise ValueError(f"amber and red: must satisfy red <= amber, got amber = {a} and red = {r}")
432
+ thresholds = {"amber": a, "red": r}
433
+ version = _version(near=int(near), far=int(far), amber=a, red=r)
434
+ if x.size < far:
435
+ return _not_evaluated(test_id, h0, alt, REF_CLIFF, version,
436
+ f"the horizon of {x.size} days is shorter than far = {int(far)}", n=int(x.size),
437
+ extras={"thresholds": thresholds})
438
+ stat = _ladder.cliff_effect(x, ta, int(near), int(far))
439
+ return TestResult(
440
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_CLIFF, policy_version=version,
441
+ light=_three_light_high(stat, a, r), statistic=stat, metric=float(x[int(far) - 1] - x[int(near) - 1]),
442
+ n=int(x.size), inputs_hash=inputs_hash(x, np.array([ta, near, far])), extras={"thresholds": thresholds})
443
+
444
+
445
+ @register(
446
+ "liq.htm_loss_effect",
447
+ family="liquidity",
448
+ name="HTM loss effect",
449
+ h0="the held-to-maturity unrealised loss does not raise the CBC and does not lengthen the survival period",
450
+ reference=REF_HTM,
451
+ decision="metric",
452
+ )
453
+ def htm_loss_effect(cbc_without: float, cbc_with: float, survival_without: float | None,
454
+ survival_with: float | None) -> TestResult:
455
+ """The CBC and the survival period with and without the held-to-maturity unrealised loss (dossier 05 lines 263, 278
456
+ and 480). Money for the CBC; survival periods in relevant days with `None` as "survives the horizon" (longer than
457
+ any
458
+ day).
459
+
460
+ statistic = the CBC removed, `cbc_without - cbc_with`, metric = its share of `cbc_without`. Light (a Contraste
461
+ internal
462
+ gate): green when the unrealised loss does not raise the CBC (statistic at least 0) and does not lengthen the
463
+ survival
464
+ period, red otherwise; not_evaluated when `cbc_without` is 0; `extras["thresholds"] = {"tolerance": 0.0}`. Golden:
465
+ `(72, 58.5, None, 48)` gives 13.5, 0.1875 and green; `(72, 80, 40, 60)` gives red."""
466
+ test_id = "liq.htm_loss_effect"
467
+ h0 = "the held-to-maturity unrealised loss does not raise the CBC and does not lengthen the survival period"
468
+ alt = "the unrealised loss raises the CBC or lengthens the survival period"
469
+ without, with_loss = _scalar(cbc_without, "cbc_without"), _scalar(cbc_with, "cbc_with")
470
+ sw = math.inf if survival_without is None else _scalar(survival_without, "survival_without")
471
+ sl = math.inf if survival_with is None else _scalar(survival_with, "survival_with")
472
+ thresholds = {"tolerance": 0.0}
473
+ version = _version(tolerance=0.0)
474
+ if without == 0.0:
475
+ return _not_evaluated(test_id, h0, alt, REF_HTM, version, "cbc_without is 0, so its share is undefined", n=2,
476
+ extras={"thresholds": thresholds})
477
+ removed = without - with_loss
478
+ ok = removed >= -EPS and sl <= sw
479
+ return TestResult(
480
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_HTM, policy_version=version,
481
+ light=Light.GREEN if ok else Light.RED, statistic=removed, metric=removed / without, n=2,
482
+ inputs_hash=inputs_hash(np.array([without, with_loss, -1.0 if math.isinf(sw) else sw,
483
+ -1.0 if math.isinf(sl) else sl])),
484
+ extras={"thresholds": thresholds, "survives_horizon": {"without": math.isinf(sw), "with": math.isinf(sl)}})
485
+
486
+
487
+ @register(
488
+ "liq.uninsured_share_sensitivity",
489
+ family="liquidity",
490
+ name="Uninsured share sensitivity",
491
+ h0="the survival period does not lengthen as the uninsured share rises",
492
+ reference=REF_UNINSURED,
493
+ decision="metric",
494
+ )
495
+ def uninsured_share_sensitivity(shares: Sequence[float], survival_days: Sequence[float | None],
496
+ tol_days: float = 0.0) -> TestResult:
497
+ """The survival period does not lengthen as the uninsured share rises (dossier 05 line 278). `shares` are increasing
498
+ shares of domestic deposits (the named parameter `uninsured_share_grid`); `survival_days` is the survival period
499
+ under
500
+ each share in relevant days, `None` surviving the horizon.
501
+
502
+ statistic = the largest increase of the survival period along the grid, in days. Light (a Contraste internal gate):
503
+ green when no step lengthens the survival period by more than `tol_days`, red otherwise; fewer than two shares:
504
+ not_evaluated; `extras["thresholds"] = {"tolerance_days": tol_days}`. Golden: `[0.5, 0.9]` with `[None, 67]` is
505
+ green
506
+ with statistic 0; `[40, 67]` is red with statistic 27."""
507
+ test_id = "liq.uninsured_share_sensitivity"
508
+ h0 = "the survival period does not lengthen as the uninsured share rises"
509
+ alt = "a higher uninsured share survives longer than a lower one"
510
+ tol = _nonneg_tol(tol_days, "tol_days")
511
+ grid = check_increasing_grid(check_unit_share(shares, "shares"), "shares")
512
+ days = _days(survival_days, "survival_days")
513
+ if days.size != grid.size:
514
+ raise ValueError(f"shares and survival_days: must have the same length, got {grid.size} and {days.size}")
515
+ thresholds = {"tolerance_days": tol}
516
+ version = _version(tolerance_days=tol)
517
+ if days.size < 2:
518
+ return _not_evaluated(test_id, h0, alt, REF_UNINSURED, version, "fewer than 2 shares", n=int(days.size),
519
+ extras={"thresholds": thresholds})
520
+ stat = _largest_increase(days)
521
+ return TestResult(
522
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_UNINSURED, policy_version=version,
523
+ light=Light.GREEN if stat <= tol + EPS else Light.RED, statistic=stat, n=int(days.size),
524
+ inputs_hash=inputs_hash(grid, np.where(np.isinf(days), -1.0, days)),
525
+ extras={"thresholds": thresholds, "survives_horizon": [bool(math.isinf(d)) for d in days]},
526
+ notes="a finite survival period is followed by 'survives the horizon': an unbounded lengthening"
527
+ if math.isinf(stat) else "")
528
+
529
+
530
+ @register(
531
+ "liq.reverse_stress_round_trip",
532
+ family="liquidity",
533
+ name="Reverse stress round trip",
534
+ h0="the survival period at the solved multiplier equals the target",
535
+ reference=REF_REVERSE,
536
+ decision="metric",
537
+ )
538
+ def reverse_stress_round_trip(solved_multiplier: float | None, survival_at_multiplier: int | None, target_days: int,
539
+ tol_days: float = 0.0, *,
540
+ survival_just_below: SurvivalResult | float | None = None) -> TestResult:
541
+ """The reverse stress round trip (dossier 05 line 279): the solved multiplier is the threshold at which the survival
542
+ period reaches the target.
543
+
544
+ Without `survival_just_below` (the 1.1.0 call): statistic = `abs(survival_at_multiplier - target_days)`, metric =
545
+ the multiplier, green when the statistic is at most `tol_days` (the named parameter `round_trip_tolerance_days`),
546
+ red otherwise. With `survival_just_below` (the survival period at `m* - 1e-6`: a `SurvivalResult`, a number of days,
547
+ or `math.inf` for "survives the horizon"), the threshold property is tested: statistic = the larger of the shortfall
548
+ `max(survival_at_multiplier - target_days, 0)` (the multiplier fails to reach the target) and the overshoot
549
+ `max(target_days + 1 - survival_just_below, 0)` (the multiplier is not the smallest one, so the period just below it
550
+ is already at or under the target); green when the statistic is at most `tol_days`, red otherwise. Overshoot is
551
+ measured against `target_days + 1`, the shortest period that does not reach the target. When the curve stepped
552
+ (`survival_at_multiplier` below the target, because the CBC grows over time) the notes give the gap
553
+ `target - SP(m*)` and the light stays green. Not_evaluated with the reason when the multiplier is `None` (a
554
+ refused solve); `extras["thresholds"] = {"tolerance_days": tol_days}`. Golden: `(2.085164, 5, 5)` gives 0 and
555
+ green; `(2.0, 7, 5)` gives 2 and red; `(None, None, 30)` gives not_evaluated;
556
+ `(1.5, 1, 5, survival_just_below=math.inf)` is green with the gap 4 in the notes."""
557
+ test_id = "liq.reverse_stress_round_trip"
558
+ h0 = "the survival period at the solved multiplier equals the target"
559
+ alt = "the survival period at the solved multiplier differs from the target"
560
+ tol = _nonneg_tol(tol_days, "tol_days")
561
+ target = int(_scalar(target_days, "target_days"))
562
+ thresholds = {"tolerance_days": tol}
563
+ version = _version(tolerance_days=tol)
564
+ if solved_multiplier is None or survival_at_multiplier is None:
565
+ return _not_evaluated(test_id, h0, alt, REF_REVERSE, version,
566
+ "the solve was refused, so there is no multiplier to round trip", n=1,
567
+ extras={"thresholds": thresholds, "target_days": target})
568
+ mult = _scalar(solved_multiplier, "solved_multiplier")
569
+ surv = _scalar(survival_at_multiplier, "survival_at_multiplier")
570
+ notes = ""
571
+ if survival_just_below is None:
572
+ stat = abs(surv - target)
573
+ below_hash = -2.0
574
+ else:
575
+ h0 = "the solved multiplier is the threshold: the target is reached at it and not just below it"
576
+ alt = "the solved multiplier does not reach the target, or a smaller multiplier already does"
577
+ if isinstance(survival_just_below, SurvivalResult):
578
+ below = math.inf if survival_just_below.survives else float(survival_just_below.day)
579
+ elif isinstance(survival_just_below, float) and math.isinf(survival_just_below):
580
+ below = math.inf
581
+ else:
582
+ below = _scalar(survival_just_below, "survival_just_below")
583
+ stat = max(surv - target, 0.0, target + 1 - below)
584
+ below_hash = -1.0 if math.isinf(below) else below
585
+ if surv < target:
586
+ notes = (f"the survival period steps past the target: it is {int(surv)} days at the threshold multiplier, "
587
+ f"a gap of {int(target - surv)} days to the target of {target} days")
588
+ return TestResult(
589
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_REVERSE, policy_version=version,
590
+ light=Light.GREEN if stat <= tol + EPS else Light.RED, statistic=stat, metric=mult, n=1,
591
+ inputs_hash=inputs_hash(np.array([mult, surv, target, below_hash])),
592
+ extras={"thresholds": thresholds, "target_days": target}, notes=notes)
593
+
594
+
595
+ @register(
596
+ "liq.htm_revaluation_vs_reported",
597
+ family="liquidity",
598
+ name="HTM revaluation vs reported",
599
+ h0=(
600
+ "the engine's revaluation of the HTM book reproduces the reported fair value within the stated share "
601
+ "of the loss"),
602
+ reference=REF_REVALUATION,
603
+ decision="metric",
604
+ )
605
+ def htm_revaluation_vs_reported(model_fair_value: float | None, reported_fair_value: float, amortised_cost: float,
606
+ green: float = 0.05, amber: float = 0.15) -> TestResult:
607
+ """The HTM book revalued from its maturity profile under the Treasury curve through the engine's `irrbb` curves
608
+ (decision Q11) against the reported fair value `SCHF`. Money in USD thousands.
609
+
610
+ statistic = `abs(model - reported) / abs(reported - amortised)`, the share of the reported unrealised loss. Light (a
611
+ Contraste internal gate): green when the statistic is at most `green`, amber when at most `amber`, red above (the
612
+ named parameters `htm_revaluation_green` and `htm_revaluation_amber`); not_evaluated with the reason when
613
+ `model_fair_value` is `None` or the reported unrealised loss is zero; `extras["thresholds"]` holds both. Golden:
614
+ `reported = 80`, `amortised = 100`: `model = 81` gives 0.05 and green; 82 gives 0.10 and amber; 85 gives 0.25
615
+ and red."""
616
+ test_id = "liq.htm_revaluation_vs_reported"
617
+ h0 = ("the engine's revaluation of the HTM book reproduces the reported fair value within the stated share "
618
+ "of the loss")
619
+ alt = "the revaluation departs from the reported fair value by more than the stated share of the reported loss"
620
+ g, a = _scalar(green, "green"), _scalar(amber, "amber")
621
+ if not 0.0 <= g <= a:
622
+ raise ValueError(f"green and amber: must satisfy 0 <= green <= amber, got {g} and {a}")
623
+ reported = _scalar(reported_fair_value, "reported_fair_value")
624
+ cost = _scalar(amortised_cost, "amortised_cost")
625
+ thresholds = {"green": g, "amber": a}
626
+ version = _version(green=g, amber=a)
627
+ if model_fair_value is None:
628
+ return _not_evaluated(test_id, h0, alt, REF_REVALUATION, version,
629
+ "model_fair_value is None: no revaluation was run", n=1,
630
+ extras={"thresholds": thresholds})
631
+ model = _scalar(model_fair_value, "model_fair_value")
632
+ loss = abs(reported - cost)
633
+ if loss == 0.0:
634
+ return _not_evaluated(test_id, h0, alt, REF_REVALUATION, version,
635
+ "the reported unrealised loss is zero, so its share is undefined", n=1,
636
+ extras={"thresholds": thresholds})
637
+ stat = abs(model - reported) / loss
638
+ return TestResult(
639
+ test_id=test_id, h0=h0, alternative=alt, reference=REF_REVALUATION, policy_version=version,
640
+ light=_three_light_low(stat, g, a), statistic=stat, metric=model - reported, n=1,
641
+ inputs_hash=inputs_hash(np.array([model, reported, cost])), extras={"thresholds": thresholds})
642
+
643
+
644
+ __all__ = ["POLICY_LABEL", "cbc_haircut_rules", "cliff_effect_diagnostic", "htm_loss_effect",
645
+ "htm_revaluation_vs_reported", "list_compounding_golden", "nlp_identity", "reverse_stress_round_trip",
646
+ "runoff_adequacy_back_test", "runoff_vs_generator_truth", "survival_monotone_in_severity",
647
+ "uninsured_share_sensitivity"]