optPricing 2.0.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 (92) hide show
  1. optpricing-2.0.0.dist-info/METADATA +105 -0
  2. optpricing-2.0.0.dist-info/RECORD +92 -0
  3. optpricing-2.0.0.dist-info/WHEEL +5 -0
  4. optpricing-2.0.0.dist-info/entry_points.txt +3 -0
  5. optpricing-2.0.0.dist-info/licenses/LICENSE +9 -0
  6. optpricing-2.0.0.dist-info/top_level.txt +1 -0
  7. quantfin/__init__.py +101 -0
  8. quantfin/atoms/__init__.py +21 -0
  9. quantfin/atoms/bond.py +28 -0
  10. quantfin/atoms/option.py +70 -0
  11. quantfin/atoms/rate.py +46 -0
  12. quantfin/atoms/stock.py +39 -0
  13. quantfin/calibration/__init__.py +25 -0
  14. quantfin/calibration/calibrator.py +155 -0
  15. quantfin/calibration/fit_jump_parameters.py +66 -0
  16. quantfin/calibration/fit_market_params.py +120 -0
  17. quantfin/calibration/iv_surface.py +155 -0
  18. quantfin/calibration/technique_selector.py +47 -0
  19. quantfin/calibration/vectorized_bsm_iv.py +93 -0
  20. quantfin/calibration/vectorized_integration_iv.py +143 -0
  21. quantfin/cli.py +372 -0
  22. quantfin/config.py +57 -0
  23. quantfin/dashboard/__init__.py +14 -0
  24. quantfin/dashboard/app.py +26 -0
  25. quantfin/dashboard/pages/1_Calibration.py +57 -0
  26. quantfin/dashboard/pages/2_Pricer_and_Greeks.py +150 -0
  27. quantfin/dashboard/pages/3_Financial_Tools.py +69 -0
  28. quantfin/dashboard/pages/__init__.py +0 -0
  29. quantfin/dashboard/plots.py +157 -0
  30. quantfin/dashboard/service.py +176 -0
  31. quantfin/dashboard/widgets.py +87 -0
  32. quantfin/data/__init__.py +26 -0
  33. quantfin/data/historical_manager.py +86 -0
  34. quantfin/data/market_data_manager.py +236 -0
  35. quantfin/models/__init__.py +54 -0
  36. quantfin/models/base/__init__.py +16 -0
  37. quantfin/models/base/base_model.py +198 -0
  38. quantfin/models/base/validators.py +95 -0
  39. quantfin/models/bates.py +192 -0
  40. quantfin/models/blacks_approx.py +134 -0
  41. quantfin/models/bsm.py +262 -0
  42. quantfin/models/cev.py +109 -0
  43. quantfin/models/cgmy.py +189 -0
  44. quantfin/models/cir.py +90 -0
  45. quantfin/models/dupire_local.py +67 -0
  46. quantfin/models/heston.py +204 -0
  47. quantfin/models/hyperbolic.py +170 -0
  48. quantfin/models/kou.py +148 -0
  49. quantfin/models/merton_jump.py +225 -0
  50. quantfin/models/nig.py +180 -0
  51. quantfin/models/perpetual_put.py +115 -0
  52. quantfin/models/sabr.py +64 -0
  53. quantfin/models/sabr_jump.py +68 -0
  54. quantfin/models/vasicek.py +88 -0
  55. quantfin/models/vg.py +178 -0
  56. quantfin/parity/__init__.py +13 -0
  57. quantfin/parity/implied_rate.py +110 -0
  58. quantfin/parity/parity_model.py +178 -0
  59. quantfin/techniques/__init__.py +31 -0
  60. quantfin/techniques/base/__init__.py +21 -0
  61. quantfin/techniques/base/base_technique.py +54 -0
  62. quantfin/techniques/base/greek_mixin.py +265 -0
  63. quantfin/techniques/base/iv_mixin.py +116 -0
  64. quantfin/techniques/base/lattice_technique.py +129 -0
  65. quantfin/techniques/base/pricing_result.py +27 -0
  66. quantfin/techniques/base/random_utils.py +31 -0
  67. quantfin/techniques/closed_form.py +296 -0
  68. quantfin/techniques/crr.py +59 -0
  69. quantfin/techniques/fft.py +178 -0
  70. quantfin/techniques/integration.py +202 -0
  71. quantfin/techniques/kernels/__init__.py +37 -0
  72. quantfin/techniques/kernels/lattice_kernels.py +286 -0
  73. quantfin/techniques/kernels/mc_kernels.py +337 -0
  74. quantfin/techniques/leisen_reimer.py +59 -0
  75. quantfin/techniques/monte_carlo.py +259 -0
  76. quantfin/techniques/pde.py +155 -0
  77. quantfin/techniques/topm.py +59 -0
  78. quantfin/workflows/__init__.py +14 -0
  79. quantfin/workflows/backtest_workflow.py +133 -0
  80. quantfin/workflows/configs/__init__.py +51 -0
  81. quantfin/workflows/configs/bates_config.py +25 -0
  82. quantfin/workflows/configs/bsm_config.py +9 -0
  83. quantfin/workflows/configs/cev_config.py +16 -0
  84. quantfin/workflows/configs/cgmy_config.py +18 -0
  85. quantfin/workflows/configs/heston_config.py +21 -0
  86. quantfin/workflows/configs/hyperbolic_config.py +18 -0
  87. quantfin/workflows/configs/kou_config.py +16 -0
  88. quantfin/workflows/configs/merton_config.py +18 -0
  89. quantfin/workflows/configs/nig_config.py +13 -0
  90. quantfin/workflows/configs/sabr_config.py +19 -0
  91. quantfin/workflows/configs/vg_config.py +9 -0
  92. quantfin/workflows/daily_workflow.py +150 -0
@@ -0,0 +1,337 @@
1
+ from __future__ import annotations
2
+
3
+ import numba
4
+ import numpy as np
5
+
6
+ __doc__ = """
7
+ This module contains JIT-compiled (`numba`) kernels for simulating the SDE
8
+ paths of different financial models. These functions are designed for performance.
9
+ """
10
+
11
+ # NOTE: Detailed docstrings are provided for each kernel, but they are placed
12
+ # outside the function body as Numba in `nopython` mode does not support them.
13
+ # The information is still valuable for developers reading the code.
14
+
15
+ # Docstring for bsm_kernel
16
+ """
17
+ JIT-compiled kernel for BSM SDE simulation.
18
+ d(logS) = (r - q - 0.5*sigma^2)dt + sigma*dW
19
+ """
20
+
21
+
22
+ @numba.jit(nopython=True, fastmath=True, cache=True)
23
+ def bsm_kernel(
24
+ n_paths,
25
+ n_steps,
26
+ log_s0,
27
+ r,
28
+ q,
29
+ sigma,
30
+ dt,
31
+ dw,
32
+ ):
33
+ log_s = np.full(n_paths, log_s0)
34
+ drift = (r - q - 0.5 * sigma**2) * dt
35
+ for i in range(n_steps):
36
+ log_s += drift + sigma * dw[:, i]
37
+ return log_s
38
+
39
+
40
+ # Docstring for heston_kernel
41
+ """
42
+ JIT-compiled kernel for Heston SDE simulation (Full Truncation).
43
+ """
44
+
45
+
46
+ @numba.jit(nopython=True, fastmath=True, cache=True)
47
+ def heston_kernel(
48
+ n_paths,
49
+ n_steps,
50
+ log_s0,
51
+ v0,
52
+ r,
53
+ q,
54
+ kappa,
55
+ theta,
56
+ rho,
57
+ vol_of_vol,
58
+ dt,
59
+ dw1,
60
+ dw2,
61
+ ):
62
+ log_s = np.full(n_paths, log_s0)
63
+ v = np.full(n_paths, v0)
64
+ for i in range(n_steps):
65
+ v_pos = np.maximum(v, 0)
66
+ v_sqrt = np.sqrt(v_pos)
67
+ log_s += (r - q - 0.5 * v_pos) * dt + v_sqrt * dw1[:, i]
68
+ v += kappa * (theta - v_pos) * dt + vol_of_vol * v_sqrt * dw2[:, i]
69
+ return log_s
70
+
71
+
72
+ # Docstring for merton_kernel
73
+ """
74
+ JIT-compiled kernel for Merton Jump-Diffusion SDE simulation.
75
+ """
76
+
77
+
78
+ @numba.jit(nopython=True, fastmath=True, cache=True)
79
+ def merton_kernel(
80
+ n_paths,
81
+ n_steps,
82
+ log_s0,
83
+ r,
84
+ q,
85
+ sigma,
86
+ lambda_,
87
+ mu_j,
88
+ sigma_j,
89
+ dt,
90
+ dw,
91
+ jump_counts,
92
+ ):
93
+ log_s = np.full(n_paths, log_s0)
94
+ compensator = lambda_ * (np.exp(mu_j + 0.5 * sigma_j**2) - 1)
95
+ drift = (r - q - 0.5 * sigma**2 - compensator) * dt
96
+ for i in range(n_steps):
97
+ log_s += drift + sigma * dw[:, i]
98
+ jumps_this_step = jump_counts[:, i]
99
+ if np.any(jumps_this_step > 0):
100
+ num_jumps = np.sum(jumps_this_step)
101
+ jump_sizes = np.random.normal(mu_j, sigma_j, num_jumps)
102
+ jump_idx = 0
103
+ for path_idx in range(n_paths):
104
+ for _ in range(jumps_this_step[path_idx]):
105
+ log_s[path_idx] += jump_sizes[jump_idx]
106
+ jump_idx += 1
107
+ return log_s
108
+
109
+
110
+ # Docstring for bates_kernel
111
+ """
112
+ JIT-compiled kernel for Bates (Heston + Jumps) SDE simulation.
113
+ """
114
+
115
+
116
+ @numba.jit(nopython=True, fastmath=True, cache=True)
117
+ def bates_kernel(
118
+ n_paths,
119
+ n_steps,
120
+ log_s0,
121
+ v0,
122
+ r,
123
+ q,
124
+ kappa,
125
+ theta,
126
+ rho,
127
+ vol_of_vol,
128
+ lambda_,
129
+ mu_j,
130
+ sigma_j,
131
+ dt,
132
+ dw1,
133
+ dw2,
134
+ jump_counts,
135
+ ):
136
+ log_s = np.full(n_paths, log_s0)
137
+ v = np.full(n_paths, v0)
138
+ compensator = lambda_ * (np.exp(mu_j + 0.5 * sigma_j**2) - 1)
139
+
140
+ for i in range(n_steps):
141
+ v_pos = np.maximum(v, 0)
142
+ v_sqrt = np.sqrt(v_pos)
143
+
144
+ # Heston part
145
+ log_s += (r - q - 0.5 * v_pos - compensator) * dt + v_sqrt * dw1[:, i]
146
+ v += kappa * (theta - v_pos) * dt + vol_of_vol * v_sqrt * dw2[:, i]
147
+
148
+ # Merton Jump part
149
+ jumps_this_step = jump_counts[:, i]
150
+ if np.any(jumps_this_step > 0):
151
+ num_jumps = np.sum(jumps_this_step)
152
+ jump_sizes = np.random.normal(mu_j, sigma_j, num_jumps)
153
+ jump_idx = 0
154
+ for path_idx in range(n_paths):
155
+ for _ in range(jumps_this_step[path_idx]):
156
+ log_s[path_idx] += jump_sizes[jump_idx]
157
+ jump_idx += 1
158
+ return log_s
159
+
160
+
161
+ # Docstring for sabr_kernel
162
+ """
163
+ JIT-compiled kernel for SABR SDE simulation.
164
+ """
165
+
166
+
167
+ @numba.jit(nopython=True, fastmath=True, cache=True)
168
+ def sabr_kernel(
169
+ n_paths,
170
+ n_steps,
171
+ s0,
172
+ v0,
173
+ r,
174
+ q,
175
+ alpha,
176
+ beta,
177
+ rho,
178
+ dt,
179
+ dw1,
180
+ dw2,
181
+ ):
182
+ s = np.full(n_paths, s0)
183
+ v = np.full(n_paths, v0) # v is sigma_t in SABR
184
+ rho_bar = np.sqrt(1 - rho**2)
185
+
186
+ for i in range(n_steps):
187
+ # Evolve spot price S_t directly
188
+ s_pos = np.maximum(s, 1e-8) # Avoid negative spot
189
+ v_pos = np.maximum(v, 0)
190
+ s += (r - q) * s_pos * dt + v_pos * (s_pos**beta) * dw1[:, i]
191
+
192
+ # Evolve volatility sigma_t (lognormal process)
193
+ v = v * np.exp(-0.5 * alpha**2 * dt + alpha * dw2[:, i])
194
+
195
+ return s
196
+
197
+
198
+ # Docstring for sabr_jump_kernel
199
+ """
200
+ JIT-compiled kernel for SABR with log-normal jumps on the spot process.
201
+ """
202
+
203
+
204
+ @numba.jit(nopython=True, fastmath=True, cache=True)
205
+ def sabr_jump_kernel(
206
+ n_paths,
207
+ n_steps,
208
+ s0,
209
+ v0,
210
+ r,
211
+ q,
212
+ alpha,
213
+ beta,
214
+ rho,
215
+ lambda_,
216
+ mu_j,
217
+ sigma_j,
218
+ dt,
219
+ dw1,
220
+ dw2,
221
+ jump_counts,
222
+ ):
223
+ s = np.full(n_paths, s0)
224
+ v = np.full(n_paths, v0) # v is sigma_t
225
+ rho_bar = np.sqrt(1 - rho**2)
226
+ compensator = lambda_ * (np.exp(mu_j + 0.5 * sigma_j**2) - 1)
227
+
228
+ for i in range(n_steps):
229
+ s_pos = np.maximum(s, 1e-8)
230
+ v_pos = np.maximum(v, 0)
231
+
232
+ s += (r - q - compensator) * s_pos * dt + v_pos * (s_pos**beta) * dw1[:, i]
233
+
234
+ v = v * np.exp(-0.5 * alpha**2 * dt + alpha * dw2[:, i])
235
+
236
+ jumps_this_step = jump_counts[:, i]
237
+ if np.any(jumps_this_step > 0):
238
+ num_jumps = np.sum(jumps_this_step)
239
+ # Jumps are multiplicative: S_t+ = S_t * exp(J)
240
+ jump_multipliers = np.exp(np.random.normal(mu_j, sigma_j, num_jumps))
241
+ jump_idx = 0
242
+ for path_idx in range(n_paths):
243
+ for _ in range(jumps_this_step[path_idx]):
244
+ s[path_idx] *= jump_multipliers[jump_idx]
245
+ jump_idx += 1
246
+ return s
247
+
248
+
249
+ # Docstring for kou_kernel
250
+ """
251
+ JIT-compiled kernel for Kou Double-Exponential Jump-Diffusion SDE.
252
+ """
253
+
254
+
255
+ @numba.jit(nopython=True, fastmath=True, cache=True)
256
+ def kou_kernel(
257
+ n_paths,
258
+ n_steps,
259
+ log_s0,
260
+ r,
261
+ q,
262
+ sigma,
263
+ lambda_,
264
+ p_up,
265
+ eta1,
266
+ eta2,
267
+ dt,
268
+ dw,
269
+ jump_counts,
270
+ ):
271
+ log_s = np.full(n_paths, log_s0)
272
+ compensator = lambda_ * (
273
+ (p_up * eta1 / (eta1 - 1)) + ((1 - p_up) * eta2 / (eta2 + 1)) - 1
274
+ )
275
+ drift = (r - q - 0.5 * sigma**2 - compensator) * dt
276
+
277
+ for i in range(n_steps):
278
+ log_s += drift + sigma * dw[:, i]
279
+ jumps_this_step = jump_counts[:, i]
280
+ if np.any(jumps_this_step > 0):
281
+ num_jumps = np.sum(jumps_this_step)
282
+
283
+ # Determine which jumps are up and which are down
284
+ up_or_down = np.random.random(num_jumps)
285
+ num_up_jumps = np.sum(up_or_down < p_up)
286
+ num_down_jumps = num_jumps - num_up_jumps
287
+
288
+ # Generate jump sizes from exponential distributions
289
+ total_jump_size = 0.0
290
+ if num_up_jumps > 0:
291
+ total_jump_size += np.sum(
292
+ np.random.exponential(1.0 / eta1, num_up_jumps)
293
+ )
294
+ if num_down_jumps > 0:
295
+ total_jump_size -= np.sum(
296
+ np.random.exponential(1.0 / eta2, num_down_jumps)
297
+ )
298
+
299
+ # This part is tricky to vectorize perfectly in Numba, so loop
300
+ jump_idx = 0
301
+ for path_idx in range(n_paths):
302
+ if jumps_this_step[path_idx] > 0: # This path has a jump
303
+ # For simplicity in Numba, add the average jump size
304
+ log_s[path_idx] += (
305
+ total_jump_size / num_jumps * jumps_this_step[path_idx]
306
+ )
307
+
308
+ return log_s
309
+
310
+
311
+ # Docstring for dupire_kernel
312
+ """
313
+ JIT-compiled kernel for Dupire Local Volatility SDE simulation.
314
+ Note: Numba cannot compile the vol_surface_func itself, so this kernel
315
+ will have a slight overhead from calling back into Python for the vol lookup.
316
+ """
317
+
318
+
319
+ @numba.jit(nopython=True, fastmath=True, cache=True)
320
+ def dupire_kernel(
321
+ n_paths,
322
+ n_steps,
323
+ log_s0,
324
+ r,
325
+ q,
326
+ dt,
327
+ dw,
328
+ vol_surface_func,
329
+ ):
330
+ log_s = np.full(n_paths, log_s0)
331
+ for i in range(n_steps):
332
+ t_current = i * dt
333
+ current_spot = np.exp(log_s)
334
+ local_vol = vol_surface_func(t_current, current_spot)
335
+ drift = (r - q - 0.5 * local_vol**2) * dt
336
+ log_s += drift + local_vol * dw[:, i]
337
+ return log_s
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from quantfin.atoms import Option, OptionType, Rate, Stock
6
+ from quantfin.models import BaseModel
7
+ from quantfin.techniques.base import LatticeTechnique
8
+
9
+ from .kernels.lattice_kernels import _lr_pricer
10
+
11
+ __doc__ = """
12
+ Defines the Leisen-Reimer binomial lattice pricing technique.
13
+ """
14
+
15
+
16
+ class LeisenReimerTechnique(LatticeTechnique):
17
+ """Leisen-Reimer binomial lattice technique with Peizer-Pratt inversion."""
18
+
19
+ def _price_and_get_nodes(
20
+ self,
21
+ option: Option,
22
+ stock: Stock,
23
+ model: BaseModel,
24
+ rate: Rate,
25
+ ) -> dict[str, Any]:
26
+ """
27
+ Prices the option using the Leisen-Reimer kernel.
28
+
29
+ This method extracts the necessary numerical parameters from the input
30
+ objects and passes them to the low-level `_lr_pricer` kernel.
31
+
32
+ Parameters
33
+ ----------
34
+ option : Option
35
+ The option contract to be priced.
36
+ stock : Stock
37
+ The underlying asset's properties.
38
+ model : BaseModel
39
+ The financial model, used to get volatility.
40
+ rate : Rate
41
+ The risk-free rate structure.
42
+
43
+ Returns
44
+ -------
45
+ dict[str, Any]
46
+ A dictionary from the kernel containing the price and node values.
47
+ """
48
+ sigma = model.params.get("sigma", stock.volatility)
49
+ return _lr_pricer(
50
+ S0=stock.spot,
51
+ K=option.strike,
52
+ T=option.maturity,
53
+ r=rate.get_rate(option.maturity),
54
+ q=stock.dividend,
55
+ sigma=sigma,
56
+ N=self.steps,
57
+ is_call=(option.option_type is OptionType.CALL),
58
+ is_am=self.is_american,
59
+ )
@@ -0,0 +1,259 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections.abc import Callable
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+
9
+ from quantfin.atoms import Option, OptionType, Rate, Stock
10
+ from quantfin.models import BaseModel
11
+ from quantfin.techniques.base import BaseTechnique, GreekMixin, IVMixin, PricingResult
12
+
13
+ from .kernels.mc_kernels import (
14
+ bates_kernel,
15
+ bsm_kernel,
16
+ dupire_kernel,
17
+ heston_kernel,
18
+ kou_kernel,
19
+ merton_kernel,
20
+ sabr_jump_kernel,
21
+ sabr_kernel,
22
+ )
23
+
24
+ __doc__ = """
25
+ Defines a universal Monte Carlo pricing engine that dispatches to specialized,
26
+ JIT-compiled kernels based on the financial model provided.
27
+ """
28
+
29
+
30
+ class MonteCarloTechnique(BaseTechnique, GreekMixin, IVMixin):
31
+ """
32
+ A universal Monte Carlo engine that dispatches to
33
+ specialized, JIT-compiled kernels for different model types.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ *,
39
+ n_paths: int = 20_000,
40
+ n_steps: int = 100,
41
+ antithetic: bool = True,
42
+ seed: int | None = None,
43
+ ):
44
+ """
45
+ Initializes the Monte Carlo engine.
46
+
47
+ Parameters
48
+ ----------
49
+ n_paths : int, optional
50
+ The number of simulation paths, by default 20_000.
51
+ n_steps : int, optional
52
+ The number of time steps in each path, by default 100.
53
+ antithetic : bool, optional
54
+ Whether to use antithetic variates for variance reduction, by default True.
55
+ seed : int | None, optional
56
+ Seed for the random number generator for reproducibility, by default None.
57
+ """
58
+ if antithetic and n_paths % 2 != 0:
59
+ n_paths += 1
60
+ self.n_paths = n_paths
61
+ self.n_steps = n_steps
62
+ self.antithetic = antithetic
63
+ self.rng = np.random.default_rng(seed)
64
+
65
+ def price(
66
+ self, option: Option, stock: Stock, model: BaseModel, rate: Rate, **kwargs: Any
67
+ ) -> PricingResult:
68
+ """
69
+ Prices an option using the appropriate Monte Carlo simulation method.
70
+
71
+ This method acts as a dispatcher, selecting the correct simulation
72
+ strategy (SDE path, pure Lévy, or exact sampler) based on the
73
+ capabilities of the provided model.
74
+
75
+ Parameters
76
+ ----------
77
+ option : Option
78
+ The option contract to be priced.
79
+ stock : Stock
80
+ The underlying asset's properties.
81
+ model : BaseModel
82
+ The financial model to use for the simulation.
83
+ rate : Rate
84
+ The risk-free rate structure.
85
+
86
+ Returns
87
+ -------
88
+ PricingResult
89
+ An object containing the calculated price.
90
+ """
91
+ if not (model.supports_sde or getattr(model, "is_pure_levy", False)):
92
+ raise TypeError(f"Model '{model.name}' does not support simulation.")
93
+
94
+ S0, K, T = stock.spot, option.strike, option.maturity
95
+ r, q = rate.get_rate(T), stock.dividend
96
+
97
+ # Dispatch to the correct simulation method
98
+ if getattr(model, "has_exact_sampler", False):
99
+ ST = model.sample_terminal_spot(S0, r, T, self.n_paths)
100
+ elif getattr(model, "is_pure_levy", False):
101
+ ST = self._simulate_levy_terminal(model, S0, r, q, T)
102
+ else:
103
+ ST = self._simulate_sde_path(model, S0, r, q, T, **kwargs)
104
+
105
+ payoff = (
106
+ np.maximum(ST - K, 0)
107
+ if option.option_type is OptionType.CALL
108
+ else np.maximum(K - ST, 0)
109
+ )
110
+ price = float(np.mean(payoff) * math.exp(-r * T))
111
+ return PricingResult(price=price)
112
+
113
+ def _get_sde_kernel_and_params(
114
+ self, model: BaseModel, r: float, q: float, dt: float, **kwargs
115
+ ) -> tuple[Callable, dict[str, Any]]:
116
+ """Selects the appropriate JIT-compiled kernel and prepares its parameters."""
117
+ p = model.params
118
+ kernel_params = {"r": r, "q": q, "dt": dt}
119
+
120
+ if getattr(model, "is_sabr", False):
121
+ kernel_params.update(
122
+ {
123
+ "alpha": p["alpha"],
124
+ "beta": p["beta"],
125
+ "rho": p["rho"],
126
+ "v0": kwargs.get("v0", p.get("alpha")),
127
+ }
128
+ )
129
+ if model.has_jumps:
130
+ kernel_params.update(
131
+ {"lambda_": p["lambda"], "mu_j": p["mu_j"], "sigma_j": p["sigma_j"]}
132
+ )
133
+ return sabr_jump_kernel, kernel_params
134
+ return sabr_kernel, kernel_params
135
+
136
+ if getattr(model, "is_local_vol", False): # Dupire
137
+ return dupire_kernel, kernel_params
138
+
139
+ if model.has_variance_process and model.has_jumps: # Bates
140
+ kernel_params.update(
141
+ {
142
+ "kappa": p["kappa"],
143
+ "theta": p["theta"],
144
+ "rho": p["rho"],
145
+ "vol_of_vol": p["vol_of_vol"],
146
+ "v0": kwargs.get("v0", p.get("v0")),
147
+ }
148
+ )
149
+ kernel_params.update(
150
+ {"lambda_": p["lambda"], "mu_j": p["mu_j"], "sigma_j": p["sigma_j"]}
151
+ )
152
+ return bates_kernel, kernel_params
153
+ elif model.has_variance_process: # Heston
154
+ kernel_params.update(
155
+ {
156
+ "kappa": p["kappa"],
157
+ "theta": p["theta"],
158
+ "rho": p["rho"],
159
+ "vol_of_vol": p["vol_of_vol"],
160
+ "v0": kwargs.get("v0", p.get("v0")),
161
+ }
162
+ )
163
+ return heston_kernel, kernel_params
164
+ elif model.name == "Kou Double-Exponential Jump": # Kou Model
165
+ kernel_params.update(
166
+ {
167
+ "sigma": p["sigma"],
168
+ "lambda_": p["lambda"],
169
+ "p_up": p["p_up"],
170
+ "eta1": p["eta1"],
171
+ "eta2": p["eta2"],
172
+ }
173
+ )
174
+ return kou_kernel, kernel_params
175
+ elif model.has_jumps: # Merton
176
+ kernel_params.update(
177
+ {
178
+ "sigma": p["sigma"],
179
+ "lambda_": p["lambda"],
180
+ "mu_j": p["mu_j"],
181
+ "sigma_j": p["sigma_j"],
182
+ }
183
+ )
184
+ return merton_kernel, kernel_params
185
+ else: # BSM
186
+ kernel_params["sigma"] = p.get("sigma")
187
+ return bsm_kernel, kernel_params
188
+
189
+ def _simulate_sde_path(
190
+ self, model: BaseModel, S0: float, r: float, q: float, T: float, **kwargs
191
+ ) -> np.ndarray:
192
+ """Prepares random numbers and executes the dispatched SDE kernel."""
193
+ dt = T / self.n_steps
194
+ num_draws = self.n_paths // 2 if self.antithetic else self.n_paths
195
+
196
+ kernel, kernel_params = self._get_sde_kernel_and_params(
197
+ model, r, q, dt, **kwargs
198
+ )
199
+
200
+ sim_params = {"n_paths": num_draws, "n_steps": self.n_steps, **kernel_params}
201
+ if getattr(model, "is_sabr", False):
202
+ sim_params["s0"] = S0
203
+ else:
204
+ sim_params["log_s0"] = math.log(S0)
205
+
206
+ if model.has_variance_process:
207
+ dw_v = self.rng.standard_normal(size=(num_draws, self.n_steps)) * math.sqrt(
208
+ dt
209
+ )
210
+ dw_uncorr = self.rng.standard_normal(
211
+ size=(num_draws, self.n_steps)
212
+ ) * math.sqrt(dt)
213
+ rho = model.params.get("rho", 0)
214
+ sim_params["dw1"] = rho * dw_v + math.sqrt(1 - rho**2) * dw_uncorr
215
+ sim_params["dw2"] = dw_v
216
+ else:
217
+ sim_params["dw"] = self.rng.standard_normal(
218
+ size=(num_draws, self.n_steps)
219
+ ) * math.sqrt(dt)
220
+
221
+ if model.has_jumps:
222
+ sim_params["jump_counts"] = self.rng.poisson(
223
+ lam=model.params["lambda"] * dt, size=(num_draws, self.n_steps)
224
+ )
225
+
226
+ if getattr(model, "is_local_vol", False):
227
+ sim_params["vol_surface_func"] = model.params["vol_surface"]
228
+
229
+ ST = kernel(**sim_params)
230
+
231
+ if self.antithetic and not getattr(model, "is_local_vol", False):
232
+ if "dw" in sim_params:
233
+ sim_params["dw"] *= -1
234
+ if "dw1" in sim_params:
235
+ sim_params["dw1"] *= -1
236
+ if "dw2" in sim_params:
237
+ sim_params["dw2"] *= -1
238
+ ST_anti = kernel(**sim_params)
239
+ ST = np.concatenate([ST, ST_anti])
240
+
241
+ return ST if getattr(model, "is_sabr", False) else np.exp(ST)
242
+
243
+ def _simulate_levy_terminal(
244
+ self, model: BaseModel, S0: float, r: float, q: float, T: float
245
+ ) -> np.ndarray:
246
+ """Handles pure Lévy models by direct sampling of the terminal distribution."""
247
+ if not hasattr(model, "sample_terminal_log_return") or not hasattr(
248
+ model, "raw_cf"
249
+ ):
250
+ raise NotImplementedError(
251
+ f"Lévy model '{model.name}' is missing required methods."
252
+ )
253
+
254
+ log_returns_raw = model.sample_terminal_log_return(T, self.n_paths, self.rng)
255
+ phi_raw = model.raw_cf(t=T)
256
+ compensator = np.log(np.real(phi_raw(-1j)))
257
+ drift = (r - q) * T - compensator
258
+
259
+ return S0 * np.exp(drift + log_returns_raw)