openqdata 0.3.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 (75) hide show
  1. openqdata/README.md +5 -0
  2. openqdata/__init__.py +15 -0
  3. openqdata/arbfree/README.md +5 -0
  4. openqdata/arbfree/__init__.py +9 -0
  5. openqdata/arbfree/arbfree.py +1494 -0
  6. openqdata/arbfree/sanos.py +316 -0
  7. openqdata/arbfree/sanos_tools.py +958 -0
  8. openqdata/arbfree/tridiag.py +85 -0
  9. openqdata/benchmark/README.md +5 -0
  10. openqdata/benchmark/__init__.py +4 -0
  11. openqdata/biz_calendar.py +506 -0
  12. openqdata/cli.py +91 -0
  13. openqdata/env.py +112 -0
  14. openqdata/fred/README.md +5 -0
  15. openqdata/fred/__init__.py +14 -0
  16. openqdata/fred/client.py +57 -0
  17. openqdata/fred/rates.py +162 -0
  18. openqdata/massive/README.md +5 -0
  19. openqdata/massive/__init__.py +15 -0
  20. openqdata/massive/client.py +1183 -0
  21. openqdata/massive/expiries.py +242 -0
  22. openqdata/massive/options/README.md +5 -0
  23. openqdata/massive/options/__init__.py +6 -0
  24. openqdata/massive/options/contracts.py +610 -0
  25. openqdata/massive/processing.py +447 -0
  26. openqdata/massive/testing/README.md +5 -0
  27. openqdata/massive/testing/__init__.py +8 -0
  28. openqdata/massive/testing/generate.py +61 -0
  29. openqdata/massive/testing/scope.py +8 -0
  30. openqdata/massive/tickers/README.md +5 -0
  31. openqdata/massive/tickers/__init__.py +5 -0
  32. openqdata/massive/tickers/basics.py +66 -0
  33. openqdata/massive/tickers/data.py +362 -0
  34. openqdata/massive/tickers/filtered_history.py +260 -0
  35. openqdata/massive/trade_conds.py +324 -0
  36. openqdata/models/README.md +5 -0
  37. openqdata/models/__init__.py +4 -0
  38. openqdata/pool.py +34 -0
  39. openqdata/tickers/README.md +5 -0
  40. openqdata/tickers/__init__.py +13 -0
  41. openqdata/tickers/ticker_calendar.py +370 -0
  42. openqdata/utils/README.md +3 -0
  43. openqdata/utils/__init__.py +35 -0
  44. openqdata/utils/cvxpy.py +47 -0
  45. openqdata/utils/pd.py +125 -0
  46. openqdata/utils/pl.py +114 -0
  47. openqdata/vixdata/README.md +5 -0
  48. openqdata/vixdata/__init__.py +6 -0
  49. openqdata/vixdata/cboe.py +119 -0
  50. openqdata/vixdata/client.py +44 -0
  51. openqdata/vixdata/formula.py +132 -0
  52. openqdata/widb/README.md +5 -0
  53. openqdata/widb/__init__.py +25 -0
  54. openqdata/widb/arbfree.py +581 -0
  55. openqdata/widb/bad.py +69 -0
  56. openqdata/widb/client.py +517 -0
  57. openqdata/widb/connection.py +72 -0
  58. openqdata/widb/day.py +1098 -0
  59. openqdata/widb/fitstats.py +328 -0
  60. openqdata/widb/options_filter.py +338 -0
  61. openqdata/widb/sanos.py +96 -0
  62. openqdata/widb/testing/README.md +5 -0
  63. openqdata/widb/testing/__init__.py +0 -0
  64. openqdata/widb/testing/generate.py +45 -0
  65. openqdata/widb/testing/scope.py +8 -0
  66. openqdata/widb/timeseries.py +434 -0
  67. openqdata/yahoo/README.md +5 -0
  68. openqdata/yahoo/__init__.py +8 -0
  69. openqdata/yahoo/client.py +229 -0
  70. openqdata-0.3.0.dist-info/METADATA +103 -0
  71. openqdata-0.3.0.dist-info/RECORD +75 -0
  72. openqdata-0.3.0.dist-info/WHEEL +5 -0
  73. openqdata-0.3.0.dist-info/licenses/LICENSE +131 -0
  74. openqdata-0.3.0.dist-info/licenses/NOTICE +1 -0
  75. openqdata-0.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,958 @@
1
+ """
2
+ SANOS
3
+ =====
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ import warnings as warnings
10
+ from dataclasses import dataclass
11
+ from typing import Literal
12
+
13
+ import cvxpy as cp
14
+ import numpy as np
15
+ from cdxcore.bs import bs
16
+ from cdxcore.err import verify, verify_inp
17
+ from cdxcore.pretty import PrettyObject
18
+ from cdxcore.verbose import Context
19
+ from cdxcore.version import version
20
+ from cvxpy import settings as cps
21
+ from cvxpy.error import SolverError
22
+ from cvxpy.reductions.cvx_attr2constr import CvxAttr2Constr, recover_value_for_leaf
23
+ from cvxpy.reductions.solution import Solution
24
+
25
+ from openqdata.arbfree.tridiag import solve_sanos_tridiagonal
26
+ from openqdata.biz_calendar import DAYS_PER_YEAR, ONE_MINUTE
27
+
28
+
29
+ @version("0.8")
30
+ @dataclass(frozen=True)
31
+ class SanosPricer:
32
+ """
33
+ Arbitrage-free option pricer based on `DLV <http://arxiv.org/abs/2211.13227>`_ and `SANOS <https://arxiv.org/abs/2601.11209>`_.
34
+ """
35
+
36
+ smoothness : float|None # SANOS smoothness or None for linear model.
37
+ expiries : np.ndarray # Model expiries. Must be increasing and positive.
38
+ variances : np.ndarray # Model variances. Must be increasing and positive.
39
+ xstrikes : list[np.ndarray] # Extended strike range. Each element must be increasing and positive.
40
+ xdensities : list[np.ndarray] # Densities for each ``xstrike``.
41
+ min_half_spread : float = 1E-4 # Minimum half spread for error calculations
42
+ min_dlv : float = 0.01 # Minimum local volatility to impose in the fit, in absolute terms. This is a soft constraint which is implemented as a penalty term in the optimization problem, so it may not be perfectly respected. If None, no minimum local volatility is imposed.
43
+ max_dlv : float = 5. # Maximum discrete local volatility.
44
+
45
+ _eps_price : float = 1E-6
46
+ _eps_density : float = 1E-7
47
+
48
+ # for DLV
49
+ _eps_dlv_dens_pos : float = 1E-4
50
+ _eps_dlv_dens_sum1 : float = 1E-4
51
+ _eps_dlv_dens_int1 : float = 1E-4
52
+ _eps_dlv_diff : float = 1E-3
53
+
54
+ def __post_init__(self):
55
+ verify_inp( self.smoothness is None or self.smoothness >= 0., lambda : f"'smoothness' must be positive or None, but found {self.smoothness:.4g}")
56
+ verify_inp( self.min_half_spread > 0., lambda : f"'min_half_spread' must be positive, but found {self.min_half_spread:.4g}" )
57
+ verify_inp( self.expiries[0] > 0., lambda : f"'expiries' must be positive, but found {self.expiries[0]:.4g}" )
58
+ verify_inp( self.variances[0] > 0., lambda : f"'variances' must be positive, but found {self.variances[0]:.4g}" )
59
+ verify_inp( len(self.expiries) == 1 or np.min(np.diff(self.expiries)) > 0., lambda : f"'expiries' must be positive and strictly increasing, but found differences {np.diff(self.expiries).min():.4g}" )
60
+ verify_inp( len(self.variances) == 1 or np.min(np.diff(self.variances)) > 0., lambda : f"'variances' must be positive and strictly increasing, but found differences {np.diff(self.variances).min():.4g}" )
61
+ verify_inp( self.expiries.shape == self.variances.shape, lambda : f"Shape of 'expiries' {self.expiries.shape} must match shape of 'variances' {self.variances.shape}" )
62
+
63
+ verify_inp( len(self.xstrikes) == len(self.xdensities) == len(self.expiries), lambda : f"Length of 'xstrikes' and 'xdensities' lists must match length of 'expiries', but found {len(self.xstrikes)}, {len(self.xdensities)} and {len(self.expiries)}" )
64
+ for i, (xstrikes_i, xdensities_i) in enumerate(zip(self.xstrikes, self.xdensities, strict=True)):
65
+ verify_inp( xstrikes_i.shape == xdensities_i.shape, lambda : f"Shape of 'xstrikes[{i}]' {xstrikes_i.shape} must match shape of 'xdensities[{i}]' {xdensities_i.shape}" )
66
+ verify_inp( xstrikes_i[0] > 0. and np.min( np.diff(xstrikes_i) ) > 0., lambda : f"'xstrikes[{i}]' must be positive and increasing, but found differences {np.diff(xstrikes_i).min():.4g}" )
67
+ verify_inp( np.all(xdensities_i >= 0.), lambda : f"'xdensities[{i}]' must be non-negative, but found {xdensities_i}" )
68
+
69
+ @property
70
+ def T(self) -> int:
71
+ return len(self.expiries)
72
+
73
+ def __call__( self, expiries: float|np.ndarray,
74
+ strikes : np.ndarray, *,
75
+ and_vols: bool = False ) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
76
+ """
77
+ Price options at ``strikes`` with expiries ``expiries``.
78
+
79
+ If ``and_vols`` is ``True`` this function returns call prices and their implied volatilities;
80
+ if ``False``, it will return only call prices.
81
+
82
+ Parameters
83
+ ----------
84
+ expiries : float | :class:`np.ndarray`
85
+ The expiry or expiries to price at.
86
+
87
+ * If ``expiries`` is a float, all strikes are evaluated at that expiry.
88
+ * If ``expiries`` is a 1D array of shape ``(N,)``, then ``strikes`` must also be a 1D array of shape ``(N,)``, and the function will price each strike at their respective expiry.
89
+ * If ``expiries`` is a 2D array of shape ``(M,1)``, then ``strikes`` must be a 2D array of shape ``(1,N)``, and the function will price each strike at each expiry, returning an array of shape ``(M,N)``.
90
+
91
+ strikes : np.ndarray
92
+ The strikes to price at. The shape of this array must be compatible with the shape of ``expiries`` as described above.
93
+
94
+ and_vols : bool, default ``False``
95
+ Whether to return implied volatilities in addition to call prices. If ``True``, the function returns a tuple of (call prices, implied volatilities).
96
+ If ``False``, it returns only call prices.
97
+ """
98
+ expiries = np.asarray(expiries,dtype=float)
99
+ strikes = np.asarray(strikes,dtype=float)
100
+ _0 = strikes.dtype.type(0.)
101
+ _1 = strikes.dtype.type(1.)
102
+ verify_inp( len(strikes.shape) > 0, lambda : "'strikes' must be a non-empty array")
103
+
104
+ def x_price( expiry : float, strikes : np.ndarray ):
105
+ verify_inp( isinstance( expiry, (float, int, np.number)) and expiry>=0, lambda : f"Expected 'expiry' to be a non-negative number, but found {str(expiry)}")
106
+
107
+ if expiry<ONE_MINUTE:
108
+ return np.maximum( _0, _1 - strikes )
109
+
110
+ if self.smoothness is None:
111
+ def call(spots):
112
+ return np.maximum( _0, spots[None,:] - strikes[:,None] )
113
+ else:
114
+ vol = self.model_vols( expiries=expiry )#applies smoothness
115
+ def call(spots):
116
+ return bs.price( k=strikes[:,None]/spots[None,:], vol=vol, sqrtT=math.sqrt(expiry), eps=self._eps_price )*spots[None,:]
117
+
118
+ ix = np.searchsorted( self.expiries, expiry )
119
+ if ix==0:
120
+ # Using q_1 for every 0<t<T_1 makes the law jump from the
121
+ # time-zero Dirac mass to q_1 as t approaches zero; interpolating
122
+ # from the Dirac mass would avoid this discontinuity.
123
+ strikes_0 = self.xstrikes[0]
124
+ p_0 = self.xdensities[0]
125
+ return call( spots=strikes_0 ) @ p_0
126
+
127
+ if ix==len(self.expiries):
128
+ strikes_T = self.xstrikes[-1]
129
+ p_T = self.xdensities[-1]
130
+ return call( spots=strikes_T ) @ p_T
131
+
132
+ diff_ixm1 = abs( expiry - self.expiries[ix-1] )
133
+ diff_ix = abs( expiry - self.expiries[ix] )
134
+ diff = diff_ix if diff_ix < diff_ixm1 else diff_ixm1
135
+
136
+ if diff<ONE_MINUTE:
137
+ ix_mind = ix if diff_ix < diff_ixm1 else ix-1
138
+ strikes_ix = self.xstrikes[ix_mind]
139
+ p_ix = self.xdensities[ix_mind]
140
+ return call( spots=strikes_ix ) @ p_ix
141
+
142
+ strikes_ixm1 = self.xstrikes[ix-1]
143
+ p_ixm1 = self.xdensities[ix-1]
144
+ c_ixm1 = call( spots=strikes_ixm1 ) @ p_ixm1
145
+
146
+ strikes_ix = self.xstrikes[ix]
147
+ p_ix = self.xdensities[ix]
148
+ c_ix = call( spots=strikes_ix ) @ p_ix
149
+
150
+ return ((expiry - self.expiries[ix-1])*c_ix + (self.expiries[ix]-expiry)*c_ixm1)/(self.expiries[ix]-self.expiries[ix-1])
151
+
152
+ if len(expiries.shape) == 0:
153
+ prices = x_price( float(expiries), strikes = strikes )
154
+ if not and_vols:
155
+ return prices
156
+ vols = bs.implied( k=strikes, prices=prices, sqrtT=math.sqrt(float(expiries)), eps=self._eps_price )
157
+ assert prices.shape == vols.shape, f"Shape error {prices.shape} != {vols.shape}"
158
+ return prices, vols
159
+
160
+ if expiries.shape == (1,):
161
+ prices = x_price( expiries[0], strikes = strikes )
162
+ if not and_vols:
163
+ return prices
164
+ vols = bs.implied( k=strikes, prices=prices, sqrtT=math.sqrt(float(expiries[0])), eps=self._eps_price )
165
+ assert prices.shape == vols.shape, f"Shape error {prices.shape} != {vols.shape}"
166
+ return prices, vols
167
+
168
+ if len(expiries.shape) == 1:
169
+ if strikes.shape == (1,):
170
+ prices = np.zeros_like(expiries, dtype=strikes.dtype)
171
+ for j, expiry in enumerate(expiries):
172
+ prices[j] = x_price( expiry=expiry, strikes=strikes )[0]
173
+ if not and_vols:
174
+ return prices
175
+ vols = bs.implied( k=strikes, prices=prices, sqrtT=np.sqrt(expiries), eps=self._eps_price )
176
+ assert prices.shape == vols.shape, f"Shape error {prices.shape} != {vols.shape}"
177
+ return prices, vols
178
+
179
+ verify_inp( strikes.shape == expiries.shape, lambda : f"If 'expiries' is a vector of length M, then 'strikes' must be a vector of length 1 or M, but found {expiries.shape} and {strikes.shape}" )
180
+ uttys = np.unique(expiries)
181
+ prices = np.zeros_like(strikes)
182
+ for utty in uttys:
183
+ mask = expiries==utty
184
+ prices[mask] = x_price( expiry=utty, strikes=strikes[mask] )
185
+ if not and_vols:
186
+ return prices
187
+ vols = bs.implied( k=strikes, prices=prices, sqrtT=np.sqrt(expiries), eps=self._eps_price )
188
+ assert prices.shape == vols.shape, f"Shape error {prices.shape} != {vols.shape}"
189
+ return prices, vols
190
+
191
+ verify_inp( len(expiries.shape) == 2 and expiries.shape[1] == 1, lambda: f"'expiries' can be a vector or a matrix if size '(M,1)'. Found shape {expiries.shape}" )
192
+ M = expiries.shape[0]
193
+ verify_inp( len(strikes.shape) == 2 and strikes.shape[0] in (M,1), lambda: f"If 'expiries' is a matrix of shape '(M,1), then 'strikes' must be a matrix of shape '(M|1,N)'. Found expiries shape {expiries.shape} and strikes {strikes.shape}" )
194
+ N = strikes.shape[1]
195
+ prices = np.zeros((M,N),dtype=strikes.dtype)
196
+ for ix, tty in enumerate(expiries[:,0]):
197
+ prices[ix,:] = x_price( expiry=tty, strikes=strikes[0 if strikes.shape[0] == 1 else ix,:] )
198
+ if not and_vols:
199
+ return prices
200
+ vols = bs.implied( k=strikes, prices=prices, sqrtT=np.sqrt(expiries), eps=self._eps_price )
201
+ assert prices.shape == vols.shape, f"Shape error {prices.shape} != {vols.shape}"
202
+ return prices, vols
203
+
204
+ def model_vols( self, expiries: float|np.ndarray ) -> float|np.ndarray:
205
+ """ Interpolates the model variances, scaled by ``smoothness`` """
206
+ assert not self.variances is None, "Internal error - variances are missing"
207
+ is_float = not hasattr(expiries,"shape")
208
+ expiries = np.asarray([float(expiries)]) if is_float else np.asarray(expiries)
209
+ expiries = np.clip( expiries, self.expiries[0], self.expiries[-1] )
210
+ vols = np.sqrt( self.smoothness * np.interp( expiries, self.expiries, self.variances ) / expiries )
211
+ assert np.all(np.isfinite(vols)), "Internal error: infinite vol"
212
+ return vols if not is_float else vols[0]
213
+
214
+ def compute_market_fit( self,
215
+ expiries : np.ndarray,
216
+ strikes : list[np.ndarray]|np.ndarray,
217
+ bids : list[np.ndarray]|np.ndarray,
218
+ asks : list[np.ndarray]|np.ndarray, *,
219
+ masks : list[np.ndarray]|np.ndarray|None = None,
220
+ and_vols : bool = True ) -> PrettyObject:
221
+ """
222
+ Compute standardized fitting error stats for the given market data.
223
+
224
+ Returns
225
+ -------
226
+ Errors : :class:`PrettyObject`
227
+ A dictionary-like object with the following fields:
228
+ * ``fits``: list of fitted prices for the input strikes, per expiry.
229
+ * ``fit_errs``: list of fitting errors for the input strikes, per expiry: the distance outside bid/ask in half spreads, ``( max( 0, fit - ask ) + max( 0, bid - fit ) ) / max( 0.5*(ask-bid), min_half_spread )``. For array input the field is ``fit_err``.
230
+ * ``fit_vols``: list of fitted vols for the input strikes, per expiry, if ``and_vols`` is ``True``.
231
+ * ``pcnt_fit``: despite its name, the fraction (between 0 and 1) of strikes whose fit is outside the actual bid/ask spread, ``sum( fit_errs > 0 ) / len(fit_errs)``.
232
+ * ``median_err``: the median fitting error among strikes whose fit is outside the bid/ask spread; zero if there are none.
233
+ * ``mean_err``: the mean fitting error among strikes whose fit is outside the bid/ask spread; zero if there are none.
234
+ """
235
+ return _compute_market_fit( pricer=self, min_half_spread=self.min_half_spread, expiries=expiries, strikes=strikes, bids=bids, asks=asks, masks=masks, and_vols=and_vols )
236
+
237
+ def dlvsqs( self, *, min_dlv : float = 0., max_dlv : float|None = None, on_all_strikes : bool = False ) -> list[np.ndarray]:
238
+ """
239
+ Compute squared discrete local volatilities.
240
+
241
+ Parameters
242
+ ----------
243
+ min_dlv : float, default 0.
244
+ Minimum discrete local volatility. If the computed DLV is below this threshold, it will be set to this value. Must be positive and less than ``max_dlv``.
245
+ max_dlv : float | None, default None
246
+ Maximum discrete local volatility. If the computed DLV is above this threshold, it will be set to this value. Must be positive and greater than ``min_dlv``.
247
+ on_all_strikes : bool, default False
248
+ If True, the function will return DLV^2 values for all strikes in ``strikes``, not just ``xstrikes[:,1:-1]``. The DLVs at the boundaries will be set to zero.
249
+ """
250
+
251
+ verify_inp( 0.<= min_dlv, lambda : f"'min_dlv' must not be negative, but found {min_dlv:.4g}" )
252
+ verify_inp( max_dlv is None or max_dlv > min_dlv, lambda : f"'min_dlv' must be positive and less than 'max_dlv', found {min_dlv:.4g} and {max_dlv:.4g}" )
253
+ min_dlvsq = float(min_dlv**2)
254
+ max_dlvsq = float(max_dlv**2) if max_dlv is not None else None
255
+
256
+ # dlvs
257
+ # We note that dC_t = 1/2 DLV^2 K^2 dT C''(K) where C''(K) = 1/2 ( k[2:] - K[:-2]) p(k)
258
+ # hence
259
+ # dC_t = DLV^2 { K^2/( k[2:] - K[:-2]) dt} p(K)
260
+ # We precompute
261
+ # dlvbox = K^2/( k[2:] - K[:-2]) dt
262
+
263
+ dts = np.diff( self.expiries, prepend=0. ).astype(np.float64,copy=False)
264
+ dlvsqs = []
265
+ _1 = np.float64(1.)
266
+ _0 = np.float64(0.)
267
+ for t, expiry in enumerate(self.expiries):
268
+ xstrikes_t = self.xstrikes[t].astype(np.float64,copy=False)
269
+ xstrikes_tm1 = self.xstrikes[t-1].astype(np.float64,copy=False) if t>0 else None
270
+ p_t = self.xdensities[t].astype(np.float64,copy=False)
271
+ p_tm1 = self.xdensities[t-1].astype(np.float64,copy=False) if t>0 else None
272
+ box = xstrikes_t[1:-1]**2 * dts[t] / ( xstrikes_t[2:] - xstrikes_t[:-2])
273
+ p_box = box * p_t[1:-1]
274
+
275
+ if not xstrikes_tm1 is None:
276
+ assert xstrikes_tm1[0] >= xstrikes_t[0] and xstrikes_tm1[-1] <= xstrikes_t[-1], f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: Expected 'xstrikes[{t-1}]' to cover 'xstrikes[{t}]', but found xstrikes[{t-1}][0]={xstrikes_tm1[0]:.4g} < xstrikes[{t}][0]={xstrikes_t[0]:.4g} or xstrikes[{t-1}][-1]={xstrikes_tm1[-1]} > xstrikes[{t}][-1]={xstrikes_t[-1]}"
277
+
278
+ C_t = np.maximum( _0, xstrikes_t[None,:] - xstrikes_t[1:-1,None] ) @ p_t
279
+ C_tm1 = np.maximum( _0, xstrikes_tm1[None,:] - xstrikes_t[:,None] ) @ p_tm1 if t>0 else np.maximum( _0, _1 - xstrikes_t )
280
+ assert abs( 1.-xstrikes_t[0] - C_tm1[0] ) < 1E-7, f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: Expected C_tm1[0] to be 1-xstrikes_t[0], but found {C_tm1[0]} instead of {1.-xstrikes_t[0]}"
281
+ assert abs( C_tm1[-1] ) < 1E-8, f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: Expected C_tm1[-1] to be 0, but found {C_tm1[-1]} instead of 0."
282
+ C_tm1[0] = 1.-xstrikes_t[0]
283
+ C_tm1[-1] = 0.
284
+ dC_t = C_t - C_tm1[1:-1]
285
+
286
+ assert np.all( np.isfinite(dC_t) ), f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: Expected dC_t to be finite, found min {np.min(dC_t)} and max {np.max(dC_t)}"
287
+ assert np.all( np.isfinite(p_box) ), f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: Expected p_box to be finite, found min {np.min(p_box)} and max {np.max(p_box)}"
288
+ assert np.min( dC_t ) > -self._eps_price*100., f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: Expected dC_t to be non-negative, found min {np.min(dC_t)} [tolerance 'prices' {self._eps_price*100.}]"
289
+ assert np.min( p_box ) > -self._eps_density*100., f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: Expected p_box to be non-negative, found min {np.min(p_box)} [tolerance 'densities' {self._eps_density*100.}]"
290
+
291
+ # DLVs are
292
+ #
293
+ # dC = DLV^2 * X * p
294
+ #
295
+ # dC should be zero if and only if p is zero.
296
+ # If that happens, the DLV value is undefined.
297
+ # Even though we have constrained the DLVs in the LP program we may end up with
298
+ # numerically differnet values. We allow those here.
299
+
300
+ p_or_dC_zero = ( dC_t <= 0. ) | ( p_box <= 0.)
301
+ too_small = dC_t <= min_dlvsq * p_box
302
+ too_big = (dC_t >= max_dlvsq * p_box) if max_dlvsq is not None else (too_small&False)
303
+
304
+ divisor = np.where( p_or_dC_zero|too_small|too_big, _1, p_box ) # dC_t can be positive while p_t is zero ... in this case we cannot determine a correct DLV - any will do.
305
+ dlvsqs_t = np.select( [p_or_dC_zero, too_small, too_big ], [0., min_dlvsq, max_dlvsq if not max_dlvsq is None else np.nan], default=(dC_t*1E6) / (divisor*1E6) )
306
+ if not np.all( np.isfinite(dlvsqs_t) ):
307
+ warnings.warn( f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: Expected dlvsqs_t to be finite, found min {np.min(dlvsqs_t)} and max {np.max(dlvsqs_t)} -- fixing it but it should not happen")
308
+ dlvsqs_t = np.where( np.isfinite(dlvsqs_t), dlvsqs_t, min_dlvsq )
309
+
310
+ if __debug__:
311
+ # check validity of the DLVsq calculation by reconstructing the density.
312
+ # here we are doing the test only on non-error identified strikes.
313
+ if np.any(~(too_small|too_big)):
314
+ dC_t_ = dlvsqs_t * p_box
315
+ errors = np.abs(dC_t_ - dC_t)[~(too_small|too_big)]
316
+ if not np.all( errors <= self._eps_price ):
317
+ msg = f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: Expected dC_t_ to match dC_t, found max absolute difference {np.max(errors)} for active strikes [tolerance 'prices' {self._eps_price}] -- this should not happen"
318
+ warnings.warn(msg)
319
+ for i in np.argsort(-errors)[:5]:
320
+ if errors[i] < self._eps_price:
321
+ break
322
+ strikes_t = xstrikes_t[1:-1]
323
+ warnings.warn( f" strike #{i} {strikes_t[~(too_small|too_big)][i]:.4g}: p_t={p_t[1:-1][~(too_small|too_big)][i]:.4g} C_t={C_t[~(too_small|too_big)][i]:.4g} C_tm1={C_tm1[1:-1][~(too_small|too_big)][i]:.4g} "+\
324
+ f"=> dC_t={dC_t[~(too_small|too_big)][i]:.4g} vs "+\
325
+ f"dlv={np.sqrt(dlvsqs_t[~(too_small|too_big)][i]):.4g} dC_t_={dC_t_[~(too_small|too_big)][i]:.4g} vs , abs error {errors[i]:.4g}; too_small={too_small[~(too_small|too_big)][i]}, too_big={too_big[~(too_small|too_big)][i]}" )
326
+ raise RuntimeError(msg)
327
+ del dC_t_
328
+
329
+ # check past call prices
330
+ # ----------------------
331
+ q_tm1 = np.diff( np.diff( C_tm1, prepend=1. ) / np.diff( xstrikes_t, prepend=0. ), append=0. )
332
+ C_tm1_ = np.maximum( _0, xstrikes_t[None,:] - xstrikes_t[1:-1,None] ) @ q_tm1
333
+ assert np.all( np.abs(C_tm1_ - C_tm1[1:-1]) <= self._eps_price ), f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: Expected C_tm1_ to match C_tm1[1:-1], found max absolute difference {np.max(np.abs(C_tm1_ - C_tm1[1:-1]))} [tolerance 'prices' {self._eps_price}]"
334
+ del C_tm1_
335
+
336
+ # full implicit solver
337
+ # compute interpolated density & check it
338
+ w = dlvsqs_t * box
339
+ w_plus = w / ( xstrikes_t[2:] - xstrikes_t[1:-1])
340
+ w_minus = w / ( xstrikes_t[1:-1] - xstrikes_t[:-2])
341
+ assert np.min( w_plus ) >= 0., f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed 'w_plus' must be non-negative, but found min {np.min(w_plus)}"
342
+ assert np.min( w_minus ) >= 0., f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed 'w_minus' must be non-negative, but found min {np.min(w_minus)}"
343
+ assert C_tm1.shape == xstrikes_t.shape, f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: expected C_tm1 and xstrikes_t to have the same shape, but found {C_tm1.shape} and {xstrikes_t.shape}"
344
+ assert w_plus.dtype == np.float64 and w_minus.dtype == np.float64 and q_tm1.dtype == np.float64, f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: expected 'w_plus', 'w_minus' and 'q_tm1' to have dtype 'float64', but found {w_plus.dtype}, {w_minus.dtype} and {q_tm1.dtype}"
345
+ q_t = solve_sanos_tridiagonal( w_minus=w_minus, w_plus=w_plus, rhs=q_tm1 )
346
+
347
+ assert np.all( q_t >= -self._eps_dlv_dens_pos ), f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed q_t must be non-negative, but found min {np.min(q_t)} [tolerance {self._eps_dlv_dens_pos:.4g}]"
348
+ assert np.abs( q_t.sum() - 1. ) < self._eps_dlv_dens_sum1, f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed q_t must sum to 1, but found sum {q_t.sum():.6f} [tolerance {self._eps_dlv_dens_sum1:.4g}]"
349
+ assert np.abs( xstrikes_t@q_t - 1. ) < self._eps_dlv_dens_int1, f"Expiry#{t} {expiry*DAYS_PER_YEAR:.1f}d: computed q_t must have expectation, but found xstrikes_t@q_t={xstrikes_t@q_t:.6f} instead of 1 [wh tolerance {self._eps_dlv_dens_int1:.4g}]"
350
+ if np.max( np.abs( q_t - p_t ) ) > self._eps_dlv_diff:
351
+ msg = f"Expiry#{t} {expiry*DAYS_PER_YEAR:.1f}d: computed q_t does not match p_t, found max absolute difference {np.max(np.abs(q_t - p_t))} [tolerance {self._eps_dlv_diff:.4g}] -- this should not happen"
352
+ warnings.warn(msg)
353
+ errors = np.abs( q_t - p_t )
354
+ for i in np.argsort(-errors)[:5]:
355
+ warnings.warn( f" strike {xstrikes_t[i]:.4g}: q_t={q_t[i]:.4g} vs p_t={p_t[i]:.4g}, abs error {errors[i]:.4g}" )
356
+ raise RuntimeError(msg)
357
+
358
+ if on_all_strikes: # makes dlvsq_t the same size as xstrikes_t
359
+ dlvsqs_t = np.concatenate( ([0.], dlvsqs_t, [0.]) )
360
+ dlvsqs.append( dlvsqs_t )
361
+
362
+ return dlvsqs
363
+
364
+ def densities_from_dlvsqs( self, dlvsqs: list[np.ndarray] ) -> list[np.ndarray]:
365
+ """
366
+ Compute densities from discrete local volatilities.
367
+
368
+ This is the inverse operation to :func:`dlvsqs`, and will return the original densities if the input ``dlvsqs`` are the same as those computed by :func:`dlvsqs` (up to numerical precision).
369
+ """
370
+ T = len(self.expiries)
371
+ assert len(dlvsqs) == T, f"Expected 'dlvsqs' to have length {T}, but found {len(dlvsqs)}"
372
+ xdensities = []
373
+ q_t = np.ones((1,), dtype=np.float64 )
374
+ xstrikes_tm1 = np.ones((1,), dtype=np.float64 )
375
+ for t, expiry in enumerate(self.expiries):
376
+ xstrikes_t = self.xstrikes[t].astype(np.float64,copy=False)
377
+ dlvsq_t = dlvsqs[t].astype(np.float64,copy=False)
378
+ Nx = len(xstrikes_t)
379
+
380
+ if dlvsq_t.shape == (Nx,):
381
+ verify_inp( dlvsq_t[0] == 0. and dlvsq_t[-1] == 0., lambda : f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: if 'dlvsqs[{t}]' has full length {Nx} matching ``xstrikes`` it must have zeros at the boundaries. Found boundary values {dlvsq_t[0]:.4g} and {dlvsq_t[-1]:.4g}" )
382
+ dlvsq_t = dlvsq_t[1:-1]
383
+ else:
384
+ verify_inp( dlvsq_t.shape == (Nx-2,), lambda : f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: if 'dlvsqs[{t}]' has length {Nx-2} it must match the inner strikes of 'xstrikes[{t}]'. Found shape {dlvsq_t.shape} instead of {(Nx-2,)}" )
385
+ verify_inp( np.all(dlvsq_t >= 0.), lambda : f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: 'dlvsqs[{t}]' must be non-negative, but found min {np.min(dlvsq_t)}" )
386
+
387
+ C_prev = np.maximum( 0., xstrikes_tm1[None,:] - xstrikes_t[:,None] ) @ q_t
388
+ C_prev[0] = 1.-xstrikes_t[0]
389
+ C_prev[-1] = 0.
390
+ q_t = np.diff( np.diff( C_prev, prepend=1. ) / np.diff( xstrikes_t, prepend=0. ), append=0. )
391
+ del C_prev
392
+
393
+ assert np.all( q_t >= -1E-5 ), f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed q_t must be non-negative, but found min {np.min(q_t)}"
394
+ assert np.abs( q_t.sum() - 1. ) < 1E-5, f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed q_t must sum to 1, but found sum {q_t.sum():.6f}"
395
+ assert np.abs( xstrikes_t@q_t - 1. ) < 1E-5, f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed q_t must have expectation, but found xstrikes_t@q_t={xstrikes_t@q_t:.6f} instead of 1"
396
+
397
+ dt = ( self.expiries[t] - ( self.expiries[t-1] if t>0 else 0. ) ).astype(np.float64,copy=False)
398
+ wup = dlvsq_t * xstrikes_t[1:-1]**2 * dt / ( ( xstrikes_t[2:] - xstrikes_t[1:-1]) * ( xstrikes_t[2:] - xstrikes_t[:-2]) )
399
+ wdn = dlvsq_t * xstrikes_t[1:-1]**2 * dt / ( ( xstrikes_t[1:-1] - xstrikes_t[:-2]) * ( xstrikes_t[2:] - xstrikes_t[:-2]) )
400
+ assert np.min( wup ) >= -1E-5, f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed 'wup' must be non-negative, but found min {np.min(wup)}"
401
+ assert np.min( wdn ) >= -1E-5, f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed 'wdn' must be non-negative, but found min {np.min(wdn)}"
402
+
403
+ q_t = solve_sanos_tridiagonal( w_minus=wdn, w_plus=wup, rhs=q_t )
404
+ assert np.all( q_t >= -self._eps_dlv_dens_pos ), f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed q_t must be non-negative, but found min {np.min(q_t)} [tolerance 'dlv_dens_pos' {self._eps_dlv_dens_pos:.4g}]"
405
+ assert np.abs( q_t.sum() - 1. ) < self._eps_dlv_dens_sum1, f"Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: computed q_t must sum to 1, but found sum {q_t.sum():.6f} [tolerance 'dlv_dens_sum1' {self._eps_dlv_dens_sum1:.4g}]"
406
+ assert np.abs( xstrikes_t@q_t - 1. ) < self._eps_dlv_dens_int1, f"Expiry#{t} {expiry*DAYS_PER_YEAR:.1f}d: computed q_t must have expectation, but found xstrikes_t@q_t={xstrikes_t@q_t:.6f} instead of 1 [tolerance 'dlv_dens_int1' {self._eps_dlv_dens_int1:.4g}]"
407
+
408
+ xdensities.append( q_t )
409
+ xstrikes_tm1 = xstrikes_t
410
+ return xdensities
411
+
412
+ @dataclass(frozen=True)
413
+ class SanosLPSolver:
414
+ timeout_seconds : float = 60*5. # timeout in seconds
415
+ algorithm : Literal["simplex", "ipm", "clarabel"] = "simplex"
416
+ no_fallback : bool = False # do not try the fallback solver if this one fails
417
+ _debug_verbose_cvxpy : set[str] | bool | None = None # Turn 'verbose' on for cvxpy, optionally scoped by solver mode
418
+
419
+ def __post_init__(self) -> None:
420
+ verify_inp(
421
+ self.algorithm in {"simplex", "ipm", "clarabel"},
422
+ lambda: f"Unsupported solver algorithm {self.algorithm!r}",
423
+ )
424
+
425
+ def __call__(self,
426
+ objective: cp.Expression,
427
+ constraints: list[cp.Constraint],
428
+ variables: list[tuple[cp.Variable, np.ndarray]],*,
429
+ message_context : callable|str|None = None,
430
+ for_expiry: bool = False,
431
+ is_fallback : bool = False,
432
+ verbose : Context = Context.quiet ) -> tuple[bool, str, bool]:
433
+ """
434
+ Solve a problem with fall back.
435
+
436
+ Returns ``(success, status_str, is_fallback)`` where ``success`` is a
437
+ boolean indicating whether the problem was solved successfully,
438
+ ``status_str`` is the status string returned by the solver, and
439
+ ``is_fallback`` is a boolean indicating whether the fallback solver was used.
440
+ """
441
+
442
+ def message():
443
+ if message_context is None:
444
+ return ""
445
+ if callable(message_context):
446
+ msg = message_context()
447
+ else:
448
+ msg = str(message_context)
449
+ return (msg + ": ") if msg != "" else ""
450
+
451
+ # Preserve the primary solver's final iterate when the fallback is
452
+ # entered after a limit or solver failure.
453
+ if not is_fallback:
454
+ for v, val in variables:
455
+ if not val is None:
456
+ assert v.shape == val.shape, f"Internal error: variable shape {v.shape} does not match provided value shape {val.shape}"
457
+ v.value = val
458
+ else:
459
+ v.value = np.zeros(v.shape, dtype=np.float64)
460
+
461
+ with warnings.catch_warnings():
462
+ warnings.filterwarnings("ignore",message=r"Solution may be inaccurate.*",category=UserWarning)
463
+ warnings.filterwarnings("error",message=r"overflow encountered in power",category=RuntimeWarning)
464
+ warnings.filterwarnings("error",message=r"invalid value encountered in matmul",category=RuntimeWarning)
465
+ try:
466
+ prob = cp.Problem( cp.Minimize( objective ), constraints )
467
+ slv, opt = self._lp_solver_settings( for_expiry=for_expiry, is_fallback=is_fallback )
468
+ prob.solve( solver=slv, **opt )
469
+ prob_status = str(prob.status)
470
+ except SolverError as e:
471
+ prob_status = "solver_error"
472
+ # CVXPY discards Clarabel's primal on NumericalError. Recover
473
+ # only the current solver's iterate, never the initial guess.
474
+ if slv == "CLARABEL" and "CLARABEL" in prob._solver_cache:
475
+ native = prob._solver_cache["CLARABEL"].get_solution()
476
+ prob_status = str(native.status)
477
+ if native.x is not None and np.all(np.isfinite(native.x)):
478
+ _, chain, inverse = prob.get_problem_data(slv)
479
+ solution = Solution(cp.USER_LIMIT, native.obj_val + inverse[-1][cps.OFFSET],
480
+ {inverse[-1][chain.reductions[-1].VAR_ID]: np.asarray(native.x)}, {}, {})
481
+ for reduction, inv in reversed(list(zip(chain.reductions[:-1], inverse[:-1]))):
482
+ if isinstance(reduction, CvxAttr2Constr) and inv:
483
+ # CVXPY normally clips bounds here, hiding violations.
484
+ new, old, _ = inv
485
+ solution.primal_vars = {key: recover_value_for_leaf(var, solution.primal_vars[new[key].id], project=False)
486
+ for key, var in old.items()}
487
+ else:
488
+ solution = reduction.invert(solution, inv)
489
+ for v in prob.variables():
490
+ v.save_value(solution.primal_vars[v.id])
491
+ prob._value = objective.value
492
+ else:
493
+ for v in prob.variables():
494
+ v.save_value(None)
495
+ else:
496
+ for v in prob.variables():
497
+ v.save_value(None)
498
+ warnings.warn(f"{message()}Solver stopped with {prob_status}: {e}. Checking its final iterate.")
499
+ except RuntimeWarning as e:
500
+ prob_status = f"overflow error ({str(e.__class__.__name__)})"
501
+ except Exception as e:
502
+ if not is_fallback:
503
+ msg = str(e)
504
+ if 'Cannot unpack invalid solution' in msg:
505
+ return self( objective=objective, constraints=constraints, variables=variables, message_context=message_context, for_expiry=for_expiry, is_fallback=True, verbose=verbose )
506
+ raise type(e)(f"{message()}Unexpected error: {str(e)}.") from e
507
+
508
+ # Numerical termination does not imply mathematical infeasibility.
509
+ # Check the original constraints and bounds; fit quality is downstream.
510
+ if prob.value is not None and np.isfinite(prob.value):
511
+ if all(v.value is not None and np.all(np.isfinite(v.value)) for v in prob.variables()):
512
+ violations = [np.max(np.abs(v.value - v.project(v.value))) for v in prob.variables()]
513
+ violations += [np.max(c.violation()) for c in constraints]
514
+ for tolerance in (1E-7, 1E-5):
515
+ if np.all(np.isfinite(violations)) and max(violations, default=0.) <= tolerance:
516
+ if prob_status not in ("optimal", "optimal_inaccurate") or tolerance > 1E-7:
517
+ warnings.warn(f"{message()}Solver status {prob_status}; accepting feasible iterate (max violation {max(violations, default=0.):.3g}, tolerance {tolerance:g}). Fit quality checked downstream.")
518
+ return True, prob_status, is_fallback
519
+
520
+ if (
521
+ prob_status not in ("infeasible", "infeasible_inaccurate")
522
+ and not is_fallback
523
+ and self.algorithm != "clarabel"
524
+ and not self.no_fallback
525
+ ):
526
+ warnings.warn(
527
+ f"{message()}Primary solver returned {prob_status} without a verified feasible iterate. "
528
+ "Attempting to solve with fallback solver."
529
+ )
530
+ return self(
531
+ objective=objective,
532
+ constraints=constraints,
533
+ variables=variables,
534
+ message_context=message_context,
535
+ for_expiry=for_expiry,
536
+ is_fallback=True,
537
+ verbose=verbose,
538
+ )
539
+ if prob_status not in ("infeasible", "infeasible_inaccurate"):
540
+ warnings.warn(f"{message()}Numerical solve unresolved ({prob_status}); no verified feasible iterate. This is not proof of mathematical infeasibility.")
541
+ return False, prob_status, is_fallback
542
+
543
+ def _lp_solver_settings( self, *, for_expiry : bool, is_fallback : bool ) -> tuple[str, dict]:
544
+ """ Return lp solver settings """
545
+ if isinstance(self._debug_verbose_cvxpy, bool):
546
+ verbose = self._debug_verbose_cvxpy
547
+ elif self._debug_verbose_cvxpy is None:
548
+ verbose = False
549
+ else:
550
+ verbose = ('expiry' if for_expiry else 'surface') in self._debug_verbose_cvxpy
551
+
552
+ if not is_fallback and self.algorithm != "clarabel":
553
+ highs_options = {
554
+ "solver": self.algorithm,
555
+ "presolve": "on",
556
+ "threads": 0,
557
+ "kkt_tolerance": 1e-7,
558
+ "time_limit": self.timeout_seconds,
559
+ }
560
+ if self.algorithm == "simplex":
561
+ # Preserve SANOS's established serial dual-simplex default.
562
+ highs_options["simplex_strategy"] = 1
563
+ solver = "HIGHS"
564
+ options = dict( warm_start=True,
565
+ highs_options=highs_options,
566
+ verbose=verbose
567
+ )
568
+ else:
569
+ solver = "CLARABEL"
570
+ options = dict(
571
+ warm_start=True,
572
+ time_limit=self.timeout_seconds,
573
+ tol_gap_abs=1e-5,
574
+ tol_gap_rel=1e-5,
575
+ tol_feas=1e-6,
576
+ tol_infeas_abs=1e-7,
577
+ tol_infeas_rel=1e-7,
578
+ reduced_tol_gap_abs=5e-5,
579
+ reduced_tol_gap_rel=5e-5,
580
+ reduced_tol_feas=5e-5,
581
+ max_threads=0,
582
+ presolve_enable=True,
583
+ equilibrate_enable=True,
584
+ verbose=verbose
585
+ )
586
+ return solver, options
587
+
588
+ # --------------------------------
589
+ # Density repair by ChatGPT
590
+ # --------------------------------
591
+
592
+ def _project_simplex(v: np.ndarray, total: float) -> np.ndarray:
593
+ """
594
+ Euclidean projection of v onto { y >= 0, sum(y) = total }.
595
+ """
596
+ verify_inp(total > 0.0, "total must be positive; got %s", total)
597
+
598
+ u = np.sort(v)[::-1]
599
+ cssv = np.cumsum(u, dtype=np.float64) - total
600
+ js = np.arange(1, v.size + 1, dtype=np.float64)
601
+
602
+ ok = u - cssv / js > 0.0
603
+ verify_inp(np.any(ok), "simplex projection failed")
604
+
605
+ rho = np.flatnonzero(ok)[-1]
606
+ theta = cssv[rho] / float(rho + 1)
607
+
608
+ return np.maximum(v - theta, 0.0)
609
+
610
+ def repair_density_nonnegative(
611
+ p: np.ndarray,
612
+ x: np.ndarray,
613
+ *,
614
+ target_sum: float = 1.0,
615
+ target_xmoment: float = 1.0,
616
+ floor: float = 0.0,
617
+ tol: float | None = None,
618
+ max_iter: int = 64,
619
+ ) -> np.ndarray:
620
+ """
621
+ Project p onto:
622
+
623
+ y >= floor
624
+ sum(y) = target_sum
625
+ x @ y = target_xmoment
626
+
627
+ For floor=0 this gives a nonnegative density.
628
+
629
+ This is the L2-closest feasible y to p.
630
+ """
631
+
632
+ p = np.asarray(p, dtype=np.float64)
633
+ x = np.asarray(x, dtype=np.float64)
634
+
635
+ verify_inp(p.ndim == 1, "p must be 1D; got shape %s", p.shape)
636
+ verify_inp(x.ndim == 1, "x must be 1D; got shape %s", x.shape)
637
+ verify_inp(p.shape == x.shape, "p and x must have same shape; got %s and %s", p.shape, x.shape)
638
+ verify_inp(np.all(np.isfinite(p)), "p must be finite")
639
+ verify_inp(np.all(np.isfinite(x)), "x must be finite")
640
+ verify_inp(target_sum > 0.0, "target_sum must be positive; got %s", target_sum)
641
+ verify_inp(floor >= 0.0, "floor must be nonnegative; got %s", floor)
642
+
643
+ n = p.size
644
+
645
+ # Transform y >= floor into r >= 0 with y = floor + r.
646
+ residual_sum = target_sum - n * floor
647
+ residual_xmoment = target_xmoment - floor * float(np.sum(x, dtype=np.float64))
648
+
649
+ verify_inp( residual_sum > 0.0, lambda : f"floor too large: target_sum - n*floor = {residual_sum}" )
650
+
651
+ q = p - floor
652
+ target_mean = residual_xmoment / residual_sum
653
+
654
+ xmin = float(np.min(x))
655
+ xmax = float(np.max(x))
656
+
657
+ verify( xmin <= target_mean <= xmax, lambda : f"no nonnegative solution: target mean {target_mean} is outside [{xmin}, {xmax}]" )
658
+
659
+ if tol is None:
660
+ tol = (
661
+ 256.0
662
+ * np.finfo(np.float64).eps
663
+ * max(1.0, residual_sum)
664
+ * max(1.0, float(np.max(np.abs(x))))
665
+ * max(1.0, np.sqrt(float(n)))
666
+ )
667
+
668
+ z = x - target_mean
669
+
670
+ def eval_beta(beta: float):
671
+ # For fixed beta, project q - beta*z onto the simplex.
672
+ r = _project_simplex(q - beta * z, residual_sum)
673
+
674
+ # Need z @ r == 0, equivalent to x @ r == residual_xmoment.
675
+ h = float(z @ r)
676
+
677
+ active = r > 0.0
678
+ za = z[active]
679
+
680
+ # derivative dh/dbeta on the current active set
681
+ if za.size >= 2:
682
+ dz = za - za.mean(dtype=np.float64)
683
+ dh = -float(dz @ dz)
684
+ else:
685
+ dh = 0.0
686
+
687
+ return r, h, dh
688
+
689
+ # Initial point.
690
+ r, h, dh = eval_beta(0.0)
691
+
692
+ if abs(h) <= tol:
693
+ return floor + r
694
+
695
+ # h(beta) is monotone decreasing.
696
+ if h > 0.0:
697
+ lo = 0.0
698
+ hi = 1.0
699
+
700
+ _, h_hi, _ = eval_beta(hi)
701
+ while h_hi > 0.0:
702
+ hi *= 2.0
703
+ verify(hi < 1e16, lambda : f"failed to bracket beta: hi = {hi}")
704
+ _, h_hi, _ = eval_beta(hi)
705
+
706
+ else:
707
+ hi = 0.0
708
+ lo = -1.0
709
+
710
+ _, h_lo, _ = eval_beta(lo)
711
+ while h_lo < 0.0:
712
+ lo *= 2.0
713
+ verify(abs(lo) < 1e16, lambda : f"failed to bracket beta: lo = {lo}")
714
+ _, h_lo, _ = eval_beta(lo)
715
+
716
+ beta = 0.5 * (lo + hi)
717
+
718
+ for _ in range(max_iter):
719
+ r, h, dh = eval_beta(beta)
720
+
721
+ if abs(h) <= tol:
722
+ y = floor + r
723
+ return y
724
+
725
+ if h > 0.0:
726
+ lo = beta
727
+ else:
728
+ hi = beta
729
+
730
+ # Bracketed Newton step.
731
+ if dh < 0.0:
732
+ beta_new = beta - h / dh
733
+ else:
734
+ beta_new = 0.5 * (lo + hi)
735
+
736
+ if not (lo < beta_new < hi):
737
+ beta_new = 0.5 * (lo + hi)
738
+
739
+ beta = beta_new
740
+
741
+ r, h, _ = eval_beta(beta)
742
+
743
+ verify( abs(h) <= 10.0 * tol, lambda : f"projection did not converge; residual moment error is {h}" )
744
+ return floor + r
745
+
746
+
747
+ def warn_and_fix_density( x, p, eps, message : callable ):
748
+ """ Wrapper around fixing and warning """
749
+
750
+ p = np.asarray(p, dtype=np.float64)
751
+ x = np.asarray(x, dtype=np.float64)
752
+
753
+ assert np.min(p) > -1E-3, f"{message()}: density has minimum {np.min(p):.6g} < -1E-3, which is too negative to be repaired."
754
+ assert abs(np.sum(p)-1.) < 1E-2, f"{message()}: density sums to {np.sum(p):.6g}, which is too close to zero to be repaired."
755
+ assert abs(p@x-1.) < 1E-2, f"{message()}: density integrates to {p@x:.6g}, which is too close to zero to be repaired."
756
+
757
+ if not np.all( p >= -eps ) or abs(np.sum(p)-1.) > eps or abs(p@x-1.) > eps:
758
+ p = repair_density_nonnegative(p=p, x=x)
759
+
760
+ assert np.all( p >= -eps ), f"{message()}: negative density {np.min(p):.6g} found after repair."
761
+ assert abs(np.sum(p)-1.) <= eps, f"{message()}: density sums to {np.sum(p):.6g} after repair."
762
+ assert abs(p@x-1.) <= eps, f"{message()}: density sums to {p@x:.6g} after repair."
763
+ return p
764
+
765
+ def _compute_market_fit( pricer : callable, min_half_spread : float,
766
+ expiries : np.ndarray,
767
+ strikes : list[np.ndarray]|np.ndarray,
768
+ bids : list[np.ndarray]|np.ndarray,
769
+ asks : list[np.ndarray]|np.ndarray, *,
770
+ masks : list[np.ndarray]|np.ndarray|None = None,
771
+ and_vols : bool = True,
772
+ ) -> PrettyObject:
773
+ """
774
+ Compute standardized fitting error stats
775
+
776
+ Returns
777
+ -------
778
+ Errors : :class:`PrettyObject`
779
+ A dictionary-like object with the following fields:
780
+ * ``fits``: list of fitted prices for the input strikes, per expiry.
781
+ * ``fit_errs``: list of fitting errors for the input strikes, per expiry: the distance outside bid/ask in half spreads, ``( max( 0, fit - ask ) + max( 0, bid - fit ) ) / max( 0.5*(ask-bid), min_half_spread )``. For array input the field is ``fit_err``.
782
+ * ``fit_vols``: list of fitted vols for the input strikes, per expiry, if ``and_vols`` is ``True``.
783
+ * ``pcnt_fit``: despite its name, the fraction (between 0 and 1) of strikes whose fit is outside the actual bid/ask spread, ``sum( fit_errs > 0 ) / len(fit_errs)``.
784
+ * ``median_err``: the median fitting error among strikes for which the fit is outside the bid/ask spread, i.e. ``median( fit_errs[fit_errs>0.] )``.
785
+ * ``mean_err``: the mean fitting error among strikes for which the fit is outside the bid/ask spread, i.e. ``mean( fit_errs[fit_errs>0.] )``.
786
+ * ``median_total_err``: the median fitting error among all strikes, i.e. ``median( fit_errs )``.
787
+ * ``mean_total_err``: the mean fitting error among all strikes, i.e. ``mean( fit_errs )``.
788
+ """
789
+ r = PrettyObject()
790
+
791
+ if isinstance( strikes, np.ndarray ):
792
+ # vector version
793
+
794
+ verify_inp( isinstance( bids, np.ndarray ) and isinstance( asks, np.ndarray ), lambda : f"If 'strikes' is a numpy array, then 'bids' and 'asks' must also be numpy arrays. Found types {type(strikes)}, {type(bids)} and {type(asks)}" )
795
+ verify_inp( isinstance( masks, np.ndarray ) or masks is None, lambda : f"If 'strikes' is a numpy array, then 'masks' must also be a numpy array or None. Found type {type(masks)}" )
796
+ verify_inp( expiries.shape == strikes.shape == bids.shape == asks.shape, lambda : f"If 'strikes', 'bids' and 'asks' are numpy arrays, then they must have the same shape as 'expiries'. Found expiries shape {expiries.shape} and strikes, bids and asks shapes {strikes.shape}, {bids.shape} and {asks.shape}" )
797
+ verify_inp( masks is None or masks.shape == strikes.shape, lambda : f"If 'masks' is a numpy array, then it must have the same shape as 'strikes'. Found masks shape {masks.shape} and strikes shape {strikes.shape}" )
798
+
799
+ if and_vols:
800
+ r.fits,\
801
+ r.fit_vols = pricer( expiries[masks] if not masks is None else expiries, strikes[masks] if not masks is None else strikes, and_vols=True )
802
+ else:
803
+ r.fits = pricer( expiries[masks] if not masks is None else expiries, strikes[masks] if not masks is None else strikes, and_vols=False )
804
+
805
+ if not masks is None:
806
+ asks = asks[masks]
807
+ bids = bids[masks]
808
+
809
+ half_spread = 0.5*(asks - bids)
810
+ verify_inp( np.min( half_spread ) > 0, lambda : f"Expected all bid/ask spreads to be positive, but found minimum half spread {half_spread.min():.4g}" )
811
+ half_spread = np.maximum( half_spread, min_half_spread )
812
+ r.fit_err = (np.maximum( 0., r.fits - asks ) + np.maximum(0., bids - r.fits) ) / half_spread
813
+ bad_fit_mask = r.fit_err > 0. # outside the actual bid/ask, as in the list version below
814
+ r.pcnt_fit = float(np.sum(bad_fit_mask)) / float(len(bad_fit_mask))
815
+ r.mean_err = np.mean(r.fit_err[bad_fit_mask] ) if np.any(bad_fit_mask) else 0.
816
+ r.median_total_err = np.median(r.fit_err)
817
+ r.mean_total_err = np.mean(r.fit_err)
818
+ r.median_err = float(np.median(r.fit_err[bad_fit_mask])) if np.any(bad_fit_mask) else 0.
819
+
820
+ if not masks is None:
821
+ x = np.zeros_like(strikes)
822
+ x[masks] = r.fits
823
+ r.fits = x
824
+ if and_vols:
825
+ x = np.zeros_like(strikes)
826
+ x[masks] = r.fit_vols
827
+ r.fit_vols = x
828
+ x = np.zeros_like(strikes)
829
+ x[masks] = r.fit_err
830
+ r.fit_err = x
831
+ del x
832
+
833
+ return r
834
+
835
+ # block version
836
+ # -------------
837
+
838
+ verify_inp( len(expiries) == len(strikes) == len(bids) == len(asks), lambda : f"Expected 'expiries', 'strikes', 'bids' and 'asks' to have the same length, but found {len(expiries)}, {len(strikes)}, {len(bids)} and {len(asks)}" )
839
+
840
+ r.fits = []
841
+ r.fit_errs = []
842
+
843
+ if and_vols:
844
+ r.fit_vols = []
845
+
846
+ masked_fit_errors = []
847
+
848
+ for t, expiry in enumerate(expiries):
849
+ masks_t = masks[t] if not masks is None else None
850
+ strikes_t = strikes[t][masks_t if not masks is None else slice(None)]
851
+ bids_t = bids[t][masks_t if not masks is None else slice(None)]
852
+ asks_t = asks[t][masks_t if not masks is None else slice(None)]
853
+
854
+ verify_inp( strikes_t.shape == bids_t.shape == asks_t.shape, lambda : f"Expected 'strikes[{t}]', 'bids[{t}]' and 'asks[{t}]' to have the same shapefor expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d, but found {strikes_t.shape}, {bids_t.shape} and {asks_t.shape}" )
855
+
856
+ if and_vols:
857
+ f,v = pricer( expiry, strikes_t, and_vols=True )
858
+ else:
859
+ f = pricer( expiry, strikes_t, and_vols=False )
860
+ v = None
861
+
862
+ half_spreads = 0.5*(asks_t - bids_t)
863
+ verify_inp( np.min( half_spreads ) > 0, lambda : f"Expected all bid/ask spreads to be positive for expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d but found minimum half spread {half_spreads.min():.4g} for expiry {expiry:.4g}" )
864
+ half_spreads = np.maximum( half_spreads, min_half_spread )
865
+ fit_err = (np.maximum( 0., f - asks_t ) + np.maximum(0., bids_t - f) ) / half_spreads
866
+ masked_fit_errors.append(fit_err)
867
+
868
+ if not masks_t is None:
869
+ x = np.zeros_like(strikes[t])
870
+ x[masks_t] = fit_err
871
+ fit_err = x
872
+ x = np.zeros_like(strikes[t])
873
+ x[masks_t] = f
874
+ f = x
875
+ if not v is None:
876
+ x = np.zeros_like(strikes[t])
877
+ x[masks_t] = v
878
+ v = x
879
+ r.fits.append(f)
880
+ r.fit_errs.append(fit_err)
881
+ if not v is None:
882
+ r.fit_vols.append(v)
883
+
884
+ masked_fit_errors = np.concatenate(masked_fit_errors)
885
+ r.pcnt_fit = float(np.sum(masked_fit_errors > 0.)) / float(len(masked_fit_errors))
886
+ r.median_err = np.median(masked_fit_errors[masked_fit_errors>0.] ) if np.any(masked_fit_errors>0.) else 0.
887
+ r.mean_err = np.mean(masked_fit_errors[masked_fit_errors>0.] ) if np.any(masked_fit_errors>0.) else 0.
888
+ r.median_total_err = np.median(masked_fit_errors)
889
+ r.mean_total_err = np.mean(masked_fit_errors)
890
+ return r
891
+
892
+
893
+
894
+
895
+ def make_variances(expiries : np.ndarray,
896
+ strikes : list[np.ndarray],
897
+ prices : list[np.ndarray],
898
+ vols : float|np.ndarray|None=None,
899
+ message_context : callable[[], str] | None = None ) -> np.ndarray:
900
+ """
901
+ Make variances for interpolation
902
+
903
+ If 'vols' is provided, this function checks that variances are increassing.
904
+ If 'vols' are not provided, this function computes ATM vols by interpolating the input 'prices' at strike 1, and then computes variances from the ATM vols, and finally makes sure that variances are increasing by flooring forward variances to a small positive value if needed.
905
+
906
+ Returns an array of variances, for ``expiries``.
907
+ """
908
+
909
+ def message(with_cols : bool = True) -> str:
910
+ if message_context is None:
911
+ return ""
912
+ if callable(message_context):
913
+ msg = message_context()
914
+ else:
915
+ msg = str(message_context)
916
+ if msg == "":
917
+ return ""
918
+ msg = msg[0].upper() + msg[1:]
919
+ if not with_cols:
920
+ return msg
921
+ return msg + ": "
922
+
923
+ T = len(expiries)
924
+ assert len(strikes) == len(prices) == T, f"Expected 'strikes' and 'prices' to have the same length as 'expiries', but found {len(strikes)}, {len(prices)} and {len(expiries)}"
925
+
926
+ if vols is None:
927
+ atm_calls = []
928
+ for t in range(T):
929
+ ixs = np.argsort( strikes[t] )
930
+ atm_calls.append( np.interp( 1., strikes[t][ixs], prices[t][ixs] ) )
931
+ atm_calls = np.asarray(atm_calls)
932
+ atm_vols = bs.implied( k=np.ones_like(atm_calls), prices=atm_calls, sqrtT=np.sqrt(expiries), eps=1E-6 )
933
+ variances = expiries * (atm_vols**2)
934
+ dts = np.diff(expiries, prepend=0.)
935
+ fwd_vars = np.maximum(0.001**2, np.diff(variances, prepend=0.) / dts ) * dts
936
+ variances = np.cumsum(fwd_vars)
937
+ del atm_calls, atm_vols, dts, fwd_vars
938
+ elif isinstance( vols, np.ndarray ):
939
+ verify_inp( vols.shape == expiries.shape, lambda : f"{message()}If 'vols' is a numpy array, it must have the same shape as 'expiries', but found {vols.shape} and {expiries.shape}" )
940
+ verify_inp( np.all(vols > 0.), lambda : f"{message()}All volatilities must be positive, but found {vols}" )
941
+ variances = expiries * (vols**2)
942
+ verify_inp( variances[0] > 0. and (len(variances)==1 or np.min(np.diff(variances)) > 0.), lambda : f"{message()}Variances derived from 'vols' must be positive and strictly increasing, but found {variances}" )
943
+ else:
944
+ variances = expiries * (float(vols)**2)
945
+ verify_inp(vols > 0., lambda : f"{message()}Volatility must be positive, but found {vols}" )
946
+ return variances
947
+
948
+
949
+ if __name__ == "__main__":
950
+ from openqdata.cli import run_module
951
+
952
+ run_module(globals())
953
+
954
+
955
+ # CVXPY shape inference must not sum uninitialized arrays.
956
+ from openqdata.utils.cvxpy import patch_cvxpy_sum_shape_from_args
957
+
958
+ patch_cvxpy_sum_shape_from_args()