spxa 1.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 (47) hide show
  1. spxa/__init__.py +68 -0
  2. spxa/_internals/__init__.py +0 -0
  3. spxa/analytics/__init__.py +27 -0
  4. spxa/analytics/cumulants.py +81 -0
  5. spxa/analytics/divergence.py +272 -0
  6. spxa/analytics/fourier.py +183 -0
  7. spxa/core/__init__.py +27 -0
  8. spxa/core/exactness.py +47 -0
  9. spxa/core/exceptions.py +47 -0
  10. spxa/core/levy_measure.py +221 -0
  11. spxa/core/process.py +479 -0
  12. spxa/core/properties.py +209 -0
  13. spxa/core/triplet.py +202 -0
  14. spxa/ops/__init__.py +38 -0
  15. spxa/ops/addition.py +144 -0
  16. spxa/ops/integral.py +298 -0
  17. spxa/ops/product.py +247 -0
  18. spxa/ops/scaling.py +134 -0
  19. spxa/ops/subordination.py +228 -0
  20. spxa/sim/__init__.py +47 -0
  21. spxa/sim/bridge.py +355 -0
  22. spxa/sim/euler.py +269 -0
  23. spxa/sim/exact.py +358 -0
  24. spxa/story/__init__.py +17 -0
  25. spxa/story/narrator.py +248 -0
  26. spxa/zoo/__init__.py +45 -0
  27. spxa/zoo/beyond/__init__.py +11 -0
  28. spxa/zoo/beyond/fbm.py +217 -0
  29. spxa/zoo/beyond/hawkes.py +247 -0
  30. spxa/zoo/beyond/ou_levy.py +230 -0
  31. spxa/zoo/levy/__init__.py +27 -0
  32. spxa/zoo/levy/brownian.py +154 -0
  33. spxa/zoo/levy/cgmy.py +327 -0
  34. spxa/zoo/levy/gamma.py +224 -0
  35. spxa/zoo/levy/inverse_gaussian.py +247 -0
  36. spxa/zoo/levy/meixner.py +324 -0
  37. spxa/zoo/levy/negative_binomial.py +293 -0
  38. spxa/zoo/levy/nig.py +259 -0
  39. spxa/zoo/levy/poisson.py +163 -0
  40. spxa/zoo/levy/stable.py +286 -0
  41. spxa/zoo/levy/tempered_stable.py +322 -0
  42. spxa/zoo/levy/vg.py +286 -0
  43. spxa/zoo/multivariate.py +448 -0
  44. spxa-1.0.0.dist-info/METADATA +124 -0
  45. spxa-1.0.0.dist-info/RECORD +47 -0
  46. spxa-1.0.0.dist-info/WHEEL +5 -0
  47. spxa-1.0.0.dist-info/top_level.txt +1 -0
spxa/__init__.py ADDED
@@ -0,0 +1,68 @@
1
+ """
2
+ spxa — Stochastic Process Algebra
3
+
4
+ Stochastic processes as first-class algebraic objects.
5
+ """
6
+
7
+ __version__ = "1.0.0"
8
+
9
+ from spxa.core import (
10
+ ExactnessLevel,
11
+ ExactnessError,
12
+ SpxaDegradationWarning,
13
+ LevyMeasure,
14
+ LevyTriplet,
15
+ Process,
16
+ ProcessProperties,
17
+ )
18
+ from spxa.zoo import (
19
+ AlphaStable,
20
+ BrownianMotion,
21
+ CGMY,
22
+ CorrelatedLevy,
23
+ FractionalBrownianMotion,
24
+ GammaProcess,
25
+ HawkesProcess,
26
+ InverseGaussianProcess,
27
+ MeixnerProcess,
28
+ MultivariateBrownianMotion,
29
+ MultivariateLevyTriplet,
30
+ NegativeBinomialProcess,
31
+ NIG,
32
+ OULevy,
33
+ PoissonProcess,
34
+ TemperedStable,
35
+ VarianceGamma,
36
+ correlated_brownian_motion,
37
+ independent_levy_vector,
38
+ )
39
+
40
+ __all__ = [
41
+ "__version__",
42
+ "ExactnessLevel",
43
+ "ExactnessError",
44
+ "SpxaDegradationWarning",
45
+ "LevyMeasure",
46
+ "LevyTriplet",
47
+ "Process",
48
+ "ProcessProperties",
49
+ "AlphaStable",
50
+ "BrownianMotion",
51
+ "CGMY",
52
+ "CorrelatedLevy",
53
+ "FractionalBrownianMotion",
54
+ "GammaProcess",
55
+ "HawkesProcess",
56
+ "InverseGaussianProcess",
57
+ "MeixnerProcess",
58
+ "MultivariateBrownianMotion",
59
+ "MultivariateLevyTriplet",
60
+ "NegativeBinomialProcess",
61
+ "NIG",
62
+ "OULevy",
63
+ "PoissonProcess",
64
+ "TemperedStable",
65
+ "VarianceGamma",
66
+ "correlated_brownian_motion",
67
+ "independent_levy_vector",
68
+ ]
File without changes
@@ -0,0 +1,27 @@
1
+ """Analytics module — divergences, Fourier pricing, cumulant tools."""
2
+
3
+ from spxa.analytics.cumulants import cumulant_table, excess_kurtosis, skewness
4
+ from spxa.analytics.divergence import (
5
+ hellinger_distance,
6
+ kl_divergence_mc,
7
+ l2_char_func_distance,
8
+ wasserstein2_distance,
9
+ )
10
+ from spxa.analytics.fourier import (
11
+ european_call_price,
12
+ european_put_price,
13
+ implied_volatility,
14
+ )
15
+
16
+ __all__ = [
17
+ "cumulant_table",
18
+ "excess_kurtosis",
19
+ "skewness",
20
+ "hellinger_distance",
21
+ "kl_divergence_mc",
22
+ "l2_char_func_distance",
23
+ "wasserstein2_distance",
24
+ "european_call_price",
25
+ "european_put_price",
26
+ "implied_volatility",
27
+ ]
@@ -0,0 +1,81 @@
1
+ """
2
+ Cumulant analysis utilities.
3
+
4
+ Provides standardised cumulant-based diagnostics for comparing processes,
5
+ computing skewness and excess kurtosis, and checking moment existence.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+
12
+ from spxa.core.process import Process
13
+
14
+
15
+ def skewness(process: Process, t: float = 1.0) -> float:
16
+ """
17
+ Return the skewness of X_t: κ_3 / κ_2^{3/2}.
18
+
19
+ Parameters
20
+ ----------
21
+ process :
22
+ Process with at least MOMENT_PROPAGATION exactness.
23
+ t :
24
+ Time. Cumulants scale as κ_n(X_t) = t · κ_n(X_1).
25
+ """
26
+ kappas = process.cumulants(order=3)
27
+ k2, k3 = kappas[2], kappas[3]
28
+ if k2 <= 0:
29
+ raise ValueError("Variance is zero or negative — skewness undefined.")
30
+ return t * k3 / (t * k2) ** 1.5
31
+
32
+
33
+ def excess_kurtosis(process: Process, t: float = 1.0) -> float:
34
+ """
35
+ Return excess kurtosis of X_t: κ_4 / κ_2².
36
+
37
+ Parameters
38
+ ----------
39
+ process :
40
+ Process with at least MOMENT_PROPAGATION exactness.
41
+ t :
42
+ Time.
43
+ """
44
+ kappas = process.cumulants(order=4)
45
+ k2, k4 = kappas[2], kappas[4]
46
+ if k2 <= 0:
47
+ raise ValueError("Variance is zero — kurtosis undefined.")
48
+ return t * k4 / (t * k2) ** 2
49
+
50
+
51
+ def cumulant_table(process: Process, order: int = 4, t: float = 1.0) -> dict[str, float]:
52
+ """
53
+ Return a named cumulant summary for X_t.
54
+
55
+ Parameters
56
+ ----------
57
+ process :
58
+ Process.
59
+ order :
60
+ Highest cumulant order to include (min 4).
61
+ t :
62
+ Time.
63
+
64
+ Returns
65
+ -------
66
+ dict with keys: mean, variance, std, skewness, excess_kurtosis,
67
+ and kappa_n for n in 1..order.
68
+ """
69
+ order = max(order, 4)
70
+ kappas = process.cumulants(order=order)
71
+ result: dict[str, float] = {}
72
+ for n, v in kappas.items():
73
+ result[f"kappa_{n}"] = t * v
74
+ k2t = t * kappas[2]
75
+ result["mean"] = t * kappas[1]
76
+ result["variance"] = k2t
77
+ result["std"] = float(np.sqrt(max(k2t, 0.0)))
78
+ if k2t > 0:
79
+ result["skewness"] = t * kappas[3] / k2t**1.5
80
+ result["excess_kurtosis"] = t * kappas[4] / k2t**2
81
+ return result
@@ -0,0 +1,272 @@
1
+ """
2
+ Divergences between Lévy processes.
3
+
4
+ For two Lévy processes X and Y with characteristic exponents ψ_X and ψ_Y,
5
+ divergence measures can be computed using:
6
+
7
+ 1. The Plancherel identity: for L² functions of the characteristic functions,
8
+ distances in frequency space translate to distances in distribution space.
9
+
10
+ 2. Direct Lévy measure comparison: for processes with known densities,
11
+ f-divergences between the Lévy measures give divergences between
12
+ finite-dimensional distributions.
13
+
14
+ 3. KL divergence between Lévy processes is infinite in general for processes
15
+ with different Lévy measures (Hellinger distance between path measures).
16
+ spxa computes the more tractable KL between marginal distributions at time t,
17
+ approximated via Gil-Pelaez inversion.
18
+
19
+ This module implements:
20
+ - Squared Hellinger distance between marginal distributions at time t
21
+ - L² (Plancherel) distance between characteristic functions
22
+ - KL divergence via importance sampling (Monte Carlo, for EXACT processes)
23
+ - Wasserstein-2 distance between marginals (via quantile function comparison)
24
+
25
+ References
26
+ ----------
27
+ Cont, R. & Tankov, P. (2004). *Financial Modelling with Jump Processes*.
28
+ Chapter 4, Section 4.6.
29
+
30
+ Sato, K.-I. (1999). *Lévy Processes and Infinitely Divisible Distributions*.
31
+ Chapter 14.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import numpy as np
37
+
38
+ from spxa.core.exactness import ExactnessLevel
39
+ from spxa.core.exceptions import ExactnessError
40
+ from spxa.core.process import Process
41
+
42
+
43
+ def l2_char_func_distance(
44
+ X: Process,
45
+ Y: Process,
46
+ t: float = 1.0,
47
+ u_max: float = 50.0,
48
+ n_points: int = 2000,
49
+ ) -> float:
50
+ """
51
+ L² distance between characteristic functions at time t.
52
+
53
+ d²_L²(X_t, Y_t) = (1/2π) ∫ |φ_X(u;t) - φ_Y(u;t)|² du
54
+
55
+ By the Plancherel theorem this equals the L² distance between the
56
+ corresponding densities (when they exist):
57
+ = ∫ |f_X(x;t) - f_Y(x;t)|² dx
58
+
59
+ Computed by numerical integration on [-u_max, u_max].
60
+
61
+ Parameters
62
+ ----------
63
+ X, Y :
64
+ Processes with ExactnessLevel.EXACT.
65
+ t :
66
+ Time. Default 1.
67
+ u_max :
68
+ Truncation of the frequency domain. Should be large enough that
69
+ |φ(u)| is negligible beyond u_max.
70
+ n_points :
71
+ Number of quadrature points.
72
+
73
+ Returns
74
+ -------
75
+ float
76
+ Non-negative L² distance squared.
77
+
78
+ Raises
79
+ ------
80
+ ExactnessError
81
+ If either process does not support char_func.
82
+
83
+ References
84
+ ----------
85
+ Plancherel theorem. See e.g. Rudin (1987), Theorem 9.13.
86
+ """
87
+ u_grid = np.linspace(-u_max, u_max, n_points)
88
+ du = u_grid[1] - u_grid[0]
89
+
90
+ cf_X = X.char_func(u=u_grid, t=t)
91
+ cf_Y = Y.char_func(u=u_grid, t=t)
92
+
93
+ diff_sq = np.abs(cf_X - cf_Y) ** 2
94
+ return float(np.trapezoid(diff_sq, u_grid) / (2 * np.pi))
95
+
96
+
97
+ def hellinger_distance(
98
+ X: Process,
99
+ Y: Process,
100
+ t: float = 1.0,
101
+ u_max: float = 50.0,
102
+ n_points: int = 2000,
103
+ ) -> float:
104
+ """
105
+ Squared Hellinger distance between marginal distributions at time t.
106
+
107
+ H²(X_t, Y_t) = 1 - Re[∫ φ_X(u/2; t) · conj(φ_Y(u/2; t)) · (1/2π) du]
108
+ = 1 - Re[φ_{X_t - Y_t'}(0)] ... (characteristic function route)
109
+
110
+ Computed via the identity:
111
+ 2H²(P, Q) = ∫ (√p - √q)² dx = 2 - 2∫ √(pq) dx
112
+
113
+ and using the fact that ∫ √(pq) dx can be expressed via the characteristic
114
+ function of (X - Y') where Y' is an independent copy of Y, evaluated at 0:
115
+ ∫ √(pq) dx = Re[(1/2π) ∫ φ_X(u/2; t) · conj(φ_Y(u/2; t)) du]
116
+
117
+ Parameters
118
+ ----------
119
+ X, Y :
120
+ Processes supporting char_func.
121
+ t :
122
+ Time. Default 1.
123
+ u_max, n_points :
124
+ Frequency domain truncation and resolution.
125
+
126
+ Returns
127
+ -------
128
+ float
129
+ Squared Hellinger distance H² ∈ [0, 1].
130
+
131
+ References
132
+ ----------
133
+ Cont & Tankov (2004), Section 4.6.
134
+ """
135
+ u_grid = np.linspace(-u_max, u_max, n_points)
136
+
137
+ cf_X_half = X.char_func(u=u_grid / 2, t=t)
138
+ cf_Y_half = Y.char_func(u=u_grid / 2, t=t)
139
+
140
+ integrand = (cf_X_half * np.conj(cf_Y_half)).real
141
+ overlap = float(np.trapezoid(integrand, u_grid) / (2 * np.pi))
142
+ overlap = np.clip(overlap, 0.0, 1.0)
143
+
144
+ return 1.0 - overlap
145
+
146
+
147
+ def wasserstein2_distance(
148
+ X: Process,
149
+ Y: Process,
150
+ t: float = 1.0,
151
+ u_max: float = 100.0,
152
+ n_points: int = 4000,
153
+ ) -> float:
154
+ """
155
+ Wasserstein-2 distance between marginal distributions at time t.
156
+
157
+ W_2²(X_t, Y_t) = ∫_0^1 (F_X^{-1}(p) - F_Y^{-1}(p))² dp
158
+
159
+ where F^{-1} is the quantile function. Computed by:
160
+ 1. Recovering CDFs from characteristic functions via Gil-Pelaez inversion.
161
+ 2. Computing quantile functions numerically.
162
+ 3. Integrating the squared difference of quantile functions.
163
+
164
+ Parameters
165
+ ----------
166
+ X, Y :
167
+ Processes supporting char_func.
168
+ t :
169
+ Time. Default 1.
170
+ u_max, n_points :
171
+ Frequency domain and x-grid resolution.
172
+
173
+ Returns
174
+ -------
175
+ float
176
+ W₂ distance (not squared).
177
+
178
+ References
179
+ ----------
180
+ Villani, C. (2003). *Topics in Optimal Transportation*. AMS. Chapter 2.
181
+ Gil-Pelaez, J. (1951). Note on the inversion theorem. *Biometrika*, 38, 481–482.
182
+ """
183
+ from scipy import integrate as sci_integrate # type: ignore[import-untyped]
184
+
185
+ def get_quantile_fn(proc: Process) -> tuple[np.ndarray, np.ndarray]:
186
+ u_grid = np.linspace(1e-6, u_max, n_points // 2)
187
+
188
+ cf_vals = proc.char_func(u=u_grid, t=t)
189
+
190
+ x_vals = np.linspace(-20.0, 20.0, n_points)
191
+ dx = x_vals[1] - x_vals[0]
192
+
193
+ pdf = np.zeros(len(x_vals))
194
+ for i, x in enumerate(x_vals):
195
+ integrand = (cf_vals * np.exp(-1j * u_grid * x)).real
196
+ pdf[i] = float(np.trapezoid(integrand, u_grid)) / np.pi
197
+
198
+ pdf = np.maximum(pdf, 0)
199
+ cdf = np.cumsum(pdf) * dx
200
+ cdf = np.clip(cdf / cdf[-1], 0, 1)
201
+
202
+ return x_vals, cdf
203
+
204
+ x_X, cdf_X = get_quantile_fn(X)
205
+ x_Y, cdf_Y = get_quantile_fn(Y)
206
+
207
+ p_grid = np.linspace(0.01, 0.99, 500)
208
+ q_X = np.interp(p_grid, cdf_X, x_X)
209
+ q_Y = np.interp(p_grid, cdf_Y, x_Y)
210
+
211
+ w2_sq = float(np.trapezoid((q_X - q_Y) ** 2, p_grid))
212
+ return float(np.sqrt(max(w2_sq, 0.0)))
213
+
214
+
215
+ def kl_divergence_mc(
216
+ X: Process,
217
+ Y: Process,
218
+ t: float = 1.0,
219
+ n_samples: int = 10_000,
220
+ rng: np.random.Generator | None = None,
221
+ ) -> float:
222
+ """
223
+ Monte Carlo estimate of KL divergence KL(X_t || Y_t).
224
+
225
+ KL(P||Q) = E_P[log(p(X)/q(X))]
226
+
227
+ Estimated using importance sampling: draw samples from X_t,
228
+ recover densities via Gil-Pelaez inversion evaluated at the samples,
229
+ and compute the log ratio.
230
+
231
+ This is an approximate method. The density inversion introduces
232
+ numerical error. Use l2_char_func_distance or hellinger_distance
233
+ for more reliable analytical divergences.
234
+
235
+ Parameters
236
+ ----------
237
+ X, Y :
238
+ Processes supporting char_func and simulate.
239
+ t :
240
+ Time.
241
+ n_samples :
242
+ Number of Monte Carlo samples.
243
+ rng :
244
+ Random number generator.
245
+
246
+ Returns
247
+ -------
248
+ float
249
+ Estimated KL(X_t || Y_t). May be negative due to numerical error
250
+ in density estimation — clamp to 0 if this occurs.
251
+ """
252
+ rng = rng or np.random.default_rng()
253
+
254
+ paths = X.simulate(n_steps=1, n_paths=n_samples, T=t, rng=rng)
255
+ samples = paths[:, -1]
256
+
257
+ u_grid = np.linspace(-100.0, 100.0, 2000)
258
+ du = u_grid[1] - u_grid[0]
259
+
260
+ def density_at(proc: Process, x_vals: np.ndarray) -> np.ndarray:
261
+ cf = proc.char_func(u=u_grid, t=t)
262
+ densities = np.zeros(len(x_vals))
263
+ for i, x in enumerate(x_vals):
264
+ integrand = (cf * np.exp(-1j * u_grid * x)).real
265
+ densities[i] = float(np.trapezoid(integrand, u_grid)) / (2 * np.pi)
266
+ return np.maximum(densities, 1e-300)
267
+
268
+ p_vals = density_at(X, samples)
269
+ q_vals = density_at(Y, samples)
270
+
271
+ log_ratios = np.log(p_vals / q_vals)
272
+ return float(np.maximum(np.mean(log_ratios), 0.0))
@@ -0,0 +1,183 @@
1
+ """
2
+ Fourier-based option pricing for Lévy process models.
3
+
4
+ For a log-price process X_t with characteristic function φ(u; t),
5
+ European option prices can be computed via the Carr-Madan formula using
6
+ FFT. This is the standard approach in quantitative finance for Lévy models.
7
+
8
+ Reference: Carr, P. & Madan, D.B. (1999). Option valuation using the fast
9
+ Fourier transform. *Journal of Computational Finance*, 2(4), 61–73.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import numpy as np
15
+
16
+ from spxa.core.process import Process
17
+
18
+
19
+ def european_call_price(
20
+ process: Process,
21
+ S0: float,
22
+ K: float,
23
+ r: float,
24
+ t: float,
25
+ alpha: float = 1.5,
26
+ n_points: int = 4096,
27
+ eta: float = 0.25,
28
+ ) -> float:
29
+ """
30
+ Price a European call option assuming X_t is the log-return process.
31
+
32
+ Uses the Carr-Madan FFT method. The log-price at time t is S0·exp(r·t + X_t).
33
+
34
+ The call price is:
35
+ C(K) = e^{-αk}/(π) · Re[∫_0^∞ e^{-iuk} ψ(u) du]
36
+
37
+ where k = log(K/S0), α is a dampening factor, and ψ(u) is the
38
+ modified characteristic function of X_t.
39
+
40
+ Parameters
41
+ ----------
42
+ process :
43
+ Log-return Lévy process. Must support char_func.
44
+ S0 :
45
+ Current asset price.
46
+ K :
47
+ Strike price.
48
+ r :
49
+ Risk-free rate (continuously compounded).
50
+ t :
51
+ Time to expiry.
52
+ alpha :
53
+ Dampening factor α > 0. Typically 1.0–2.0. Larger values
54
+ give better accuracy for OTM options but may cause overflow.
55
+ n_points :
56
+ FFT grid size. Must be a power of 2.
57
+ eta :
58
+ Spacing in the integration domain.
59
+
60
+ Returns
61
+ -------
62
+ float
63
+ Call price.
64
+
65
+ References
66
+ ----------
67
+ Carr, P. & Madan, D.B. (1999). Option valuation using the fast Fourier
68
+ transform. *Journal of Computational Finance*, 2(4), 61–73.
69
+ """
70
+ lam = 2 * np.pi / (n_points * eta)
71
+ b = n_points * lam / 2
72
+ k = np.log(K / S0)
73
+
74
+ u_grid = np.arange(n_points) * eta
75
+ u_shifted = u_grid - (alpha + 1) * 1j
76
+
77
+ # Use char_func_exact if the process provides it (avoids slow LK quadrature)
78
+ cf_fn = getattr(process, "char_func_exact", None) or process.char_func
79
+ cf_vals = cf_fn(u=u_shifted, t=t)
80
+
81
+ numerator = np.exp(-r * t) * cf_vals
82
+ denominator = alpha**2 + alpha - u_grid**2 + 1j * (2 * alpha + 1) * u_grid
83
+
84
+ psi = numerator / denominator
85
+
86
+ simpson_weights = np.ones(n_points)
87
+ simpson_weights[0] = 1 / 3
88
+ simpson_weights[-1] = 1 / 3
89
+ simpson_weights[1:-1:2] = 4 / 3
90
+ simpson_weights[2:-2:2] = 2 / 3
91
+
92
+ x = np.exp(1j * b * u_grid) * psi * simpson_weights * eta
93
+
94
+ fft_result = np.fft.fft(x)
95
+
96
+ k_grid = -b + lam * np.arange(n_points)
97
+ call_prices = (np.exp(-alpha * k_grid) / np.pi * fft_result).real
98
+
99
+ call_price = float(np.interp(k, k_grid, call_prices)) * S0
100
+ return max(call_price, max(S0 - K * np.exp(-r * t), 0.0))
101
+
102
+
103
+ def european_put_price(
104
+ process: Process,
105
+ S0: float,
106
+ K: float,
107
+ r: float,
108
+ t: float,
109
+ **kwargs: object,
110
+ ) -> float:
111
+ """
112
+ Price a European put via put-call parity.
113
+
114
+ P = C - S0 + K·e^{-rt}
115
+
116
+ Parameters
117
+ ----------
118
+ process, S0, K, r, t :
119
+ Same as european_call_price.
120
+ **kwargs :
121
+ Passed to european_call_price.
122
+
123
+ Returns
124
+ -------
125
+ float
126
+ Put price.
127
+ """
128
+ call = european_call_price(process=process, S0=S0, K=K, r=r, t=t, **kwargs)
129
+ return call - S0 + K * np.exp(-r * t)
130
+
131
+
132
+ def implied_volatility(
133
+ price: float,
134
+ S0: float,
135
+ K: float,
136
+ r: float,
137
+ t: float,
138
+ option_type: str = "call",
139
+ tol: float = 1e-6,
140
+ max_iter: int = 100,
141
+ ) -> float:
142
+ """
143
+ Compute Black-Scholes implied volatility from an option price via bisection.
144
+
145
+ Parameters
146
+ ----------
147
+ price :
148
+ Observed option price.
149
+ S0, K, r, t :
150
+ Asset price, strike, rate, time.
151
+ option_type :
152
+ 'call' or 'put'.
153
+ tol :
154
+ Convergence tolerance on price.
155
+ max_iter :
156
+ Maximum bisection iterations.
157
+
158
+ Returns
159
+ -------
160
+ float
161
+ Implied volatility σ. Returns NaN if no solution found.
162
+ """
163
+ from scipy.stats import norm # type: ignore[import-untyped]
164
+
165
+ def bs_price(sigma: float) -> float:
166
+ d1 = (np.log(S0 / K) + (r + 0.5 * sigma**2) * t) / (sigma * np.sqrt(t))
167
+ d2 = d1 - sigma * np.sqrt(t)
168
+ if option_type == "call":
169
+ return S0 * norm.cdf(d1) - K * np.exp(-r * t) * norm.cdf(d2)
170
+ return K * np.exp(-r * t) * norm.cdf(-d2) - S0 * norm.cdf(-d1)
171
+
172
+ lo, hi = 1e-6, 10.0
173
+ for _ in range(max_iter):
174
+ mid = (lo + hi) / 2
175
+ diff = bs_price(mid) - price
176
+ if abs(diff) < tol:
177
+ return mid
178
+ if diff > 0:
179
+ hi = mid
180
+ else:
181
+ lo = mid
182
+
183
+ return float("nan")
spxa/core/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """Core algebraic engine for spxa."""
2
+
3
+ from spxa.core.exactness import ExactnessLevel
4
+ from spxa.core.exceptions import ExactnessError, SpxaDegradationWarning, SpxaError
5
+ from spxa.core.levy_measure import (
6
+ CompoundLevyMeasure,
7
+ DensityLevyMeasure,
8
+ LevyMeasure,
9
+ ScaledLevyMeasure,
10
+ )
11
+ from spxa.core.process import Process
12
+ from spxa.core.properties import ProcessProperties
13
+ from spxa.core.triplet import LevyTriplet
14
+
15
+ __all__ = [
16
+ "ExactnessLevel",
17
+ "ExactnessError",
18
+ "SpxaDegradationWarning",
19
+ "SpxaError",
20
+ "CompoundLevyMeasure",
21
+ "DensityLevyMeasure",
22
+ "LevyMeasure",
23
+ "ScaledLevyMeasure",
24
+ "Process",
25
+ "ProcessProperties",
26
+ "LevyTriplet",
27
+ ]
spxa/core/exactness.py ADDED
@@ -0,0 +1,47 @@
1
+ """Exactness levels for stochastic process operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import Enum, auto
6
+
7
+
8
+ class ExactnessLevel(Enum):
9
+ """
10
+ Describes the analytical guarantee attached to a process or operation result.
11
+
12
+ Levels are ordered: EXACT > MOMENT_PROPAGATION > SIMULATION_ONLY.
13
+ Operations between two processes degrade to the minimum level of the operands.
14
+
15
+ Attributes
16
+ ----------
17
+ EXACT :
18
+ The Lévy–Khintchine triplet is known in closed form.
19
+ All arithmetic is exact: triplet addition, cumulant derivation, and
20
+ characteristic function evaluation are analytically correct.
21
+ Applies only to independent Lévy processes.
22
+ MOMENT_PROPAGATION :
23
+ A closed-form triplet is unavailable or inapplicable (e.g. fBM, Hawkes,
24
+ OU-Lévy, or compositions that leave the Lévy class).
25
+ Finite moments are tracked exactly where computable; the full distribution
26
+ is not available in closed form.
27
+ SIMULATION_ONLY :
28
+ No analytical handle exists. Sample paths can be generated but no
29
+ distributional quantities are computed.
30
+ """
31
+
32
+ EXACT = auto()
33
+ MOMENT_PROPAGATION = auto()
34
+ SIMULATION_ONLY = auto()
35
+
36
+ def __le__(self, other: ExactnessLevel) -> bool:
37
+ order = [ExactnessLevel.EXACT, ExactnessLevel.MOMENT_PROPAGATION, ExactnessLevel.SIMULATION_ONLY]
38
+ return order.index(self) <= order.index(other)
39
+
40
+ def __lt__(self, other: ExactnessLevel) -> bool:
41
+ return self != other and self <= other
42
+
43
+ @staticmethod
44
+ def combine(a: ExactnessLevel, b: ExactnessLevel) -> ExactnessLevel:
45
+ """Return the minimum (most degraded) of two exactness levels."""
46
+ order = [ExactnessLevel.EXACT, ExactnessLevel.MOMENT_PROPAGATION, ExactnessLevel.SIMULATION_ONLY]
47
+ return order[max(order.index(a), order.index(b))]