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,192 @@
1
+ """Exposure measures of a netting set (dossier 05 C.1; CRE53.11 to CRE53.20 from the addendum R9): EE and ENE, the
2
+ effective EE and EPE, PFE, netting, the effective maturity, the analytic EE of a single swap (ladder rung 2) and ladder
3
+ rung 1.
4
+
5
+ EE is the positive exposure to the counterparty, ENE the bank's own reported positive. Paths are rows, grid points
6
+ columns. Contract: ``engine-ccr-api`` 1.0.0, module exposure.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib
12
+ import math
13
+ from collections.abc import Callable
14
+
15
+ import numpy as np
16
+
17
+ from riskvalidation.ccr.hw1f import swaption_jamshidian
18
+ from riskvalidation.ccr.swaps import TIME_TOL, Swap, _accruals, cash_flow_times, reset_times
19
+ from riskvalidation.lgd_ead._checks import mat, same_length, scalar, vec
20
+
21
+ HORIZON_TOL = 1e-9
22
+ """Tolerance, in years, when a grid point is compared with the one-year horizon."""
23
+
24
+
25
+ def _grid(grid: np.ndarray) -> np.ndarray:
26
+ g = vec(grid, "grid")
27
+ if g[0] < 0.0 or np.any(np.diff(g) <= 0.0):
28
+ raise ValueError("grid must be nonnegative and strictly increasing")
29
+ return g
30
+
31
+
32
+ def expected_exposure(values: np.ndarray, numeraire: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray]:
33
+ """``(ee, mc_se)`` each (K,): ``ee = mean(max(values, 0) / N)`` and its Monte Carlo
34
+ standard error ``std / sqrt(P)`` (sample standard deviation, ``ddof = 1``). ``numeraire`` (P, K)
35
+ is ``N(t)`` for the discounted measure, ``None`` for the undiscounted Basel style. ENE is
36
+ ``expected_exposure(-values)``."""
37
+ v = mat(values, "values")
38
+ if v.shape[0] < 2:
39
+ raise ValueError("values needs at least 2 paths")
40
+ if numeraire is None:
41
+ pos = np.maximum(v, 0.0)
42
+ else:
43
+ n = mat(numeraire, "numeraire")
44
+ if n.shape != v.shape:
45
+ raise ValueError(f"numeraire must have the shape of values {v.shape}, got {n.shape}")
46
+ if np.any(n <= 0.0):
47
+ raise ValueError("numeraire must be positive")
48
+ pos = np.maximum(v, 0.0) / n
49
+ return pos.mean(axis=0), pos.std(axis=0, ddof=1) / math.sqrt(v.shape[0])
50
+
51
+
52
+ def effective_ee(ee: np.ndarray, current_exposure: float = 0.0) -> np.ndarray:
53
+ """``Effective EE_{t_k} = max(Effective EE_{t_{k-1}}, EE_{t_k})`` with
54
+ ``Effective EE_{t_0}`` the current exposure (CRE53.12 equation 2); non-decreasing and at least ``ee``."""
55
+ e = vec(ee, "ee")
56
+ c = scalar(current_exposure, "current_exposure")
57
+ return np.maximum.accumulate(np.maximum(e, c))
58
+
59
+
60
+ def _time_average(grid: np.ndarray, profile: np.ndarray, horizon: float, name: str) -> float:
61
+ g = _grid(grid)
62
+ p = vec(profile, name)
63
+ same_length(grid=g, **{name: p})
64
+ h = scalar(horizon, "horizon")
65
+ if h <= 0.0:
66
+ raise ValueError("horizon must be positive")
67
+ mask = g <= h + HORIZON_TOL
68
+ if not np.any(mask):
69
+ raise ValueError(f"horizon: no grid point at or before {h} (the first is {g[0]})")
70
+ dt = np.diff(np.concatenate([[0.0], g]))
71
+ covered = float(g[mask][-1])
72
+ if covered <= 0.0:
73
+ raise ValueError("horizon: the covered time is zero")
74
+ return float(np.sum((p * dt)[mask]) / covered)
75
+
76
+
77
+ def effective_epe(grid: np.ndarray, eff_ee: np.ndarray, horizon: float = 1.0) -> float:
78
+ """The effective EPE (EEPE): ``sum_{t_k <= min(1, maturity)} Effective EE_k dt_k``
79
+ with ``dt_k = t_k - t_{k-1}``, ``t_0 = 0`` (CRE53.13 equation 3), normalised by the
80
+ covered time so that a constant profile returns its value."""
81
+ return _time_average(grid, eff_ee, horizon, "eff_ee")
82
+
83
+
84
+ def epe(grid: np.ndarray, ee: np.ndarray, horizon: float = 1.0) -> float:
85
+ """The plain time-weighted average of EE over the first year (dossier 05 C.1, ``EPE_B``)."""
86
+ return _time_average(grid, ee, horizon, "ee")
87
+
88
+
89
+ def pfe(values: np.ndarray, quantile: float, seed: int = 0, n_bootstrap: int = 200) -> tuple[np.ndarray, np.ndarray]:
90
+ """``(pfe, mc_se)`` each (K,):
91
+ ``PFE_alpha(t) = (inf {x : F_t(x) >= alpha})^+``, the positive part of the
92
+ inverse empirical quantile. The standard error is the order-statistic one,
93
+ ``sqrt(q (1 - q) / P) / density``, estimated by the standard deviation of the
94
+ quantile over ``n_bootstrap`` seeded resamples of the paths."""
95
+ v = mat(values, "values")
96
+ q = scalar(quantile, "quantile")
97
+ if not 0.0 < q < 1.0:
98
+ raise ValueError("quantile must lie in (0, 1)")
99
+ nb = int(n_bootstrap)
100
+ if nb != n_bootstrap or nb < 2:
101
+ raise ValueError("n_bootstrap must be an integer of at least 2")
102
+ p = v.shape[0]
103
+ point = np.maximum(np.quantile(v, q, axis=0, method="inverted_cdf"), 0.0)
104
+ rng = np.random.default_rng(seed)
105
+ boot = np.empty((nb, v.shape[1]))
106
+ for b in range(nb):
107
+ boot[b] = np.quantile(v[rng.integers(0, p, size=p)], q, axis=0, method="inverted_cdf")
108
+ return point, boot.std(axis=0, ddof=1)
109
+
110
+
111
+ def net_values(values_by_trade: np.ndarray) -> np.ndarray:
112
+ """(P, K) the netting-set value: the sum over trades of the (S, P, K) values. The netted EE is at most the sum of
113
+ the single-trade EE; the difference is the netting benefit."""
114
+ c = np.array(values_by_trade, dtype=float)
115
+ if c.ndim != 3:
116
+ raise ValueError(f"values_by_trade must be three-dimensional (S, P, K), got shape {c.shape}")
117
+ if c.size == 0 or not np.all(np.isfinite(c)):
118
+ raise ValueError("values_by_trade is empty or contains non-finite values")
119
+ return c.sum(axis=0)
120
+
121
+
122
+ def netting_benefit(ee_by_trade: np.ndarray, ee_netted: np.ndarray) -> np.ndarray:
123
+ """(K,) ``sum_s EE_s - EE_netted``; non-negative when the EEs come from the same paths."""
124
+ e = mat(ee_by_trade, "ee_by_trade")
125
+ n = vec(ee_netted, "ee_netted")
126
+ if e.shape[1] != n.size:
127
+ raise ValueError(f"ee_netted has {n.size} points for ee_by_trade with {e.shape[1]} columns")
128
+ return e.sum(axis=0) - n
129
+
130
+
131
+ def effective_maturity(grid: np.ndarray, ee: np.ndarray, eff_ee: np.ndarray, df: np.ndarray, cap: float = 5.0) -> float:
132
+ """CRE53.20:
133
+ ``M = (sum_{t_k <= 1} EffEE dt df + sum_{t_k > 1} EE dt df) / (sum_{t_k <= 1} EffEE dt df)``,
134
+ capped at ``cap`` (5 years); 1 exactly when every point is within one year. Raises when the effective EE is zero
135
+ over the first year (the ratio is undefined)."""
136
+ g = _grid(grid)
137
+ e, f, d = vec(ee, "ee"), vec(eff_ee, "eff_ee"), vec(df, "df")
138
+ same_length(grid=g, ee=e, eff_ee=f, df=d)
139
+ c = scalar(cap, "cap")
140
+ if c < 1.0:
141
+ raise ValueError("cap must be at least 1")
142
+ if np.any(d <= 0.0):
143
+ raise ValueError("df must be positive")
144
+ dt = np.diff(np.concatenate([[0.0], g]))
145
+ first = g <= 1.0 + HORIZON_TOL
146
+ s1 = float(np.sum((f * dt * d)[first]))
147
+ if s1 <= 0.0:
148
+ raise ValueError("eff_ee is zero over the first year: the effective maturity is undefined")
149
+ s2 = float(np.sum((e * dt * d)[~first]))
150
+ return min((s1 + s2) / s1, c)
151
+
152
+
153
+ def analytic_ee_single_swap(swap: Swap, grid: np.ndarray, a: float, sigma: float, p0: Callable,
154
+ forward: Callable) -> np.ndarray:
155
+ """(K,) the undiscounted EE of a single swap, ladder rung 2 (addendum R4, derived):
156
+ ``EE_B(t) = Swaption(0; t) / P(0, t)``, the payer swaption for a payer swap and the
157
+ receiver one for a receiver swap, expiring at ``t`` on the remaining swap (flows at or before ``t`` excluded) from
158
+ ``swaption_jamshidian``. The identity holds on the reset dates only, so a grid point that is neither a reset date
159
+ nor at or after the maturity raises ``ValueError``; EE is 0 from the maturity.
160
+
161
+ The identity is a statement of the risk-neutral measure: compare the discounted simulated EE with ``P(0, t)``
162
+ times this profile, a check of the engine and not of a real-world exposure."""
163
+ g = _grid(grid)
164
+ times, resets, accr = cash_flow_times(swap), reset_times(swap), _accruals(swap)
165
+ out = np.zeros(g.size)
166
+ for k, t in enumerate(g):
167
+ if t >= swap.maturity - TIME_TOL:
168
+ continue
169
+ if np.min(np.abs(resets - t)) > TIME_TOL:
170
+ raise ValueError(f"grid point t={t} is neither a reset date of the swap nor at or after its maturity: "
171
+ "the analytic EE holds on the reset dates only")
172
+ after = times > t + TIME_TOL
173
+ amounts = swap.notional * swap.fixed_rate * accr[after]
174
+ amounts[-1] += swap.notional
175
+ price = swaption_jamshidian(swap.is_payer, float(t), times[after], amounts, a, sigma, p0, forward,
176
+ nominal=swap.notional)
177
+ out[k] = price / float(np.asarray(p0(np.array(float(t)))))
178
+ return out
179
+
180
+
181
+ def rung1_ead(v: float, c: float, addon_aggregate: float, margined: bool = False, th: float = 0.0, mta: float = 0.0,
182
+ nica: float = 0.0) -> float:
183
+ """Ladder rung 1 (decision D3): SA-CCR's ``1.4 (RC + PFE)``, a thin wrapper of
184
+ ``riskvalidation.regulatory.sa_ccr.netting_set_ead`` that only ties the ladder numbering to a public name; the
185
+ result equals its ``.ead`` exactly. The aggregate add-on is the sum of the five asset classes (CRE52.24), so it is
186
+ carried whole in one class and the rest are zero. The module is resolved when called (it ships with unit U9-E1)."""
187
+ agg = scalar(addon_aggregate, "addon_aggregate")
188
+ if agg < 0.0:
189
+ raise ValueError("addon_aggregate must be nonnegative")
190
+ sa = importlib.import_module("riskvalidation.regulatory.sa_ccr")
191
+ result = sa.netting_set_ead(v, c, sa.AddOnByClass(interest_rate=agg), margined, th, mta, nica)
192
+ return result.ead
@@ -0,0 +1,426 @@
1
+ """The Hull-White one-factor model on any time grid: ``r_t = phi(t) + x_t`` with ``x_t`` an
2
+ Ornstein-Uhlenbeck process ``dx = -a x dt + sigma dW`` (addendum R4, QuantLib 1.44
3
+ ``hullwhite.hpp``), its affine bond prices, the zero-coupon bond option and the Jamshidian swaption, and the historical
4
+ AR(1) estimate of ``a`` and ``sigma`` (addendum R6, Brigo et al. arXiv 0812.4210).
5
+
6
+ The curve and forward functions of ``irrbb.curves`` and ``irrbb.simulation`` are reused by import, never copied, and
7
+ ``irrbb.simulation.hw1f_scenarios`` is unchanged (contract ``engine-irrbb-api``). Contract: ``engine-ccr-api`` 1.0.0,
8
+ module hw1f. A curve is passed as two callables on arrays of years: ``p0(t)`` today's discount factor ``P(0, t)``
9
+ and ``forward(t)`` the instantaneous forward ``f(0, t)``; ``curve_functions`` builds them from a zero curve. Every
10
+ function with randomness takes a seed and uses ``numpy.random.default_rng(seed)``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import datetime as _dt
16
+ import math
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass
19
+
20
+ import numpy as np
21
+ from scipy.optimize import brentq
22
+ from scipy.special import ndtr
23
+
24
+ from riskvalidation.irrbb.curves import zero_rates_at
25
+ from riskvalidation.irrbb.simulation import _forward_curve
26
+ from riskvalidation.lgd_ead._checks import mat, same_length, scalar, vec
27
+
28
+ SQRT_EPS = math.sqrt(float(np.finfo(float).eps))
29
+ """Below this mean reversion the closed forms use their limit (QuantLib ``hullwhite.cpp``: ``a < sqrt(eps)``)."""
30
+
31
+ JAMSHIDIAN_BRACKET = (-10.0, 10.0)
32
+ """The bracket of the Brent search for r* (QuantLib ``jamshidianswaptionengine.cpp``, addendum R4)."""
33
+
34
+ JAMSHIDIAN_XTOL = 1e-12
35
+ """The tolerance of the Brent search. QuantLib uses 1e-8; the engine solves tighter so that the parity identity of the
36
+ swaption holds to 1e-9 for any bracket."""
37
+
38
+ DAYS_PER_YEAR = 365.25
39
+ """Calendar days to years, used only for the default step and the history span of ``calibrate_ar1``."""
40
+
41
+ Curve = Callable[[np.ndarray], np.ndarray]
42
+
43
+
44
+ def _eval(fn: Callable, x: np.ndarray | float) -> np.ndarray:
45
+ """A curve callable on an array (or a scalar) of times, returned as a float array of the same shape."""
46
+ arg = np.asarray(x, dtype=float)
47
+ return np.asarray(fn(arg), dtype=float).reshape(arg.shape)
48
+
49
+
50
+ def _mean_reversion(a: float) -> float:
51
+ v = scalar(a, "a")
52
+ if v < 0.0:
53
+ raise ValueError("a (mean reversion) must be nonnegative")
54
+ return v
55
+
56
+
57
+ def _volatility(sigma: float) -> float:
58
+ v = scalar(sigma, "sigma")
59
+ if v < 0.0:
60
+ raise ValueError("sigma must be nonnegative")
61
+ return v
62
+
63
+
64
+ def _times(x: np.ndarray | float, name: str) -> np.ndarray:
65
+ a = np.array(x, dtype=float)
66
+ if not np.all(np.isfinite(a)):
67
+ raise ValueError(f"{name} contains non-finite values")
68
+ if np.any(a < 0.0):
69
+ raise ValueError(f"{name} must be nonnegative")
70
+ return a
71
+
72
+
73
+ def curve_functions(zero_rates: np.ndarray, tenors: np.ndarray) -> tuple[Curve, Curve]:
74
+ """``(p0, forward)`` of a continuously compounded zero curve, linear in tenor with flat extrapolation:
75
+ ``P(0, t) = exp(-R(t) t)`` through ``irrbb.curves.zero_rates_at`` and
76
+ ``f(0, t) = R(t) + t R'(t)`` through ``irrbb.simulation._forward_curve``. Both accept
77
+ an array or a scalar of years."""
78
+ z, ten = vec(zero_rates, "zero_rates"), vec(tenors, "tenors")
79
+ same_length(zero_rates=z, tenors=ten)
80
+ if np.any(np.diff(ten) <= 0.0) or ten[0] <= 0.0:
81
+ raise ValueError("tenors must be strictly increasing and positive")
82
+
83
+ def p0(t: np.ndarray) -> np.ndarray:
84
+ flat = np.asarray(t, dtype=float).reshape(-1)
85
+ return np.exp(-zero_rates_at(ten, z, flat) * flat).reshape(np.shape(t))
86
+
87
+ def forward(t: np.ndarray) -> np.ndarray:
88
+ flat = np.asarray(t, dtype=float).reshape(-1)
89
+ return _forward_curve(z, ten, flat).reshape(np.shape(t))
90
+
91
+ return p0, forward
92
+
93
+
94
+ def phi(t: np.ndarray, a: float, sigma: float, forward: Curve) -> np.ndarray:
95
+ """The fitting parameter
96
+ ``phi(t) = f(0, t) + (sigma (1 - exp(-a t)) / a)^2 / 2``
97
+ (QuantLib ``FittingParameter``); for ``a`` below ``sqrt(eps)`` the bracket is ``sigma t``.
98
+ ``phi(0) = f(0, 0)`` and ``sigma = 0`` gives ``f(0, t)``."""
99
+ tt = _times(t, "t")
100
+ a_, s_ = _mean_reversion(a), _volatility(sigma)
101
+ bracket = s_ * bond_b(np.zeros_like(tt), tt, a_)
102
+ return _eval(forward, tt) + 0.5 * bracket**2
103
+
104
+
105
+ def bond_b(t: np.ndarray, big_t: np.ndarray, a: float) -> np.ndarray:
106
+ """``B(t, T) = (1 - exp(-a (T - t))) / a``, ``T - t`` for ``a`` below ``sqrt(eps)``; zero at ``T = t``."""
107
+ t_, big = _times(t, "t"), _times(big_t, "big_t")
108
+ a_ = _mean_reversion(a)
109
+ tau = big - t_
110
+ if np.any(tau < -1e-12):
111
+ raise ValueError("big_t must not be before t")
112
+ tau = np.maximum(tau, 0.0)
113
+ if a_ < SQRT_EPS:
114
+ return tau
115
+ return -np.expm1(-a_ * tau) / a_
116
+
117
+
118
+ def bond_a(t: np.ndarray, big_t: np.ndarray, a: float, sigma: float, p0: Curve, forward: Curve) -> np.ndarray:
119
+ """``A(t, T) = P(0, T) / P(0, t) exp(B f(0, t) - sigma^2 / (4 a) (1 - exp(-2 a t)) B^2)``
120
+ (``HullWhite::A``, written as ``0.25 (sigma B)^2 B(0, 2 t)`` so that the limit ``a`` to 0
121
+ needs no division). ``A(t, t) = 1``; at ``t = 0`` it is
122
+ ``P(0, T) exp(B(0, T) f(0, 0))``, not ``P(0, T)``."""
123
+ t_, big = _times(t, "t"), _times(big_t, "big_t")
124
+ a_, s_ = _mean_reversion(a), _volatility(sigma)
125
+ b = bond_b(t_, big, a_)
126
+ b2t = bond_b(np.zeros_like(t_), 2.0 * t_, a_)
127
+ ratio = _eval(p0, big) / _eval(p0, t_)
128
+ return ratio * np.exp(b * _eval(forward, t_) - 0.25 * (s_ * b) ** 2 * b2t)
129
+
130
+
131
+ def bond_price(r: np.ndarray, t: float, big_t: float, a: float, sigma: float, p0: Curve, forward: Curve) -> np.ndarray:
132
+ """``P(t, T) = A(t, T) exp(-B(t, T) r)`` for the short rates ``r`` at ``t``. At
133
+ ``t = 0`` with ``r = phi(0)`` it reprices ``P(0, T)`` to 1e-12; decreasing in ``r``."""
134
+ rr = np.array(r, dtype=float)
135
+ if not np.all(np.isfinite(rr)):
136
+ raise ValueError("r contains non-finite values")
137
+ tt, big = scalar(t, "t"), scalar(big_t, "big_t")
138
+ if tt < 0.0 or big < tt - 1e-12:
139
+ raise ValueError(f"t must satisfy 0 <= t <= big_t, got t={tt} and big_t={big}")
140
+ big = max(big, tt)
141
+ ta, ba = np.array(tt), np.array(big)
142
+ return bond_a(ta, ba, a, sigma, p0, forward) * np.exp(-bond_b(ta, ba, a) * rr)
143
+
144
+
145
+ def simulate_state(grid: np.ndarray, a: float, sigma: float, n_paths: int, seed: int,
146
+ antithetic: bool = True) -> np.ndarray:
147
+ """(P, K) paths of the Ornstein-Uhlenbeck state with ``x(0) = 0``, simulated exactly:
148
+ ``x(t_i) = x(t_{i-1}) e^{-a dt} + sigma sqrt((1 - e^{-2 a dt}) / (2 a)) z``
149
+ (addendum R6, equations 49 to 52), so the law does not depend on the step. Antithetic: the second half mirrors the
150
+ first (path ``i + P / 2`` is minus path ``i``), so the sample mean is zero and ``n_paths`` must
151
+ be even."""
152
+ g = vec(grid, "grid")
153
+ if g[0] != 0.0 or np.any(np.diff(g) <= 0.0):
154
+ raise ValueError("grid must start at 0 and be strictly increasing")
155
+ a_, s_ = _mean_reversion(a), _volatility(sigma)
156
+ n = int(n_paths)
157
+ if n != n_paths or n < 1:
158
+ raise ValueError("n_paths must be a positive integer")
159
+ if antithetic and n % 2:
160
+ raise ValueError(f"n_paths must be even with antithetic paths, got {n}")
161
+ rng = np.random.default_rng(seed)
162
+ half = n // 2 if antithetic else n
163
+ z = rng.standard_normal((half, g.size - 1))
164
+ if antithetic:
165
+ z = np.vstack([z, -z])
166
+ dt = np.diff(g)
167
+ decay = np.exp(-a_ * dt)
168
+ if a_ < SQRT_EPS:
169
+ vol = s_ * np.sqrt(dt)
170
+ else:
171
+ vol = s_ * np.sqrt(-np.expm1(-2.0 * a_ * dt) / (2.0 * a_))
172
+ x = np.zeros((n, g.size))
173
+ for k in range(g.size - 1):
174
+ x[:, k + 1] = x[:, k] * decay[k] + vol[k] * z[:, k]
175
+ return x
176
+
177
+
178
+ def simulate_short_rate(grid: np.ndarray, a: float, sigma: float, forward: Curve, n_paths: int,
179
+ seed: int) -> np.ndarray:
180
+ """(P, K) short rates ``r = phi(t) + x`` on the grid, antithetic (``n_paths`` even). The mean of
181
+ ``r(t)`` is ``phi(t)`` and the discounted bond prices are martingales (``bank_account`` is the numeraire)."""
182
+ x = simulate_state(grid, a, sigma, n_paths, seed)
183
+ return x + phi(np.asarray(grid, dtype=float), a, sigma, forward)[None, :]
184
+
185
+
186
+ PHI_SERIES_THRESHOLD = 0.5
187
+ """Below ``a t`` of this size the integral of ``phi`` uses its power series in ``a t`` (the limit ``t^3 / 6`` and its
188
+ corrections, truncated at about 1e-12 relative); above it the closed form, whose cancellation is about
189
+ ``eps / (a t)^2`` relative to the term (4e-16)."""
190
+
191
+ _PHI_SERIES = tuple((-1.0) ** k * (2.0**k - 2.0) / math.factorial(k + 1) / 2.0 for k in range(2, 19))
192
+ """Coefficients ``c_k`` of ``(1 / (2 a^2)) [t - 2 (1 - e^{-a t}) / a + (1 - e^{-2 a t}) / (2 a)]``, which is
193
+ ``t^3 sum_k c_k (a t)^{k-2}``,
194
+ from the expansions of the two exponentials; ``c_2 = 1/6`` is the limit."""
195
+
196
+
197
+ def _phi_integral_term(t: np.ndarray, a: float) -> np.ndarray:
198
+ """``(1 / (2 a^2)) [t - 2 (1 - e^{-a t}) / a + (1 - e^{-2 a t}) / (2 a)]``, the part of the integral of ``phi``
199
+ from 0 to ``t`` that is multiplied by ``sigma^2``; ``t^3 / 6`` in the limit ``a`` to 0. Where ``a t`` is below
200
+ ``PHI_SERIES_THRESHOLD`` the series is used, so that the closed form never loses its digits to cancellation."""
201
+ tt = np.asarray(t, dtype=float)
202
+ u = a * tt
203
+ series = np.zeros_like(tt)
204
+ for c in reversed(_PHI_SERIES):
205
+ series = series * u + c
206
+ series = tt**3 * series
207
+ if a == 0.0:
208
+ return series
209
+ closed = (tt + (2.0 * np.expm1(-u) - 0.5 * np.expm1(-2.0 * u)) / a) / (2.0 * a**2)
210
+ return np.where(u < PHI_SERIES_THRESHOLD, series, closed)
211
+
212
+
213
+ def bank_account(grid: np.ndarray, short_rate: np.ndarray, a: float, sigma: float, p0: Curve,
214
+ forward: Curve) -> np.ndarray:
215
+ """(P, K) the numeraire ``N(t) = exp(integral of r)`` of the paths, ``N(0) = 1``, the numeraire of
216
+ ``exposure.expected_exposure`` in the discounted measure.
217
+
218
+ With ``r = phi + x`` the deterministic part is integrated exactly,
219
+ ``integral_0^t phi = -ln P(0, t) + sigma^2 (1 / (2 a^2)) [t - 2 (1 - e^{-a t}) / a + (1 - e^{-2 a t}) / (2 a)]``
220
+ (``sigma^2 t^3 / 6`` as ``a`` tends to 0), and only the state ``x = r - phi`` is integrated by the trapezoid rule
221
+ on the grid. The trapezoid on ``r`` itself misses the integral of ``phi`` by an amount that depends on the grid
222
+ (the forward of a zero curve jumps at its pillars), a bias in every discounted exposure. At ``sigma = 0`` the
223
+ discount factor ``1 / N(t)`` is ``P(0, t)`` on any grid. ``a``, ``sigma``, ``p0`` and ``forward`` are those of
224
+ ``simulate_short_rate``."""
225
+ g = vec(grid, "grid")
226
+ if g[0] != 0.0 or np.any(np.diff(g) <= 0.0):
227
+ raise ValueError("grid must start at 0 and be strictly increasing")
228
+ r = mat(short_rate, "short_rate")
229
+ if r.shape[1] != g.size:
230
+ raise ValueError(f"short_rate has {r.shape[1]} columns for a grid of {g.size} points")
231
+ a_, s_ = _mean_reversion(a), _volatility(sigma)
232
+ x = r - phi(g, a_, s_, forward)[None, :]
233
+ area = np.cumsum(0.5 * (x[:, 1:] + x[:, :-1]) * np.diff(g)[None, :], axis=1)
234
+ det = -np.log(_eval(p0, g)) + s_**2 * _phi_integral_term(g, a_)
235
+ return np.exp(np.hstack([np.zeros((r.shape[0], 1)), area]) + det[None, :])
236
+
237
+
238
+ def bond_option_vol(expiry: float, bond_maturity: float, a: float, sigma: float) -> float:
239
+ """``sigma_p = sigma B(T, S) sqrt((1 - e^{-2 a T}) / (2 a))``
240
+ of ``HullWhite::discountBondOption`` (``sigma B sqrt(T)`` for ``a`` below ``sqrt(eps)``)."""
241
+ big_t, s = scalar(expiry, "expiry"), scalar(bond_maturity, "bond_maturity")
242
+ if big_t < 0.0:
243
+ raise ValueError("expiry must be nonnegative")
244
+ if s < big_t:
245
+ raise ValueError("bond_maturity must not be before expiry")
246
+ a_, s_ = _mean_reversion(a), _volatility(sigma)
247
+ b = float(bond_b(np.array(big_t), np.array(s), a_))
248
+ variance = float(bond_b(np.array(0.0), np.array(2.0 * big_t), a_)) / 2.0
249
+ return s_ * b * math.sqrt(variance)
250
+
251
+
252
+ def _zbo(is_call: bool, strike: np.ndarray, p0t: float, p0s: np.ndarray, sp: np.ndarray) -> np.ndarray:
253
+ """Black on the forward bond: call
254
+ ``P(0, S) N(h) - K P(0, T) N(h - s)``, put by the mirror; intrinsic for
255
+ ``s = 0``."""
256
+ k = strike * p0t
257
+ out = np.empty_like(p0s)
258
+ flat = sp <= 0.0
259
+ sign = 1.0 if is_call else -1.0
260
+ out[flat] = np.maximum(sign * (p0s[flat] - k[flat]), 0.0)
261
+ live = ~flat
262
+ h = np.log(p0s[live] / k[live]) / sp[live] + 0.5 * sp[live]
263
+ if is_call:
264
+ out[live] = p0s[live] * ndtr(h) - k[live] * ndtr(h - sp[live])
265
+ else:
266
+ out[live] = k[live] * ndtr(sp[live] - h) - p0s[live] * ndtr(-h)
267
+ return np.maximum(out, 0.0)
268
+
269
+
270
+ def bond_option(is_call: bool, strike: float, expiry: float, bond_maturity: float, a: float, sigma: float,
271
+ p0: Curve) -> float:
272
+ """The price per unit nominal of a European option, expiring at ``T``, on a zero-coupon bond maturing at ``S`` with
273
+ strike ``K`` (a bond price):
274
+ ``ZBC = P(0, S) N(h) - K P(0, T) N(h - sigma_p)`` with
275
+ ``h = ln(P(0, S) / (K P(0, T))) / sigma_p + sigma_p / 2``;
276
+ put-call parity ``ZBC - ZBP = P(0, S) - K P(0, T)``. With
277
+ ``sigma_p = 0`` the forward intrinsic value."""
278
+ k = scalar(strike, "strike")
279
+ if k <= 0.0:
280
+ raise ValueError("strike must be positive")
281
+ sp = bond_option_vol(expiry, bond_maturity, a, sigma)
282
+ p0t = float(_eval(p0, np.array(float(expiry))))
283
+ p0s = _eval(p0, np.array([float(bond_maturity)]))
284
+ return float(_zbo(bool(is_call), np.array([k]), p0t, p0s, np.array([sp]))[0])
285
+
286
+
287
+ def _infer_nominal(amounts: np.ndarray) -> float:
288
+ """The nominal added to the last amount of a constant-coupon fixed leg: ``a_n - a_1``."""
289
+ if amounts.size < 2 or not np.allclose(amounts[:-1], amounts[0], rtol=1e-12, atol=0.0):
290
+ raise ValueError("nominal cannot be inferred from fixed_amounts (it needs at least two payments with equal "
291
+ "coupons); pass nominal")
292
+ n = float(amounts[-1] - amounts[0])
293
+ if n <= 0.0:
294
+ raise ValueError("nominal inferred from fixed_amounts is not positive; pass nominal")
295
+ return n
296
+
297
+
298
+ def swaption_jamshidian(is_payer: bool, expiry: float, fixed_times: np.ndarray, fixed_amounts: np.ndarray, a: float,
299
+ sigma: float, p0: Curve, forward: Curve, nominal: float | None = None) -> float:
300
+ """The European swaption on the remaining swap starting at the expiry, by the Jamshidian decomposition (addendum R4,
301
+ QuantLib ``jamshidianswaptionengine.cpp``): ``r*`` solves
302
+ ``N - sum c_i P(T_e, T_i; r*) = 0`` by Brent, the leg strikes are
303
+ ``K_i = P(T_e, T_i; r*)`` and the value is ``sum c_i ZBO(K_i)``, a put for a payer
304
+ swaption and a call for a receiver. ``fixed_times`` are the payment times after the expiry, ``fixed_amounts`` the
305
+ coupon amounts with the nominal added to the last; the result is in the money of the nominal, at time 0.
306
+
307
+ ``nominal`` is the notional ``N`` of the equation. The contract's signature has no such argument; it is optional and
308
+ inferred as the last amount minus the first when the coupons are constant, and otherwise required (a one-payment leg
309
+ cannot be split into coupon and nominal). Payer minus receiver equals the forward swap value."""
310
+ te = scalar(expiry, "expiry")
311
+ if te < 0.0:
312
+ raise ValueError("expiry must be nonnegative")
313
+ times, amounts = vec(fixed_times, "fixed_times"), vec(fixed_amounts, "fixed_amounts")
314
+ same_length(fixed_times=times, fixed_amounts=amounts)
315
+ if np.any(np.diff(times) <= 0.0) or times[0] <= te:
316
+ raise ValueError("fixed_times must be strictly increasing and after the expiry")
317
+ if np.any(amounts < 0.0) or amounts[-1] <= 0.0:
318
+ raise ValueError("fixed_amounts must be nonnegative with a positive last amount")
319
+ n = _infer_nominal(amounts) if nominal is None else scalar(nominal, "nominal")
320
+ if n <= 0.0:
321
+ raise ValueError("nominal must be positive")
322
+ a_, s_ = _mean_reversion(a), _volatility(sigma)
323
+ ta, tb = np.full(times.size, te), times
324
+ big_a = bond_a(ta, tb, a_, s_, p0, forward)
325
+ big_b = bond_b(ta, tb, a_)
326
+
327
+ def gap(r: float) -> float:
328
+ return n - float(np.sum(amounts * big_a * np.exp(-big_b * r)))
329
+
330
+ lo, hi = JAMSHIDIAN_BRACKET
331
+ if gap(lo) * gap(hi) > 0.0:
332
+ raise ValueError("the coupon bond equation has no root in the bracket [-10, 10]")
333
+ r_star = brentq(gap, lo, hi, xtol=JAMSHIDIAN_XTOL)
334
+ strikes = big_a * np.exp(-big_b * r_star)
335
+ p0t = float(_eval(p0, np.array(te)))
336
+ p0s = _eval(p0, times)
337
+ sp = np.array([bond_option_vol(te, float(s), a_, s_) for s in times])
338
+ legs = _zbo(not bool(is_payer), strikes, p0t, p0s, sp)
339
+ return float(np.sum(amounts * legs))
340
+
341
+
342
+ @dataclass(frozen=True)
343
+ class Ar1Fit:
344
+ a: float
345
+ sigma: float
346
+ theta: float
347
+ a_se: float
348
+ sigma_se: float
349
+ n_obs: int
350
+ sample_start: str
351
+ sample_end: str
352
+
353
+
354
+ def ar1_to_hw1f(b: float, delta: float, dt: float) -> tuple[float, float]:
355
+ """The map of addendum R6, equations 55 to 57: ``a = -ln b / dt`` and
356
+ ``sigma = delta / sqrt((b^2 - 1) dt / (2 ln b))``; ``b`` must
357
+ lie in (0, 1)."""
358
+ b_, d_, dt_ = scalar(b, "b"), scalar(delta, "delta"), scalar(dt, "dt")
359
+ if not 0.0 < b_ < 1.0:
360
+ raise ValueError(f"the series is not mean-reverting: the AR(1) coefficient b = {b_} must lie in (0, 1)")
361
+ if d_ < 0.0 or dt_ <= 0.0:
362
+ raise ValueError("delta must be nonnegative and dt positive")
363
+ a_ = -math.log(b_) / dt_
364
+ sigma = d_ / math.sqrt((b_**2 - 1.0) * dt_ / (2.0 * math.log(b_)))
365
+ return a_, sigma
366
+
367
+
368
+ def calibrate_ar1(dates: list[str], short_rate: np.ndarray, before: str, min_years: float = 3.0,
369
+ dt: float | None = None) -> Ar1Fit:
370
+ """OLS of ``x(t_i)`` on ``x(t_{i-1})`` for the observations strictly before ``before`` (no look-ahead), mapped to
371
+ ``a`` and ``sigma`` by ``ar1_to_hw1f``, ``theta = c / (1 - b)`` (addendum R6, Brigo et
372
+ al. arXiv 0812.4210). The residual spread is ``delta = std(resid, ddof = 1)``, as the listing of addendum R6 has it
373
+ (the OLS variance of ``b`` keeps its divisor ``m - 2``). The
374
+ standard errors are the OLS standard error of ``b`` propagated to ``a`` by the delta method, and for ``sigma`` the
375
+ delta method on ``(b, delta)`` with the OLS standard error of ``b`` and the normal-theory
376
+ ``delta / sqrt(2 (m - 2))`` of the residual spread, the two taken as independent.
377
+
378
+ ``dt`` defaults to the median spacing of the dates in years of ``DAYS_PER_YEAR`` days. Fewer than ``min_years`` of
379
+ history raises (CRE53.51); so does ``b`` outside (0, 1). ``n_obs`` is the number of observations used."""
380
+ try:
381
+ parsed = [_dt.date.fromisoformat(str(d)) for d in dates]
382
+ cut = _dt.date.fromisoformat(str(before))
383
+ except ValueError as exc:
384
+ raise ValueError(f"dates and before must be ISO dates: {exc}") from exc
385
+ x_all = vec(short_rate, "short_rate")
386
+ if len(parsed) != x_all.size:
387
+ raise ValueError(f"dates and short_rate must have the same length, got {len(parsed)} and {x_all.size}")
388
+ days = np.array([d.toordinal() for d in parsed], dtype=float)
389
+ if np.any(np.diff(days) <= 0.0):
390
+ raise ValueError("dates must be strictly increasing")
391
+ keep = np.array([d < cut for d in parsed], dtype=bool)
392
+ x, d_days = x_all[keep], days[keep]
393
+ n_obs = int(x.size)
394
+ if n_obs < 4:
395
+ raise ValueError(f"short_rate needs at least 4 observations before {before}, got {n_obs}")
396
+ span = (d_days[-1] - d_days[0]) / DAYS_PER_YEAR
397
+ min_y = scalar(min_years, "min_years")
398
+ if span < min_y:
399
+ raise ValueError(f"min_years: {span:.3f} years of history before {before} is below the {min_y} required "
400
+ "(CRE53.51)")
401
+ step = float(np.median(np.diff(d_days)) / DAYS_PER_YEAR) if dt is None else scalar(dt, "dt")
402
+ if step <= 0.0:
403
+ raise ValueError("dt must be positive")
404
+ y, xl = x[1:], x[:-1]
405
+ m = y.size
406
+ design = np.column_stack([np.ones(m), xl])
407
+ coef = np.linalg.lstsq(design, y, rcond=None)[0]
408
+ resid = y - design @ coef
409
+ df = m - 2
410
+ s2 = float(resid @ resid) / df
411
+ c, b = float(coef[0]), float(coef[1])
412
+ cov = s2 * np.linalg.inv(design.T @ design)
413
+ se_b = math.sqrt(max(float(cov[1, 1]), 0.0))
414
+ if not 0.0 < b < 1.0:
415
+ raise ValueError(f"the series is not mean-reverting: the AR(1) coefficient b = {b} must lie in (0, 1)")
416
+ delta = float(np.std(resid, ddof=1))
417
+ a_hat, sigma_hat = ar1_to_hw1f(b, delta, step)
418
+ a_se = se_b / (b * step)
419
+ h = 2.0 * math.log(b) / ((b**2 - 1.0) * step) # sigma = delta sqrt(h)
420
+ dh = ((2.0 / b) * (b**2 - 1.0) - 4.0 * b * math.log(b)) / ((b**2 - 1.0) ** 2 * step)
421
+ dsigma_db = delta * dh / (2.0 * math.sqrt(h))
422
+ dsigma_ddelta = math.sqrt(h)
423
+ se_delta = delta / math.sqrt(2.0 * df)
424
+ sigma_se = math.sqrt((dsigma_db * se_b) ** 2 + (dsigma_ddelta * se_delta) ** 2)
425
+ kept = [d for d, k in zip(parsed, keep, strict=True) if k]
426
+ return Ar1Fit(a_hat, sigma_hat, c / (1.0 - b), a_se, sigma_se, n_obs, kept[0].isoformat(), kept[-1].isoformat())