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.
- riskvalidation/__init__.py +30 -0
- riskvalidation/aggregation/__init__.py +11 -0
- riskvalidation/aggregation/band.py +151 -0
- riskvalidation/aggregation/bounds.py +191 -0
- riskvalidation/aggregation/copulas.py +241 -0
- riskvalidation/aggregation/model_risk.py +133 -0
- riskvalidation/aggregation/simple.py +147 -0
- riskvalidation/ccr/__init__.py +13 -0
- riskvalidation/ccr/collateral.py +175 -0
- riskvalidation/ccr/cva.py +193 -0
- riskvalidation/ccr/exposure.py +192 -0
- riskvalidation/ccr/hw1f.py +426 -0
- riskvalidation/ccr/swaps.py +172 -0
- riskvalidation/core/__init__.py +1 -0
- riskvalidation/core/build.py +57 -0
- riskvalidation/core/hashing.py +48 -0
- riskvalidation/core/policy.py +130 -0
- riskvalidation/core/registry.py +65 -0
- riskvalidation/core/result.py +117 -0
- riskvalidation/core/suite.py +78 -0
- riskvalidation/engines/__init__.py +2 -0
- riskvalidation/engines/low_default.py +170 -0
- riskvalidation/engines/pd_curve.py +529 -0
- riskvalidation/engines/vasicek.py +72 -0
- riskvalidation/fairness/__init__.py +10 -0
- riskvalidation/fairness/_checks.py +115 -0
- riskvalidation/fairness/conditional.py +201 -0
- riskvalidation/fairness/inference.py +64 -0
- riskvalidation/fairness/metrics.py +261 -0
- riskvalidation/fairness/plants.py +240 -0
- riskvalidation/fairness/policy.py +97 -0
- riskvalidation/fairness/replication.py +39 -0
- riskvalidation/fairness/situation.py +307 -0
- riskvalidation/generators/__init__.py +68 -0
- riskvalidation/generators/_base.py +145 -0
- riskvalidation/generators/counts.py +232 -0
- riskvalidation/generators/drift.py +107 -0
- riskvalidation/generators/framingham.py +124 -0
- riskvalidation/generators/paths.py +349 -0
- riskvalidation/generators/ratings.py +186 -0
- riskvalidation/generators/scores.py +347 -0
- riskvalidation/harness/__init__.py +46 -0
- riskvalidation/harness/exact.py +137 -0
- riskvalidation/harness/performance.py +74 -0
- riskvalidation/harness/rates.py +103 -0
- riskvalidation/harness/run.py +197 -0
- riskvalidation/irrbb/__init__.py +9 -0
- riskvalidation/irrbb/behavioural.py +206 -0
- riskvalidation/irrbb/curves.py +286 -0
- riskvalidation/irrbb/eve_nii.py +245 -0
- riskvalidation/irrbb/shocks.py +171 -0
- riskvalidation/irrbb/simulation.py +203 -0
- riskvalidation/irrbb/slotting.py +184 -0
- riskvalidation/lgd_ead/__init__.py +8 -0
- riskvalidation/lgd_ead/_checks.py +50 -0
- riskvalidation/lgd_ead/ccf.py +228 -0
- riskvalidation/lgd_ead/downturn.py +64 -0
- riskvalidation/lgd_ead/floors.py +114 -0
- riskvalidation/lgd_ead/lgd_models.py +297 -0
- riskvalidation/lgd_ead/workout.py +162 -0
- riskvalidation/liquidity/__init__.py +9 -0
- riskvalidation/liquidity/_checks.py +78 -0
- riskvalidation/liquidity/cbc.py +158 -0
- riskvalidation/liquidity/deposits.py +151 -0
- riskvalidation/liquidity/ladder.py +119 -0
- riskvalidation/liquidity/reverse.py +141 -0
- riskvalidation/liquidity/runoff.py +220 -0
- riskvalidation/liquidity/scenarios.py +272 -0
- riskvalidation/market/__init__.py +8 -0
- riskvalidation/market/caviar.py +239 -0
- riskvalidation/market/conventions.py +83 -0
- riskvalidation/market/evt.py +111 -0
- riskvalidation/market/frtb.py +175 -0
- riskvalidation/market/garch.py +204 -0
- riskvalidation/market/gas_fz.py +219 -0
- riskvalidation/market/historical.py +96 -0
- riskvalidation/market/parametric.py +78 -0
- riskvalidation/market/scoring.py +145 -0
- riskvalidation/ml/__init__.py +11 -0
- riskvalidation/ml/_checks.py +67 -0
- riskvalidation/ml/_logistic.py +82 -0
- riskvalidation/ml/cbpe.py +91 -0
- riskvalidation/ml/challenger.py +73 -0
- riskvalidation/ml/conformal.py +116 -0
- riskvalidation/ml/dataquality.py +130 -0
- riskvalidation/ml/effects.py +67 -0
- riskvalidation/ml/explanations.py +125 -0
- riskvalidation/ml/generalisation.py +79 -0
- riskvalidation/ml/leakage.py +99 -0
- riskvalidation/ml/plants.py +425 -0
- riskvalidation/ml/policy.py +182 -0
- riskvalidation/ml/robustness.py +286 -0
- riskvalidation/ml/seeds.py +106 -0
- riskvalidation/oprisk/__init__.py +18 -0
- riskvalidation/oprisk/_checks.py +60 -0
- riskvalidation/oprisk/aggregate.py +375 -0
- riskvalidation/oprisk/distributions.py +758 -0
- riskvalidation/oprisk/scenarios.py +342 -0
- riskvalidation/oprisk/sla.py +80 -0
- riskvalidation/oprisk/sma.py +169 -0
- riskvalidation/policies/__init__.py +4 -0
- riskvalidation/policies/default.json +273 -0
- riskvalidation/portfolio/__init__.py +16 -0
- riskvalidation/portfolio/asrf_fit.py +283 -0
- riskvalidation/portfolio/copula.py +129 -0
- riskvalidation/portfolio/creditrisk_plus.py +232 -0
- riskvalidation/portfolio/euler.py +126 -0
- riskvalidation/portfolio/granularity.py +135 -0
- riskvalidation/portfolio/importance.py +277 -0
- riskvalidation/portfolio/portfolio.py +309 -0
- riskvalidation/provisions/__init__.py +8 -0
- riskvalidation/provisions/_checks.py +100 -0
- riskvalidation/provisions/ecl.py +233 -0
- riskvalidation/provisions/local_cl.py +360 -0
- riskvalidation/provisions/local_es.py +157 -0
- riskvalidation/provisions/overlays.py +102 -0
- riskvalidation/provisions/reconciliation.py +157 -0
- riskvalidation/provisions/staging.py +211 -0
- riskvalidation/provisions/term_structure.py +199 -0
- riskvalidation/regulatory/__init__.py +14 -0
- riskvalidation/regulatory/ba_cva.py +138 -0
- riskvalidation/regulatory/frtb.py +345 -0
- riskvalidation/regulatory/irb.py +314 -0
- riskvalidation/regulatory/lcr_nsfr.py +369 -0
- riskvalidation/regulatory/output_floor.py +45 -0
- riskvalidation/regulatory/sa_ccr.py +486 -0
- riskvalidation/regulatory/standardised.py +348 -0
- riskvalidation/stress/__init__.py +9 -0
- riskvalidation/stress/capital.py +476 -0
- riskvalidation/stress/paths.py +108 -0
- riskvalidation/stress/reverse.py +179 -0
- riskvalidation/stress/satellites.py +268 -0
- riskvalidation/stress/scenario_models.py +274 -0
- riskvalidation/transitions/__init__.py +0 -0
- riskvalidation/transitions/em.py +120 -0
- riskvalidation/transitions/embedding.py +221 -0
- riskvalidation/transitions/estimators.py +213 -0
- riskvalidation/transitions/intervals.py +306 -0
- riskvalidation/transitions/mobility.py +57 -0
- riskvalidation/transitions/ttc.py +171 -0
- riskvalidation/validation/__init__.py +103 -0
- riskvalidation/validation/_common.py +57 -0
- riskvalidation/validation/aggregation.py +425 -0
- riskvalidation/validation/calibration.py +757 -0
- riskvalidation/validation/ccr.py +530 -0
- riskvalidation/validation/discrimination.py +314 -0
- riskvalidation/validation/fairness.py +632 -0
- riskvalidation/validation/ifrs9.py +693 -0
- riskvalidation/validation/irrbb.py +389 -0
- riskvalidation/validation/lgd_ead.py +469 -0
- riskvalidation/validation/liquidity.py +647 -0
- riskvalidation/validation/market.py +807 -0
- riskvalidation/validation/ml.py +958 -0
- riskvalidation/validation/oprisk.py +357 -0
- riskvalidation/validation/portfolio.py +353 -0
- riskvalidation/validation/rating_system.py +245 -0
- riskvalidation/validation/stability.py +256 -0
- riskvalidation/validation/stress.py +552 -0
- riskvalidation/validation/transitions.py +386 -0
- riskvalidation-0.8.0.dist-info/METADATA +136 -0
- riskvalidation-0.8.0.dist-info/RECORD +164 -0
- riskvalidation-0.8.0.dist-info/WHEEL +5 -0
- riskvalidation-0.8.0.dist-info/licenses/LICENSE +21 -0
- riskvalidation-0.8.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""The model risk measures of dossier 06 B.12 over the set of aggregation models of the band: sensitivity information,
|
|
2
|
+
never a
|
|
3
|
+
regulatory capital figure (dossier 06 l.699-704).
|
|
4
|
+
|
|
5
|
+
- Barrieu and Scandolo (2015), "Assessing financial model risk", European Journal of Operational Research
|
|
6
|
+
242(2):546-556:
|
|
7
|
+
the add-on multiplier AM = max rho / rho(X0) - 1 ("generalizes the Basel multiplier") and the relative measure RM =
|
|
8
|
+
(max rho - rho(X0)) / (max rho - min rho) (dossier 06 l.692-698).
|
|
9
|
+
- Glasserman and Xu (2014), "Robust risk measurement and model risk", Quantitative Finance 14(1):29-58: the worst case
|
|
10
|
+
of
|
|
11
|
+
E[m V] over the likelihood ratios m with relative entropy E[m log m] <= eta is attained at m_theta = exp(theta V) /
|
|
12
|
+
E[exp(theta V)], with theta > 0 set (by bisection) so that the entropy constraint binds (dossier 06 l.684-691); the
|
|
13
|
+
worst
|
|
14
|
+
case is computed by reweighting the baseline sample.
|
|
15
|
+
|
|
16
|
+
Contract: `engine-aggregation-api` 1.0.0, module aggregation.model_risk.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import math
|
|
22
|
+
from collections.abc import Sequence
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
from riskvalidation.portfolio.portfolio import float_vector
|
|
28
|
+
|
|
29
|
+
MAX_DOUBLINGS = 200
|
|
30
|
+
MAX_BISECTIONS = 300
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class ModelRisk:
|
|
35
|
+
"""`rho_x0` the risk measure under the reference model, `rho_max` and `rho_min` over the set (money), `am` =
|
|
36
|
+
rho_max /
|
|
37
|
+
rho_x0 - 1 and `rm` = (rho_max - rho_x0) / (rho_max - rho_min) in [0, 1] (decimals)."""
|
|
38
|
+
|
|
39
|
+
rho_x0: float
|
|
40
|
+
rho_max: float
|
|
41
|
+
rho_min: float
|
|
42
|
+
am: float
|
|
43
|
+
rm: float
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def barrieu_scandolo(rhos: Sequence[float], reference_index: int) -> ModelRisk:
|
|
47
|
+
"""AM and RM of the risk measures `rhos` (money, one per model of the set, the band rows) with the reference model
|
|
48
|
+
at
|
|
49
|
+
`reference_index`. RM is 0 when rho_max = rho_min (this contract's convention for the undefined 0 / 0; UNVERIFIED in
|
|
50
|
+
the paper). Golden: (100, 130, 90) with reference 0 gives AM 0.3 and RM 0.75."""
|
|
51
|
+
x = float_vector(rhos, "rhos")
|
|
52
|
+
if isinstance(reference_index, bool) or not isinstance(reference_index, (int, np.integer)):
|
|
53
|
+
raise ValueError(f"reference_index must be an integer, got {reference_index!r}")
|
|
54
|
+
if not 0 <= reference_index < x.size:
|
|
55
|
+
raise ValueError(f"reference_index must lie in [0, {x.size - 1}], got {reference_index}")
|
|
56
|
+
rho_x0 = float(x[reference_index])
|
|
57
|
+
if not rho_x0 > 0.0:
|
|
58
|
+
raise ValueError(f"rho_x0 (the risk measure under the reference model) must be positive, got {rho_x0}")
|
|
59
|
+
rho_max, rho_min = float(x.max()), float(x.min())
|
|
60
|
+
span = rho_max - rho_min
|
|
61
|
+
rm = 0.0 if span == 0.0 else (rho_max - rho_x0) / span
|
|
62
|
+
return ModelRisk(rho_x0=rho_x0, rho_max=rho_max, rho_min=rho_min, am=rho_max / rho_x0 - 1.0, rm=rm)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class GlassermanXu:
|
|
67
|
+
"""`theta` the tilt (in the inverse units of V), `relative_entropy` E[m log m] at theta (equal to the budget to
|
|
68
|
+
`tol`),
|
|
69
|
+
`baseline` = E[V] and `worst_case` = E[m V] in the units of V."""
|
|
70
|
+
|
|
71
|
+
theta: float
|
|
72
|
+
relative_entropy: float
|
|
73
|
+
baseline: float
|
|
74
|
+
worst_case: float
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _entropy(x: np.ndarray, theta: float) -> tuple[float, np.ndarray]:
|
|
78
|
+
"""The relative entropy E[m log m] of m = exp(theta x) / E exp(theta x) for x <= 0 (stable), and m."""
|
|
79
|
+
log_w = theta * x
|
|
80
|
+
w = np.exp(log_w)
|
|
81
|
+
mean_w = float(w.mean())
|
|
82
|
+
m = w / mean_w
|
|
83
|
+
return float(np.mean(m * (log_w - math.log(mean_w)))), m
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def glasserman_xu_worst_case(v: np.ndarray, budget: float, tol: float = 1e-10) -> GlassermanXu:
|
|
87
|
+
"""sup over m with E[m log m] <= budget of E[m V] on the baseline sample `v` (S,), by the exponential tilt of the
|
|
88
|
+
module
|
|
89
|
+
docstring. `budget` > 0 is the relative entropy budget eta. Refused: a budget that is not attainable on the sample
|
|
90
|
+
(the entropy of the tilt rises to log(S / k) with k the number of sample points at the maximum, at most log S), a
|
|
91
|
+
constant V and a nonpositive budget. Golden: V = (0, 1) equally likely, theta = 1: m = (0.5379, 1.4621), entropy
|
|
92
|
+
0.1109,
|
|
93
|
+
worst case 0.7311 against the baseline 0.5; the budget 0.1109 recovers theta = 1."""
|
|
94
|
+
x = float_vector(v, "v")
|
|
95
|
+
if x.size < 2:
|
|
96
|
+
raise ValueError("v needs at least 2 values")
|
|
97
|
+
eta, eps = float(budget), float(tol)
|
|
98
|
+
if not (math.isfinite(eta) and eta > 0.0):
|
|
99
|
+
raise ValueError(f"budget must be positive, got {budget}")
|
|
100
|
+
if not (math.isfinite(eps) and eps > 0.0):
|
|
101
|
+
raise ValueError(f"tol must be positive, got {tol}")
|
|
102
|
+
spread = float(np.ptp(x))
|
|
103
|
+
if spread == 0.0:
|
|
104
|
+
raise ValueError("v is constant: no tilt changes its mean")
|
|
105
|
+
top = float(x.max())
|
|
106
|
+
attainable = math.log(x.size / int(np.sum(x == top)))
|
|
107
|
+
if eta >= attainable:
|
|
108
|
+
raise ValueError(f"budget {eta} must be below the largest entropy attainable on the sample, log(S / k) = "
|
|
109
|
+
f"{attainable:.6g} (at most log S = {math.log(x.size):.6g})")
|
|
110
|
+
scaled = (x - top) / spread # in [-1, 0]
|
|
111
|
+
hi = 1.0
|
|
112
|
+
for _ in range(MAX_DOUBLINGS):
|
|
113
|
+
if _entropy(scaled, hi)[0] >= eta:
|
|
114
|
+
break
|
|
115
|
+
hi *= 2.0
|
|
116
|
+
else:
|
|
117
|
+
raise ValueError(f"budget {eta} is not reached by any tilt of the sample")
|
|
118
|
+
lo = 0.0
|
|
119
|
+
theta_s, h, m = hi, 0.0, None
|
|
120
|
+
for _ in range(MAX_BISECTIONS):
|
|
121
|
+
theta_s = 0.5 * (lo + hi)
|
|
122
|
+
h, m = _entropy(scaled, theta_s)
|
|
123
|
+
if abs(h - eta) <= eps:
|
|
124
|
+
break
|
|
125
|
+
if h < eta:
|
|
126
|
+
lo = theta_s
|
|
127
|
+
else:
|
|
128
|
+
hi = theta_s
|
|
129
|
+
else:
|
|
130
|
+
raise ValueError(f"the entropy constraint did not bind to tol {eps} (reached {h}, budget {eta})")
|
|
131
|
+
assert m is not None
|
|
132
|
+
return GlassermanXu(theta=theta_s / spread, relative_entropy=h, baseline=float(x.mean()),
|
|
133
|
+
worst_case=float(np.mean(m * x)))
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""The first rungs of the aggregation ladder and the closed-form allocation and diversification quantities (dossier 05
|
|
2
|
+
G.1 items 1, 2 and 4, and G.4).
|
|
3
|
+
|
|
4
|
+
Capital is economic capital on the unexpected-loss basis, `EC = VaR_level(L) - EL` (dossier 04 l.652-653; BCBS 2005
|
|
5
|
+
explanatory note, section 4.4). Money is a float in the caller's currency, correlations are decimals. The simple sum
|
|
6
|
+
is the
|
|
7
|
+
headline capital of the case; every other figure of the aggregation modules is information, not capital (dossier 05
|
|
8
|
+
l.519). The engine computes and states no compliance claim.
|
|
9
|
+
|
|
10
|
+
Contract: `engine-aggregation-api` 1.0.0, module aggregation.simple.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from riskvalidation.portfolio.portfolio import check_level, float_vector, var_from_sample
|
|
21
|
+
|
|
22
|
+
CORR_TOL = 1e-9
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _matrix(x: object, name: str) -> np.ndarray:
|
|
26
|
+
a = np.array(x, dtype=float)
|
|
27
|
+
if a.ndim != 2 or a.shape[0] != a.shape[1]:
|
|
28
|
+
raise ValueError(f"{name} must be a square matrix, got shape {a.shape}")
|
|
29
|
+
if a.size == 0:
|
|
30
|
+
raise ValueError(f"{name} is empty")
|
|
31
|
+
if not np.all(np.isfinite(a)):
|
|
32
|
+
raise ValueError(f"{name} contains non-finite values")
|
|
33
|
+
return a
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _nonnegative_vector(x: object, name: str) -> np.ndarray:
|
|
37
|
+
a = float_vector(x, name)
|
|
38
|
+
if np.any(a < 0.0):
|
|
39
|
+
raise ValueError(f"{name} must not contain a negative element")
|
|
40
|
+
return a
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def simple_sum(ec: np.ndarray) -> float:
|
|
44
|
+
"""The sum of the marginal economic capitals (dossier 05 G.1 item 1), the headline capital of the case.
|
|
45
|
+
|
|
46
|
+
`ec` (K,) money, each >= 0. Equals `variance_covariance(ec, R)` for R all ones. Golden: (3, 4) gives 7.0.
|
|
47
|
+
"""
|
|
48
|
+
return float(np.sum(_nonnegative_vector(ec, "ec")))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def check_correlation(corr: np.ndarray, tol: float = CORR_TOL) -> None:
|
|
52
|
+
"""Raises ValueError unless `corr` is a square, symmetric (to `tol`) matrix with a unit diagonal (to `tol`), every
|
|
53
|
+
entry in [-1, 1] and a smallest eigenvalue >= -tol (positive semi-definite); returns None otherwise."""
|
|
54
|
+
a = _matrix(corr, "corr")
|
|
55
|
+
if not (math.isfinite(tol) and tol >= 0.0):
|
|
56
|
+
raise ValueError("tol must be nonnegative")
|
|
57
|
+
if np.max(np.abs(a - a.T)) > tol:
|
|
58
|
+
raise ValueError("corr must be symmetric")
|
|
59
|
+
if np.max(np.abs(np.diag(a) - 1.0)) > tol:
|
|
60
|
+
raise ValueError("corr must have a unit diagonal")
|
|
61
|
+
if np.any(np.abs(a) > 1.0 + tol):
|
|
62
|
+
raise ValueError("corr entries must lie in [-1, 1]")
|
|
63
|
+
smallest = float(np.linalg.eigvalsh(0.5 * (a + a.T))[0])
|
|
64
|
+
if smallest < -tol:
|
|
65
|
+
raise ValueError(f"corr must be positive semi-definite (smallest eigenvalue {smallest:.6g})")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def variance_covariance(ec: np.ndarray, corr: np.ndarray) -> float:
|
|
69
|
+
"""EC_tot = sqrt(EC' R EC) (dossier 05 G.1 item 2): exact for elliptical losses with a common quantile scaling, an
|
|
70
|
+
approximation otherwise. `ec` (K,) money, `corr` (K, K). Goldens: (3, 4) with R the identity 5.0, R all ones 7.0,
|
|
71
|
+
R = [[1, 0.5], [0.5, 1]] sqrt(37) = 6.0828."""
|
|
72
|
+
e = _nonnegative_vector(ec, "ec")
|
|
73
|
+
r = _matrix(corr, "corr")
|
|
74
|
+
check_correlation(r)
|
|
75
|
+
if r.shape[0] != e.size:
|
|
76
|
+
raise ValueError(f"ec and corr must have the same length, got {e.size} and {r.shape[0]}")
|
|
77
|
+
return math.sqrt(max(float(e @ r @ e), 0.0))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def hybrid_quantile(samples: np.ndarray, q: float) -> float:
|
|
81
|
+
"""The hybrid VaR of Rosenberg and Schuermann (dossier 05 G.1 item 4, "H-VaR"): the quantile of each column combined
|
|
82
|
+
with the empirical correlation of the columns, sqrt(v' R_emp v) with v_k = var_from_sample(samples[:, k], q).
|
|
83
|
+
|
|
84
|
+
`samples` (S, K) money, a loss sample per risk on a common row index. The dossier names the approach and not the
|
|
85
|
+
estimator: the Pearson correlation of the columns is the contract's definition (UNVERIFIED against the paper).
|
|
86
|
+
"""
|
|
87
|
+
x = np.array(samples, dtype=float)
|
|
88
|
+
if x.ndim != 2:
|
|
89
|
+
raise ValueError(f"samples must be two-dimensional, got shape {x.shape}")
|
|
90
|
+
if not np.all(np.isfinite(x)):
|
|
91
|
+
raise ValueError("samples contains non-finite values")
|
|
92
|
+
if x.shape[0] < 2:
|
|
93
|
+
raise ValueError("samples needs at least 2 rows: a correlation is undefined")
|
|
94
|
+
level = check_level(q)
|
|
95
|
+
if np.any(np.ptp(x, axis=0) == 0.0):
|
|
96
|
+
raise ValueError("samples has a constant column: its correlation is undefined")
|
|
97
|
+
v = np.array([var_from_sample(x[:, k], level) for k in range(x.shape[1])])
|
|
98
|
+
if np.any(v < 0.0):
|
|
99
|
+
raise ValueError(f"the square-root formula needs nonnegative quantiles, got {v.tolist()}")
|
|
100
|
+
r = np.corrcoef(x, rowvar=False).reshape(x.shape[1], x.shape[1])
|
|
101
|
+
return math.sqrt(max(float(v @ r @ v), 0.0))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def diversification_factor(rho_total: float, rho_marginals: Sequence[float]) -> float:
|
|
105
|
+
"""DF = rho(L) / sum rho(L_i) (dossier 05 G.4). Not forced to be at most 1: VaR is not subadditive (dossier 05 G.3),
|
|
106
|
+
the sign of every benefit is reported by the validation test and never repaired here. Golden: (6.0828, [3, 4]) gives
|
|
107
|
+
0.8690."""
|
|
108
|
+
total = float(rho_total)
|
|
109
|
+
if not math.isfinite(total):
|
|
110
|
+
raise ValueError("rho_total must be finite")
|
|
111
|
+
parts = float_vector(rho_marginals, "rho_marginals")
|
|
112
|
+
denom = float(parts.sum())
|
|
113
|
+
if denom <= 0.0:
|
|
114
|
+
raise ValueError(f"the sum of rho_marginals must be positive, got {denom}")
|
|
115
|
+
return total / denom
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def euler_diversification_benefit(rho_contribution: float, rho_standalone: float) -> float:
|
|
119
|
+
"""1 - rho(L_i | L) / rho(L_i) (dossier 05 G.4); zero when the contribution equals the standalone measure.
|
|
120
|
+
Golden: (6, 8) gives 0.25."""
|
|
121
|
+
contribution, standalone = float(rho_contribution), float(rho_standalone)
|
|
122
|
+
if not math.isfinite(contribution):
|
|
123
|
+
raise ValueError("rho_contribution must be finite")
|
|
124
|
+
if not (math.isfinite(standalone) and standalone > 0.0):
|
|
125
|
+
raise ValueError(f"rho_standalone must be positive, got {rho_standalone}")
|
|
126
|
+
return 1.0 - contribution / standalone
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def std_contributions(cov: np.ndarray, c: float = 1.0) -> np.ndarray:
|
|
130
|
+
"""The Euler contributions of the standard deviation measure, c cov[L_i, L] / sqrt(var L) (Tasche, eq. 3.4;
|
|
131
|
+
dossier 05
|
|
132
|
+
G.4), so that the variance-covariance total allocates exactly. `cov` (K, K) the covariance of (L_1, ..., L_K) in
|
|
133
|
+
money
|
|
134
|
+
squared. Golden: [[4, 2], [2, 9]] gives (1.4552, 2.6679), summing to sqrt(17) = 4.1231."""
|
|
135
|
+
a = _matrix(cov, "cov")
|
|
136
|
+
mult = float(c)
|
|
137
|
+
if not math.isfinite(mult):
|
|
138
|
+
raise ValueError("c must be finite")
|
|
139
|
+
scale = max(1.0, float(np.max(np.abs(a))))
|
|
140
|
+
if np.max(np.abs(a - a.T)) > CORR_TOL * scale:
|
|
141
|
+
raise ValueError("cov must be symmetric")
|
|
142
|
+
if float(np.linalg.eigvalsh(0.5 * (a + a.T))[0]) < -CORR_TOL * scale:
|
|
143
|
+
raise ValueError("cov must be positive semi-definite")
|
|
144
|
+
var_total = float(a.sum())
|
|
145
|
+
if not var_total > 0.0:
|
|
146
|
+
raise ValueError("the variance of the total is zero: the standard deviation contributions are undefined")
|
|
147
|
+
return mult * a.sum(axis=1) / math.sqrt(var_total)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Counterparty credit risk: the Hull-White one-factor model on any time grid, fixed-float swaps along paths, the
|
|
2
|
+
exposure measures (EE, ENE, effective EE and EPE, PFE, netting, effective maturity), collateral with the margin period
|
|
3
|
+
of risk and the dynamic initial margin, and CVA, DVA and wrong-way risk (dossier 05 C, the U9 research addendum R1 to R6
|
|
4
|
+
and R9).
|
|
5
|
+
|
|
6
|
+
Modules are imported by path (for example ``from riskvalidation.ccr import hw1f``); nothing is
|
|
7
|
+
re-exported here. Money is a float in the currency of the netting set, rates are decimals compounded continuously, times
|
|
8
|
+
are years from the valuation date and the margin period of risk is in business days with 250 to the year. EE is the
|
|
9
|
+
positive exposure to the counterparty, ENE the bank's own reported positive, CVA a positive cost and DVA a positive
|
|
10
|
+
benefit. The engine computes and states no compliance claim. It is pure NumPy and SciPy: ORE and QuantLib never enter
|
|
11
|
+
it, and the reconciliation against them is the caller's. The validation tests are in ``riskvalidation.validation.ccr``.
|
|
12
|
+
Contract: ``engine-ccr-api`` 1.0.0.
|
|
13
|
+
"""
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Collateral, the margin period of risk and the dynamic initial margin: ORE's credit support amount and delivery amount
|
|
2
|
+
equations with the close-out grid approach and a sticky-date close-out (addendum R3, ORE ``xva.tex`` at tag 1.8.17.0),
|
|
3
|
+
the CRE53.24 to CRE53.26 floors, and ORE's regression dynamic initial margin (addendum R2).
|
|
4
|
+
|
|
5
|
+
The Andersen, Pykhtin and Sokol (2017) MPoR timelines are not modelled. The dynamic initial margin is a regression
|
|
6
|
+
proxy, never SIMM: the SIMM methodology is published under a notice that restricts its use to a market participant's own
|
|
7
|
+
transactions, so its risk weights are not reimplemented here. Contract: ``engine-ccr-api`` 1.0.0, module collateral.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
from scipy.stats import norm
|
|
16
|
+
|
|
17
|
+
from riskvalidation.lgd_ead._checks import mat, scalar, vec
|
|
18
|
+
|
|
19
|
+
MIN_QUANTILE = 0.5
|
|
20
|
+
"""The lowest confidence level of the dynamic initial margin: below it the factor ``Phi^-1(q)`` is negative and the DIM
|
|
21
|
+
could not be non-negative."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _nonnegative(x: float, name: str, *, allow_inf: bool = False) -> float:
|
|
25
|
+
v = float(x)
|
|
26
|
+
if math.isnan(v) or (math.isinf(v) and not allow_inf) or v < 0.0:
|
|
27
|
+
raise ValueError(f"{name} must be nonnegative" + (" (infinity allowed)" if allow_inf else ""))
|
|
28
|
+
return v
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def credit_support_amount(npv: np.ndarray, independent_amount: float, threshold_receive: float,
|
|
32
|
+
threshold_pay: float) -> np.ndarray:
|
|
33
|
+
"""With ``x = NPV + IA``: ``max(0, x - Th_rec)`` if ``x >= 0``,
|
|
34
|
+
``min(0, x + Th_pay)`` if ``x < 0`` (ORE ``eq:CSA``). With ``NPV = 0``,
|
|
35
|
+
``Th_rec = 0`` and ``IA > 0`` the amount equals ``IA``: the independent amount is an offset to
|
|
36
|
+
the threshold. A threshold may be infinite (no margin is called on that side)."""
|
|
37
|
+
n = np.array(npv, dtype=float)
|
|
38
|
+
if not np.all(np.isfinite(n)):
|
|
39
|
+
raise ValueError("npv contains non-finite values")
|
|
40
|
+
ia = scalar(independent_amount, "independent_amount")
|
|
41
|
+
th_r = _nonnegative(threshold_receive, "threshold_receive", allow_inf=True)
|
|
42
|
+
th_p = _nonnegative(threshold_pay, "threshold_pay", allow_inf=True)
|
|
43
|
+
x = n + ia
|
|
44
|
+
return np.where(x >= 0.0, np.maximum(0.0, x - th_r), np.minimum(0.0, x + th_p))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def delivery_amount(csa: np.ndarray, collateral: np.ndarray, outstanding_calls: np.ndarray, mta: float) -> np.ndarray:
|
|
48
|
+
"""``Delta = CSA - C - M`` and ``D = Delta`` if
|
|
49
|
+
``|Delta| >= MTA``, else 0 (ORE ``eq:DA``); with ``MTA = 0`` it is ``Delta``."""
|
|
50
|
+
c, k, m = np.array(csa, dtype=float), np.array(collateral, dtype=float), np.array(outstanding_calls, dtype=float)
|
|
51
|
+
if not (c.shape == k.shape == m.shape):
|
|
52
|
+
raise ValueError(
|
|
53
|
+
f"csa, collateral and outstanding_calls must have the same shape, got {c.shape}, {k.shape}, {m.shape}")
|
|
54
|
+
if not (np.all(np.isfinite(c)) and np.all(np.isfinite(k)) and np.all(np.isfinite(m))):
|
|
55
|
+
raise ValueError("csa, collateral and outstanding_calls must be finite")
|
|
56
|
+
t = _nonnegative(mta, "mta")
|
|
57
|
+
delta = c - k - m
|
|
58
|
+
return np.where(np.abs(delta) >= t, delta, 0.0)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def mpor_floor(repo_only: bool = False, n_trades: int = 0, illiquid: bool = False,
|
|
62
|
+
disputes_over_two: bool = False) -> int:
|
|
63
|
+
"""The supervisory floor in business days: 5 for repo-style netting sets and 10 otherwise (CRE53.24); 20 when the
|
|
64
|
+
number of trades exceeds 5000 or the collateral is illiquid or an OTC derivative cannot be easily replaced
|
|
65
|
+
(``illiquid`` covers both); more than two disputes longer than the MPoR over two quarters double the floor that
|
|
66
|
+
applies (CRE53.25)."""
|
|
67
|
+
if int(n_trades) != n_trades or n_trades < 0:
|
|
68
|
+
raise ValueError("n_trades must be a nonnegative integer")
|
|
69
|
+
floor = 5 if repo_only else 10
|
|
70
|
+
if n_trades > 5000 or illiquid:
|
|
71
|
+
floor = 20
|
|
72
|
+
return 2 * floor if disputes_over_two else floor
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def mpor_with_remargining(floor: int, remargining_days: int) -> int:
|
|
76
|
+
"""CRE53.26: ``F + N - 1`` for re-margining every ``N`` days; ``N = 1`` gives ``F``."""
|
|
77
|
+
if int(floor) != floor or floor < 1:
|
|
78
|
+
raise ValueError("floor must be a positive integer")
|
|
79
|
+
if int(remargining_days) != remargining_days or remargining_days < 1:
|
|
80
|
+
raise ValueError("remargining_days must be a positive integer")
|
|
81
|
+
return int(floor) + int(remargining_days) - 1
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def collateralised_exposure(value_closeout: np.ndarray, collateral: np.ndarray) -> np.ndarray:
|
|
85
|
+
"""``max(V(t) - C(t), 0)`` (ORE; Hull and White 2012 equation 4): ``V`` the netting-set value on the
|
|
86
|
+
close-out grid and ``C`` the balance determined at the default date minus the MPoR. Positive even with zero
|
|
87
|
+
thresholds and minimum transfer amounts because of the lag, and tending to zero with the MPoR."""
|
|
88
|
+
v, c = np.array(value_closeout, dtype=float), np.array(collateral, dtype=float)
|
|
89
|
+
if v.shape != c.shape:
|
|
90
|
+
raise ValueError(f"value_closeout and collateral must have the same shape, got {v.shape} and {c.shape}")
|
|
91
|
+
if not (np.all(np.isfinite(v)) and np.all(np.isfinite(c))):
|
|
92
|
+
raise ValueError("value_closeout and collateral must be finite")
|
|
93
|
+
return np.maximum(v - c, 0.0)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def variation_margin_exposure(values_main: np.ndarray, values_closeout: np.ndarray, independent_amount: float,
|
|
97
|
+
threshold_receive: float, threshold_pay: float,
|
|
98
|
+
mta: float) -> tuple[np.ndarray, np.ndarray]:
|
|
99
|
+
"""``(exposure, collateral_balance)`` each (P, K). The balance follows ``credit_support_amount`` and
|
|
100
|
+
``delivery_amount`` on the main grid, date by date from a zero balance with no outstanding calls (each call settles
|
|
101
|
+
at its date, the lag being the close-out grid); the exposure is
|
|
102
|
+
``collateralised_exposure(values_closeout, balance)``. The close-out values are those of the sticky-date
|
|
103
|
+
approach (a swap with no flow in the window needs no spike).
|
|
104
|
+
|
|
105
|
+
A netting set with no CSA (both thresholds infinite) is uncollateralised: ORE takes the default value on the main
|
|
106
|
+
grid, so the exposure is ``max(values_main, 0)`` and the balance 0."""
|
|
107
|
+
vm, vc = mat(values_main, "values_main"), mat(values_closeout, "values_closeout")
|
|
108
|
+
if vm.shape != vc.shape:
|
|
109
|
+
raise ValueError(f"values_closeout must have the shape of values_main {vm.shape}, got {vc.shape}")
|
|
110
|
+
ia = scalar(independent_amount, "independent_amount")
|
|
111
|
+
th_r = _nonnegative(threshold_receive, "threshold_receive", allow_inf=True)
|
|
112
|
+
th_p = _nonnegative(threshold_pay, "threshold_pay", allow_inf=True)
|
|
113
|
+
t = _nonnegative(mta, "mta")
|
|
114
|
+
if math.isinf(th_r) and math.isinf(th_p):
|
|
115
|
+
return np.maximum(vm, 0.0), np.zeros_like(vm)
|
|
116
|
+
balance = np.zeros(vm.shape[0])
|
|
117
|
+
held = np.empty_like(vm)
|
|
118
|
+
zero = np.zeros_like(balance)
|
|
119
|
+
for k in range(vm.shape[1]):
|
|
120
|
+
csa = credit_support_amount(vm[:, k], ia, th_r, th_p)
|
|
121
|
+
balance = balance + delivery_amount(csa, balance, zero, t)
|
|
122
|
+
held[:, k] = balance
|
|
123
|
+
return collateralised_exposure(vc, held), held
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def dynamic_initial_margin(values_now: np.ndarray, values_mpor: np.ndarray, flows: np.ndarray, quantile: float,
|
|
127
|
+
horizon_calendar_days: int, mpor_calendar_days: int, order: int = 2,
|
|
128
|
+
regressor: np.ndarray | None = None) -> np.ndarray:
|
|
129
|
+
"""(P,) the dynamic initial margin per path (ORE ``xva.tex`` and ``dimregressioncalculator.cpp``, addendum R2), a
|
|
130
|
+
regression proxy and never SIMM. ``X = V(t + MPoR) + F - V(t)``; ``E[X^2]``
|
|
131
|
+
is the regression of ``X^2`` on a polynomial of the regressor of the given order (order 0 is the sample variance;
|
|
132
|
+
the default regressor is ``values_now``); ``S = sqrt(max(E[X^2] - E[X]^2, 0))`` with
|
|
133
|
+
``E[X]`` the sample mean; and
|
|
134
|
+
``DIM = Phi^-1(quantile) S sqrt(horizon_calendar_days / mpor_calendar_days)``, both in
|
|
135
|
+
CALENDAR days as ORE computes ``horizonCalendarDays / mporCalendarDays`` (10 business days are 14 calendar
|
|
136
|
+
days, 20 are 28). Zero where ``S`` is zero; non-negative, so the quantile must be at least 0.5."""
|
|
137
|
+
now, nxt, f = vec(values_now, "values_now"), vec(values_mpor, "values_mpor"), vec(flows, "flows")
|
|
138
|
+
for name, arr in (("values_mpor", nxt), ("flows", f)):
|
|
139
|
+
if arr.size != now.size:
|
|
140
|
+
raise ValueError(f"{name} must have the length of values_now ({now.size}), got {arr.size}")
|
|
141
|
+
q = scalar(quantile, "quantile")
|
|
142
|
+
if not MIN_QUANTILE <= q < 1.0:
|
|
143
|
+
raise ValueError(f"quantile must lie in [{MIN_QUANTILE}, 1), got {q}")
|
|
144
|
+
h, m = scalar(horizon_calendar_days, "horizon_calendar_days"), scalar(mpor_calendar_days, "mpor_calendar_days")
|
|
145
|
+
if h <= 0.0:
|
|
146
|
+
raise ValueError("horizon_calendar_days must be positive")
|
|
147
|
+
if m <= 0.0:
|
|
148
|
+
raise ValueError("mpor_calendar_days must be positive")
|
|
149
|
+
if int(order) != order or order < 0:
|
|
150
|
+
raise ValueError("order must be a nonnegative integer")
|
|
151
|
+
reg = now if regressor is None else vec(regressor, "regressor")
|
|
152
|
+
if reg.size != now.size:
|
|
153
|
+
raise ValueError(f"regressor must have the length of values_now ({now.size}), got {reg.size}")
|
|
154
|
+
x = nxt + f - now
|
|
155
|
+
sd = float(np.std(reg))
|
|
156
|
+
z = (reg - float(np.mean(reg))) / sd if sd > 0.0 else np.zeros_like(reg)
|
|
157
|
+
design = np.vander(z, int(order) + 1, increasing=True)
|
|
158
|
+
coef = np.linalg.lstsq(design, x**2, rcond=None)[0]
|
|
159
|
+
second = design @ coef
|
|
160
|
+
s = np.sqrt(np.maximum(second - float(np.mean(x)) ** 2, 0.0))
|
|
161
|
+
return float(norm.ppf(q)) * s * math.sqrt(h / m)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def apply_initial_margin(exposure_before_im: np.ndarray, dim: np.ndarray) -> np.ndarray:
|
|
165
|
+
"""``max(exposure - DIM, 0)`` (ORE ``nettedexposurecalculator.cpp``); at most the exposure, unchanged
|
|
166
|
+
for ``DIM = 0``. IM applies only with variation margin ("don't apply initial margin without VM"): the
|
|
167
|
+
caller passes the VM exposure."""
|
|
168
|
+
e, d = np.array(exposure_before_im, dtype=float), np.array(dim, dtype=float)
|
|
169
|
+
if e.shape != d.shape:
|
|
170
|
+
raise ValueError(f"exposure_before_im and dim must have the same shape, got {e.shape} and {d.shape}")
|
|
171
|
+
if not (np.all(np.isfinite(e)) and np.all(np.isfinite(d))):
|
|
172
|
+
raise ValueError("exposure_before_im and dim must be finite")
|
|
173
|
+
if np.any(d < 0.0):
|
|
174
|
+
raise ValueError("dim must be nonnegative")
|
|
175
|
+
return np.maximum(e - d, 0.0)
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""CVA, DVA and wrong-way risk (dossier 05 C.2; Hull and White 2012, "CVA and wrong way risk", Financial Analysts
|
|
2
|
+
Journal 68(5):58-69, addendum R1): the credit triangle, the discretised CVA and DVA, and the hazard rate that depends on
|
|
3
|
+
the portfolio value, ``h(t) = exp[a(t) + b w(t)]``, with the sequential calibration of ``a(t)``
|
|
4
|
+
of the paper's Appendix.
|
|
5
|
+
|
|
6
|
+
CVA is a positive cost and DVA a positive benefit. The simple bilateral form ``BCVA = CVA - DVA`` is
|
|
7
|
+
the only one; the first-to-default form is not implemented. ORE's wrong-way example is a different model (a correlated
|
|
8
|
+
credit LGM), so no ORE golden applies to ``wwr_cva``. Contract: ``engine-ccr-api`` 1.0.0, module cva.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from scipy.optimize import brentq
|
|
17
|
+
|
|
18
|
+
from riskvalidation.lgd_ead._checks import mat, same_length, scalar, vec
|
|
19
|
+
|
|
20
|
+
LOG_A_BRACKET = (-60.0, 5.0)
|
|
21
|
+
"""The starting bracket of the search for ``a(t_k)``; the upper end is extended until the average survival is below the
|
|
22
|
+
target, the lower end is the hazard exp(-60), essentially zero."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _lgd(x: float, name: str) -> float:
|
|
26
|
+
v = scalar(x, name)
|
|
27
|
+
if not 0.0 < v <= 1.0:
|
|
28
|
+
raise ValueError(f"{name} must lie in (0, 1], got {v}")
|
|
29
|
+
return v
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def survival_from_spread(spread: np.ndarray, t: np.ndarray, lgd: float) -> np.ndarray:
|
|
33
|
+
"""The credit triangle ``lambda = s / LGD`` and
|
|
34
|
+
``S(t) = exp(-s t / LGD)`` (dossier 05 C.2; Hull and White equation 6 and page 13).
|
|
35
|
+
``S(0) = 1``, non-increasing in ``t``, 1 for a zero spread."""
|
|
36
|
+
s = np.array(spread, dtype=float)
|
|
37
|
+
tt = np.array(t, dtype=float)
|
|
38
|
+
if not np.all(np.isfinite(s)) or np.any(s < 0.0):
|
|
39
|
+
raise ValueError("spread must be finite and nonnegative")
|
|
40
|
+
if not np.all(np.isfinite(tt)) or np.any(tt < 0.0):
|
|
41
|
+
raise ValueError("t must be finite and nonnegative")
|
|
42
|
+
return np.exp(-s * tt / _lgd(lgd, "lgd"))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def default_probabilities(survival: np.ndarray) -> np.ndarray:
|
|
46
|
+
"""(K,) ``PD(t_{i-1}, t_i) = S(t_{i-1}) - S(t_i)`` from the (K+1,) survival curve at
|
|
47
|
+
``t_0 = 0, ..., t_K``; non-negative and summing to ``S(0) - S(t_K)``. A survival curve
|
|
48
|
+
that rises or leaves (0, 1] is refused."""
|
|
49
|
+
s = vec(survival, "survival")
|
|
50
|
+
if s.size < 2:
|
|
51
|
+
raise ValueError("survival needs at least 2 points")
|
|
52
|
+
if np.any(s <= 0.0) or np.any(s > 1.0):
|
|
53
|
+
raise ValueError("survival must lie in (0, 1]")
|
|
54
|
+
pd = s[:-1] - s[1:]
|
|
55
|
+
if np.any(pd < 0.0):
|
|
56
|
+
raise ValueError("survival must be non-increasing")
|
|
57
|
+
return pd
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _loss(exposure: np.ndarray, pd: np.ndarray, lgd: float, exposure_name: str, pd_name: str,
|
|
61
|
+
lgd_name: str) -> tuple[float, np.ndarray]:
|
|
62
|
+
e, p = vec(exposure, exposure_name), vec(pd, pd_name)
|
|
63
|
+
same_length(**{exposure_name: e, pd_name: p})
|
|
64
|
+
if np.any(e < 0.0):
|
|
65
|
+
raise ValueError(f"{exposure_name} must be nonnegative")
|
|
66
|
+
if np.any(p < 0.0) or np.any(p > 1.0):
|
|
67
|
+
raise ValueError(f"{pd_name} must lie in [0, 1]")
|
|
68
|
+
terms = p * _lgd(lgd, lgd_name) * e
|
|
69
|
+
return float(np.sum(terms)), terms
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def cva(epe_discounted: np.ndarray, pd: np.ndarray, lgd: float) -> tuple[float, np.ndarray]:
|
|
73
|
+
"""``(cva, terms)``: ``CVA = sum PD(t_{i-1}, t_i) LGD EPE(t_i)`` (dossier 05 C.2,
|
|
74
|
+
the advanced discretisation), a positive cost; ``terms`` (K,) are the bucket terms in money. A zero spread
|
|
75
|
+
(``pd = 0``) gives exactly 0; linear in ``lgd`` and in the EE."""
|
|
76
|
+
return _loss(epe_discounted, pd, lgd, "epe_discounted", "pd", "lgd")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def dva(ene_discounted: np.ndarray, pd_bank: np.ndarray, lgd_bank: float) -> tuple[float, np.ndarray]:
|
|
80
|
+
"""``(dva, terms)``: ``DVA = sum PD_Bank LGD_Bank ENE(t_i)`` with the bank's own
|
|
81
|
+
default probabilities and the discounted ENE (dossier 05 C.2), a positive benefit; zero with a zero bank spread."""
|
|
82
|
+
return _loss(ene_discounted, pd_bank, lgd_bank, "ene_discounted", "pd_bank", "lgd_bank")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def b_from_two_points(w1: float, hazard1: float, w2: float, hazard2: float) -> float:
|
|
86
|
+
"""``b = (ln h2 - ln h1) / (w2 - w1)`` for a flat hazard term
|
|
87
|
+
structure (Hull and White 2012 page 16), per unit of ``w`` (USD million in the paper); ``h1 = h2`` gives
|
|
88
|
+
0."""
|
|
89
|
+
a, b = scalar(w1, "w1"), scalar(w2, "w2")
|
|
90
|
+
h1, h2 = scalar(hazard1, "hazard1"), scalar(hazard2, "hazard2")
|
|
91
|
+
if h1 <= 0.0:
|
|
92
|
+
raise ValueError("hazard1 must be positive")
|
|
93
|
+
if h2 <= 0.0:
|
|
94
|
+
raise ValueError("hazard2 must be positive")
|
|
95
|
+
if a == b:
|
|
96
|
+
raise ValueError("w2 must differ from w1")
|
|
97
|
+
return (math.log(h2) - math.log(h1)) / (b - a)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def wwr_calibrate_a(w: np.ndarray, survival_target: np.ndarray, dt: np.ndarray, b: float, sigma_noise: float = 0.0,
|
|
101
|
+
eps: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray]:
|
|
102
|
+
"""``(a, h)`` with ``a`` (K,) and the hazards ``h`` (P, K) per year:
|
|
103
|
+
``h_ij = exp(a_i + b w_ij + sigma eps_ij)``. Sequential calibration (Hull
|
|
104
|
+
and White Appendix, page 22): for each ``k`` the average over paths of
|
|
105
|
+
``exp(-sum_{i <= k} h_ij dt_i)`` equals ``survival_target[k]``; ``k = 1`` by a root
|
|
106
|
+
search from ``w_1j``, then ``k = 2`` from ``w_2j`` and the ``h_1j``, and so on. ``w`` is the simulated
|
|
107
|
+
portfolio value in the unit ``b`` is stated in and ``survival_target`` the spread-implied survival
|
|
108
|
+
``exp(-s_k t_k / (1 - R))``. With ``b = 0`` every path has the same hazard. A
|
|
109
|
+
target that nonnegative hazards cannot reach (the survival would have to rise) is refused."""
|
|
110
|
+
w_ = mat(w, "w")
|
|
111
|
+
p, k = w_.shape
|
|
112
|
+
tgt, d = vec(survival_target, "survival_target"), vec(dt, "dt")
|
|
113
|
+
if tgt.size != k:
|
|
114
|
+
raise ValueError(f"survival_target must have {k} entries (one per column of w), got {tgt.size}")
|
|
115
|
+
if d.size != k:
|
|
116
|
+
raise ValueError(f"dt must have {k} entries (one per column of w), got {d.size}")
|
|
117
|
+
if np.any(d <= 0.0):
|
|
118
|
+
raise ValueError("dt must be positive")
|
|
119
|
+
if np.any(tgt <= 0.0) or np.any(tgt > 1.0):
|
|
120
|
+
raise ValueError("survival_target must lie in (0, 1]")
|
|
121
|
+
b_, noise = scalar(b, "b"), scalar(sigma_noise, "sigma_noise")
|
|
122
|
+
if noise < 0.0:
|
|
123
|
+
raise ValueError("sigma_noise must be nonnegative")
|
|
124
|
+
shift = b_ * w_
|
|
125
|
+
if noise > 0.0:
|
|
126
|
+
if eps is None:
|
|
127
|
+
raise ValueError("eps is required when sigma_noise is positive")
|
|
128
|
+
e = mat(eps, "eps")
|
|
129
|
+
if e.shape != w_.shape:
|
|
130
|
+
raise ValueError(f"eps must have the shape of w {w_.shape}, got {e.shape}")
|
|
131
|
+
shift = shift + noise * e
|
|
132
|
+
a = np.empty(k)
|
|
133
|
+
h = np.empty((p, k))
|
|
134
|
+
cum = np.zeros(p)
|
|
135
|
+
for i in range(k):
|
|
136
|
+
base = float(np.mean(np.exp(-cum)))
|
|
137
|
+
if not tgt[i] < base:
|
|
138
|
+
raise ValueError(f"survival_target[{i}] = {tgt[i]} cannot be reached with nonnegative hazards: the average "
|
|
139
|
+
f"survival before the step is already {base}")
|
|
140
|
+
|
|
141
|
+
def gap(x: float, i: int = i, cum: np.ndarray = cum) -> float:
|
|
142
|
+
with np.errstate(over="ignore"):
|
|
143
|
+
return float(np.mean(np.exp(-cum - d[i] * np.exp(x + shift[:, i])))) - float(tgt[i])
|
|
144
|
+
|
|
145
|
+
lo, hi = LOG_A_BRACKET
|
|
146
|
+
grow = 0
|
|
147
|
+
while gap(hi) > 0.0 and grow < 40:
|
|
148
|
+
hi += 5.0
|
|
149
|
+
grow += 1
|
|
150
|
+
if gap(lo) <= 0.0 or gap(hi) > 0.0:
|
|
151
|
+
raise ValueError(f"survival_target[{i}] = {tgt[i]} is not reachable within the search bracket")
|
|
152
|
+
a[i] = brentq(gap, lo, hi, xtol=1e-15, maxiter=500)
|
|
153
|
+
with np.errstate(over="ignore"):
|
|
154
|
+
h[:, i] = np.exp(a[i] + shift[:, i])
|
|
155
|
+
cum = cum + h[:, i] * d[i]
|
|
156
|
+
return a, h
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def wwr_cva(w: np.ndarray, exposure_discounted: np.ndarray, survival_target: np.ndarray, dt: np.ndarray, lgd: float,
|
|
160
|
+
b: float) -> tuple[float, float]:
|
|
161
|
+
"""``(cva, mc_se)`` of the Hull and White model:
|
|
162
|
+
``CVA = LGD sum_i mean_j [PD_ij E_ij]`` with ``PD_ij`` the path-wise default
|
|
163
|
+
probability of bucket ``i``, ``S_ij(t_{i-1}) - S_ij(t_i)``, from the hazards of ``wwr_calibrate_a``;
|
|
164
|
+
``E_ij`` is the discounted positive exposure (P, K) and ``mc_se`` the standard error of the path mean. With
|
|
165
|
+
``b = 0`` the hazard does not depend on the path and the value is that of the independent ``cva`` on the
|
|
166
|
+
same paths, computed by it (bit for bit). Wrong-way risk (``b > 0`` with a positively correlated exposure)
|
|
167
|
+
raises CVA."""
|
|
168
|
+
w_ = mat(w, "w")
|
|
169
|
+
e = mat(exposure_discounted, "exposure_discounted")
|
|
170
|
+
if e.shape != w_.shape:
|
|
171
|
+
raise ValueError(f"exposure_discounted must have the shape of w {w_.shape}, got {e.shape}")
|
|
172
|
+
if np.any(e < 0.0):
|
|
173
|
+
raise ValueError("exposure_discounted must be nonnegative")
|
|
174
|
+
lg = _lgd(lgd, "lgd")
|
|
175
|
+
tgt = vec(survival_target, "survival_target")
|
|
176
|
+
p = w_.shape[0]
|
|
177
|
+
d = vec(dt, "dt")
|
|
178
|
+
if d.size != w_.shape[1] or np.any(d <= 0.0):
|
|
179
|
+
raise ValueError(f"dt must have {w_.shape[1]} positive entries, got {d.size} entries with a minimum of "
|
|
180
|
+
f"{float(d.min()) if d.size else float('nan')}")
|
|
181
|
+
if scalar(b, "b") == 0.0:
|
|
182
|
+
if tgt.size != w_.shape[1]:
|
|
183
|
+
raise ValueError(f"survival_target must have {w_.shape[1]} entries, got {tgt.size}")
|
|
184
|
+
pd = default_probabilities(np.concatenate([[1.0], tgt]))
|
|
185
|
+
value, _ = cva(e.mean(axis=0), pd, lg)
|
|
186
|
+
per_path = lg * (e @ pd)
|
|
187
|
+
else:
|
|
188
|
+
_, h = wwr_calibrate_a(w_, tgt, dt, b)
|
|
189
|
+
surv = np.exp(-np.cumsum(h * d[None, :], axis=1))
|
|
190
|
+
full = np.hstack([np.ones((p, 1)), surv])
|
|
191
|
+
per_path = lg * np.sum((full[:, :-1] - full[:, 1:]) * e, axis=1)
|
|
192
|
+
value = float(per_path.mean())
|
|
193
|
+
return value, float(per_path.std(ddof=1) / math.sqrt(p))
|