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,360 @@
1
+ r"""CMF CNCB Chapter B-1 provisions (Chile): the standard methods for group portfolios, the individual-assessment
2
+ categories, the default portfolio, the 0.50% minimum and the additional provisions.
3
+
4
+ Source: Contraste dossier 03 sections D.2 to D.6, read from the CMF "Compendio de Normas Contables para Bancos"
5
+ (CNCB, https://www.cmfchile.cl/portal/normativa/624/articles-29177_doc_pdf.pdf, read 2026-10-04; base Circular 2.243 of
6
+ 2019-12-20, later circulars to 2.346 of 2024-03-06). Every table below is transcribed cell by cell from that
7
+ dossier, with its source paragraph in a comment. Parameters are decimals: 1.0916 per cent is 0.010916. The B-1
8
+ provision factor is PE = PI x PDI (B-1 N 3.1).
9
+
10
+ Chilean loan provisions in local statutory accounts are B-1, not IFRS 9 impairment: CNCB Chapter A-2 N 5 does not
11
+ apply IFRS 9 Chapter 5.5 to loans and contingent credits (dossier 03 D.1, dossier 02 F.5). This module keeps the two
12
+ regimes apart and computes no expected credit loss in the IFRS 9 sense. The functions compute; they state no
13
+ compliance claim. The CMF reform proposal of August 2026 (dossier 03 D.7: recalibrated PI scale, internal methods,
14
+ collateral as LGD) is not in force and is not implemented here.
15
+
16
+ The additional provisions (B-1 N 9) are a separate line (:func:`b1_additional_provisions`); no function of this module
17
+ adds them to a comparable B-1 total, and the 0.50% minimum applies to the individually assessed normal portfolio
18
+ only (:func:`b1_minimum_normal_check`).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ from dataclasses import dataclass
25
+
26
+ # --------------------------------------------------------------------------------------------------------------
27
+ # B-1 N 2.1 "Hoja 3": individual assessment, Normal (A1 to A6) and Subestandar (B1 to B4). (PI, PDI, PE) decimals.
28
+ # Dossier 03 D.3.
29
+ _INDIVIDUAL: dict[str, tuple[float, float, float]] = {
30
+ "A1": (0.0004, 0.9, 0.00036),
31
+ "A2": (0.001, 0.825, 0.000825),
32
+ "A3": (0.0025, 0.875, 0.0021875),
33
+ "A4": (0.02, 0.875, 0.0175),
34
+ "A5": (0.0475, 0.9, 0.04275),
35
+ "A6": (0.1, 0.9, 0.09),
36
+ "B1": (0.15, 0.925, 0.13875),
37
+ "B2": (0.22, 0.925, 0.2035),
38
+ "B3": (0.33, 0.975, 0.32175),
39
+ "B4": (0.45, 0.975, 0.43875),
40
+ }
41
+
42
+ # B-1 N 2.2 "Hoja 8": default portfolio. (inclusive upper bound of TPE, PP); C6 has no upper bound. Dossier 03 D.3.
43
+ _DEFAULT_BUCKETS: tuple[tuple[str, float | None, float], ...] = (
44
+ ("C1", 0.03, 0.02),
45
+ ("C2", 0.20, 0.10),
46
+ ("C3", 0.30, 0.25),
47
+ ("C4", 0.50, 0.40),
48
+ ("C5", 0.80, 0.65),
49
+ ("C6", None, 0.90),
50
+ )
51
+
52
+ _DPD = ("0", "1-29", "30-59", "60-89", "default")
53
+
54
+ # B-1 N 3.1.1, Circular 2.346 "Hoja 11": residential mortgages (and residential leasing), dossier 03 D.5.
55
+ # PVG buckets <= 40%, <= 80%, <= 90%, > 90%; columns are _DPD. PE is the transcribed cell (it equals PI x PDI within the
56
+ # table's own rounding of 5e-7 as a decimal).
57
+ _MORTGAGE_PVG_UPPER = (0.40, 0.80, 0.90, None)
58
+ _MORTGAGE_PI = (
59
+ (0.010916, 0.213407, 0.460536, 0.751614, 1.0),
60
+ (0.019158, 0.274332, 0.520824, 0.789511, 1.0),
61
+ (0.02515, 0.2793, 0.5258, 0.796952, 1.0),
62
+ (0.0274, 0.2843, 0.5308, 0.803677, 1.0),
63
+ )
64
+ _MORTGAGE_PDI = (
65
+ (0.000225, 0.000441, 0.000482, 0.000482, 0.000537),
66
+ (0.021955, 0.028233, 0.029192, 0.029192, 0.030413),
67
+ (0.215527, 0.2166, 0.2192, 0.221331, 0.22231),
68
+ (0.272, 0.2903, 0.2959, 0.301558, 0.302436),
69
+ )
70
+ _MORTGAGE_PE = (
71
+ (0.000002, 0.000094, 0.000222, 0.000362, 0.000537),
72
+ (0.000421, 0.007745, 0.015204, 0.023047, 0.030413),
73
+ (0.005421, 0.060496, 0.115255, 0.17639, 0.22231),
74
+ (0.007453, 0.082532, 0.157064, 0.242355, 0.302436),
75
+ )
76
+
77
+ # B-1 N 3.1.2 (a): commercial leasing, dossier 03 D.5. PI by days past due; PDI by PVB bucket.
78
+ _LEASING_PI = {
79
+ True: (0.0079, 0.0794, 0.2876, 0.5876, 1.0), # real estate
80
+ False: (0.0161, 0.1202, 0.4088, 0.6938, 1.0), # non real estate
81
+ }
82
+ _LEASING_PVB_UPPER = (0.40, 0.50, 0.80, 0.90, None)
83
+ _LEASING_PDI = {
84
+ True: (0.0005, 0.0005, 0.051, 0.232, 0.362),
85
+ False: (0.182, 0.57, 0.684, 0.751, 0.789),
86
+ }
87
+
88
+ # B-1 N 3.1.2 (b): student loans, dossier 03 D.5. When payment is due: PI by days past due, one PDI; not due: one PI and
89
+ # one PDI per scheme.
90
+ _STUDENT_PI_DUE = {
91
+ "CAE": (0.052, 0.372, 0.59, 0.728, 1.0),
92
+ "CORFO": (0.029, 0.15, 0.434, 0.719, 1.0),
93
+ }
94
+ _STUDENT_PDI_DUE = 0.709
95
+ _STUDENT_NOT_DUE = {"CAE": (0.416, 0.503), "CORFO": (0.165, 0.458)} # (PI, PDI)
96
+
97
+ # B-1 N 3.1.2 (c): generic commercial loans and factoring, dossier 03 D.5.
98
+ _COMMERCIAL_PI_GUARANTEE_LE_100 = (0.0186, 0.116, 0.2533, 0.4131, 1.0)
99
+ _COMMERCIAL_PI_GUARANTEE_GT_100 = (0.0268, 0.1345, 0.2692, 0.4131, 1.0)
100
+ _COMMERCIAL_PI_NO_GUARANTEE = (0.0491, 0.2293, 0.453, 0.6163, 1.0)
101
+ _COMMERCIAL_PTVG_UPPER = (0.60, 0.75, 0.90, None)
102
+ _COMMERCIAL_PDI_GUARANTEE = (0.05, 0.203, 0.322, 0.43)
103
+ _COMMERCIAL_PDI_GUARANTEE_RECOURSE = (0.032, 0.128, 0.203, 0.271)
104
+ _COMMERCIAL_PDI_NO_GUARANTEE = 0.569
105
+ _COMMERCIAL_PDI_NO_GUARANTEE_RECOURSE = 0.359
106
+
107
+ # B-1 N 3.1.3, Circular 2.346: consumer loans, dossier 03 D.5. Rows: maximum days past due in the bank 0-7, 8-30, 31-60,
108
+ # 61-89; columns: (mortgage, no 30+ system arrears), (mortgage, 30+ system arrears), (no mortgage, no arrears),
109
+ # (no mortgage, arrears). Defaulted debtors (90 days or more) have PI 1.
110
+ _CONSUMER_ROW_UPPER = (7, 30, 60, 89)
111
+ _CONSUMER_PI = (
112
+ (0.033, 0.146, 0.066, 0.198),
113
+ (0.204, 0.416, 0.306, 0.485),
114
+ (0.502, 0.63, 0.651, 0.663),
115
+ (0.626, 0.817, 0.723, 0.869),
116
+ )
117
+ _CONSUMER_PRODUCTS = ("leasing-auto", "instalment", "cards-lines-other")
118
+ _CONSUMER_PDI_MORTGAGE = (0.332, 0.477, 0.495)
119
+ _CONSUMER_PDI_NO_MORTGAGE = (0.332, 0.566, 0.603)
120
+
121
+ _MINIMUM_RATE = 0.005 # B-1 N 2.1.3: minimum provision of the individually assessed Normal portfolio (dossier 03 D.3)
122
+
123
+ _ROUND = 9 # decimals kept before a bucket comparison, so a float at a boundary lands in its inclusive bucket
124
+
125
+
126
+ def _bucket(value: float, uppers: tuple[float | None, ...], name: str, rule: str) -> int:
127
+ """Index of the first bucket whose inclusive upper bound is at least ``value`` (``None`` is unbounded)."""
128
+ if not math.isfinite(value) or value < 0:
129
+ raise ValueError(f"{name} must be a non-negative number, got {value!r} ({rule})")
130
+ v = round(float(value), _ROUND)
131
+ for i, upper in enumerate(uppers):
132
+ if upper is None or v <= upper:
133
+ return i
134
+ raise AssertionError("unreachable") # pragma: no cover
135
+
136
+
137
+ def _dpd_index(dpd_bucket: str, allowed: tuple[str, ...], rule: str) -> int:
138
+ if dpd_bucket not in allowed:
139
+ raise ValueError(f"days-past-due bucket {dpd_bucket!r} is outside {list(allowed)} ({rule})")
140
+ return allowed.index(dpd_bucket)
141
+
142
+
143
+ def _money(value: float, name: str) -> float:
144
+ if not math.isfinite(value) or value < 0:
145
+ raise ValueError(f"{name} must be a non-negative amount, got {value!r}")
146
+ return float(value)
147
+
148
+
149
+ def _rate(value: float, name: str) -> float:
150
+ if not math.isfinite(value) or not 0.0 <= value <= 1.0:
151
+ raise ValueError(f"{name} must be a decimal in [0, 1], got {value!r}")
152
+ return float(value)
153
+
154
+
155
+ def b1_individual_category(category: str) -> tuple[float, float, float]:
156
+ """(PI, PDI, PE) decimals of an individual-assessment category A1..A6, B1..B4 (CNCB B-1 N 2.1, "Hoja 3").
157
+
158
+ Raises ``KeyError`` for any other category.
159
+ """
160
+ try:
161
+ return _INDIVIDUAL[category]
162
+ except (KeyError, TypeError):
163
+ raise KeyError(
164
+ f"category {category!r} is outside A1..A6 and B1..B4 (CNCB B-1 N 2.1, individual assessment)"
165
+ ) from None
166
+
167
+
168
+ def b1_individual_provision(eap: float, ea: float, category: str, guarantor_category: str | None = None) -> float:
169
+ r"""Provision of an individually assessed Normal or Substandard debtor (B-1 N 2.1.3).
170
+
171
+ $(EAP - EA) PI PDI + EA PI_{aval} PDI_{aval}$: ``eap`` is the exposure subject to provisions (loans plus contingent
172
+ credits less collateral at realisable value) and ``ea`` the guaranteed exposure, which is never deducted from
173
+ the exposure; the guaranteed part takes the guarantor's category.
174
+ """
175
+ eap = _money(eap, "eap")
176
+ ea = _money(ea, "ea")
177
+ if ea > eap:
178
+ raise ValueError(f"guaranteed exposure {ea!r} exceeds the exposure subject to provisions {eap!r} (B-1 N 2.1.3)")
179
+ own = (eap - ea) * _pe(category)
180
+ if ea == 0.0:
181
+ return own
182
+ if guarantor_category is None:
183
+ raise ValueError("a guaranteed exposure needs the guarantor's category (B-1 N 2.1.3 and N 4.1)")
184
+ return own + ea * _pe(guarantor_category)
185
+
186
+
187
+ def _pe(category: str) -> float:
188
+ pi, pdi, _ = b1_individual_category(category)
189
+ return pi * pdi
190
+
191
+
192
+ def b1_default_provision(exposure: float, recoverable: float) -> tuple[float, str, float]:
193
+ """(TPE, category, provision) of a debtor in the default portfolio (B-1 N 2.2, "Hoja 8").
194
+
195
+ $TPE = (E - R)/E$, rounded to 1e-9 before the bucket comparison; the provision is $E \\cdot PP$ with the category's
196
+ PP. Upper bounds are inclusive: C1 to 3%, C2 to 20%, C3 to 30%, C4 to 50%, C5 to 80%, C6 above.
197
+ """
198
+ if not math.isfinite(exposure) or exposure <= 0:
199
+ raise ValueError(f"exposure must be positive, got {exposure!r} (B-1 N 2.2: TPE = (E - R) / E)")
200
+ if not math.isfinite(recoverable) or not 0.0 <= recoverable <= exposure:
201
+ raise ValueError(f"recoverable amount {recoverable!r} must lie in [0, exposure={exposure!r}] (B-1 N 2.2)")
202
+ tpe = round((exposure - recoverable) / exposure, _ROUND)
203
+ uppers = tuple(upper for _, upper, _ in _DEFAULT_BUCKETS)
204
+ category, _, pp = _DEFAULT_BUCKETS[_bucket(tpe, uppers, "TPE", "B-1 N 2.2")]
205
+ return tpe, category, exposure * pp
206
+
207
+
208
+ def b1_mortgage_pe(pvg: float, dpd_bucket: str) -> tuple[float, float, float]:
209
+ """(PI, PDI, PE) of a residential mortgage (B-1 N 3.1.1, Circular 2.346 "Hoja 11"; 20 cells).
210
+
211
+ ``pvg`` is the outstanding principal over the mortgage collateral value, a decimal; buckets <= 40%, <= 80%,
212
+ <= 90%, > 90%. ``dpd_bucket`` is one of ``0``, ``1-29``, ``30-59``, ``60-89``, ``default``. PE is the transcribed
213
+ cell. Also applies to residential leasing.
214
+ """
215
+ j = _dpd_index(dpd_bucket, _DPD, "B-1 N 3.1.1 residential mortgages")
216
+ i = _bucket(pvg, _MORTGAGE_PVG_UPPER, "pvg", "B-1 N 3.1.1 residential mortgages")
217
+ return _MORTGAGE_PI[i][j], _MORTGAGE_PDI[i][j], _MORTGAGE_PE[i][j]
218
+
219
+
220
+ def b1_leasing_pe(pvb: float, dpd_bucket: str, real_estate: bool) -> tuple[float, float, float]:
221
+ """(PI, PDI, PE = PI x PDI) of commercial leasing (B-1 N 3.1.2 (a)).
222
+
223
+ ``pvb`` is the present value of the lease over the asset value; PVB buckets <= 40%, <= 50%, <= 80%, <= 90%, > 90%.
224
+ """
225
+ j = _dpd_index(dpd_bucket, _DPD, "B-1 N 3.1.2 (a) commercial leasing")
226
+ i = _bucket(pvb, _LEASING_PVB_UPPER, "pvb", "B-1 N 3.1.2 (a) commercial leasing")
227
+ key = bool(real_estate)
228
+ pi, pdi = _LEASING_PI[key][j], _LEASING_PDI[key][i]
229
+ return pi, pdi, pi * pdi
230
+
231
+
232
+ def b1_student_loan_pe(scheme: str, dpd_bucket: str) -> tuple[float, float, float]:
233
+ """(PI, PDI, PE = PI x PDI) of a student loan (B-1 N 3.1.2 (b)); ``scheme`` CAE or CORFO.
234
+
235
+ ``dpd_bucket`` is ``0``, ``1-29``, ``30-59``, ``60-89``, ``default`` (payment due) or ``not-due``.
236
+ """
237
+ rule = "B-1 N 3.1.2 (b) student loans"
238
+ if scheme not in _STUDENT_PI_DUE:
239
+ raise ValueError(f"scheme {scheme!r} is outside ['CAE', 'CORFO'] ({rule})")
240
+ if dpd_bucket == "not-due":
241
+ pi, pdi = _STUDENT_NOT_DUE[scheme]
242
+ else:
243
+ j = _dpd_index(dpd_bucket, _DPD + ("not-due",), rule)
244
+ pi, pdi = _STUDENT_PI_DUE[scheme][j], _STUDENT_PDI_DUE
245
+ return pi, pdi, pi * pdi
246
+
247
+
248
+ def b1_commercial_pe(dpd_bucket: str, ptvg: float | None,
249
+ factoring_with_recourse: bool = False) -> tuple[float, float, float]:
250
+ """(PI, PDI, PE = PI x PDI) of a generic commercial loan or factoring (B-1 N 3.1.2 (c)).
251
+
252
+ ``ptvg`` is the obligations over the value of real guarantees, a decimal, or ``None`` for no guarantee. With a
253
+ guarantee, PI depends on PTVG at most or above 100% and PDI on the buckets <= 60%, <= 75%, <= 90%, > 90%; factoring
254
+ with recourse to the assignor has its own PDI column.
255
+ """
256
+ rule = "B-1 N 3.1.2 (c) generic commercial loans and factoring"
257
+ j = _dpd_index(dpd_bucket, _DPD, rule)
258
+ if ptvg is None:
259
+ pi = _COMMERCIAL_PI_NO_GUARANTEE[j]
260
+ pdi = _COMMERCIAL_PDI_NO_GUARANTEE_RECOURSE if factoring_with_recourse else _COMMERCIAL_PDI_NO_GUARANTEE
261
+ else:
262
+ i = _bucket(ptvg, _COMMERCIAL_PTVG_UPPER, "ptvg", rule)
263
+ le_100 = round(float(ptvg), _ROUND) <= 1.0
264
+ pi = (_COMMERCIAL_PI_GUARANTEE_LE_100 if le_100 else _COMMERCIAL_PI_GUARANTEE_GT_100)[j]
265
+ pdi = (_COMMERCIAL_PDI_GUARANTEE_RECOURSE if factoring_with_recourse else _COMMERCIAL_PDI_GUARANTEE)[i]
266
+ return pi, pdi, pi * pdi
267
+
268
+
269
+ def b1_consumer_pe(max_dpd_in_bank: int, has_mortgage_in_system: bool, arrears_30_in_system_3m: bool,
270
+ product: str) -> tuple[float, float, float]:
271
+ """(PI, PDI, PE = PI x PDI) of a consumer loan (B-1 N 3.1.3, Circular 2.346).
272
+
273
+ PI from the debtor's maximum days past due in the bank (0-7, 8-30, 31-60, 61-89; 90 or more gives 1), whether
274
+ the debtor holds a residential mortgage in the system and whether it had a debt 30+ days past due in the
275
+ system in the previous three months (16 cells). PDI by ``product`` (``leasing-auto``, ``instalment``,
276
+ ``cards-lines-other``) and the mortgage in the system.
277
+ """
278
+ rule = "B-1 N 3.1.3 consumer loans"
279
+ if product not in _CONSUMER_PRODUCTS:
280
+ raise ValueError(f"product {product!r} is outside {list(_CONSUMER_PRODUCTS)} ({rule})")
281
+ if not math.isfinite(max_dpd_in_bank) or max_dpd_in_bank < 0 or int(max_dpd_in_bank) != max_dpd_in_bank:
282
+ raise ValueError(f"max_dpd_in_bank must be a non-negative integer, got {max_dpd_in_bank!r} ({rule})")
283
+ pdis = _CONSUMER_PDI_MORTGAGE if has_mortgage_in_system else _CONSUMER_PDI_NO_MORTGAGE
284
+ pdi = pdis[_CONSUMER_PRODUCTS.index(product)]
285
+ if max_dpd_in_bank >= 90:
286
+ pi = 1.0
287
+ else:
288
+ row = next(r for r, upper in enumerate(_CONSUMER_ROW_UPPER) if max_dpd_in_bank <= upper)
289
+ col = (0 if has_mortgage_in_system else 2) + (1 if arrears_30_in_system_3m else 0)
290
+ pi = _CONSUMER_PI[row][col]
291
+ return pi, pdi, pi * pdi
292
+
293
+
294
+ def b1_group_provision(group_exposure: float, pe_group: float, guaranteed_share: float = 0.0,
295
+ pe_guarantor: float = 0.0) -> float:
296
+ """Group-portfolio provision with guarantor substitution (B-1 N 4.1).
297
+
298
+ $EG (1 - EA) PE_{group} + EG\\, EA\\, PE_{aval}$, ``guaranteed_share`` being EA/100 in [0, 1]. The 0.50% minimum
299
+ is not applied here: it belongs to the individually assessed Normal portfolio only.
300
+ """
301
+ eg = _money(group_exposure, "group_exposure")
302
+ share = _rate(guaranteed_share, "guaranteed_share")
303
+ pe_g = _rate(pe_group, "pe_group")
304
+ pe_a = _rate(pe_guarantor, "pe_guarantor")
305
+ return eg * (1.0 - share) * pe_g + eg * share * pe_a
306
+
307
+
308
+ @dataclass(frozen=True)
309
+ class MinimumCheck:
310
+ """Result of the 0.50% minimum on the individually assessed Normal portfolio (B-1 N 2.1.3)."""
311
+
312
+ minimum_rate: float
313
+ minimum_amount: float
314
+ binding: bool
315
+ top_up: float
316
+
317
+
318
+ def b1_minimum_normal_check(normal_exposure: float, normal_provision: float) -> MinimumCheck:
319
+ """The 0.50% minimum provision on the individually assessed Normal portfolio, A1 to A6 (B-1 N 2.1.3).
320
+
321
+ ``normal_exposure`` (loans plus contingent credits) and ``normal_provision`` are those of that portfolio only:
322
+ not the group-assessed book and not the whole performing book. The minimum is always enforced:
323
+ ``top_up = max(0, minimum - provision)`` and ``binding = top_up > 0``.
324
+ """
325
+ exposure = _money(normal_exposure, "normal_exposure")
326
+ provision = _money(normal_provision, "normal_provision")
327
+ minimum = _MINIMUM_RATE * exposure
328
+ top_up = max(0.0, minimum - provision)
329
+ return MinimumCheck(minimum_rate=_MINIMUM_RATE, minimum_amount=minimum, binding=top_up > 0.0, top_up=top_up)
330
+
331
+
332
+ def b1_group_max_rule(standard: float, internal: float | None,
333
+ internal_not_objected: bool = False) -> tuple[float, str]:
334
+ """(applied, method) of the group-assessment max rule (B-1 N 3).
335
+
336
+ The larger of the standard and the internal method (method ``max``), unless the internal method has the CMF
337
+ "no objection", then the internal one (``internal``); no internal method gives the standard (``standard``).
338
+ """
339
+ standard = _money(standard, "standard")
340
+ if internal is None:
341
+ return standard, "standard"
342
+ internal = _money(internal, "internal")
343
+ if internal_not_objected:
344
+ return internal, "internal"
345
+ return max(standard, internal), "max"
346
+
347
+
348
+ def b1_additional_provisions(amount: float, policy_min: float, policy_max: float) -> float:
349
+ """Additional (counter-cyclical, general) provisions inside the board's policy limits (B-1 N 9).
350
+
351
+ Returned as their own line: never part of a comparable B-1 total and never used to cover model deficiencies.
352
+ Raises ``ValueError`` outside ``[policy_min, policy_max]`` or when the limits are inverted.
353
+ """
354
+ if policy_min > policy_max:
355
+ raise ValueError(f"policy limits are inverted: min {policy_min!r} > max {policy_max!r} (B-1 N 9)")
356
+ if not math.isfinite(amount) or not policy_min <= amount <= policy_max:
357
+ raise ValueError(
358
+ f"additional provisions {amount!r} are outside the board policy [{policy_min!r}, {policy_max!r}] (B-1 N 9)"
359
+ )
360
+ return float(amount)
@@ -0,0 +1,157 @@
1
+ r"""Banco de Espana Circular 4/2017 Annex 9 (Anejo 9, "Analisis y cobertura del riesgo de credito"): the coverage
2
+ tables of the alternative solutions and the category-to-stage mapping.
3
+
4
+ Source: Contraste dossier 03 sections K.2 and K.3, read 2026-10-04 from Circular 4/2017 (BOE-A-2017-14334) as amended by
5
+ Circular 6/2021 of 22 December (BOE-A-2021-21666), whose tables of points 140, 144 and 172 apply from 2022-06-30.
6
+ Coverage is applied to the amount not covered by effective guarantees:
7
+ $Cobertura = c_{s,k} \max(0, EAD - \sum_g ValorAjustado_g)$.
8
+
9
+ Point numbers (144, 140) are as of Circular 6/2021. Whether they shifted after Circular 1/2025 is UNVERIFIED in the
10
+ dossier and stays a documented limitation. Not transcribed (dossier K.3): the collateral haircut table for effective
11
+ guarantees, the treatment of a doubtful risk for reasons other than arrears, the country-risk tables revised by
12
+ Circular 1/2025. The functions compute; they state no compliance claim. Percentages are decimals here: 1.9 per cent is
13
+ 0.019.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from collections.abc import Sequence
20
+
21
+ # Point 144 (riesgo normal; riesgo normal en vigilancia especial), decimals of the uncovered amount. Dossier 03 K.3.
22
+ _POINT_144: dict[str, tuple[float, float]] = {
23
+ "A.1.1": (0.019, 0.30), # Construccion y promocion inmobiliaria, incl. suelo
24
+ "A.1.2": (0.02, 0.188), # Construccion de obra civil
25
+ "A.1.3": (0.006, 0.096), # Resto de financiacion especializada
26
+ "A.2.1": (0.006, 0.096), # Grandes empresas
27
+ "A.2.2": (0.011, 0.178), # Pymes
28
+ "A.2.3": (0.014, 0.139), # Empresarios individuales
29
+ "B.1.1": (0.007, 0.18), # Vivienda habitual, LTV <= 80%
30
+ "B.1.2": (0.007, 0.18), # Vivienda habitual, LTV > 80%
31
+ "B.1.3": (0.007, 0.18), # Vivienda distinta de la habitual
32
+ "B.2": (0.018, 0.202), # Credito al consumo
33
+ "B.2.1": (0.01, 0.116), # of which credit cards
34
+ "B.3": (0.018, 0.202), # Otros fines
35
+ }
36
+
37
+ # Point 140 (riesgo dudoso por razon de la morosidad), decimals of the uncovered amount by age of the past-due
38
+ # amounts; columns >90d-6m, 6-9m, 9-12m, 12-15m, 15-18m, 18-21m, >21m. Dossier 03 K.3.
39
+ _ROW_A11 = (0.70, 0.75, 0.85, 0.90, 0.95, 1.0, 1.0)
40
+ _ROW_A12 = (0.55, 0.65, 0.70, 0.80, 0.95, 1.0, 1.0)
41
+ _ROW_A13 = (0.55, 0.65, 0.75, 0.90, 0.95, 1.0, 1.0)
42
+ _ROW_A22 = (0.65, 0.70, 0.75, 0.85, 0.90, 0.95, 1.0)
43
+ _ROW_A23 = (0.35, 0.45, 0.60, 0.65, 0.80, 0.95, 1.0)
44
+ _ROW_B1 = (0.45, 0.50, 0.65, 0.70, 0.85, 0.95, 1.0) # B.1.1 / B.1.2 / B.1.3 Vivienda
45
+ _ROW_B2 = (0.55, 0.65, 0.80, 0.85, 0.95, 1.0, 1.0) # B.2 Consumo (and B.2.1 cards), B.3 Otros fines
46
+ _POINT_140: dict[str, tuple[float, ...]] = {
47
+ "A.1.1": _ROW_A11,
48
+ "A.1.2": _ROW_A12,
49
+ "A.1.3": _ROW_A13,
50
+ "A.2.1": _ROW_A13, # Grandes empresas: the same row as A.1.3 in the dossier
51
+ "A.2.2": _ROW_A22,
52
+ "A.2.3": _ROW_A23,
53
+ "B.1.1": _ROW_B1,
54
+ "B.1.2": _ROW_B1,
55
+ "B.1.3": _ROW_B1,
56
+ "B.2": _ROW_B2,
57
+ "B.2.1": _ROW_B2,
58
+ "B.3": _ROW_B2,
59
+ }
60
+
61
+ # Point 140 counts months; converted once at 30.4375 days per month rounded to the nearest day (Contraste's
62
+ # convention; a bank's own day count overrides it in the caller): 6, 9, 12, 15, 18, 21 months. Upper bounds are
63
+ # inclusive and the first bucket opens above 90 days.
64
+ _DAYS_PER_MONTH = 30.4375
65
+ _UPPER_DAYS = tuple(round(m * _DAYS_PER_MONTH) for m in (6, 9, 12, 15, 18, 21)) # 183, 274, 365, 457, 548, 639
66
+ _MIN_DOUBTFUL_DAYS = 90 # the doubtful buckets exist for arrears above 90 days
67
+
68
+ # Category to stage (norma 29.11; the mapping Circular 6/2021 states for reporting). Dossier 03 K.2.
69
+ _STAGE = {
70
+ "normal": "stage1",
71
+ "normal-special-watch": "stage2",
72
+ "doubtful": "stage3",
73
+ "written-off": "written-off",
74
+ }
75
+
76
+
77
+ def _check_segment(segment: str, point: str) -> None:
78
+ if segment not in _POINT_144:
79
+ raise ValueError(f"segment {segment!r} is outside {list(_POINT_144)} (Annex 9 {point})")
80
+
81
+
82
+ def annex9_uncovered_amount(ead: float, adjusted_guarantee_values: Sequence[float]) -> float:
83
+ """``max(0, EAD - sum(adjusted guarantees))``: the amount not covered by effective guarantees (Annex 9)."""
84
+ if not math.isfinite(ead) or ead < 0:
85
+ raise ValueError(f"ead must be a non-negative amount, got {ead!r}")
86
+ total = 0.0
87
+ for g in adjusted_guarantee_values:
88
+ if not math.isfinite(g) or g < 0:
89
+ raise ValueError(f"an adjusted guarantee value must be a non-negative amount, got {g!r}")
90
+ total += g
91
+ return max(0.0, float(ead) - total)
92
+
93
+
94
+ def annex9_normal_coverage(segment: str, category: str) -> float:
95
+ """Coverage decimal of point 144 for ``normal`` or ``normal-special-watch`` in a segment (from 2022-06-30).
96
+
97
+ Segments: A.1.1, A.1.2, A.1.3, A.2.1, A.2.2, A.2.3, B.1.1, B.1.2, B.1.3, B.2, B.2.1, B.3.
98
+ """
99
+ _check_segment(segment, "point 144")
100
+ normal, watch = _POINT_144[segment]
101
+ if category == "normal":
102
+ return normal
103
+ if category == "normal-special-watch":
104
+ return watch
105
+ raise ValueError(f"category {category!r} is outside ['normal', 'normal-special-watch'] (Annex 9 point 144)")
106
+
107
+
108
+ def annex9_doubtful_coverage(segment: str, days_past_due: int) -> float:
109
+ """Coverage decimal of point 140 for a doubtful account by the age of its oldest past-due amount, in days.
110
+
111
+ Buckets (90, 183], (183, 274], (274, 365], (365, 457], (457, 548], (548, 639] and above 639 days (upper bounds
112
+ inclusive; the seven columns >90d-6m to >21m). Raises ``ValueError`` for 90 days or fewer.
113
+ """
114
+ _check_segment(segment, "point 140")
115
+ if not math.isfinite(days_past_due) or days_past_due <= _MIN_DOUBTFUL_DAYS:
116
+ raise ValueError(
117
+ f"days past due {days_past_due!r} must exceed {_MIN_DOUBTFUL_DAYS}: Annex 9 point 140 covers doubtful "
118
+ "risk by arrears above 90 days"
119
+ )
120
+ row = _POINT_140[segment]
121
+ for k, upper in enumerate(_UPPER_DAYS):
122
+ if days_past_due <= upper:
123
+ return row[k]
124
+ return row[-1]
125
+
126
+
127
+ def annex9_category_to_stage(category: str) -> str:
128
+ """``stage1``, ``stage2``, ``stage3`` or ``written-off`` for an Annex 9 category (norma 29.11, Circular 6/2021)."""
129
+ try:
130
+ return _STAGE[category]
131
+ except (KeyError, TypeError):
132
+ raise ValueError(f"category {category!r} is outside {list(_STAGE)} (Circular 4/2017 norma 29.11)") from None
133
+
134
+
135
+ def annex9_coverage(segment: str, category: str, ead: float, adjusted_guarantee_values: Sequence[float],
136
+ days_past_due: int | None = None) -> float:
137
+ """Coverage amount ``c x annex9_uncovered_amount(ead, adjusted_guarantee_values)`` (Annex 9).
138
+
139
+ For ``doubtful`` the coefficient is point 140 by ``days_past_due`` (required and above 90); otherwise point 144.
140
+ ``written-off`` returns 0. A doubtful account for reasons other than arrears has no transcribed coverage (dossier
141
+ 03 K.3): with ``days_past_due`` missing or at most 90 this raises ``ValueError`` and the caller reports the account
142
+ as not evaluated.
143
+ """
144
+ if category == "written-off":
145
+ _check_segment(segment, "coverage")
146
+ annex9_uncovered_amount(ead, adjusted_guarantee_values)
147
+ return 0.0
148
+ if category == "doubtful":
149
+ if days_past_due is None:
150
+ raise ValueError(
151
+ "a doubtful account needs days_past_due above 90; a doubtful risk for reasons other than arrears has "
152
+ "no transcribed coverage (dossier 03 K.3): report the account as not evaluated"
153
+ )
154
+ c = annex9_doubtful_coverage(segment, days_past_due)
155
+ else:
156
+ c = annex9_normal_coverage(segment, category)
157
+ return c * annex9_uncovered_amount(ead, adjusted_guarantee_values)
@@ -0,0 +1,102 @@
1
+ """Overlays as explicit line items (dossier 02 I.1 item 9; ECB July 2024; BCBS d350 paras 50 and 51).
2
+
3
+ Each overlay is reported separately in every output and never merged into the model ECL. The stage rule is a
4
+ convention of the contract `engine-provisions-api`, not an IFRS rule: an overlay with a stage is carried in that
5
+ stage's allowance closing; an overlay with `stage = None` (portfolio level) is carried in the stage1 closing, because
6
+ the roll-forward has no portfolio row. This module states no compliance claim.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from collections.abc import Sequence
13
+ from dataclasses import dataclass
14
+ from datetime import date
15
+
16
+ METHODS = ("simulation", "scenario", "expert")
17
+ TARGETS = ("pd", "lgd", "ead", "staging-share")
18
+ STAGING_EFFECTS = ("none", "transfers-to-stage2")
19
+ STAGES = ("stage1", "stage2", "stage3", "poci")
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Overlay:
24
+ """One overlay: money in `currency`, signed (a positive amount raises the allowance)."""
25
+
26
+ id: str
27
+ rationale_en: str
28
+ rationale_es: str
29
+ method: str
30
+ target: str
31
+ segment_id: str | None
32
+ stage: str | None
33
+ amount: float
34
+ staging_effect: str
35
+ review_date: str
36
+ currency: str
37
+
38
+ def __post_init__(self) -> None:
39
+ if not isinstance(self.id, str) or not self.id.strip():
40
+ raise ValueError("Overlay.id must be a non-empty string")
41
+ for field, value in (("rationale_en", self.rationale_en), ("rationale_es", self.rationale_es)):
42
+ if not isinstance(value, str) or not value.strip():
43
+ raise ValueError(f"Overlay.{field} must be a non-empty string")
44
+ for field, value, allowed in (
45
+ ("method", self.method, METHODS),
46
+ ("target", self.target, TARGETS),
47
+ ("staging_effect", self.staging_effect, STAGING_EFFECTS),
48
+ ):
49
+ if value not in allowed:
50
+ raise ValueError(f"Overlay.{field} must be one of {allowed}, got {value!r}")
51
+ if self.stage is not None and self.stage not in STAGES:
52
+ raise ValueError(f"Overlay.stage must be None or one of {STAGES}, got {self.stage!r}")
53
+ if not math.isfinite(float(self.amount)):
54
+ raise ValueError(f"Overlay.amount must be finite, got {self.amount!r}")
55
+ try:
56
+ date.fromisoformat(self.review_date)
57
+ except (TypeError, ValueError) as exc:
58
+ raise ValueError(f"Overlay.review_date must be an ISO date, got {self.review_date!r}") from exc
59
+ if not (isinstance(self.currency, str) and len(self.currency) == 3 and self.currency.isalpha()
60
+ and self.currency.isupper()):
61
+ raise ValueError(f"Overlay.currency must be an ISO 4217 code, got {self.currency!r}")
62
+
63
+ @property
64
+ def carried_stage(self) -> str:
65
+ """The stage whose allowance closing carries this overlay (portfolio level goes to stage1)."""
66
+ return self.stage if self.stage is not None else "stage1"
67
+
68
+
69
+ def check_unique(overlays: Sequence[Overlay]) -> None:
70
+ """Overlay ids are unique within a run; raises `ValueError` otherwise."""
71
+ seen: set[str] = set()
72
+ for o in overlays:
73
+ if o.id in seen:
74
+ raise ValueError(f"overlay ids must be unique within a run, {o.id!r} repeats")
75
+ seen.add(o.id)
76
+
77
+
78
+ def sum_amounts(overlays: Sequence[Overlay]) -> float:
79
+ """The sum of the signed overlay amounts, exactly rounded."""
80
+ check_unique(overlays)
81
+ return math.fsum(float(o.amount) for o in overlays)
82
+
83
+
84
+ def overlay_lines(overlays: Sequence[Overlay]) -> list[dict]:
85
+ """The waterfall lines of the overlays, one each, in id order; never merged into another line."""
86
+ check_unique(overlays)
87
+ return [
88
+ {"id": f"overlay-{o.id}", "kind": "overlay", "overlay_id": o.id, "amount": float(o.amount), "stage": o.stage}
89
+ for o in sorted(overlays, key=lambda x: x.id)
90
+ ]
91
+
92
+
93
+ def overlay_share(overlay_total: float, total_allowance: float) -> float:
94
+ """overlay_total / total_allowance; raises when the allowance is not positive (no placeholder)."""
95
+ if not float(total_allowance) > 0.0:
96
+ raise ValueError(f"total_allowance must be positive to state an overlay share, got {total_allowance!r}")
97
+ return float(overlay_total) / float(total_allowance)
98
+
99
+
100
+ def total_allowance(model_ecl: float, overlays: Sequence[Overlay]) -> float:
101
+ """model_ecl + sum(overlay.amount): the allowance with the overlays as separate lines."""
102
+ return float(model_ecl) + sum_amounts(overlays)