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,138 @@
1
+ """The basic approach to CVA risk, BA-CVA (MAR50.9, MAR50.14 to MAR50.25, in force 2023-01-01, published 2020-07-08;
2
+ dossier 01 E.1).
3
+
4
+ Reduced version (MAR50.14 to MAR50.16), capital = DS K_reduced with DS = 0.65:
5
+
6
+ K_reduced = sqrt((rho sum_c SCVA_c)^2 + (1 - rho^2) sum_c SCVA_c^2), rho = 50 percent
7
+ SCVA_c = (1 / alpha) RW_c sum_NS M_NS EAD_NS DF_NS, alpha = 1.4
8
+ DF_NS = (1 - exp(-0.05 M_NS)) / (0.05 M_NS) (1 for IMM banks)
9
+
10
+ Full version (MAR50.20 to MAR50.25): K_full = beta K_reduced + (1 - beta) K_hedged, beta = 0.25, with
11
+
12
+ K_hedged = sqrt((rho sum_c (SCVA_c - SNH_c) - IH)^2 + (1 - rho^2) sum_c (SCVA_c - SNH_c)^2 + sum_c HMA_c).
13
+
14
+ The counterparty risk weights are MAR50.16 Table 1. There is no verified official numeric example (research addendum
15
+ R8): the tests rest on the invariants of dossier 01 M.1 (rho = 1 gives the sum of the SCVA, hedges never take K_full
16
+ below beta K_reduced). Not implemented: the computation of SNH_c, IH and HMA_c from the hedge instruments (the caller
17
+ passes the terms), the MAR50.18 eligible-hedge rule, and SA-CVA (MAR50.27 onward). The engine computes and states no
18
+ compliance claim.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import math
24
+
25
+ from riskvalidation.regulatory.standardised import RegulatoryParameter, _finite, _nonnegative
26
+
27
+ MAR50_IN_FORCE = "2023-01-01"
28
+ MATERIALITY_THRESHOLD_EUR = 1e11 # MAR50.9: EUR 100 billion
29
+ ALPHA = 1.4 # MAR50.15
30
+ RHO = 0.5 # MAR50.14
31
+ BETA = 0.25 # MAR50.20
32
+ DS = 0.65 # MAR50.14, MAR50.20
33
+ DISCOUNT_RATE = 0.05 # MAR50.15
34
+
35
+ #: MAR50.16 Table 1: (investment grade, high yield or not rated) risk weights by sector, as decimals
36
+ _TABLE_1 = {
37
+ "sovereigns-central-banks-mdbs": (0.005, 0.02),
38
+ "local-government-public": (0.01, 0.04),
39
+ "financials": (0.05, 0.12),
40
+ "basic-materials-energy-industrials": (0.03, 0.07),
41
+ "consumer-transport-administrative": (0.03, 0.085),
42
+ "technology-telecoms": (0.02, 0.055),
43
+ "health-care-utilities-professional": (0.015, 0.05),
44
+ "other": (0.05, 0.12),
45
+ }
46
+ SECTOR_RISK_WEIGHTS: dict[tuple[str, str], RegulatoryParameter] = {}
47
+ for _sector, (_ig, _hy) in _TABLE_1.items():
48
+ SECTOR_RISK_WEIGHTS[(_sector, "risk_weight_investment_grade")] = RegulatoryParameter(
49
+ _ig, "MAR50.16", "MAR50.16 Table 1", MAR50_IN_FORCE
50
+ )
51
+ SECTOR_RISK_WEIGHTS[(_sector, "risk_weight_high_yield_or_not_rated")] = RegulatoryParameter(
52
+ _hy, "MAR50.16", "MAR50.16 Table 1", MAR50_IN_FORCE
53
+ )
54
+ del _sector, _ig, _hy
55
+
56
+
57
+ def materiality_threshold_applies(aggregate_notional_eur: float) -> bool:
58
+ """MAR50.9: true at or below EUR 100 billion of aggregate non-centrally-cleared derivative notional."""
59
+ return _nonnegative("aggregate_notional_eur", aggregate_notional_eur) <= MATERIALITY_THRESHOLD_EUR
60
+
61
+
62
+ def sector_risk_weight(sector: str, investment_grade: bool) -> RegulatoryParameter:
63
+ """MAR50.16 Table 1: the counterparty risk weight by sector and credit quality (investment grade or not)."""
64
+ column = "risk_weight_investment_grade" if investment_grade else "risk_weight_high_yield_or_not_rated"
65
+ if (sector, column) not in SECTOR_RISK_WEIGHTS:
66
+ raise ValueError(f"sector {sector!r} is not a row of MAR50.16 Table 1 (MAR50.16)")
67
+ return SECTOR_RISK_WEIGHTS[(sector, column)]
68
+
69
+
70
+ def discount_factor(m: float, imm_bank: bool = False) -> float:
71
+ """MAR50.15: (1 - exp(-0.05 M)) / (0.05 M), the effective maturity M in years; 1 for a bank using the IMM."""
72
+ maturity = _finite("m", m)
73
+ if maturity <= 0.0:
74
+ raise ValueError(f"m must be positive, got {m!r}")
75
+ if imm_bank:
76
+ return 1.0
77
+ return -math.expm1(-DISCOUNT_RATE * maturity) / (DISCOUNT_RATE * maturity) # expm1: no cancellation for a short M
78
+
79
+
80
+ def scva(
81
+ risk_weight: float, netting_sets: list[tuple[float, float]], imm_bank: bool = False, alpha: float = ALPHA
82
+ ) -> float:
83
+ """MAR50.15: (1 / alpha) RW sum_NS M_NS EAD_NS DF_NS over the counterparty's netting sets given as (M in years,
84
+ EAD)."""
85
+ rw = _nonnegative("risk_weight", risk_weight)
86
+ a = _finite("alpha", alpha)
87
+ if a <= 0.0:
88
+ raise ValueError(f"alpha must be positive, got {alpha!r}")
89
+ total = 0.0
90
+ for m, ead in netting_sets:
91
+ maturity = _finite("netting_sets", m)
92
+ if maturity <= 0.0:
93
+ raise ValueError(f"netting_sets must hold a positive M in years, got {m!r}")
94
+ total += maturity * _nonnegative("netting_sets", ead) * discount_factor(maturity, imm_bank)
95
+ return rw * total / a
96
+
97
+
98
+ def _rho(rho: float) -> float:
99
+ r = _finite("rho", rho)
100
+ if not 0.0 <= r <= 1.0:
101
+ raise ValueError(f"rho must lie in [0, 1], got {rho!r}")
102
+ return r
103
+
104
+
105
+ def k_reduced(scvas: list[float], rho: float = RHO) -> float:
106
+ """MAR50.14: sqrt((rho sum SCVA)^2 + (1 - rho^2) sum SCVA^2); with rho = 1 the sum of the SCVA."""
107
+ r = _rho(rho)
108
+ x = [_nonnegative("scvas", v) for v in scvas]
109
+ return math.sqrt((r * sum(x)) ** 2 + (1.0 - r * r) * sum(v * v for v in x))
110
+
111
+
112
+ def k_hedged(scva_minus_snh: list[float], ih: float, hma: list[float], rho: float = RHO) -> float:
113
+ """MAR50.21 to MAR50.25: sqrt((rho sum (SCVA - SNH) - IH)^2 + (1 - rho^2) sum (SCVA - SNH)^2 + sum HMA)."""
114
+ r = _rho(rho)
115
+ x = [_finite("scva_minus_snh", v) for v in scva_minus_snh]
116
+ index_hedge = _finite("ih", ih)
117
+ misalignment = [_nonnegative("hma", v) for v in hma]
118
+ if len(misalignment) != len(x):
119
+ raise ValueError(
120
+ f"hma has {len(misalignment)} entries for {len(x)} counterparties: one term per counterparty is required"
121
+ )
122
+ radicand = (r * sum(x) - index_hedge) ** 2 + (1.0 - r * r) * sum(v * v for v in x) + sum(misalignment)
123
+ return math.sqrt(max(0.0, radicand))
124
+
125
+
126
+ def k_full(k_reduced_value: float, k_hedged_value: float, beta: float = BETA) -> float:
127
+ """MAR50.20: beta K_reduced + (1 - beta) K_hedged."""
128
+ b = _finite("beta", beta)
129
+ if not 0.0 <= b <= 1.0:
130
+ raise ValueError(f"beta must lie in [0, 1], got {beta!r}")
131
+ return b * _nonnegative("k_reduced_value", k_reduced_value) + (1.0 - b) * _nonnegative(
132
+ "k_hedged_value", k_hedged_value
133
+ )
134
+
135
+
136
+ def capital(k: float, ds: float = DS) -> float:
137
+ """MAR50.14 and MAR50.20: DS x K with the discount scalar DS = 0.65."""
138
+ return _nonnegative("ds", ds) * _nonnegative("k", k)
@@ -0,0 +1,345 @@
1
+ """The capital aggregation of the sensitivities-based method (SBM) and the liquidity-horizon cascade (MAR21, MAR33;
2
+ dossier 01 D.2 and D.3, research addendum R7).
3
+
4
+ Bucket and cross-bucket aggregation of delta (MAR21.4):
5
+
6
+ WS_k = RW_k s_k, K_b = sqrt(max(0, sum_k WS_k^2 + sum_{k != l} rho_kl WS_k WS_l)), S_b = sum_{k in b} WS_k
7
+ delta = sqrt(max(0, sum_b K_b^2 + sum_{b != c} gamma_bc S_b S_c))
8
+
9
+ with S_b replaced by max(min(sum WS, K_b), -K_b) when the radicand is negative (MAR21.4(5)(b)). Under the three
10
+ correlation scenarios of MAR21.6 (medium: the prescribed value; high: min(1.25 rho, 1); low: max(2 rho - 1, 0.75 rho))
11
+ the SBM requirement is the maximum over the scenarios of delta + vega + curvature (MAR21.7). GIRR delta sensitivities
12
+ are s_k = (V(r + 0.0001) - V(r)) / 0.0001 (MAR21.19), the change in value for a one basis point shift DIVIDED BY
13
+ 0.0001, not the PV01 per basis point. The GIRR parameters are those of the research addendum R7 (MAR21.42 Table 1,
14
+ MAR21.45, MAR21.46 Table 2, MAR21.50, MAR21.99); for a specified currency the weights may be divided by sqrt(2) at the
15
+ bank's discretion (MAR21.44). The cascade is MAR33.4. Not implemented (stated limits): vega (the footnote 24
16
+ risk-weight formula is not transcribed), the MAR21.101 curvature cross-bucket step beyond MAR21.5 (UNVERIFIED), the
17
+ other six risk classes, DRC, RRAO and SA-CVA. The existing `riskvalidation.market.frtb` holds the backtesting and PLA
18
+ statistics; the two modules do not import each other. The engine computes and states no compliance claim.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ from dataclasses import dataclass
25
+
26
+ import numpy as np
27
+
28
+ from riskvalidation.regulatory.standardised import RegulatoryParameter, _finite, _nonnegative
29
+
30
+ MAR21_IN_FORCE = "2023-01-01"
31
+ MAR33_IN_FORCE = "2023-01-01"
32
+ SCENARIOS = ("low", "medium", "high")
33
+ SQRT2 = math.sqrt(2.0)
34
+
35
+ #: MAR21.8: the GIRR delta tenors in years
36
+ GIRR_TENORS = (0.25, 0.5, 1.0, 2.0, 3.0, 5.0, 10.0, 15.0, 20.0, 30.0)
37
+ #: MAR21.42 Table 1: risk weights in percent by tenor
38
+ _GIRR_RISK_WEIGHTS_PERCENT = (1.7, 1.7, 1.6, 1.3, 1.2, 1.1, 1.1, 1.1, 1.1, 1.1)
39
+ #: MAR21.46 Table 2 (same bucket, different tenor, same curve), in percent as printed (addendum R7)
40
+ _TABLE_2_PERCENT = (
41
+ (100.0, 97.0, 91.4, 81.1, 71.9, 56.6, 40.0, 40.0, 40.0, 40.0),
42
+ (97.0, 100.0, 97.0, 91.4, 86.1, 76.3, 56.6, 41.9, 40.0, 40.0),
43
+ (91.4, 97.0, 100.0, 97.0, 94.2, 88.7, 76.3, 65.7, 56.6, 41.9),
44
+ (81.1, 91.4, 97.0, 100.0, 98.5, 95.6, 88.7, 82.3, 76.3, 65.7),
45
+ (71.9, 86.1, 94.2, 98.5, 100.0, 98.0, 93.2, 88.7, 84.4, 76.3),
46
+ (56.6, 76.3, 88.7, 95.6, 98.0, 100.0, 97.0, 94.2, 91.4, 86.1),
47
+ (40.0, 56.6, 76.3, 88.7, 93.2, 97.0, 100.0, 98.5, 97.0, 94.2),
48
+ (40.0, 41.9, 65.7, 82.3, 88.7, 94.2, 98.5, 100.0, 99.0, 97.0),
49
+ (40.0, 40.0, 56.6, 76.3, 84.4, 91.4, 97.0, 99.0, 100.0, 98.5),
50
+ (40.0, 40.0, 41.9, 65.7, 76.3, 86.1, 94.2, 97.0, 98.5, 100.0),
51
+ )
52
+ GIRR_SAME_TENOR_OTHER_CURVE = 0.999 # MAR21.45
53
+ GIRR_GAMMA = 0.5 # MAR21.50
54
+ GIRR_CURVATURE_SHOCK = 0.017 # MAR21.99: the highest delta risk weight, applied to all tenors
55
+
56
+ #: MAR33.4 Table 1: the liquidity horizons in days
57
+ LIQUIDITY_HORIZONS = (10, 20, 40, 60, 120)
58
+ LIQUIDITY_HORIZONS_TABLE_1: dict[tuple[str, str], RegulatoryParameter] = {
59
+ (f"j{j}", "liquidity_horizon_days"): RegulatoryParameter(float(lh), "MAR33.4", "MAR33.4 Table 1", MAR33_IN_FORCE)
60
+ for j, lh in enumerate(LIQUIDITY_HORIZONS, start=1)
61
+ }
62
+ #: MAR33.12 Table 2: the liquidity horizon in days by risk factor class (the row "commodity volatility, 60 or 120
63
+ # days" is
64
+ #: ambiguous in dossier 01 D.3 and is not transcribed)
65
+ _TABLE_2_DAYS = {
66
+ "interest-rate-specified-currencies": 10,
67
+ "interest-rate-other": 20,
68
+ "interest-rate-volatility": 60,
69
+ "credit-spread-sovereign-investment-grade": 20,
70
+ "credit-spread-sovereign-high-yield": 40,
71
+ "credit-spread-corporate-investment-grade": 40,
72
+ "credit-spread-corporate-high-yield": 60,
73
+ "credit-spread-volatility": 120,
74
+ "equity-large-cap": 10,
75
+ "equity-small-cap": 20,
76
+ "equity-large-cap-volatility": 20,
77
+ "equity-small-cap-volatility": 60,
78
+ "fx-specified-pairs": 10,
79
+ "fx-other-pairs": 20,
80
+ "fx-volatility": 40,
81
+ "commodity-energy-and-carbon": 20,
82
+ "commodity-precious-and-non-ferrous-metals": 20,
83
+ "commodity-other": 60,
84
+ }
85
+ LIQUIDITY_HORIZONS_TABLE_2: dict[tuple[str, str], RegulatoryParameter] = {
86
+ (key, "liquidity_horizon_days"): RegulatoryParameter(float(days), "MAR33.12", "MAR33.12 Table 2", MAR33_IN_FORCE)
87
+ for key, days in _TABLE_2_DAYS.items()
88
+ }
89
+
90
+
91
+ def _readonly(a: np.ndarray) -> np.ndarray:
92
+ a = np.array(a, dtype=float)
93
+ a.setflags(write=False)
94
+ return a
95
+
96
+
97
+ @dataclass(frozen=True, eq=False)
98
+ class GirrParameters:
99
+ """The GIRR delta parameters of the research addendum R7 with their paragraphs and the in-force date."""
100
+
101
+ tenors: np.ndarray # years (MAR21.8)
102
+ risk_weights: np.ndarray # decimals as applied: Table 1, divided by sqrt(2) when `sqrt2_applied`
103
+ risk_weights_table: np.ndarray # decimals as printed in MAR21.42 Table 1
104
+ correlation: np.ndarray # (10, 10), MAR21.46 Table 2 as decimals
105
+ same_tenor_other_curve: float # MAR21.45
106
+ gamma: float # MAR21.50
107
+ curvature_shock: float # MAR21.99, divided by sqrt(2) when `sqrt2_applied` (derived, addendum R7)
108
+ curvature_shock_undivided: float # MAR21.99: 0.017
109
+ sqrt2_applied: bool # MAR21.44: at the bank's discretion for a specified currency
110
+ in_force: str
111
+ paragraphs: dict[str, str]
112
+
113
+
114
+ def girr_parameters(specified_currency: bool = True) -> GirrParameters:
115
+ """The GIRR delta tenors, risk weights, correlations, gamma and curvature shock (research addendum R7).
116
+
117
+ The curvature shock a consumer applies is `curvature_shock_undivided` (0.017): MAR21.99 bases it on "the highest
118
+ prescribed delta risk weight", and MAR21.44's division by sqrt(2) names the delta risk weights of MAR21.42 to
119
+ MAR21.43 only. `curvature_shock` (0.017 / sqrt(2) = 0.012021) is a derived reading, kept exposed and labelled.
120
+
121
+ With `specified_currency` the risk weights (and the curvature shock) are divided by sqrt(2) (MAR21.44) and
122
+ `sqrt2_applied` says so; the specified currencies are EUR, USD, GBP, AUD, JPY, SEK, CAD and the bank's domestic
123
+ reporting currency.
124
+ """
125
+ table = np.array(_GIRR_RISK_WEIGHTS_PERCENT) / 100.0
126
+ divisor = SQRT2 if specified_currency else 1.0
127
+ paragraphs = {
128
+ "tenors": "MAR21.8",
129
+ "risk_weights": "MAR21.42 Table 1" + (" divided by sqrt(2), MAR21.44" if specified_currency else ""),
130
+ "correlation": "MAR21.46 Table 2",
131
+ "same_tenor_other_curve": "MAR21.45",
132
+ "gamma": "MAR21.50",
133
+ "curvature_shock": "MAR21.99" + (" divided by sqrt(2), MAR21.44 (derived)" if specified_currency else ""),
134
+ }
135
+ return GirrParameters(
136
+ tenors=_readonly(np.array(GIRR_TENORS)),
137
+ risk_weights=_readonly(table / divisor),
138
+ risk_weights_table=_readonly(table),
139
+ correlation=_readonly(np.array(_TABLE_2_PERCENT) / 100.0),
140
+ same_tenor_other_curve=GIRR_SAME_TENOR_OTHER_CURVE,
141
+ gamma=GIRR_GAMMA,
142
+ curvature_shock=GIRR_CURVATURE_SHOCK / divisor,
143
+ curvature_shock_undivided=GIRR_CURVATURE_SHOCK,
144
+ sqrt2_applied=bool(specified_currency),
145
+ in_force=MAR21_IN_FORCE,
146
+ paragraphs=paragraphs,
147
+ )
148
+
149
+
150
+ def _array(name: str, x: object, ndim: int | None = None, shape: tuple[int, ...] | None = None) -> np.ndarray:
151
+ try:
152
+ a = np.array(x, dtype=float)
153
+ except (TypeError, ValueError):
154
+ raise ValueError(f"{name} must be a numeric array") from None
155
+ if ndim is not None and a.ndim != ndim:
156
+ raise ValueError(f"{name} must have {ndim} dimension(s), got shape {a.shape}")
157
+ if shape is not None and a.shape != shape:
158
+ raise ValueError(f"{name} must have shape {shape}, got {a.shape}")
159
+ if not np.all(np.isfinite(a)):
160
+ raise ValueError(f"{name} must be finite")
161
+ return a
162
+
163
+
164
+ def _correlation_under(name: str, rho: object, scenario: str) -> np.ndarray:
165
+ if scenario not in SCENARIOS:
166
+ raise ValueError(f"scenario {scenario!r} is not one of low, medium, high (MAR21.6)")
167
+ r = _array(name, rho)
168
+ if np.any(np.abs(r) > 1.0 + 1e-12):
169
+ raise ValueError(f"{name} must lie in [-1, 1]")
170
+ if scenario == "high":
171
+ return np.minimum(1.25 * r, 1.0)
172
+ if scenario == "low":
173
+ return np.maximum(2.0 * r - 1.0, 0.75 * r)
174
+ return r.copy()
175
+
176
+
177
+ def scenario_correlation(rho: np.ndarray, scenario: str) -> np.ndarray:
178
+ """MAR21.6: medium is rho; high is min(1.25 rho, 1); low is max(2 rho - 1, 0.75 rho). Applies to rho and to gamma
179
+ alike."""
180
+ return np.asarray(_correlation_under("rho", rho, scenario), dtype=float)
181
+
182
+
183
+ def _offdiagonal(m: np.ndarray) -> np.ndarray:
184
+ out = np.array(m, dtype=float)
185
+ np.fill_diagonal(out, 0.0)
186
+ return out
187
+
188
+
189
+ def bucket_charge(ws: np.ndarray, rho: np.ndarray, scenario: str = "medium") -> float:
190
+ """MAR21.4: K_b = sqrt(max(0, sum WS_k^2 + sum_{k != l} rho_kl WS_k WS_l)) with rho of the scenario."""
191
+ w = _array("ws", ws, ndim=1)
192
+ n = w.shape[0]
193
+ r = _correlation_under("rho", _array("rho", rho, shape=(n, n)), scenario)
194
+ radicand = float(w @ w + w @ _offdiagonal(r) @ w)
195
+ return math.sqrt(max(0.0, radicand))
196
+
197
+
198
+ @dataclass(frozen=True)
199
+ class CrossBucket:
200
+ """The cross-bucket charge and whether the MAR21.4(5)(b) fallback applied (the radicand with the plain S_b was
201
+ negative)."""
202
+
203
+ charge: float
204
+ fallback_used: bool
205
+
206
+
207
+ def cross_bucket_charge_detail(
208
+ k_b: np.ndarray, s_b: np.ndarray, gamma: np.ndarray, scenario: str = "medium"
209
+ ) -> CrossBucket:
210
+ """MAR21.4: the charge of `cross_bucket_charge` and `fallback_used`, true exactly when the radicand with the plain
211
+ S_b is negative and S_b is replaced by max(min(S_b, K_b), -K_b) (MAR21.4(5)(b))."""
212
+ k = _array("k_b", k_b, ndim=1)
213
+ if np.any(k < 0.0):
214
+ raise ValueError("k_b must be at least 0")
215
+ s = _array("s_b", s_b, shape=k.shape)
216
+ g = _offdiagonal(_correlation_under("gamma", _array("gamma", gamma, shape=(k.size, k.size)), scenario))
217
+ radicand = float(k @ k + s @ g @ s)
218
+ fallback = radicand < 0.0
219
+ if fallback:
220
+ s = np.maximum(np.minimum(s, k), -k)
221
+ radicand = float(k @ k + s @ g @ s)
222
+ return CrossBucket(math.sqrt(max(0.0, radicand)), fallback)
223
+
224
+
225
+ def cross_bucket_charge(k_b: np.ndarray, s_b: np.ndarray, gamma: np.ndarray, scenario: str = "medium") -> float:
226
+ """MAR21.4: sqrt(sum K_b^2 + sum_{b != c} gamma_bc S_b S_c), with the MAR21.4(5)(b) replacement of S_b if it is
227
+ negative."""
228
+ return cross_bucket_charge_detail(k_b, s_b, gamma, scenario).charge
229
+
230
+
231
+ @dataclass(frozen=True, eq=False)
232
+ class SbmResult:
233
+ """The weighted sensitivities, the bucket charge under low, medium and high, and the charge, their maximum
234
+ (MAR21.7)."""
235
+
236
+ weighted: np.ndarray
237
+ k_by_scenario: tuple[float, float, float]
238
+ charge: float
239
+
240
+
241
+ def girr_delta_charge(sensitivities: np.ndarray, tenors: np.ndarray, params: GirrParameters) -> SbmResult:
242
+ """MAR21.4 to MAR21.7 for one GIRR bucket (a single currency): the delta charge of ten tenor sensitivities.
243
+
244
+ `sensitivities` is s_k = (V(r + 0.0001) - V(r)) / 0.0001 at each tenor (MAR21.19), money per unit of rate; a PV01
245
+ of 4,500 USD per basis point is s_k = 4.5e7.
246
+ """
247
+ n = len(params.tenors)
248
+ s = _array("sensitivities", sensitivities, shape=(n,))
249
+ t = _array("tenors", tenors, ndim=1)
250
+ if t.shape != params.tenors.shape or not np.allclose(t, params.tenors, rtol=0.0, atol=1e-12):
251
+ raise ValueError(f"tenors must be the GIRR tenors {tuple(params.tenors.tolist())} (MAR21.8)")
252
+ weighted = _readonly(params.risk_weights * s)
253
+ k = tuple(bucket_charge(weighted, params.correlation, name) for name in SCENARIOS)
254
+ return SbmResult(weighted, (k[0], k[1], k[2]), max(k))
255
+
256
+
257
+ def _psi(x: np.ndarray, y: np.ndarray) -> np.ndarray:
258
+ """psi(x, y) = 0 if both are negative and 1 otherwise (MAR21.5), as a matrix over the pairs."""
259
+ return (~((x < 0.0)[:, None] & (y < 0.0)[None, :])).astype(float)
260
+
261
+
262
+ def curvature_charge(
263
+ cvr_plus: np.ndarray, cvr_minus: np.ndarray, rho: np.ndarray, gamma: np.ndarray, scenario: str = "medium"
264
+ ) -> float:
265
+ """MAR21.5: the curvature charge of B buckets of K factors, with the psi rule.
266
+
267
+ `rho` is the (K, K) DELTA correlation and `gamma` the (B, B) DELTA cross-bucket correlation; both are squared here
268
+ (MAR21.100 and MAR21.101: the curvature correlations are the squares of the delta ones) and then take the
269
+ correlation scenario (MAR21.6). K_b = max(K_b+, K_b-); S_b is the sum of the CVR of the scenario that selected K_b:
270
+ the upward one when K_b+ > K_b-, the downward one when K_b+ < K_b-, and on a tie (K_b+ = K_b-) the upward one if
271
+ sum CVR+ > sum CVR-, otherwise the downward one (MAR21.5(3)(a)(iii)).
272
+ """
273
+ plus = _array("cvr_plus", cvr_plus, ndim=2)
274
+ minus = _array("cvr_minus", cvr_minus, shape=plus.shape)
275
+ n_buckets, n_factors = plus.shape
276
+ delta_rho = _array("rho", rho, shape=(n_factors, n_factors))
277
+ r = _offdiagonal(_correlation_under("rho", delta_rho**2, scenario))
278
+ delta_gamma = _array("gamma", gamma, shape=(n_buckets, n_buckets))
279
+ g = _offdiagonal(_correlation_under("gamma", delta_gamma**2, scenario))
280
+ k_b = np.zeros(n_buckets)
281
+ s_b = np.zeros(n_buckets)
282
+ for b in range(n_buckets):
283
+ roots = []
284
+ for cvr in (plus[b], minus[b]):
285
+ radicand = float(np.sum(np.maximum(cvr, 0.0) ** 2) + cvr @ (r * _psi(cvr, cvr)) @ cvr)
286
+ roots.append(math.sqrt(max(0.0, radicand)))
287
+ sum_plus, sum_minus = float(np.sum(plus[b])), float(np.sum(minus[b]))
288
+ up = roots[0] > roots[1] or (roots[0] == roots[1] and sum_plus > sum_minus) # MAR21.5(3)(a)(iii)
289
+ k_b[b] = max(roots)
290
+ s_b[b] = sum_plus if up else sum_minus
291
+ radicand = float(k_b @ k_b + s_b @ (g * _psi(s_b, s_b)) @ s_b)
292
+ return math.sqrt(max(0.0, radicand))
293
+
294
+
295
+ @dataclass(frozen=True)
296
+ class SbmCapital:
297
+ """The SBM requirement: the sum of the three measures per scenario (low, medium, high), their maximum and its
298
+ scenario."""
299
+
300
+ by_scenario: tuple[float, float, float]
301
+ capital: float
302
+ scenario: str
303
+
304
+
305
+ def _by_scenario(label: str, values: dict[str, float]) -> dict[str, float]:
306
+ missing = [s for s in SCENARIOS if s not in values]
307
+ if missing:
308
+ raise ValueError(f"{label} must hold the scenarios low, medium and high; missing {missing[0]!r}")
309
+ return {s: _nonnegative(label, values[s]) for s in SCENARIOS}
310
+
311
+
312
+ def sbm_capital(delta: dict[str, float], vega: dict[str, float], curvature: dict[str, float]) -> SbmCapital:
313
+ """MAR21.7: the maximum over the three scenarios of delta + vega + curvature, each summed over the risk classes."""
314
+ d = _by_scenario("delta", delta)
315
+ v = _by_scenario("vega", vega)
316
+ c = _by_scenario("curvature", curvature)
317
+ totals = tuple(d[s] + v[s] + c[s] for s in SCENARIOS)
318
+ best = max(range(3), key=lambda i: totals[i])
319
+ return SbmCapital((totals[0], totals[1], totals[2]), totals[best], SCENARIOS[best])
320
+
321
+
322
+ def liquidity_cascade_es(es_t_full: float, es_t_by_horizon: dict[int, float], base_horizon: int = 10) -> float:
323
+ """MAR33.4: sqrt(ES_T(P)^2 + sum_{j >= 2} (ES_T(P, j) sqrt((LH_j - LH_{j-1}) / T))^2) with the Table 1 horizons.
324
+
325
+ `es_t_by_horizon` maps a liquidity horizon in days (10, 20, 40, 60, 120) to ES_T(P, j), the ES shocking only the
326
+ factors with horizon at least LH_j; a missing horizon contributes nothing, and an entry for 10 days is ES_T(P)
327
+ itself and must equal `es_t_full`.
328
+ """
329
+ full = _nonnegative("es_t_full", es_t_full)
330
+ t = _finite("base_horizon", base_horizon)
331
+ if t <= 0.0:
332
+ raise ValueError(f"base_horizon must be positive, got {base_horizon!r}")
333
+ for lh in es_t_by_horizon:
334
+ if lh not in LIQUIDITY_HORIZONS:
335
+ raise ValueError(
336
+ f"es_t_by_horizon has the horizon {lh!r}, not one of {LIQUIDITY_HORIZONS} days (MAR33.4 Table 1)"
337
+ )
338
+ values = {lh: _nonnegative("es_t_by_horizon", es_t_by_horizon[lh]) for lh in es_t_by_horizon}
339
+ if 10 in values and not math.isclose(values[10], full, rel_tol=1e-9, abs_tol=1e-12):
340
+ raise ValueError("es_t_by_horizon[10] is ES_T(P) and must equal es_t_full")
341
+ total = full * full
342
+ for j in range(1, len(LIQUIDITY_HORIZONS)):
343
+ es_j = values.get(LIQUIDITY_HORIZONS[j], 0.0)
344
+ total += (es_j * math.sqrt((LIQUIDITY_HORIZONS[j] - LIQUIDITY_HORIZONS[j - 1]) / t)) ** 2
345
+ return math.sqrt(total)