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,476 @@
1
+ """The capital engine of the macro stress test (dossier 05 H.1 layer 3) on a static balance sheet under the EBA rules.
2
+
3
+ Static balance sheet (decision E4; EBA Methodological Note 2025-01-20, addendum F6): paras 33 and 34 maturing assets and
4
+ liabilities are replaced with similar instruments, no workout or cure of S3 assets, no capital measures after the
5
+ reference date, the same business mix; para 90 S3 exposures are not replaced, new S3 exposures move into the stock of S3
6
+ keeping the total constant, no cures, charge-offs or write-offs within the three years; para 91 the initial residual
7
+ maturity is kept; para 92 a constant balance sheet for impairments; para 24 year-end starting figures and a three-year
8
+ horizon.
9
+
10
+ The three-year IAPE projection for the base, the stress without mitigation and the stress with mitigation, and the
11
+ deficit (dossier 03 l.197-206); the internal capital target `OI >= 8% + c_DSIB + c_P2 + c_CCoB + c_CCyB + c_d` of RWA
12
+ (03 l.152-169) with its headroom; the Chilean capital stack (03 G.4, l.911-920); the P2G proxy, a Contraste
13
+ approximation (03 l.1001-1005); the rows of the Annex 3 summary (03 l.232-241; addendum F7). The revenue side (decision
14
+ Q10): the headline CET1 path is loss-only depletion and a labelled row adds PPNR from a stated constant fee and cost
15
+ ratio. Money is one currency and never converted; shares are shares of RWA.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Mapping, Sequence
21
+ from dataclasses import dataclass
22
+
23
+ import numpy as np
24
+
25
+ MIN_PE = 0.08 # the 8 percent minimum effective equity over RWA (03 l.152-169)
26
+ P2R_CAP = 0.04 # the cap of the art. 66 quinquies requirement over RWA (03 l.52, l.253-254)
27
+ CHILEAN_CET1_FLOOR = 0.045 # 4.5 percent CET1 (03 G.4, l.911-920)
28
+ CHILEAN_CONSERVATION = 0.025 # 2.5 percent conservation buffer, art. 66 bis (03 G.4)
29
+ CCYB_MAX = 0.025 # the largest countercyclical buffer the stack accepts (contract engine-stress-api)
30
+ # : the 34 rows of the CMF Annex 3 summary with the labels as printed (addendum F7; Circular 2.365 of 2025-07-08,
31
+ # Resolution 6801;
32
+ # : https://www.cmfchile.cl/portal/principal/623/articles-29808_doc_pdf.pdf, Annex 3 from pdf p.29). The ids 2.T2, 2.AT1
33
+ # and 2.CET1
34
+ #: are the contract's ids for the three unnumbered components of row 2.
35
+ ANNEX3_ROWS: tuple[tuple[str, str], ...] = (
36
+ ("1", "Ratios de capital"),
37
+ ("1.1", "PE / APR"),
38
+ ("1.2", "T1 / APR"),
39
+ ("1.3", "CET1 / APR"),
40
+ ("2", "Patrimonio efectivo"),
41
+ ("2.T2", "T2"),
42
+ ("2.AT1", "AT1"),
43
+ ("2.CET1", "CET1"),
44
+ ("3", "APR"),
45
+ ("4", "Cuantificacion del capital necesario"),
46
+ ("4.1", "Riesgo de credito"),
47
+ ("4.1.1", "Metodo estandar"),
48
+ ("4.1.2", "Modelo interno"),
49
+ ("4.2", "Riesgo de mercado (ME)"),
50
+ ("4.3", "Riesgo operacional (ME)"),
51
+ ("4.4", "Riesgo de concentracion"),
52
+ ("4.4.1", "Individual"),
53
+ ("4.4.2", "Sectorial"),
54
+ ("4.4.3", "Otro tipo"),
55
+ ("4.5", "RMLB"),
56
+ ("4.6", "Riesgo estrategico"),
57
+ ("4.7", "Riesgo reputacional"),
58
+ ("4.8", "Otros riesgos materiales"),
59
+ ("5", "OI"),
60
+ ("6", "Cuantificacion del capital necesario por riesgos no cubiertos en pilar 1 (4.4+4.5+4.6+4.7+4.8)"),
61
+ ("7", "Exigencia minima de PE, en periodo de planificacion (8%+7.1+7.2)"),
62
+ ("7.1", "Exigencia adicional de PE por art.66 quater (banco sistemico)"),
63
+ ("7.2", "Exigencia adicional de PE por art.66 quinquies"),
64
+ (
65
+ "8",
66
+ "Cuantificacion del capital necesario por riesgos no cubiertos en pilar 1, "
67
+ "y no exigidos por art.66 quinquies (6-7.2)",
68
+ ),
69
+ ("9", "Colchones de conservacion y contra ciclico, en periodo de planificacion (art.66 bis y 66 ter)"),
70
+ ("10.1", "Impacto en indice de capital basico de las pruebas de tension severas, sin mitigacion"),
71
+ ("10.2", "Impacto en indice de capital basico de las pruebas de tension severas, con mitigacion"),
72
+ ("11", "Componente d) del OI"),
73
+ ("12", "Holgura de indice de patrimonio efectivo respecto del OI (1.1 - 5)"),
74
+ )
75
+ #: the keys of `internal_capital` of `annex3_summary`, with the Annex 3 row each fills in column D
76
+ INTERNAL_CAPITAL_KEYS = {
77
+ "credit": "4.1.2",
78
+ "concentration_individual": "4.4.1",
79
+ "concentration_sectoral": "4.4.2",
80
+ "concentration_other": "4.4.3",
81
+ "irrbb": "4.5",
82
+ "strategic": "4.6",
83
+ "reputational": "4.7",
84
+ "other": "4.8",
85
+ }
86
+ PLAN_CASES = ("base", "stress-without-mitigation", "stress-with-mitigation")
87
+
88
+
89
+ def _num(x: float, name: str) -> float:
90
+ try:
91
+ v = float(x)
92
+ except (TypeError, ValueError) as exc:
93
+ raise ValueError(f"{name} is not a number") from exc
94
+ if not np.isfinite(v):
95
+ raise ValueError(f"{name} is non-finite")
96
+ return v
97
+
98
+
99
+ def _series(x: Sequence[float], name: str) -> np.ndarray:
100
+ a = np.array(x, dtype=float)
101
+ if a.ndim != 1 or a.size == 0:
102
+ raise ValueError(f"{name} must be a non-empty one-dimensional series, got shape {a.shape}")
103
+ if not np.all(np.isfinite(a)):
104
+ raise ValueError(f"{name} contains non-finite values")
105
+ return a
106
+
107
+
108
+ def _share(x: float, name: str) -> float:
109
+ v = _num(x, name)
110
+ if v < 0.0:
111
+ raise ValueError(f"{name} must not be negative, got {v}")
112
+ return v
113
+
114
+
115
+ # ----------------------------------------------------------------------------------------------------------------
116
+ # The headline path and the PPNR row
117
+
118
+
119
+ def cet1_path_loss_only(cet1_0: float, losses: Sequence[float]) -> np.ndarray:
120
+ """Loss-only depletion (decision Q10): the CET1 at each year end is the CET1 at the jump-off less the cumulated
121
+ losses of the
122
+ years so far, with no revenue invented. `losses` (Y,) are not negative; returns (Y,)."""
123
+ start = _num(cet1_0, "cet1_0")
124
+ loss = _series(losses, "losses")
125
+ if np.any(loss < 0.0):
126
+ raise ValueError("losses must not be negative")
127
+ return start - np.cumsum(loss)
128
+
129
+
130
+ @dataclass(frozen=True)
131
+ class PpnrRow:
132
+ """A labelled PPNR row (never the headline); maps onto the document row `headline_cet1.ppnr.rows[*]`."""
133
+
134
+ nii: float
135
+ fee_income: float
136
+ operating_cost: float
137
+ ppnr: float
138
+
139
+
140
+ def ppnr_row(nii: float, fee_ratio: float, cost_ratio: float) -> PpnrRow:
141
+ """`fee_income = fee_ratio * nii`, `operating_cost = cost_ratio * (nii + fee_income)`, `ppnr = nii + fee_income -
142
+ operating_cost`. Both ratios are decimals in [0, 1] and named assumptions of the case (decision Q10); their
143
+ definitions are the contract's proposal (the Federal Reserve's efficiency-ratio element of the 2026 PPNR suite, 05
144
+ H.3, is the precedent for a
145
+ cost ratio; the dossiers give no model for PPNR, 05 l.402)."""
146
+ n = _num(nii, "nii")
147
+ fr, cr = _num(fee_ratio, "fee_ratio"), _num(cost_ratio, "cost_ratio")
148
+ for name, v in (("fee_ratio", fr), ("cost_ratio", cr)):
149
+ if not 0.0 <= v <= 1.0:
150
+ raise ValueError(f"the ratio {name} must lie in [0, 1], got {v}")
151
+ fee = fr * n
152
+ cost = cr * (n + fee)
153
+ return PpnrRow(nii=n, fee_income=fee, operating_cost=cost, ppnr=n + fee - cost)
154
+
155
+
156
+ # ----------------------------------------------------------------------------------------------------------------
157
+ # The internal capital target and the Chilean stack
158
+
159
+
160
+ @dataclass(frozen=True)
161
+ class InternalTarget:
162
+ """The internal effective-equity target `OI`; shares of RWA; maps onto the block `internal_capital_target`."""
163
+
164
+ min_pe: float # 0.08
165
+ c_dsib: float
166
+ c_p2: float
167
+ c_ccob: float
168
+ c_ccyb: float
169
+ c_d: float
170
+ oi: float
171
+ p2r: float = 0.0 # the art. 66 quinquies requirement (Annex 3 rows 7 and 7.2), at most `c_p2`
172
+
173
+
174
+ def internal_capital_target(
175
+ c_dsib: float, c_p2: float, c_ccob: float, c_ccyb: float, c_d: float, p2r: float = 0.0
176
+ ) -> InternalTarget:
177
+ """`OI = 8% + c_DSIB + c_P2 + c_CCoB + c_CCyB + c_d` of RWA (03 l.152-169). `p2r` is the art. 66 quinquies
178
+ requirement, the floor of `c_p2` (`c_P2,bank >= c_66 quinquies`); `p2r` is bounded by the 4 percent cap of RWA (03
179
+ l.52, l.253-254) and `c_p2` is the bank's own estimate, at least `p2r`, with no cap. `c_p2` and `c_d` are labelled
180
+ assumptions of the case (decision Q4);
181
+ `c_d` may be zero (03 B.2: "podria ser nula")."""
182
+ parts = {
183
+ "c_dsib": _share(c_dsib, "c_dsib"),
184
+ "c_p2": _share(c_p2, "c_p2"),
185
+ "c_ccob": _share(c_ccob, "c_ccob"),
186
+ "c_ccyb": _share(c_ccyb, "c_ccyb"),
187
+ "c_d": _share(c_d, "c_d"),
188
+ }
189
+ req = _share(p2r, "p2r")
190
+ if req > P2R_CAP:
191
+ raise ValueError(
192
+ f"p2r = {req} is above the {P2R_CAP} cap of RWA on the art. 66 quinquies requirement (03 l.253)"
193
+ )
194
+ if parts["c_p2"] < req:
195
+ raise ValueError(
196
+ f"c_p2 = {parts['c_p2']} is below p2r = {req}: the bank's estimate includes the art. 66 quinquies "
197
+ "requirement"
198
+ )
199
+ oi = MIN_PE + parts["c_dsib"] + parts["c_p2"] + parts["c_ccob"] + parts["c_ccyb"] + parts["c_d"]
200
+ return InternalTarget(
201
+ min_pe=MIN_PE,
202
+ c_dsib=parts["c_dsib"],
203
+ c_p2=parts["c_p2"],
204
+ c_ccob=parts["c_ccob"],
205
+ c_ccyb=parts["c_ccyb"],
206
+ c_d=parts["c_d"],
207
+ oi=oi,
208
+ p2r=req,
209
+ )
210
+
211
+
212
+ def chilean_cet1_stack(c_ccyb: float, c_dsib: float, p2_cet1: float) -> float:
213
+ """The minimum CET1/RWA of the Chilean legal stack `4.5% + 2.5% + RCC + c_DSIB + the CET1 share of c_P2` (03 G.4,
214
+ l.911-920; RAN 21-13): the failure point of the reverse stress (decision Q11). Shares of RWA; the countercyclical
215
+ buffer is at most
216
+ 0.025."""
217
+ ccyb, dsib, p2 = _share(c_ccyb, "c_ccyb"), _share(c_dsib, "c_dsib"), _share(p2_cet1, "p2_cet1")
218
+ if ccyb > CCYB_MAX:
219
+ raise ValueError(f"c_ccyb = {ccyb} is above {CCYB_MAX}")
220
+ return CHILEAN_CET1_FLOOR + CHILEAN_CONSERVATION + ccyb + dsib + p2
221
+
222
+
223
+ # ----------------------------------------------------------------------------------------------------------------
224
+ # The three-year plan
225
+
226
+
227
+ @dataclass(frozen=True)
228
+ class PlanYear:
229
+ """One year of a capital-plan case; maps onto the document rows `capital_plan.cases[*].years[*]`."""
230
+
231
+ year: int # 1 to 3
232
+ rwa: float
233
+ cet1: float
234
+ at1: float
235
+ t2: float
236
+ pe: float # cet1 + at1 + t2
237
+ requirement_pct: float
238
+ pe_pct: float
239
+ headroom_pct: float # pe_pct - requirement_pct
240
+ deficit: float # max(0, requirement_pct * rwa - pe)
241
+
242
+
243
+ def _years(rwa: float, cet1: np.ndarray, at1: float, t2: float, requirement: float) -> tuple[PlanYear, ...]:
244
+ out = []
245
+ for k, c1 in enumerate(cet1, start=1):
246
+ pe = float(c1) + at1 + t2
247
+ pct = pe / rwa
248
+ out.append(
249
+ PlanYear(
250
+ year=k,
251
+ rwa=rwa,
252
+ cet1=float(c1),
253
+ at1=at1,
254
+ t2=t2,
255
+ pe=pe,
256
+ requirement_pct=requirement,
257
+ pe_pct=pct,
258
+ headroom_pct=pct - requirement,
259
+ deficit=max(0.0, requirement * rwa - pe),
260
+ )
261
+ )
262
+ return tuple(out)
263
+
264
+
265
+ def capital_plan(
266
+ rwa: float,
267
+ cet1_0: float,
268
+ at1: float,
269
+ t2: float,
270
+ base_cet1: Sequence[float],
271
+ stress_losses: Sequence[float],
272
+ mitigation_effects: Sequence[float],
273
+ oi: float,
274
+ legal_minimum: float,
275
+ ) -> dict[str, tuple[PlanYear, ...]]:
276
+ """The three cases of the IAPE projection (03 l.197-206): `base` (CET1 from the caller's baseline, requirement
277
+ `oi`), `stress-without-mitigation` (CET1 from `cet1_path_loss_only`, requirement `legal_minimum`) and `stress-with-
278
+ mitigation` (the loss-only path plus the cumulated mitigation effects, requirement `legal_minimum`).
279
+
280
+ Static balance sheet (para 33): `rwa` is the same every year, and AT1 and T2 stay at their jump-off values in every
281
+ case (no capital measure after the reference date). `mitigation_effects` are the effect of the mitigation actions on
282
+ CET1 of each year, not cumulated, and not negative (a mitigation action that lowered CET1 would break the rule that
283
+ the mitigated PE is never
284
+ below the unmitigated one)."""
285
+ r = _num(rwa, "rwa")
286
+ if r <= 0.0:
287
+ raise ValueError("rwa must be positive")
288
+ start = _num(cet1_0, "cet1_0")
289
+ a1, t = _share(at1, "at1"), _share(t2, "t2")
290
+ base = _series(base_cet1, "base_cet1")
291
+ loss = _series(stress_losses, "stress_losses")
292
+ mit = _series(mitigation_effects, "mitigation_effects")
293
+ if not base.size == loss.size == mit.size:
294
+ raise ValueError(
295
+ f"base_cet1, stress_losses and mitigation_effects must have the same length, got {base.size}, "
296
+ f"{loss.size} and {mit.size}"
297
+ )
298
+ if np.any(mit < 0.0):
299
+ raise ValueError("mitigation_effects must not be negative")
300
+ target, legal = _share(oi, "oi"), _share(legal_minimum, "legal_minimum")
301
+ stressed = cet1_path_loss_only(start, loss)
302
+ return {
303
+ "base": _years(r, base, a1, t, target),
304
+ "stress-without-mitigation": _years(r, stressed, a1, t, legal),
305
+ "stress-with-mitigation": _years(r, stressed + np.cumsum(mit), a1, t, legal),
306
+ }
307
+
308
+
309
+ def p2g_proxy(cet1_ratio_0: float, cet1_ratios_severe: Sequence[float], usable_buffers_and_mitigation: float) -> float:
310
+ """`max(0, max_t [(CET1/RWA)_0 - (CET1/RWA)_t severe] - usable)` (03 l.1001-1005, FAQ 24: "the maximum deterioration
311
+ inside the three-year projection horizon", referenced to CET1/RWA). A Contraste approximation: the CMF calibration
312
+ grid is not public
313
+ and the value is not a P2G requirement; the document block carries the label `contraste-approximation`."""
314
+ start = _num(cet1_ratio_0, "cet1_ratio_0")
315
+ severe = _series(cet1_ratios_severe, "cet1_ratios_severe")
316
+ usable = _share(usable_buffers_and_mitigation, "usable_buffers_and_mitigation")
317
+ return max(0.0, float(np.max(start - severe)) - usable)
318
+
319
+
320
+ # ----------------------------------------------------------------------------------------------------------------
321
+ # The Annex 3 summary
322
+
323
+ _NA = {"value": None, "status": "not-applicable"}
324
+ _RI = {"value": None, "status": "RI"}
325
+ _NTF = {"value": None, "status": "not-to-be-filled"}
326
+
327
+
328
+ def _v(x: float) -> dict:
329
+ return {"value": float(x), "status": "value"}
330
+
331
+
332
+ def _need(mapping: Mapping, key: str, what: str) -> object:
333
+ if key not in mapping:
334
+ raise ValueError(f"{what} has no key {key!r}")
335
+ return mapping[key]
336
+
337
+
338
+ def annex3_summary(
339
+ capital: Mapping[str, float],
340
+ target: InternalTarget,
341
+ rwa_by_risk: Mapping[str, float],
342
+ internal_capital: Mapping[str, float | None],
343
+ plan: Mapping[str, tuple[PlanYear, ...]],
344
+ mitigation_applies: bool,
345
+ ) -> tuple[dict, ...]:
346
+ """The 34 rows of the CMF Annex 3 summary (`ANNEX3_ROWS`), each `{"row_id", "label_cmf", "a", "b", "c", "d"}` with
347
+ the four columns A (percent of RWA), B (amount), C (legal requirement) and D (internal measurement) as cells
348
+ `{"value", "status"}` of status `value`, `RI` (an immaterial risk), `not-to-be-filled` (market and operational risk
349
+ under the standardised method) or `not-applicable`.
350
+
351
+ `capital` holds `cet1`, `at1` and `t2` in money (CLP millions in the product; the form states thousand pesos);
352
+ `rwa_by_risk` holds `credit`, `market` and `operational`, and RWA is their sum; `internal_capital` holds one key per
353
+ `INTERNAL_CAPITAL_KEYS` with the internal capital of the risk in money, or None for an immaterial risk (status
354
+ `RI`); `plan` is the `capital_plan` result (the two stress cases give rows 10.1 and 10.2);
355
+ its RWA must equal the sum of `rwa_by_risk` (relative difference at most 1e-9), else `ValueError` naming both
356
+ values. Rows 7, 7.2 and 8 read the target's `p2r` (the art. 66 quinquies requirement), never `c_p2` (the bank's own
357
+ estimate, which only enters the OI of row 5). Row 10.1 is the largest fall of CET1/RWA from the jump-off in the
358
+ stress without mitigation, row 10.2 the same with mitigation, `not-applicable` when `mitigation_applies` is false
359
+ (the form: "N/A if the stress leads to no mitigation actions")."""
360
+ cet1 = _share(_need(capital, "cet1", "capital"), "capital['cet1']")
361
+ at1 = _share(_need(capital, "at1", "capital"), "capital['at1']")
362
+ t2 = _share(_need(capital, "t2", "capital"), "capital['t2']")
363
+ rwa_risk = {
364
+ k: _share(_need(rwa_by_risk, k, "rwa_by_risk"), f"rwa_by_risk[{k!r}]")
365
+ for k in ("credit", "market", "operational")
366
+ }
367
+ rwa = sum(rwa_risk.values())
368
+ if rwa <= 0.0:
369
+ raise ValueError("the RWA (the sum of rwa_by_risk) must be positive")
370
+ internal: dict[str, float | None] = {}
371
+ for key in INTERNAL_CAPITAL_KEYS:
372
+ raw = _need(internal_capital, key, "internal_capital")
373
+ internal[key] = None if raw is None else _share(raw, f"internal_capital[{key!r}]")
374
+ plans = {}
375
+ for case in (
376
+ ("stress-without-mitigation", "stress-with-mitigation")
377
+ if mitigation_applies
378
+ else ("stress-without-mitigation",)
379
+ ):
380
+ years = _need(plan, case, "plan")
381
+ if not years:
382
+ raise ValueError(f"plan[{case!r}] has no years")
383
+ plans[case] = years
384
+ for case, years in plans.items():
385
+ plan_rwa = years[0].rwa
386
+ if abs(plan_rwa - rwa) > 1e-9 * max(abs(plan_rwa), abs(rwa)):
387
+ raise ValueError(
388
+ f"the RWA of rwa_by_risk ({rwa!r}) differs from the RWA of plan[{case!r}] ({plan_rwa!r})"
389
+ )
390
+ cet1_ratio = cet1 / rwa
391
+ pe = cet1 + at1 + t2
392
+ legal = {
393
+ "credit": MIN_PE * rwa_risk["credit"],
394
+ "market": MIN_PE * rwa_risk["market"],
395
+ "operational": MIN_PE * rwa_risk["operational"],
396
+ }
397
+
398
+ def internal_cell(key: str) -> dict:
399
+ return _RI if internal[key] is None else _v(internal[key])
400
+
401
+ quantified = [v for k, v in internal.items() if k != "credit" and v is not None]
402
+ row6 = float(sum(quantified))
403
+ row7a = target.min_pe + target.c_dsib + target.p2r
404
+ cells: dict[str, tuple[dict, dict, dict, dict]] = {
405
+ "1": (_NA, _NA, _NA, _NA),
406
+ "1.1": (_v(pe / rwa), _v(pe), _NA, _NA),
407
+ "1.2": (_v((cet1 + at1) / rwa), _v(cet1 + at1), _NA, _NA),
408
+ "1.3": (_v(cet1_ratio), _v(cet1), _NA, _NA),
409
+ "2": (_v(pe / rwa), _v(pe), _NA, _NA),
410
+ "2.T2": (_v(t2 / rwa), _v(t2), _NA, _NA),
411
+ "2.AT1": (_v(at1 / rwa), _v(at1), _NA, _NA),
412
+ "2.CET1": (_v(cet1_ratio), _v(cet1), _NA, _NA),
413
+ "3": (_v(1.0), _v(rwa), _NA, _NA),
414
+ "4": (_NA, _NA, _v(MIN_PE * rwa), _NA),
415
+ "4.1": (_NA, _NA, _v(legal["credit"]), _NA),
416
+ "4.1.1": (_NA, _NA, _v(legal["credit"]), _NA),
417
+ "4.1.2": (_NA, _NA, _NA, internal_cell("credit")),
418
+ "4.2": (_NA, _NA, _v(legal["market"]), _NTF),
419
+ "4.3": (_NA, _NA, _v(legal["operational"]), _NTF),
420
+ "4.4": (_NA, _NA, _NA, _NA),
421
+ "4.4.1": (_NA, _NA, _NA, internal_cell("concentration_individual")),
422
+ "4.4.2": (_NA, _NA, _NA, internal_cell("concentration_sectoral")),
423
+ "4.4.3": (_NA, _NA, _NA, internal_cell("concentration_other")),
424
+ "4.5": (_NA, _NA, _NA, internal_cell("irrbb")),
425
+ "4.6": (_NA, _NA, _NA, internal_cell("strategic")),
426
+ "4.7": (_NA, _NA, _NA, internal_cell("reputational")),
427
+ "4.8": (_NA, _NA, _NA, internal_cell("other")),
428
+ "5": (_v(target.oi), _v(target.oi * rwa), _NA, _NA),
429
+ "6": (_v(row6 / rwa), _v(row6), _NA, _NA),
430
+ "7": (_v(row7a), _v(row7a * rwa), _NA, _NA),
431
+ "7.1": (_v(target.c_dsib), _v(target.c_dsib * rwa), _NA, _NA),
432
+ "7.2": (_v(target.p2r), _v(target.p2r * rwa), _NA, _NA),
433
+ "8": (_v(row6 / rwa - target.p2r), _v(row6 - target.p2r * rwa), _NA, _NA),
434
+ "9": (_v(target.c_ccob + target.c_ccyb), _v((target.c_ccob + target.c_ccyb) * rwa), _NA, _NA),
435
+ "11": (_v(target.c_d), _v(target.c_d * rwa), _NA, _NA),
436
+ "12": (_v(pe / rwa - target.oi), _v(pe - target.oi * rwa), _NA, _NA),
437
+ }
438
+ for row_id, case in (("10.1", "stress-without-mitigation"), ("10.2", "stress-with-mitigation")):
439
+ if case not in plans:
440
+ cells[row_id] = (_NA, _NA, _NA, _NA)
441
+ else:
442
+ fall = max(cet1_ratio - y.cet1 / y.rwa for y in plans[case])
443
+ cells[row_id] = (_v(fall), _NA, _NA, _NA)
444
+ return tuple(
445
+ {"row_id": rid, "label_cmf": label, "a": a, "b": b, "c": c, "d": d}
446
+ for (rid, label) in ANNEX3_ROWS
447
+ for (a, b, c, d) in (cells[rid],)
448
+ )
449
+
450
+
451
+ # ----------------------------------------------------------------------------------------------------------------
452
+ # The EBA static balance sheet
453
+
454
+
455
+ def eba_static_balance_sheet(stage_balances: np.ndarray, new_s3_flows: np.ndarray) -> np.ndarray:
456
+ """The stage balances after each period under the para 90 rule: the new stage 3 exposures of a period move into the
457
+ stock of stage 3 and reduce stages 1 and 2 pro rata to their balances, the total exposure is constant, nothing
458
+ leaves stage 3 (no cures, charge-offs or write-offs) and nothing is replaced. `stage_balances` (3,) in stages 1, 2,
459
+ 3; `new_s3_flows` (H,); returns
460
+ (H, 3). A flow larger than stages 1 plus 2 is refused."""
461
+ s = np.array(stage_balances, dtype=float)
462
+ f = _series(new_s3_flows, "new_s3_flows")
463
+ if s.shape != (3,) or not np.all(np.isfinite(s)) or np.any(s < 0.0):
464
+ raise ValueError(f"stage_balances must be three non-negative balances (stages 1, 2, 3), got {s.tolist()}")
465
+ if np.any(f < 0.0):
466
+ raise ValueError("new_s3_flows must not be negative: nothing leaves stage 3")
467
+ out = np.empty((f.size, 3))
468
+ for h, flow in enumerate(f):
469
+ s12 = s[0] + s[1]
470
+ if flow > s12 + 1e-12 * max(1.0, s12):
471
+ raise ValueError(f"new_s3_flows[{h}] = {flow} is larger than stages 1 plus 2 ({s12})")
472
+ if flow > 0.0:
473
+ share = min(1.0, flow / s12)
474
+ s = np.array([s[0] - s[0] * share, s[1] - s[1] * share, s[2] + flow])
475
+ out[h] = s
476
+ return out
@@ -0,0 +1,108 @@
1
+ """Scenario path handling: the shape of a published path (its change from its jump-off) transposed onto the last
2
+ observed value, reversion to the baseline after the published horizon, annual to quarterly conversion, deviation paths,
3
+ and the check that a path's vintage does not postdate the observation date (SDD l.169).
4
+
5
+ The engine form of the rule `cases/c06/macro.py` applies in the product (R14 of the unit sizing); `REVERSION_QUARTERS`
6
+ is that module's product convention (a convention, not a source value). A path keeps the unit of its source (percent for
7
+ the Federal Reserve and EBA paths).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import datetime as _dt
13
+
14
+ import numpy as np
15
+
16
+ #: the product convention of `cases/c06/macro.py`; the models field `capital_engine.reversion_quarters`
17
+ REVERSION_QUARTERS = 12
18
+
19
+
20
+ def _vec(x: object, name: str) -> np.ndarray:
21
+ a = np.array(x, dtype=float)
22
+ if a.ndim != 1 or a.size == 0:
23
+ raise ValueError(f"{name} must be a non-empty one-dimensional array, got shape {a.shape}")
24
+ if not np.all(np.isfinite(a)):
25
+ raise ValueError(f"{name} contains non-finite values")
26
+ return a
27
+
28
+
29
+ def _num(x: float, name: str) -> float:
30
+ v = float(x)
31
+ if not np.isfinite(v):
32
+ raise ValueError(f"{name} is non-finite")
33
+ return v
34
+
35
+
36
+ def transpose_path(levels: np.ndarray, source_jump_off: float, target_value: float, n: int) -> np.ndarray:
37
+ """`target_value + (levels - source_jump_off)` for the first `n` periods, aligned by their distance from the jump-
38
+ off
39
+ (decision Q6): the shape of the published path on the last observed value."""
40
+ lv = _vec(levels, "levels")
41
+ jump, target = _num(source_jump_off, "source_jump_off"), _num(target_value, "target_value")
42
+ if int(n) != n or n < 1:
43
+ raise ValueError(f"n must be a positive integer, got {n!r}")
44
+ if n > lv.size:
45
+ raise ValueError(f"n = {n} is above the {lv.size} periods of levels (extend with revert_to_baseline)")
46
+ return target + (lv[: int(n)] - jump)
47
+
48
+
49
+ def revert_to_baseline(path: np.ndarray, baseline_tail: float, n: int, reversion_quarters: int) -> np.ndarray:
50
+ """Past the published horizon the path reverts linearly to the baseline tail: for `k > len(path)`,
51
+ `w = min(1, (k - len(path)) / reversion_quarters)` and `value = path[-1] + w (baseline_tail - path[-1])`; the first
52
+ `len(path)` values are unchanged. `n` is the number of periods returned (`n >= len(path)`)."""
53
+ p = _vec(path, "path")
54
+ tail = _num(baseline_tail, "baseline_tail")
55
+ if int(reversion_quarters) != reversion_quarters or reversion_quarters < 1:
56
+ raise ValueError(f"reversion_quarters must be an integer of at least 1, got {reversion_quarters!r}")
57
+ if int(n) != n or n < p.size:
58
+ raise ValueError(f"n = {n} is below the {p.size} periods of path")
59
+ out = np.empty(int(n))
60
+ out[: p.size] = p
61
+ k = np.arange(p.size + 1, int(n) + 1)
62
+ w = np.minimum(1.0, (k - p.size) / float(reversion_quarters))
63
+ out[p.size :] = p[-1] + w * (tail - p[-1])
64
+ return out
65
+
66
+
67
+ def annual_to_quarterly(year_end_levels: np.ndarray, jump_off_level: float) -> np.ndarray:
68
+ """Quarter `k` (1 to 4) of year `y` is `prev + (cur - prev) k / 4`: the year-end levels joined linearly from the
69
+ jump-off level; the fourth quarter equals the year-end level. Whether the EBA workbook values are year averages or
70
+ year-end values is
71
+ UNVERIFIED in the research record (F6); they are treated as year-end levels."""
72
+ ye = _vec(year_end_levels, "year_end_levels")
73
+ prev = np.concatenate([[_num(jump_off_level, "jump_off_level")], ye[:-1]])
74
+ k = np.arange(1, 5) / 4.0
75
+ out = prev[:, None] + (ye - prev)[:, None] * k[None, :]
76
+ out[:, 3] = ye # the fourth quarter is the year-end level itself, with no rounding of the join
77
+ return out.reshape(-1)
78
+
79
+
80
+ def level_from_deviation(baseline: np.ndarray, deviation: np.ndarray, kind: str) -> np.ndarray:
81
+ """A level from a deviation of the baseline run: `plus` is `baseline + deviation` (rates, unemployment), `percent`
82
+ is
83
+ `baseline * (1 + deviation / 100)` (GDP, a percent difference). NGFS scenario runs hold deviations from the Baseline
84
+ run (F8)."""
85
+ b, d = np.array(baseline, dtype=float), np.array(deviation, dtype=float)
86
+ if kind not in ("plus", "percent"):
87
+ raise ValueError(f"unknown kind {kind!r}: expected 'plus' or 'percent'")
88
+ if b.shape != d.shape:
89
+ raise ValueError(f"baseline and deviation must have the same shape, got {b.shape} and {d.shape}")
90
+ if not (np.all(np.isfinite(b)) and np.all(np.isfinite(d))):
91
+ raise ValueError("baseline or deviation contains non-finite values")
92
+ return b + d if kind == "plus" else b * (1.0 + d / 100.0)
93
+
94
+
95
+ def _date(s: str, name: str) -> _dt.date:
96
+ try:
97
+ return _dt.date.fromisoformat(str(s))
98
+ except ValueError as exc:
99
+ raise ValueError(f"{name} {s!r} is not an ISO date") from exc
100
+
101
+
102
+ def check_vintage(vintage_date: str, observation_date: str) -> None:
103
+ """Reject a path whose vintage postdates the model's observation date (SDD l.169, the `macro_path` family rule);
104
+ equal
105
+ dates pass."""
106
+ v, o = _date(vintage_date, "vintage_date"), _date(observation_date, "observation_date")
107
+ if v > o:
108
+ raise ValueError(f"the vintage {vintage_date} postdates the observation date {observation_date}")