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,1494 @@
1
+ """
2
+ Arbitrage-free fits of option markets
3
+ =====================================
4
+
5
+ :class:`MkArbFree` fits arbitrage-free call prices to bid/ask quotes. It has two modes:
6
+
7
+ * ``expiry``: fits each expiry on its own. Strikes which cannot be fitted within bid/ask are masked, and an
8
+ expiry is dropped if fewer than half of its strikes can be fitted.
9
+
10
+ * ``surface`` (the default): after the per-expiry step, fits one surface without calendar or strike arbitrage
11
+ across all expiries. With ``smoothness=None`` the surface is linear between strikes; with ``smoothness > 0``
12
+ it is a SANOS surface. For the linear surface a fit within bid/ask exists, up to numerical precision,
13
+ if and only if the quotes are free of arbitrage.
14
+
15
+ :meth:`MkArbFree.__call__` returns an :class:`ArbFreePricer`, which holds the fit and prices arbitrary strikes
16
+ and expiries.
17
+
18
+ The surface fit minimizes ``(1-w) * sum_i e_i + w * sum_i |fit_i - mid_i| / h_i`` over all quotes ``i``, with
19
+ ``w = mid_fit_weight``. ``e_i`` is the distance of quote ``i`` outside bid/ask divided by ``h_i``, the half spread
20
+ floored at ``min_half_spread``.
21
+
22
+ **Method.** ``mid_fit_weight`` selects the program: ``w = 1`` is a pure fit to the mids, which has fewer variables and is
23
+ the fastest; a small ``w`` fits to the bid/ask. **Reweighting.** With ``reweight_max_iter > 1`` the surface fit is repeated
24
+ with each quote weighted by ``1/(excess + 0.1)``, the excess taken from the previous fit in half spreads, until
25
+ ``reweight_min_within`` of the quotes are within bid/ask, the gain of a fit falls below 0.25 points, or the maximum number of
26
+ fits is reached. The weights multiply the distance outside bid/ask or, for ``w = 1``, the distance from the mid. The fit with
27
+ the highest share within bid/ask is kept. Reweighting raises that share and worsens the fit of the quotes which stay outside.
28
+
29
+ Two internal margins, both fractions of the half spread, tighten the bid/ask: ``_eps_no_arb`` (0.01) is where the
30
+ slack ``e_i`` starts counting, so that a fit which can be inside bid/ask is strictly inside; ``_eps_hard_fit`` (1e-5)
31
+ is the margin of the hard per-expiry fit, which decides which strikes are masked, and only guards numerical precision.
32
+
33
+ *Developer note:* a difficult day for testing, probably with wrong data, is ``SPX 2005-11-21``.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import math
39
+ import warnings as warnings
40
+ from dataclasses import asdict, dataclass
41
+
42
+ import cvxpy as cp
43
+ import numpy as np
44
+ from cdxcore.bs import bs
45
+ from cdxcore.err import verify_inp
46
+ from cdxcore.pretty import PrettyObject
47
+ from cdxcore.verbose import Context
48
+ from cdxcore.version import version
49
+
50
+ from openqdata.arbfree import IMPOSE_FLOOR_ON_DENSITY
51
+ from openqdata.arbfree.sanos_tools import (
52
+ SanosLPSolver,
53
+ _compute_market_fit,
54
+ warn_and_fix_density,
55
+ )
56
+ from openqdata.biz_calendar import DAYS_PER_YEAR, ONE_MINUTE
57
+
58
+ #: If a surface solver stops early with fewer than this share of quotes within bid/ask, the other solver is run.
59
+ EARLY_STOP_MIN_WITHIN = 0.9
60
+
61
+
62
+ @version("0.81")
63
+ class ArbFreePricer(PrettyObject):
64
+ """
65
+ Arbitrage-Free Option pricer based on DLV/SANOS.
66
+
67
+ This class contains the result of :meth:`MkArbFree.__call__`.
68
+ This function call may drop expiries if they have arbitrage which cannot be resolved.
69
+ To map the expiries stored in this class back to the input expiries, use the ``input_index`` field.
70
+
71
+ The class attributes are:
72
+
73
+ * ``expiries``: array ``(T,)`` of expiries used. This may be fewer expiries than provided as input.
74
+
75
+ * ``input_index``: array of size ``(T,)`` which maps each returned expiry to the index of the input expiry it corresponds to. In other words ``output_expiries == [ input_expiries[j] for j in input_index ]``.
76
+
77
+ * ``masks``: a list of ``T`` boolean masks by expiry indicating which strikes were considered during the no-arb fit.
78
+ The mask for expiry ``j`` has the same length ``Nj`` as the ``strikes[ input_expiries[j] ]``.
79
+
80
+ The mask is False for boundary strikes which were trimmed when extending the strike range, and for strikes which the per-expiry fit could not fit within bid/ask.
81
+ The fit penalizes ``max( 0, fit[mask] - ask[mask] ) + max( 0, bid[mask] - fit[mask] )`` in half spreads; see the module documentation for the objective.
82
+
83
+ * ``strikes``: a copy of the ``T`` input strike arrays for the expiries used.
84
+
85
+ * ``bids``: a copy of the ``T`` arrays of input bids for the expiries used.
86
+
87
+ * ``asks``: a copy of the ``T`` arrays of input asks for the expiries used.
88
+
89
+ * ``fits1``: list of ``T`` per-expiry fitted arbitrage-free prices within bid/ask (where masked) for the input ``strikes`` used. The element ``fit1[j]`` is a vector of length ``strikes[j]``.
90
+ Within numerical accuracy we have ``bids[j][mask[j]] <= fit1[j][mask[j]] <= asks[j][mask[j]]``.
91
+
92
+ * ``fitsX``: list of ``T`` surface fitted arbitrage-free prices for the input ``strikes``.
93
+ These prices are globally arbitrage-free across the surface, but they are not necessarily within bid/ask spread; they are the closest fit
94
+ among strikes with ``mask`` True.
95
+
96
+ Up to machine precision existence
97
+ of ``fitsX`` within bid/ask spread in the linear case ``smoothness=0`` is equivalent to absence of arbitrage.
98
+
99
+ This field is None if ``no_arb_mode`` is "expiry".
100
+
101
+ Besides the pure fits, this class also contains the ingredients of the DLV/SANOS model.
102
+
103
+ * For the **"expiry"** ``no_arb_mode``
104
+ the function :meth:`MkArbFree.__call__` will generate internal model ``xstrikes`` around the provided market strikes. For those strikes it will
105
+ compute a ``xdensities`` per expiry.
106
+
107
+ * ``xstrikes``: an extended strike list with two boundary strikes add. Boundary strikes are widening in time; c.f. https://arxiv.org/pdf/2601.11209 remark 2.7.
108
+
109
+ * ``xdensities``: list of densities for ``xstrikes``, per expiry. Up to machine precision, each density is positive, sums to one, intergates to one
110
+ in the sense that `` xstrikes[t]@xdensities[t] == 1``
111
+ and reprices ``fits``.
112
+
113
+ * ``run_time_expiry``: the time taken for the per-expiry first, in seconds.
114
+
115
+ * For the **"surface"** ``no_arb_mode``
116
+ the function :meth:`MkArbFree.__call__` will generate internal model ``mstrikes`` around the provided market strikes which are a superset of the extended ``xstrike`` grid.
117
+ This surface grid is constructed by adding strikes from the next expiry if they are not too close to existing strikes.
118
+ This is typically a much denser set than the input strikes. Each expiry is guaranteed to have their ``xstrikes`` among the respective model strikes.
119
+
120
+ These fields are None if ``no_arb_mode`` is not "surface".
121
+
122
+ * ``mstrikes``: the list of internal model strikes per expiry used.
123
+
124
+ * ``mdensities```: the list of densities for ``mstrikes``. Up to machine precision, each density is positive, sums to one, intergates to one
125
+ in the sense that `` mstrikes[t]@mdensities[t] == 1``
126
+ and reprices ``fits``. Moreover, the family of ``mdensities`` is martingale density, each later density evaluaes a convex function
127
+ higher than the a previous density.
128
+
129
+ * ``xix_to_mix``: a list of arrays which gives for every ``xstrike[t]`` the position in ``mstrikes[t]``, i.e. ``mstrikes[t][xix_to_mix[t]] == xstrikes[t]``.
130
+ The element ``xix_to_mix[t]`` is ``None`` if no additional strikes were added to expiry ``t``, i.e. the strikes coincide.
131
+
132
+ * ``run_time_surface``: the time taken for the surface fit, in seconds.
133
+ """
134
+
135
+ def __init__(self, smoothness : float|None = None):
136
+ self.smoothness : float|None = smoothness
137
+ self.expiry_linear: bool = False
138
+ self.min_half_spread : float = 1E-4
139
+ self.expiries : np.ndarray = []
140
+ self.variances : np.ndarray = []
141
+ self.input_index : np.ndarray = []
142
+
143
+ self.masks : list[np.ndarray] = []
144
+ self.strikes : list[np.ndarray] = []
145
+ self.asks : list[np.ndarray] = []
146
+ self.bids : list[np.ndarray] = []
147
+ self.fits1 : list[np.ndarray] = []
148
+ self.fitsX : list[np.ndarray]|None = None
149
+
150
+ self.xstrikes : list[np.ndarray] = []
151
+ self.xdensities : list[np.ndarray] = []
152
+
153
+ self.xix_to_mix : list[np.ndarray]|None = None
154
+ self.mstrikes : list[np.ndarray]|None = None
155
+ self.mdensities : list[np.ndarray]|None = None
156
+
157
+ self.run_time_expiry : float|None = None
158
+ self.run_time_surface : float|None = None
159
+
160
+ def to_dict(self) -> dict[str, object]:
161
+ """Return an HDF5-compatible representation of the pricer."""
162
+ def encode(value):
163
+ if value is None:
164
+ return self._none_sentinel
165
+ if isinstance(value, list):
166
+ return [encode(item) for item in value]
167
+ return value
168
+
169
+ return {key: encode(value) for key, value in self.items()}
170
+
171
+ @staticmethod
172
+ def from_dict(d: dict[str, object]) -> ArbFreePricer:
173
+ """Reconstruct a pricer serialized by :meth:`to_dict`."""
174
+ verify_inp(isinstance(d, dict), lambda: f"Expected 'd' to be a dict, found {type(d)}")
175
+
176
+ def decode(value):
177
+ if isinstance(value, str) and value == ArbFreePricer._none_sentinel:
178
+ return None
179
+ if isinstance(value, list):
180
+ return [decode(item) for item in value]
181
+ return value
182
+
183
+ decoded = {key: decode(value) for key, value in d.items()}
184
+ pricer = ArbFreePricer(smoothness=decoded.get("smoothness"))
185
+ expected_fields = set(pricer)
186
+ verify_inp(
187
+ set(decoded) == expected_fields,
188
+ lambda: (
189
+ "Serialized ArbFreePricer fields do not match the current implementation. "
190
+ f"Missing fields: {sorted(expected_fields - set(decoded))}; "
191
+ f"unexpected fields: {sorted(set(decoded) - expected_fields)}"
192
+ ),
193
+ )
194
+ pricer.update(decoded)
195
+ pricer._make_numpy()
196
+ return pricer
197
+
198
+ _none_sentinel = "__ARB_FREE_PRICER_NONE__"
199
+ _eps_price = 1E-6
200
+ _eps_density = 1E-7
201
+
202
+ def price( self, expiries : float|np.ndarray, strikes : float|np.ndarray, *, and_vols: bool = False, mode : str|None = None ) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
203
+ """
204
+ Price options at ``strikes`` with expiries ``expiries``.
205
+
206
+ Use ``mode`` to chose which pricing kernel to use: "expiry" uses the per-expiry fit
207
+ which may not be free of arbitrage in time; "surface" uses the full surface
208
+ fit which is free of arbitrage in time. ``None`` will chose the latter
209
+ if available, otherwise the former.
210
+
211
+ If ``and_vols`` is ``True`` this function returns call prices and their implied volatilities;
212
+ if ``False``, it will return only call prices.
213
+
214
+ Parameters
215
+ ----------
216
+ expiries : float | :class:`np.ndarray`
217
+ The expiry or expiries to price at.
218
+
219
+ * If ``expiries`` is a float, all strikes are evaluated at that expiry.
220
+ * 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.
221
+ * 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)``.
222
+
223
+ strikes : float | :class:`np.ndarray`
224
+ The strikes to price at. The shape of this array must be compatible with the shape of ``expiries`` as described above.
225
+
226
+ and_vols : bool, default ``False``
227
+ Whether to return implied volatilities in addition to call prices. If ``True``, the function returns a tuple of (call prices, implied volatilities).
228
+ If ``False``, it returns only call prices.
229
+
230
+ mode : str | None, default ``None``
231
+ Which pricing kernel to use: "expiry" uses the per-expiry fit which may not be free of arbitrage in time; "surface" uses the full surface fit which is free of arbitrage in time. ``None`` will chose the latter if available, otherwise the former.
232
+ """
233
+
234
+ assert isinstance(self.expiries, np.ndarray), "Internal error - forgot to make my 'expiries' a numpy array"
235
+ verify_inp( mode is None or mode in ["surface","expiry"], lambda : f"Expected 'mode' to be one of 'surface', 'expiry' or None, but found {str(mode)}" )
236
+ per_expiry = mode=="expiry" if not mode is None else ( self.fitsX is None )
237
+ verify_inp( per_expiry or not self.fitsX is None, f"Cannot use 'mode' \"surface\" since no surface fit is available")
238
+
239
+ # prices are written into arrays shaped like the strikes: integer strikes would truncate them
240
+ strikes = np.asarray(strikes, dtype=np.result_type(np.asarray(strikes).dtype, np.float64)) if not isinstance(strikes, (int,float,np.number)) else np.array([float(strikes)])
241
+
242
+ def x_price( expiry, strikes, and_vols ):
243
+ 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)}")
244
+
245
+ if self.smoothness is None or expiry<ONE_MINUTE or (self.expiry_linear and per_expiry):
246
+ def call( spots, strikes ):
247
+ return np.maximum( 0., spots - strikes )
248
+ else:
249
+ vol = self.interpolate_atm_vols( expiries=expiry ) * math.sqrt(self.smoothness)
250
+ def call( spots, strikes ):
251
+ return bs.price( k=strikes/spots, vol=vol, sqrtT=math.sqrt(expiry), eps=self._eps_price )*spots
252
+
253
+ def prices():
254
+ if expiry<ONE_MINUTE:
255
+ return np.maximum( 0., 1 - strikes )
256
+
257
+ ix = np.searchsorted( self.expiries, expiry )
258
+ if ix==0:
259
+ strikes_0 = self.xstrikes[0] if per_expiry else self.mstrikes[0]
260
+ p_0 = self.xdensities[0] if per_expiry else self.mdensities[0]
261
+ return call( spots=strikes_0[None,:], strikes=strikes[:,None] ) @ p_0
262
+
263
+ if ix==len(self.expiries):
264
+ strikes_T = self.xstrikes[-1] if per_expiry else self.mstrikes[-1]
265
+ p_T = self.xdensities[-1] if per_expiry else self.mdensities[-1]
266
+ return call( spots=strikes_T[None,:], strikes=strikes[:,None] ) @ p_T
267
+
268
+ diff_ixm1 = abs( expiry - self.expiries[ix-1] )
269
+ diff_ix = abs( expiry - self.expiries[ix] )
270
+ diff = diff_ix if diff_ix < diff_ixm1 else diff_ixm1
271
+
272
+ if diff<ONE_MINUTE:
273
+ ix_mind = ix if diff_ix < diff_ixm1 else ix-1
274
+ strikes_ix = self.xstrikes[ix_mind] if per_expiry else self.mstrikes[ix_mind]
275
+ p_ix = self.xdensities[ix_mind] if per_expiry else self.mdensities[ix_mind]
276
+ return call( spots=strikes_ix[None,:], strikes=strikes[:,None] ) @ p_ix
277
+
278
+ strikes_ixm1 = self.xstrikes[ix-1] if per_expiry else self.mstrikes[ix-1]
279
+ p_ixm1 = self.xdensities[ix-1] if per_expiry else self.mdensities[ix-1]
280
+ c_ixm1 = call( spots=strikes_ixm1[None,:], strikes=strikes[:,None] ) @ p_ixm1
281
+
282
+ strikes_ix = self.xstrikes[ix] if per_expiry else self.mstrikes[ix]
283
+ p_ix = self.xdensities[ix] if per_expiry else self.mdensities[ix]
284
+ c_ix = call( spots=strikes_ix[None,:], strikes=strikes[:,None] ) @ p_ix
285
+
286
+ return ((expiry - self.expiries[ix-1])*c_ix + (self.expiries[ix]-expiry)*c_ixm1)/(self.expiries[ix]-self.expiries[ix-1])
287
+ c = prices()
288
+ if not and_vols:
289
+ return c
290
+
291
+ v = bs.implied( k=strikes, prices=c, sqrtT=math.sqrt(expiry), eps=self._eps_price )
292
+ return c,v
293
+
294
+ if hasattr(expiries,"shape"):
295
+ if len(expiries.shape)==0:
296
+ expiries = float( expiries.item() )
297
+ elif expiries.shape == (1,):
298
+ expiries = float( expiries[0] )
299
+
300
+ if isinstance(expiries, (float, int, np.number)):
301
+ return x_price( expiry=expiries, strikes=strikes, and_vols=and_vols )
302
+
303
+ expiries = np.asarray(expiries)
304
+
305
+ if len(expiries.shape) == 1:
306
+ verify_inp( expiries.shape == strikes.shape, lambda : f"If 'expiries' is a 1D vector, then 'strikes' must have the same shape, but found {expiries.shape} and {strikes.shape}" )
307
+
308
+ uttys = np.unique(expiries)
309
+ results = np.zeros_like(strikes)
310
+ vols = np.zeros_like(strikes) if and_vols else None
311
+ for utty in uttys:
312
+ mask = expiries==utty
313
+ if not and_vols:
314
+ results[mask] = x_price( expiry=utty, strikes=strikes[mask], and_vols=False )
315
+ else:
316
+ results[mask], vols[mask] = x_price( expiry=utty, strikes=strikes[mask], and_vols=True )
317
+ if not and_vols:
318
+ return results
319
+ return results, vols
320
+
321
+ if strikes.shape == (1,):
322
+ strikes = strikes.reshape(1,1)
323
+ 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}" )
324
+ M = expiries.shape[0]
325
+ 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 of shape {expiries.shape} and strikes of shape {strikes.shape}" )
326
+ N = strikes.shape[1]
327
+ results = np.zeros((M,N),dtype=strikes.dtype)
328
+ vols = np.zeros((M,N),dtype=strikes.dtype) if and_vols else None
329
+ for ix, tty in enumerate(expiries[:,0]):
330
+ if not and_vols:
331
+ results[ix,:] = x_price( expiry=tty, strikes=strikes[0 if strikes.shape[0] == 1 else ix,:], and_vols=False )
332
+ else:
333
+ results[ix,:], vols[ix,:] = x_price( expiry=tty, strikes=strikes[0 if strikes.shape[0] == 1 else ix,:], and_vols=True )
334
+ if not and_vols:
335
+ return results
336
+ return results, vols
337
+
338
+ def interpolate_atm_vols( self, expiries: float|np.ndarray ) -> float|np.ndarray:
339
+ """ Interpolates the (ATM) variances (not smoothed) """
340
+ assert not self.variances is None, "Internal error - variances are missing"
341
+ is_float = not hasattr(expiries,"shape")
342
+ expiries = np.asarray([float(expiries)]) if is_float else np.asarray(expiries)
343
+ expiries = np.clip( expiries, self.expiries[0], self.expiries[-1] )
344
+ vols = np.sqrt( np.interp( expiries, self.expiries, self.variances ) / expiries )
345
+ assert np.all(np.isfinite(vols)), "Internal error: infinite vol"
346
+ return vols if not is_float else vols[0]
347
+
348
+ def compute_market_fit( self, expiries : np.ndarray, strikes : list[np.ndarray], bids : list[np.ndarray], asks : list[np.ndarray], masks : list[np.ndarray]|None = None, *, and_vols : bool = True ) -> PrettyObject:
349
+ """
350
+ Compute standardized fitting error stats
351
+
352
+ Returns
353
+ -------
354
+ Errors : :class:`PrettyObject`
355
+ A dictionary-like object with the following fields:
356
+ * ``fits``: list of fitted prices for the input strikes, per expiry.
357
+ * ``fit_vols``: list of fitted vols for the input strikes, per expiry.
358
+ * ``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 )``.
359
+ * ``pcnt_fit``: despite its name, the fraction (between 0 and 1) of strikes whose fit is outside the bid/ask spread, ``sum( fit_errs > 0 ) / len(fit_errs)``.
360
+ * ``median_err``: the median fitting error among strikes whose fit is outside the bid/ask spread, ``median( fit_errs[fit_errs>0.] )``; zero if there are none.
361
+ * ``mean_err``: the mean fitting error among strikes whose fit is outside the bid/ask spread, ``mean( fit_errs[fit_errs>0.] )``; zero if there are none.
362
+
363
+ """
364
+ return _compute_market_fit( lambda expires, strikes, and_vols : self.price( expiries=expires, strikes=strikes, and_vols=and_vols ),
365
+ self.min_half_spread, expiries=expiries, strikes=strikes, bids=bids, asks=asks, masks=masks, and_vols=and_vols )
366
+
367
+ @property
368
+ def T(self) -> int:
369
+ return len(self.expiries)
370
+
371
+ def _make_numpy(self):
372
+ self.smoothness = float(self.smoothness) if not self.smoothness is None else None
373
+ self.expiries = np.asarray(self.expiries)
374
+ self.variances = np.asarray(self.variances)
375
+ self.input_index = np.asarray(self.input_index, dtype=np.int32)
376
+
377
+ self.masks = [ np.asarray(x) for x in self.masks ]
378
+ self.strikes = [ np.asarray(x) for x in self.strikes ]
379
+ self.asks = [ np.asarray(x) for x in self.asks ]
380
+ self.bids = [ np.asarray(x) for x in self.bids ]
381
+ self.fits1 = [ np.asarray(x) for x in self.fits1 ]
382
+ self.fitsX = [ np.asarray(x) for x in self.fitsX ] if not self.fitsX is None else None
383
+
384
+ self.xstrikes = [ np.asarray(x) for x in self.xstrikes ]
385
+ self.xdensities = [ np.asarray(x) for x in self.xdensities ]
386
+
387
+ self.xix_to_mix = [ (np.asarray(x,dtype=np.int32) if not x is None else None) for x in self.xix_to_mix ] if not self.xix_to_mix is None else None
388
+ self.mstrikes = [ np.asarray(x) for x in self.mstrikes ] if not self.mstrikes is None else None
389
+ self.mdensities = [ np.asarray(x) for x in self.mdensities ] if not self.mdensities is None else None
390
+
391
+ self.run_time_expiry = float(self.run_time_expiry) if not self.run_time_expiry is None else None
392
+ self.run_time_surface = float(self.run_time_surface) if not self.run_time_surface is None else None
393
+
394
+ T = len(self.expiries)
395
+ assert self.variances.shape == (T,), f"Internal error: 'variances' must be of shape (T,), but found {self.variances.shape}"
396
+ assert self.input_index.shape == (T,), f"Internal error: 'input_index' must be of shape (T,), but found {self.input_index.shape}"
397
+
398
+ assert len(self.masks) == T, f"Internal error: 'masks' must be a list of length {T}, but found {len(self.masks)}"
399
+ assert len(self.strikes) == T, f"Internal error: 'strikes' must be a list of length {T}, but found {len(self.strikes)}"
400
+ assert len(self.asks) == T, f"Internal error: 'asks' must be a list of length {T}, but found {len(self.asks)}"
401
+ assert len(self.bids) == T, f"Internal error: 'bids' must be a list of length {T}, but found {len(self.bids)}"
402
+ assert len(self.fits1) == T, f"Internal error: 'fits1' must be a list of length {T}, but found {len(self.fits1)}"
403
+
404
+ assert len(self.xstrikes) == T, f"Internal error: 'xstrikes' must be a list of length {T}, but found {len(self.xstrikes)}"
405
+ assert len(self.xdensities) == T, f"Internal error: 'xdensities' must be a list of length {T}, but found {len(self.xdensities)}"
406
+
407
+ if not self.mstrikes is None:
408
+ assert self.fitsX is None or len(self.fitsX) == T, f"Internal error: 'fitsX' must be a list of length {T}, but found {len(self.fitsX)}"
409
+ assert len(self.mstrikes) == T, f"Internal error: 'mstrikes' must be a list of length {T}, but found {len(self.mstrikes)}"
410
+ assert len(self.mdensities) == T, f"Internal error: 'mdensities' must be a list of length {T}, but found {len(self.mdensities)}"
411
+
412
+ for t in range(T):
413
+ mask_t = self.masks[t]
414
+ strikes_t = self.strikes[t]
415
+ asks_t = self.asks[t]
416
+ bids_t = self.bids[t]
417
+ fits1_t = self.fits1[t]
418
+ fitsX_t = self.fitsX[t] if not self.fitsX is None else None
419
+
420
+ assert mask_t.shape == strikes_t.shape == asks_t.shape == bids_t.shape == fits1_t.shape, f"Internal error: 'masks[{t}]', 'strikes[{t}]', 'asks[{t}]', 'bids[{t}]' and 'fits1[{t}]' must all have the same shape, but found {mask_t.shape}, {strikes_t.shape}, {asks_t.shape}, {bids_t.shape} and {fits1_t.shape}"
421
+
422
+ xstrikes_t = self.xstrikes[t]
423
+ xdensities_t = self.xdensities[t]
424
+ assert xstrikes_t.shape == xdensities_t.shape, f"Internal error: 'xstrikes[{t}]' and 'xdensities[{t}]' must have the same shape, but found {xstrikes_t.shape} and {xdensities_t.shape}"
425
+
426
+ if not self.mstrikes is None:
427
+ assert fitsX_t is None or fitsX_t.shape == mask_t.shape, f"Internal error: 'fitsX[{t}]' must have the same shape as 'masks[{t}]', but found {fitsX_t.shape} and {mask_t.shape}"
428
+ mstrikes_t = self.mstrikes[t]
429
+ mdensities_t = self.mdensities[t]
430
+ assert mstrikes_t.shape == mdensities_t.shape, f"Internal error: 'mstrikes[{t}]' and 'mdensities[{t}]' must have the same shape, but found {mstrikes_t.shape} and {mdensities_t.shape}"
431
+
432
+ @version("0.58", dependencies=[ArbFreePricer])
433
+ @dataclass(frozen=True)
434
+ class MkArbFree:
435
+ """
436
+ A utility class which generates a "closest" arbitrage free market using the ideas from the paper https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2642630.
437
+
438
+ Given a market with expiries, strikes, bid and asks this functional:
439
+ 1) Expands the strike range following https://arxiv.org/pdf/2601.11209 remark 2.7: it adds one strike below and one above the quotes where the call is at intrinsic value,
440
+ trimming boundary strikes whose slope does not allow this. Expiries with fewer than ``min_strikes_per_expiry`` strikes are dropped. If no boundary strike can be found the fit fails with an error.
441
+ 2) Fits per expiry a no-arbitrage price within the bid-ask spread. Strikes which cannot be fitted within bid/ask are masked; an expiry is dropped if fewer than half
442
+ of its strikes can be fitted.
443
+ 3) In ``surface`` mode, fits a surface free of calendar and strike arbitrage across the remaining expiries. For the linear surface a fit within bid/ask exists if and only if
444
+ the quotes are free of arbitrage. The strike grid used is returned as ``mstrikes``.
445
+
446
+ See :meth:`MkArbFree.__call__` for more details on the input and output of this functional.
447
+ """
448
+ no_arb_mode : str = "surface" #: "expiry": per-expiry fits only. "surface": also fit one arbitrage-free surface across expiries.
449
+ smoothness : float|None = None #: SANOS smoothness eta: the smoothing kernel has volatility sqrt(eta) times the ATM volatility. None or 0 is the linear surface.
450
+ surface_expiry_linear : bool = True # In 'surface' mode, if smoothness is > 0, whether to run per 'expiry' in linear mode.
451
+
452
+ # control over process parameters
453
+ min_half_spread : float = 1E-4 #: Floor on the half bid/ask spread which scales the fit errors and the objective.
454
+ mid_fit_weight : float = 0.1 #: Weight w of the summed distance from the mid; 1-w weights the summed distance outside bid/ask. See the module documentation.
455
+ min_atm_vol : float = 0.05 #: Minimum ATM vol.
456
+ min_dlv : float|None = None #: Optional lower bound on the discrete local volatility (DLV) of the surface.
457
+ max_dlv : float|None = None #: Optional upper bound on the discrete local volatility (DLV) of the surface.
458
+
459
+ # reweighting of the surface fit
460
+ reweight_max_iter : int = 1 #: Maximum number of surface fits. 1 fits once; with more, the fit is repeated with reweighted quotes to raise the share of quotes within bid/ask.
461
+ reweight_min_within : float = 0.9 #: Reweighting stops once this share of the quotes is within bid/ask. Not used if ``reweight_max_iter`` is 1.
462
+
463
+ # timeout
464
+ timeout_seconds : float|None = 60.*5. #: Time limit for the optimization solver, in seconds. This is passed to the CVXPY solver options as "time_limit".
465
+
466
+ # micro paramters
467
+ min_strikes_per_expiry : int = 5 #: (expert use only) Minimum strikes per expiry. Expiries with fewer strikes will be dropped.
468
+ min_density : float = 1E-4 #: (expert use only) Minimum density value to consider in the optimization. Strikes with lower values will be dropped.
469
+ min_dC_eps : float = 1E-3 #: (expert use only) Minimum dC/dK slope at the boundaries. Expiries with steeper slopes will be dropped.
470
+
471
+ # protected variables do not alter the ID of this field (because they start with '_')
472
+ _debug_verbose_cvxpy : set[str]|None = None
473
+ _remove_no_arb_strikes: bool = True
474
+ _eps_price : float = 1E-6
475
+ _eps_density : float = 1E-7
476
+ _eps_dens_1 : float = 1E-4 #: (expert use only) What passes as ``sum(p)==1`` and ``p@K==1`` for the fitted density.
477
+ _eps_no_arb : float = 0.01 #: The slack of a quote starts this fraction of the half spread inside bid/ask.
478
+ _eps_hard_fit : float = 1E-5 #: The hard per-expiry fit stays this fraction of the half spread inside bid/ask.
479
+ _reweight_eps : float = 0.1 #: A reweighted quote has weight 1/(excess + this), with the excess of the previous fit in half spreads.
480
+ _reweight_min_gain : float = 0.0025 #: Reweighting stops when a fit raises the share within bid/ask by less than this.
481
+
482
+ def __post_init__(self):
483
+ if self.smoothness is not None and self.smoothness == 0.:
484
+ # zero smoothness is the linear model; one representation gives one cache key
485
+ object.__setattr__(self, "smoothness", None)
486
+ verify_inp( self.no_arb_mode in ["expiry", "surface"], lambda : f"'no_arb_mode' must be one of 'expiry' or 'surface', but found '{self.no_arb_mode}'" )
487
+ verify_inp( self.min_strikes_per_expiry >= 3, lambda : f"'min_strikes_per_expiry' must be at least 3, but found {self.min_strikes_per_expiry}" )
488
+ verify_inp( self.min_dC_eps > 0., lambda : f"'min_dC_eps' must be positive, but found {self.min_dC_eps}" )
489
+ verify_inp( self.min_half_spread > 0., lambda : f"'min_half_spread' must be positive, but found {self.min_half_spread}" )
490
+ verify_inp( self.min_density > 0., lambda : f"'min_density' must be positive, but found {self.min_density}" )
491
+ verify_inp( self.timeout_seconds is None or self.timeout_seconds >= 0., lambda : f"'timeout_seconds' must be positive or None, but found {self.timeout_seconds}" )
492
+ verify_inp( self.smoothness is None or self.smoothness >= 0., lambda : f"'smoothness' must be positive or None, but found {self.smoothness:.4g}")
493
+ verify_inp( self.mid_fit_weight >= 0. and self.mid_fit_weight <= 1., lambda : f"'mid_fit_weight' must be between 0 and 1, but found {self.mid_fit_weight:.4g}" )
494
+ verify_inp( self.min_atm_vol >= 0., lambda : f"'min_atm_vol' must be non-negative, but found {self.min_atm_vol:.4g}" )
495
+ verify_inp( self.reweight_max_iter >= 1, lambda : f"'reweight_max_iter' must be at least 1, but found {self.reweight_max_iter}" )
496
+ verify_inp( self.reweight_min_within > 0. and self.reweight_min_within <= 1., lambda : f"'reweight_min_within' must be in (0,1], but found {self.reweight_min_within:.4g}" )
497
+
498
+ def __str__(self) -> str:
499
+ """ Very compact but still readable summary """
500
+ surface_expiry_linear = self.surface_expiry_linear and self.no_arb_mode=="surface" and not self.smoothness is None
501
+ return f"{self.no_arb_mode},{f'std={self.smoothness:.2g},' if self.smoothness is not None else ''}{'elin' if surface_expiry_linear else ''}mhs={self.min_half_spread:.3g},"+\
502
+ f"mw={self.mid_fit_weight:.3g},mav={self.min_atm_vol:.2g},"+\
503
+ ( f"midl={self.min_dlv:.3g}," if not self.min_dlv is None else "" ) + ( f"mxdv={self.max_dlv:.3g}," if not self.max_dlv is None else "" ) +\
504
+ f"mik={self.min_strikes_per_expiry},mdn={self.min_density:.3g},dC={self.min_dC_eps:.3g},dps={self._eps_dens_1:.1g}" +\
505
+ f",rw={self.reweight_max_iter}" + ( f"@{self.reweight_min_within:.3g}" if self.reweight_max_iter > 1 else "" )
506
+
507
+ def __unique_hash__( self, unique_hash, debug_trace ) -> str:
508
+ """ Overwrite hash function to ignore non-functional parameters """
509
+ r = asdict(self)
510
+ r.pop("timeout_seconds", None)
511
+ if self.no_arb_mode!="surface" or self.smoothness is None:
512
+ r.pop("surface_expiry_linear", None)
513
+ if self.reweight_max_iter <= 1:
514
+ # a single fit does not use the threshold: it must not give two identities to the same fit
515
+ r.pop("reweight_min_within", None)
516
+ return unique_hash(r, debug_trace=debug_trace)
517
+
518
+ def to_linear(self) -> MkArbFree:
519
+ """ Return a version of this object configured for linear arbitrage-free fitting """
520
+ r = asdict(self)
521
+ r["smoothness"] = None
522
+ return MkArbFree(**r)
523
+
524
+ def is_linear(self) -> bool:
525
+ return self.smoothness is None or self.smoothness == 0.
526
+
527
+ def __call__(self,
528
+ expiries : np.ndarray,
529
+ strikes : list[np.ndarray],
530
+ bids : list[np.ndarray],
531
+ asks : list[np.ndarray], *,
532
+ vols : np.ndarray|float|None = None, # ATM volatilities per expiry, used for smoothing; a float applies to all expiries, None estimates them from the quotes
533
+ message_context: str|callable[[], str] | None = None,
534
+ info : dict|None = None,
535
+ verbose : Context = Context.all ) -> ArbFreePricer:
536
+ """
537
+ Make market data arbitrage-free using ideas from the paper https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2642630.
538
+
539
+ Given a market with expiries, strikes, bid and asks this functional:
540
+ 1) Expands the strike range following https://arxiv.org/pdf/2601.11209 remark 2.7: it adds one strike below and one above the quotes where the call is at intrinsic value,
541
+ trimming boundary strikes whose slope does not allow this. Expiries with fewer than ``min_strikes_per_expiry`` strikes are dropped. If no boundary strike can be found the fit fails with an error.
542
+ 2) Fits per expiry a no-arbitrage price within the bid-ask spread. Strikes which cannot be fitted within bid/ask are masked; an expiry is dropped if fewer than half
543
+ of its strikes can be fitted.
544
+ 3) In ``surface`` mode, fits a surface free of calendar and strike arbitrage across the remaining expiries. For the linear surface a fit within bid/ask exists if and only if
545
+ the quotes are free of arbitrage. The strike grid used is returned as ``mstrikes``.
546
+
547
+ This function is usually very fast, but it can get stuck when the overall surface is close to arbitrage in areas which have very little
548
+ room to adjust.
549
+
550
+ This function returns a :class:`ArbFreePricer` object which contains the result of the fit, and can be used to price options at arbitrary strikes and expiries using the fitted model.
551
+
552
+ Parameters
553
+ ----------
554
+ expiries : :class:``numpy.ndarray`
555
+ Increasing array of expiries (in years).
556
+ strikes : list[:class:``numpy.ndarray`]
557
+ List of strike arrays, one per expiry. Each strike array must be strictly increasing and positive, and must have the same shape as the corresponding bid and ask arrays.
558
+ bids : list[:class:``numpy.ndarray`]
559
+ List of bid price arrays, one per expiry.
560
+ asks : list[:class:``numpy.ndarray`]
561
+ List of ask price arrays, one per expiry.
562
+ vols : :class:``numpy.ndarray`` | float | None, default ``None``
563
+ Volatilities per expiry used when ``smoothness`` is not None.
564
+ If left to ``None``, the function will compute an approximate mid-atm volatility from the provided bid and ask prices per expiry.
565
+ info : dict | None, default ``None``
566
+ If a dictionary is given, the fitter reports in it how the fit went: ``num_surface_fits`` is the number of surface fits made,
567
+ which is above 1 if the fit was reweighted and 0 if there is no surface fit. ``within_first_fit`` and ``within_kept_fit`` are the
568
+ shares of quotes within bid/ask after the first surface fit and in the fit kept, over all quotes of the retained expiries.
569
+ message_context : str | callable[[], str] | None, default None
570
+ Optional context to prepend to error and warning messages.
571
+ This can be a string or a callable which returns a string, e.g. a lambda which returns a string with dynamic information such as the current expiry being processed. If None, no context is prepended.
572
+ verbose : :class:`Context`, default ``Context.all``
573
+ Verbose context for logging.
574
+
575
+ Returns
576
+ -------
577
+ Fitted market: :class:`ArbFreePricer`
578
+ See above.
579
+ """
580
+ def message(with_cols : bool = True) -> str:
581
+ if message_context is None:
582
+ return ""
583
+ if callable(message_context):
584
+ msg = message_context()
585
+ else:
586
+ msg = str(message_context)
587
+ if msg == "":
588
+ return ""
589
+ msg = msg[0].upper() + msg[1:]
590
+ if not with_cols:
591
+ return msg
592
+ return msg + ": "
593
+
594
+ T = len(expiries)
595
+
596
+ verify_inp( T > 0, lambda : f"{message()}Expected at least one expiry, but found {T}" )
597
+ verify_inp( len(strikes) == T, lambda : f"{message()}Expected number of strike arrays {T} to match number of expiries {len(expiries)}" )
598
+ verify_inp( len(bids) == T, lambda : f"{message()}Expected number of bid arrays {T} to match number of expiries {len(expiries)}" )
599
+ verify_inp( len(asks) == T, lambda : f"{message()}Expected number of ask arrays {T} to match number of expiries {len(expiries)}" )
600
+ verify_inp( expiries[0] > 0. and (len(expiries)==1 or np.min(np.diff(expiries)) > 0.), lambda : f"{message()}Expiries must be positive and strictly increasing, but found {expiries}" )
601
+ for t in range(T):
602
+ verify_inp( np.shape(strikes[t]) == np.shape(bids[t]) == np.shape(asks[t]), lambda : f"{message()}Expiry #{t}: 'strikes', 'bids' and 'asks' must have the same shape, but found {np.shape(strikes[t])}, {np.shape(bids[t])} and {np.shape(asks[t])}" )
603
+ verify_inp( np.all(np.isfinite(strikes[t])) and np.all(np.isfinite(bids[t])) and np.all(np.isfinite(asks[t])), lambda : f"{message()}Expiry #{t}: strikes, bids and asks must be finite" )
604
+ verify_inp( np.all(np.asarray(asks[t]) > np.asarray(bids[t])), lambda : f"{message()}Expiry #{t}: every ask must be above its bid" )
605
+
606
+ def make_variances():
607
+ if vols is None:
608
+ atm_calls = []
609
+ for t in range(T):
610
+ ixs = np.argsort( strikes[t] )
611
+ atm_calls.append( np.interp( 1., strikes[t][ixs], (bids[t][ixs]+asks[t][ixs])/2. ) )
612
+ atm_calls = np.asarray(atm_calls)
613
+ atm_vols = bs.implied( k=np.ones_like(atm_calls), prices=atm_calls, sqrtT=np.sqrt(expiries), eps=self._eps_price )
614
+ variances = expiries * (np.maximum(atm_vols, self.min_atm_vol)**2)
615
+ dts = np.diff(expiries, prepend=0.)
616
+ fwd_vars = np.maximum(0.001**2, np.diff(variances, prepend=0.) / dts ) * dts
617
+ variances = np.cumsum(fwd_vars)
618
+ del atm_calls, atm_vols, dts, fwd_vars
619
+ elif isinstance( vols, np.ndarray ):
620
+ 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}" )
621
+ verify_inp( np.all(vols > 0.), lambda : f"{message()}All volatilities must be positive, but found {vols}" )
622
+ variances = expiries * (vols**2)
623
+ 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}" )
624
+ else:
625
+ variances = expiries * (float(vols)**2)
626
+ verify_inp(vols > 0., lambda : f"{message()}Volatility must be positive, but found {vols}" )
627
+ return variances
628
+ variances = make_variances()
629
+ del vols
630
+
631
+ # generate strike range, fit per-expiry
632
+ # -------------------------------------
633
+ # Add strikes to the left and right which are consistent with the no-arb condition.
634
+
635
+ r = ArbFreePricer(self.smoothness)
636
+ r.min_half_spread = self.min_half_spread
637
+ r.expiries = []
638
+ r.variances = []
639
+ r.xstrikes = []
640
+ r.xdensities = []
641
+ r.masks = []
642
+ r.strikes = []
643
+ r.asks = []
644
+ r.bids = []
645
+ r.fits1 = []
646
+ tme = verbose.timer()
647
+ r.expiry_linear = self.surface_expiry_linear and self.no_arb_mode=="surface" and not self.smoothness is None
648
+
649
+ for t, expiry in enumerate(expiries):
650
+ def local_message():
651
+ msg = message(False)
652
+ ext = f"expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d"
653
+ if msg == "":
654
+ msg = ext[0].upper() + ext[1:]
655
+ else:
656
+ msg += " " + ext
657
+ return msg
658
+ verbose.write(lambda : f"\r{local_message()}: Generating extended strikes... ", end='')
659
+
660
+ # strikes
661
+ # -------
662
+
663
+ strikes_t = strikes[t]
664
+
665
+ if len(strikes_t) < self.min_strikes_per_expiry:
666
+ verbose.write(lambda : f"\r{local_message()}: Skipping expiry since it has fewer than {self.min_strikes_per_expiry} strikes.")
667
+ continue
668
+
669
+ xstrikes_t, mask_t, notice = self.make_extended_strikes( strikes_t,
670
+ bids=bids[t],
671
+ asks=asks[t],
672
+ prev_lower = r.xstrikes[-1][0] if len(r.xstrikes) > 0 else None,
673
+ prev_upper = r.xstrikes[-1][-1] if len(r.xstrikes) > 0 else None,
674
+ message_context = local_message)
675
+ assert not xstrikes_t is None, "Internal error: xstrikes_t is None."
676
+ if not notice is None:
677
+ verbose.write(lambda : notice() + ": ", head=False, end='')
678
+ assert np.all( xstrikes_t[1:-1] == strikes_t[mask_t] ), "Mask error...?"
679
+ verbose.write(lambda : f"using {len(xstrikes_t)} extended strikes based on {len(strikes_t)} market strikes.", head=False)
680
+
681
+ # linear fit per expiry
682
+ # ---------------------
683
+
684
+ strikes_t = strikes[t]
685
+ bid_t = bids[t]
686
+ ask_t = asks[t]
687
+ verify_inp( bid_t.shape == ask_t.shape == strikes_t.shape, lambda : f"{local_message()}: 'strikes[{t}]', 'bids[{t}]' and 'asks[{t}]' must all have the same shape, but found {strikes_t.shape}, {bid_t.shape} and {ask_t.shape}" )
688
+ verify_inp( np.min( ask_t - bid_t ) > 0., lambda : f"{local_message()}: All options must have positive bid/ask spread, but found minimum spread {np.min(ask_t - bid_t):.4g}" )
689
+
690
+ p_t, fit_t = self.expiry_density(
691
+ expiry = expiry,
692
+ variance = variances[t],
693
+ strikes_t = strikes_t,
694
+ bid_t = bid_t,
695
+ ask_t = ask_t,
696
+ mask_t = mask_t,
697
+ xstrikes_t = xstrikes_t,
698
+ force_linear = r.expiry_linear,
699
+ message_context = local_message,
700
+ verbose = verbose)
701
+ assert xstrikes_t.shape == p_t.shape, f"Internal error: {local_message()}Shape of xstrikes {xstrikes_t.shape} does not match shape of density {p_t.shape}"
702
+
703
+ fit_mask = ( fit_t >= bid_t - self._eps_price ) & ( fit_t <= ask_t + self._eps_price ) & mask_t
704
+ fit_mask_live = fit_mask[mask_t]
705
+
706
+ if not np.all(fit_mask_live):
707
+ if np.sum(fit_mask_live) < len(fit_mask_live)//2:
708
+ verbose.write(lambda : f"\r{local_message()}: skipping expiry since we cannot fit an arbitrage-free mid within bid/ask spread for more than half of the strikes.")
709
+ continue
710
+
711
+ if self._remove_no_arb_strikes:
712
+ assert np.all( xstrikes_t[1:-1] == strikes_t[mask_t] ), "Mask error...?" # only true up here.
713
+ xfit_mask = np.concatenate(([True], fit_mask_live, [True]))
714
+ xstrikes_R_t = xstrikes_t[xfit_mask]
715
+
716
+ pR_t, fitR_t = self.expiry_density(
717
+ expiry=expiry,
718
+ variance=variances[t],
719
+ strikes_t=strikes_t,
720
+ bid_t=bid_t,
721
+ ask_t=ask_t,
722
+ mask_t=fit_mask,
723
+ xstrikes_t=xstrikes_R_t,
724
+ force_linear = r.expiry_linear,
725
+ message_context=local_message,
726
+ verbose=verbose,
727
+ )
728
+
729
+ fitR_mask = ( fitR_t >= bid_t - self._eps_price ) & ( fitR_t <= ask_t + self._eps_price ) & fit_mask
730
+ fitR_mask_live = fitR_mask[fit_mask]
731
+ if np.all(fitR_mask_live):
732
+ verbose.write(lambda : f"\r{local_message()}: fit achived after removing {np.sum(~fit_mask)} of {len(fit_mask)} strikes.")
733
+ xstrikes_t = xstrikes_R_t
734
+ p_t = pR_t
735
+ fit_t = fitR_t
736
+ else:
737
+ verbose.write(lambda : f"\r{local_message()}: removing {np.sum(~fit_mask)} of {len(fit_mask)} strikes did not achieve fit; keeping all strikes but masking the options out.")
738
+ del pR_t, fitR_t, fitR_mask, fitR_mask_live
739
+
740
+ mask_t = fit_mask
741
+ del fit_mask, fit_mask_live
742
+
743
+ m_bid_t = bids[t][mask_t]
744
+ m_ask_t = asks[t][mask_t]
745
+ m_fit_t = fit_t[mask_t]
746
+ assert np.all( m_fit_t >= m_bid_t - self._eps_price ) and np.all( m_fit_t <= m_ask_t + self._eps_price ), f"Internal error: {local_message()}Expiry #{t} {expiry*DAYS_PER_YEAR:.1f}d: fitted mid is not within bid/ask spread after attempted fixes. This should not happen."
747
+
748
+ assert xstrikes_t.shape == p_t.shape, f"Internal error: {local_message()}Shape of xstrikes {xstrikes_t.shape} does not match shape of density {p_t.shape}"
749
+
750
+ # store result
751
+ r.expiries.append( expiry )
752
+ r.variances.append( variances[t] )
753
+ r.input_index.append( t )
754
+
755
+ r.xstrikes.append( xstrikes_t )
756
+ r.xdensities.append( p_t )
757
+
758
+ r.masks.append( mask_t )
759
+ r.strikes.append( strikes[t] )
760
+ r.bids.append( bids[t] )
761
+ r.asks.append( asks[t] )
762
+ r.fits1.append( fit_t ) # fit is computed for all strikes, also those unmasked
763
+
764
+ r.expiries = np.array(r.expiries, dtype=np.float64)
765
+ r.variances = np.array(r.variances, dtype=np.float64)
766
+ r.run_time_expiry = tme.seconds
767
+
768
+ def expiry_message():
769
+ msg = message(False)
770
+ if msg == "":
771
+ return "Expiry fit"
772
+ else:
773
+ return msg + " expiry fit"
774
+ verbose.write(lambda : f"\r{expiry_message()}: Generated {len(r.expiries)} {'linear' if self.smoothness is None else f'{self.smoothness:.2f}-smooth'} arbitrage-free expiries with extended strikes from {T} market expiries. This took {tme}.")
775
+
776
+ if self.no_arb_mode != "surface":
777
+ r._make_numpy()
778
+ return r
779
+
780
+ # backward-dense grid
781
+ # -------------------
782
+ # Carry grid forward as long as the strike range isn't too tight.
783
+ # We are using the xstrike_t grid from which we removed all strikes
784
+ # for which the per-expiry density is zero
785
+
786
+ T = len(r.expiries)
787
+ r.mstrikes = [None]*T
788
+ r.mdensities = None #set below
789
+ r.xix_to_mix = [None]*T
790
+ r.fitsX = []
791
+
792
+ min_dx = None
793
+ mguess_p = [None]*T
794
+ tme = verbose.timer()
795
+
796
+ for t in range(T-1,-1,-1):
797
+ # fix strikes
798
+ # 1) Ensure outside strike range is increasing.
799
+ # 2) Add strikes of next expiry if not too close to existing strikes. Always keep current strikes
800
+ xstrikes_t = r.xstrikes[t]
801
+ mstrikes_t = xstrikes_t
802
+ mp_t = r.xdensities[t]
803
+ project = None
804
+ if t<T-1:
805
+ next_mstrikes = r.mstrikes[t+1]
806
+ assert next_mstrikes[0] <= xstrikes_t[0] and next_mstrikes[-1] >= xstrikes_t[-1], f"Internal error: {message()}next_mstrikes[0] {next_mstrikes[0]:.3f} > xstrikes_t[0] {xstrikes_t[0]:.3f} or next_mstrikes[-1] {next_mstrikes[-1]:.3f} < xstrikes_t[-1] {xstrikes_t[-1]:.3f}"
807
+
808
+ min_dx = np.diff(mstrikes_t).min()
809
+ collect = []
810
+ project = []
811
+ mgpcl = []
812
+ inext = 0
813
+ add_any = False
814
+
815
+ # skip next strikes until relevant
816
+ while next_mstrikes[inext] <= xstrikes_t[0]+min_dx:
817
+ inext += 1
818
+
819
+ project.append( len(collect) )
820
+ collect = [ xstrikes_t[0] ]
821
+ mgpcl = [ mp_t[0] ]
822
+
823
+ for ithis in range(1, xstrikes_t.shape[0]):
824
+ k = xstrikes_t[ithis]
825
+ # add next strikes up to 'k'
826
+ while next_mstrikes[inext] <= k-min_dx:
827
+ if next_mstrikes[inext] - collect[-1] >= min_dx:
828
+ collect.append( next_mstrikes[inext] )
829
+ mgpcl.append( 0. )
830
+ add_any = True
831
+ inext += 1
832
+ project.append( len(collect) )
833
+ collect.append( k )
834
+ mgpcl.append( mp_t[ithis] )
835
+ # skip next_mstrikes which are too close to k
836
+ while next_mstrikes[inext] <= k+min_dx:
837
+ inext += 1
838
+ if inext >= next_mstrikes.shape[0]:
839
+ break
840
+
841
+ assert len(collect) == len(mgpcl), f"Internal error: {message()}collect length {len(collect)} does not match mgpcl length {len(mgpcl)}"
842
+ if add_any:
843
+ mstrikes_t = np.array(collect, dtype=xstrikes_t.dtype)
844
+ mp_t = np.array(mgpcl, dtype=np.float64)
845
+ assert np.min( np.diff( mstrikes_t ) ) >= min_dx-1E-6, f"Internal error: {message()}min dx {np.diff(mstrikes_t).min():.6g} < min_dx {min_dx:.6g}"
846
+ assert mstrikes_t[0] == xstrikes_t[0] and mstrikes_t[-1] == xstrikes_t[-1], f"Internal error: {message()}mstrikes_t[0] {mstrikes_t[0]:.3f} != xstrikes_t[0] {xstrikes_t[0]:.3f} or mstrikes_t[-1] {mstrikes_t[-1]:.3f} != xstrikes_t[-1] {xstrikes_t[-1]:.3f}"
847
+ project = np.array( project, dtype=np.int32 )
848
+ else:
849
+ project = None
850
+
851
+ assert project is None or np.allclose( xstrikes_t, mstrikes_t[project] ), f"Internal error: {message()}projection error, xstrikes_t {xstrikes_t} should be equal to mstrikes_t[project] {mstrikes_t[project]}"
852
+ r.mstrikes[t] = mstrikes_t
853
+ r.xix_to_mix[t] = project
854
+ mguess_p[t] = mp_t
855
+
856
+ # solve surface no-arb
857
+ # --------------------
858
+
859
+ def surface_message():
860
+ msg = message(False)
861
+ if msg == "":
862
+ return "Surface fit"
863
+ else:
864
+ return msg + " surface fit"
865
+
866
+ def fit_surface( quote_weights ):
867
+ return self.surface_densities(
868
+ expiries = r.expiries,
869
+ variances = r.variances,
870
+ strikes = r.strikes,
871
+ asks = r.asks,
872
+ bids = r.bids,
873
+ masks = r.masks,
874
+ xstrikes = r.mstrikes,
875
+ xguessed_p = mguess_p,
876
+ quote_weights = quote_weights,
877
+ hard_fit = False,
878
+ message_context = surface_message,
879
+ verbose = verbose
880
+ )
881
+
882
+ def excess( fits ):
883
+ """ Distance outside bid/ask in floored half spreads, per expiry, for every quote of the retained expiries """
884
+ return [ ( np.maximum( 0., fit_t - ask_t ) + np.maximum( 0., bid_t - fit_t ) ) / np.maximum( (ask_t - bid_t)/2., self.min_half_spread )
885
+ for fit_t, bid_t, ask_t in zip( fits, r.bids, r.asks ) ]
886
+
887
+ # The first fit weights all quotes equally. Each further fit weights quote i by 1/(excess_i + eps) with the excess
888
+ # of the previous fit: quotes which are inside or nearly inside become expensive to miss and quotes far outside cheap.
889
+ # This raises the number of quotes within bid/ask, at the expense of the quotes it gives up on. The fit with the
890
+ # highest share within bid/ask is kept.
891
+ surface = fit_surface( None )
892
+ num_surface_fits = 1
893
+ within = lambda exc : float( np.mean( np.concatenate(exc) <= 0. ) )
894
+ excess_k = excess( surface.fits )
895
+ first = best = within_k = within( excess_k )
896
+ if self.reweight_max_iter > 1:
897
+ for k in range( 1, self.reweight_max_iter ):
898
+ if within_k >= self.reweight_min_within:
899
+ break
900
+ weights = [ 1. / ( exc_t[mask_t] + self._reweight_eps ) for exc_t, mask_t in zip( excess_k, r.masks ) ]
901
+ scale = float( np.mean( np.concatenate(weights) ) )
902
+ surface_k = fit_surface( [ w / scale for w in weights ] )
903
+ num_surface_fits += 1
904
+ excess_k = excess( surface_k.fits )
905
+ previous, within_k = within_k, within( excess_k )
906
+ verbose.write(lambda : f"{surface_message()}: reweighted fit {k+1} has {within_k*100.:.2f}% of quotes within bid/ask, after {previous*100.:.2f}%." )
907
+ if within_k > best:
908
+ best, surface = within_k, surface_k
909
+ if within_k - previous < self._reweight_min_gain:
910
+ break
911
+
912
+ if info is not None:
913
+ info["num_surface_fits"] = num_surface_fits
914
+ info["within_first_fit"] = first
915
+ info["within_kept_fit"] = best
916
+ r.fitsX = surface.fits
917
+ r.mdensities = surface.xdensities
918
+ r.run_time_surface = tme.seconds
919
+
920
+ # make numpy
921
+ r._make_numpy()
922
+ return r
923
+
924
+ def surface_densities( self, *,
925
+ expiries : np.ndarray,
926
+ variances : np.ndarray,
927
+ strikes : list[np.ndarray],
928
+ asks : list[np.ndarray],
929
+ bids : list[np.ndarray],
930
+ masks : list[np.ndarray]|None,
931
+ xstrikes : list[np.ndarray],
932
+ xguessed_p : list[np.ndarray]|None = None,
933
+ quote_weights : list[np.ndarray]|None = None,
934
+ force_linear : bool = False,
935
+ hard_fit : bool = False,
936
+ message_context : callable|str|None = None,
937
+ verbose : Context = Context.quiet
938
+ ):
939
+ """
940
+ Stand-alone smooth or linear fit to a given surface
941
+
942
+ ``quote_weights`` optionally gives, per expiry, one weight per active quote. The weights multiply the distance outside
943
+ bid/ask in the objective or, if ``mid_fit_weight`` is 1 and there is no such term, the distance from the mid.
944
+ """
945
+ def message(with_cols : bool = True) -> str:
946
+ if message_context is None:
947
+ return ""
948
+ if callable(message_context):
949
+ msg = message_context()
950
+ else:
951
+ msg = str(message_context)
952
+ if msg == "":
953
+ return ""
954
+ assert msg[-2:] != ": ", f"Internal error: message_context should not end with ': ' found '{msg}'"
955
+ msg = msg[0].upper() + msg[1:]
956
+ if not with_cols:
957
+ return msg
958
+ return msg + ": "
959
+
960
+ T = len(expiries)
961
+ assert T == len(strikes) == len(xstrikes) == len(asks) == len(bids) == len(variances), f"Internal error: length of expiries {len(expiries)}, strikes {len(strikes)}, xstrikes {len(xstrikes)}, asks {len(asks)}, bids {len(bids)}, and variances {len(variances)} must all be the same."
962
+ assert xguessed_p is None or len(xguessed_p) == T, f"Internal error: length of xguessed_p {len(xguessed_p)} must be the same as length of expiries {T}."
963
+ assert masks is None or len(masks) == T, f"Internal error: length of masks {len(masks)} must be the same as length of expiries {T}."
964
+ assert quote_weights is None or len(quote_weights) == T, f"Internal error: length of quote_weights {len(quote_weights)} must be the same as length of expiries {T}."
965
+
966
+ with verbose.write_t(f"\r{message()}Finding {'linear' if self.smoothness is None else f'{self.smoothness:.2f}-smooth'} arbitrage-free prices {'between bid/ask ' if hard_fit else ''}across {sum( len(xt) for xt in xstrikes )} strikes... ", end='') as tme:
967
+ variables = []
968
+ constraints = []
969
+ objective = 0.
970
+ xdensities = []
971
+ CXs = []
972
+
973
+ avhs_sum = 0.
974
+ avhs_count = 0
975
+ for t in range(T):
976
+ mask_t = masks[t] if masks is not None and masks[t] is not None else slice(None,None)
977
+ avhs_sum += np.sum( asks[t][mask_t] - bids[t][mask_t] )/2.
978
+ avhs_count += len(asks[t][mask_t])
979
+ average_hspread = avhs_sum / max(1, avhs_count)
980
+ eff_mid_fit_weight = self.mid_fit_weight if not hard_fit else 1.
981
+ del avhs_sum, avhs_count
982
+
983
+ for t in range(T):
984
+ expiry = expiries[t]
985
+ strikes_t = strikes[t]
986
+ xstrikes_t = xstrikes[t]
987
+ mask_t = masks[t] if not masks is None else slice(None,None)
988
+ ask_t = asks[t][mask_t]
989
+ bid_t = bids[t][mask_t]
990
+ xguess_t = np.clip( xguessed_p[t], 0., None ) if not xguessed_p is None else None
991
+ assert xguess_t is None or xguess_t.shape == xstrikes_t.shape, f"Internal error: length of xguessed_p[{t}] {len(xguess_t)} must be the same as length of xstrikes[{t}] {len(xstrikes_t)}."
992
+
993
+ # density
994
+ q_t = cp.Variable(len(xstrikes_t), bounds=[0.,1.])#nonneg=True)
995
+ assert q_t.shape == (len(xstrikes_t),), f"Internal error: shape of q_t {q_t.shape} must be the same as length of xstrikes_t {len(xstrikes_t)}."
996
+ assert xguess_t is None or q_t.shape == xguess_t.shape, f"Internal error: shape of q_t {q_t.shape} must be the same as shape of xguess_t {xguess_t.shape}."
997
+ variables += [(q_t, xguess_t)]
998
+ constraints += [ cp.sum( q_t ) == 1.,
999
+ q_t @ xstrikes_t == 1., # martingale condition
1000
+ q_t <= 1.
1001
+ ]
1002
+
1003
+ # martingale
1004
+ Cm = np.maximum( 0., xstrikes_t[None,:] - xstrikes_t[1:-1,None] ) @ q_t # model strikes - do not use "call"
1005
+ if t>0:
1006
+ assert xstrikes[t-1].shape == xdensities[t-1].shape, f"Internal error {message()}: shape mismatch between previous and current mstrikes, {xstrikes[t-1].shape} vs {xdensities[t-1].shape}"
1007
+ Cm1 = np.maximum( 0., xstrikes[t-1][None,:] - xstrikes_t[1:-1,None] ) @ xdensities[t-1]
1008
+ constraints += [ Cm >= Cm1 ]
1009
+ else:
1010
+ Cm1 = np.maximum( 0., 1. - xstrikes_t[1:-1] ) # model strikes, previous density is dirac at 1
1011
+
1012
+ # dlv constaints
1013
+ # dC = 1/2 * dlvsq * x^2 * dt * K^2 / (1/2 (k^+ - k^-)) q
1014
+ box = xstrikes_t[1:-1]**2 * ( expiries[t] - ( expiries[t-1] if t>0 else 0. ) ) / ( xstrikes_t[2:] - xstrikes_t[:-2])
1015
+ if not self.min_dlv is None:
1016
+ constraints += [ Cm - Cm1 >= cp.multiply( box * (self.min_dlv**2), q_t[1:-1] ) ]
1017
+ if not self.max_dlv is None:
1018
+ constraints += [ Cm - Cm1 <= cp.multiply( box * (self.max_dlv**2), q_t[1:-1] ) ]
1019
+ del box, Cm1
1020
+
1021
+ # fit
1022
+ def call( spots, strikes ):
1023
+ if force_linear or self.smoothness is None or self.smoothness == 0. or expiry < ONE_MINUTE:
1024
+ return np.maximum( 0., spots - strikes )
1025
+ expiry_ = np.clip( expiry, expiries[0], expiries[-1] )
1026
+ vol = math.sqrt( self.smoothness * np.interp( expiry_, expiries, variances ) / expiry_ )
1027
+ assert np.isfinite(vol), f"Internal error: {message()}infinite vol"
1028
+ if vol == 0.:
1029
+ return np.maximum( 0., spots - strikes )
1030
+ return bs.price( k=strikes/spots, vol=vol, sqrtT=math.sqrt(expiry), eps=self._eps_price )*spots
1031
+
1032
+ CX = call( spots=xstrikes_t[None,:], strikes=strikes_t[:,None] )
1033
+ fit_mid = CX[mask_t,:] @ q_t # market strikes
1034
+ half_spread = (ask_t - bid_t)/2.
1035
+ mid_t = (bid_t + ask_t)/2.
1036
+ whalf_spread = np.maximum( half_spread, self.min_half_spread ) / average_hspread
1037
+
1038
+ if hard_fit:
1039
+ # the hard fit asks for a price within bid/ask, with a small margin for numerical precision
1040
+ constraints += [ fit_mid <= ask_t - half_spread * self._eps_hard_fit,
1041
+ fit_mid >= bid_t + half_spread * self._eps_hard_fit ]
1042
+
1043
+ # A slack per quote: zero while the fit is inside the (slightly tightened) bid/ask, otherwise the
1044
+ # distance outside in weighted half spreads.
1045
+ guess_fit = CX[mask_t,:] @ xguess_t if not xguess_t is None else None
1046
+ if eff_mid_fit_weight < 1.:
1047
+ e_init = np.clip( np.maximum( guess_fit - ask_t, bid_t - guess_fit ) / whalf_spread, 0., None) if guess_fit is not None else None
1048
+ e_box = cp.Variable(len(bid_t), bounds=[0.,1E6])#nonneg=True)
1049
+ assert e_init is None or e_box.shape == e_init.shape, f"Internal error: shape of e_box {e_box.shape} must be the same as shape of e_init {e_init.shape}."
1050
+ variables += [ (e_box, None) ]
1051
+
1052
+ constraints += [
1053
+ fit_mid <= ask_t - half_spread * self._eps_no_arb + cp.multiply(whalf_spread, e_box),
1054
+ fit_mid >= bid_t + half_spread * self._eps_no_arb - cp.multiply(whalf_spread, e_box)
1055
+ ]
1056
+
1057
+ omega_t = quote_weights[t] if quote_weights is not None else None
1058
+ objective += (1. - eff_mid_fit_weight) * ( cp.sum(e_box) if omega_t is None else cp.sum(cp.multiply(omega_t, e_box)) )
1059
+ del e_box
1060
+
1061
+ if eff_mid_fit_weight > 0.:
1062
+ # one variable per quote: the distance from the mid in weighted half spreads
1063
+ z_init = np.abs( guess_fit - mid_t ) / whalf_spread if guess_fit is not None else None
1064
+ z_mid = cp.Variable(len(bid_t), bounds=[0.,1E6])
1065
+ assert z_init is None or z_mid.shape == z_init.shape, f"Internal error: shape of z_mid {z_mid.shape} must be the same as shape of z_init {z_init.shape}."
1066
+ variables += [ (z_mid, None) ]
1067
+
1068
+ constraints += [
1069
+ fit_mid - mid_t <= cp.multiply(whalf_spread, z_mid),
1070
+ mid_t - fit_mid <= cp.multiply(whalf_spread, z_mid),
1071
+ ]
1072
+
1073
+ omega_t = quote_weights[t] if quote_weights is not None and eff_mid_fit_weight >= 1. else None
1074
+ objective += eff_mid_fit_weight * ( cp.sum(z_mid) if omega_t is None else cp.sum(cp.multiply(omega_t, z_mid)) )
1075
+ del z_mid
1076
+
1077
+ xdensities.append(q_t)
1078
+ CXs.append(CX)
1079
+
1080
+ # HiGHS first, Clarabel second. A smooth surface couples every strike of every expiry; the simplex
1081
+ # method rarely finishes such a problem within the time limit, so HiGHS uses its interior-point method.
1082
+ smooth = not (force_linear or self.smoothness is None)
1083
+ primary = "ipm" if smooth else "simplex"
1084
+
1085
+ def solve( algorithm : str, no_fallback : bool = False ):
1086
+ return SanosLPSolver(timeout_seconds=self.timeout_seconds,
1087
+ algorithm=algorithm,
1088
+ no_fallback=no_fallback,
1089
+ _debug_verbose_cvxpy=self._debug_verbose_cvxpy)(
1090
+ objective=objective,
1091
+ variables=variables,
1092
+ constraints=constraints,
1093
+ message_context=lambda : message(False),
1094
+ verbose=verbose )
1095
+
1096
+ def share_within() -> float:
1097
+ """ Share of the fitted quotes whose current fit lies within bid/ask """
1098
+ inside = total = 0
1099
+ for t in range(T):
1100
+ mask_t = masks[t] if not masks is None else slice(None,None)
1101
+ fit_t = CXs[t][mask_t,:] @ xdensities[t].value
1102
+ inside += int(np.sum( (fit_t >= bids[t][mask_t] - 1E-9) & (fit_t <= asks[t][mask_t] + 1E-9) ))
1103
+ total += len(fit_t)
1104
+ return inside / max(1, total)
1105
+
1106
+ success, status, fell_back = solve( primary )
1107
+
1108
+ # A solver which stopped early returns a point which satisfies the constraints but need not be close
1109
+ # to the optimum. If fewer than EARLY_STOP_MIN_WITHIN of the quotes are fitted, the other solver runs
1110
+ # and the better of the two results is kept.
1111
+ if success and status != "optimal" and not fell_back:
1112
+ share = share_within()
1113
+ if share < EARLY_STOP_MIN_WITHIN:
1114
+ other = "clarabel"
1115
+ kept = [ v.value.copy() for v, _ in variables ]
1116
+ warnings.warn(f"{message()}Solver stopped early with status '{status}' and {share*100.:.1f}% of quotes within bid/ask; running the other solver ('{other}').")
1117
+ success2, status2, _ = solve( other, no_fallback=True )
1118
+ share2 = share_within() if success2 else -1.
1119
+ if success2 and ( status2 == "optimal" or share2 > share ):
1120
+ status, fell_back = status2, True
1121
+ else:
1122
+ for (v, _), value in zip( variables, kept ):
1123
+ v.value = value
1124
+
1125
+ if fell_back:
1126
+ verbose.write(lambda : f"had to fall back to a slower solver... ", head=False, end='' )
1127
+
1128
+ if not success:
1129
+ if status in ["infeasible", "infeasible_inaccurate"]:
1130
+ if hard_fit:
1131
+ return None
1132
+ raise RuntimeError(f"{message()}Cannot find no-arbitrage surface mids: problem infeasible??")
1133
+ if status in ["unbounded", "unbounded_inaccurate", "infeasible_or_unbounded"]:
1134
+ raise RuntimeError(f"{message()}Cannot find no-arbitrage surface mids: problem unbounded? This should not happen. Please contact the authors with an example.")
1135
+ if hard_fit:
1136
+ # the hard bid/ask fit is an optional refinement: on a time limit or numerical
1137
+ # trouble the caller keeps its soft fit
1138
+ return None
1139
+ if status == "user_limit":
1140
+ raise RuntimeError(f"{message()}Cannot find no-arbitrage surface mids: reached timeout {self.timeout_seconds} and/or iteration limit.")
1141
+ raise RuntimeError(f"{message()}Cannot find no-arbitrage surface mids: solver returned status '{status}'.")
1142
+
1143
+ if status != "optimal":
1144
+ verbose.write(lambda : f"solver returned '{status}' -- proceeding anyway... ", head=False, end='' )
1145
+
1146
+ # compute call prices for the original strikes
1147
+ fits = []
1148
+ xdensities = [ q.value for q in xdensities ]
1149
+ for t in range(T):
1150
+ expiry = expiries[t]
1151
+ strikes_t = strikes[t]
1152
+ xstrikes_t = xstrikes[t]
1153
+ CX = CXs[t]
1154
+ q_t = xdensities[t]
1155
+ if np.min(q_t) < -self._eps_density or abs( np.sum( q_t )-1. ) > self._eps_dens_1 or abs( q_t@xstrikes_t - 1. ) > self._eps_dens_1:
1156
+ warnings.warn(f"{message()}Warning: no-arbitrage density does not satisfy basic properties after optimization: min {q_t.min():.3e}, sum {q_t.sum():.6f}, integral {q_t@xstrikes_t:.6f} -- attempting fix.")
1157
+ q_t = warn_and_fix_density( xstrikes_t, q_t, eps=self._eps_density, message = lambda : f"{message()}expiry {expiry*DAYS_PER_YEAR:.2f}d: surface density after optimization" )
1158
+
1159
+ # zero out some density
1160
+ floor = max( self.min_density / float(len(q_t)), self._eps_density ) if IMPOSE_FLOOR_ON_DENSITY else 0.
1161
+ is_zero = q_t < floor
1162
+ if np.any(is_zero):
1163
+ q_t[is_zero] = 0.
1164
+ q_t = warn_and_fix_density( xstrikes_t, q_t, eps=self._eps_density, message = lambda : f"{message()} expiry {expiry*DAYS_PER_YEAR:.2f}d: surface density" )
1165
+ xdensities[t] = q_t
1166
+ fit_t = CX @ q_t
1167
+ assert fit_t.shape == strikes_t.shape, f"Internal error: {message()}Shape of fit_t {fit_t.shape} does not match shape of strikes_t {strikes_t.shape}"
1168
+ fits.append( fit_t )
1169
+ verbose.write(lambda : f"done. This took {tme}.", head=False )
1170
+
1171
+ # make numpy
1172
+ return PrettyObject(
1173
+ xdensities = xdensities,
1174
+ fits = fits,
1175
+ CXs = CXs)
1176
+
1177
+ def expiry_density(self, *,
1178
+ expiry : float,
1179
+ variance : float,
1180
+ strikes_t : np.ndarray,
1181
+ bid_t : np.ndarray,
1182
+ ask_t : np.ndarray,
1183
+ mask_t : np.ndarray|None,
1184
+ xstrikes_t : np.ndarray,
1185
+ force_linear : bool = False,
1186
+ message_context : str|callable|None = None,
1187
+ verbose : Context = Context.all,
1188
+ end : str = "\n") -> tuple[np.ndarray, np.ndarray]:
1189
+ """
1190
+ Fit a single expiry given market and model strikes.
1191
+
1192
+ This function will first attempt a soft fit. If that soft fit is within bid/ask for all ``strikes_t``
1193
+ the function returns. If this fit is not within bid/ask, then the
1194
+ function attempts a hard fit in the soft fit starting point. It successful, it returns
1195
+ the hard fit. If not successful it returns the soft fit, which is not all within bid/ask.
1196
+
1197
+ Parameters
1198
+ -----------
1199
+ expiry: float
1200
+ Time to expiry in years.
1201
+ variance : float | None
1202
+ Variance for the expiry, used only if ``self.smoothness`` is not None.
1203
+ If ``variance`` is zero or ``None``, the function attempts a linear fit.
1204
+ strikes_t : np.ndarray
1205
+ Strikes for the expiry.
1206
+ bid_t : np.ndarray
1207
+ Bid prices for the strikes.
1208
+ ask_t : np.ndarray
1209
+ Ask prices for the strikes.
1210
+ xstrikes_t : np.ndarray
1211
+ Strikes for the density grid. The first and last point should be outside the range of strikes_t, and the rest should include all strikes_t.
1212
+ force_linear : boo,l, default ``False``
1213
+ If ``True``, the function attempts a linear fit even if ``self.smoothness`` is not None or the variance is positive.
1214
+ message_context : str|callable|None, default ``None``
1215
+ Optional context for error and debug messages. If a string is provided, it is used as a prefix for all messages.
1216
+ If a callable is provided, it is called to generate the message prefix at each call site.
1217
+ verbose : Context, default ``Context.all``
1218
+ Verbosity context for logging messages.
1219
+ end : str, default ``"\n"``
1220
+ For ``verbose`` output: how to end the output. Using ``end=''`` will surpess a line feed.
1221
+
1222
+ Returns
1223
+ -------
1224
+ Fit : ``tuple[np.ndarray, np.ndarray, bool]``
1225
+ Returns a tuple with:
1226
+
1227
+ * ``xdensity``: the fitted density on the xstrikes_t grid
1228
+ * ``fit``: the fitted call prices on the strikes_t grid
1229
+ """
1230
+ def message(with_cols : bool = True) -> str:
1231
+ if message_context is None:
1232
+ return ""
1233
+ if callable(message_context):
1234
+ msg = message_context()
1235
+ else:
1236
+ msg = str(message_context)
1237
+ if msg == "":
1238
+ return ""
1239
+ msg = msg[0].upper() + msg[1:]
1240
+ if not with_cols:
1241
+ return msg
1242
+ return msg + ": "
1243
+
1244
+ assert expiry > 0, f"Internal error {message(False)}: expiry must be positive, but found {expiry}"
1245
+ assert variance >= 0, f"Internal error {message(False)}: variance must be non-negative, but found {variance}"
1246
+ assert strikes_t.shape == bid_t.shape == ask_t.shape, f"Internal error{message(False)}: strikes_t, bid_t and ask_t must all have the same shape, but found {strikes_t.shape}, {bid_t.shape} and {ask_t.shape}"
1247
+
1248
+ # find fit between bid/ask without hard constraints first
1249
+ # -------------------------------------------------------
1250
+ tme = verbose.timer()
1251
+
1252
+ # soft fit first
1253
+ # --------------
1254
+
1255
+ expiries = np.array([expiry], dtype=np.float64)
1256
+ variances = np.array([variance], dtype=np.float64) if not variance is None else None
1257
+ msk_t = mask_t if not mask_t is None else slice(None,None)
1258
+
1259
+ r = self.surface_densities(
1260
+ expiries = expiries,
1261
+ variances = variances,
1262
+ strikes = [strikes_t],
1263
+ asks = [ask_t],
1264
+ bids = [bid_t],
1265
+ masks = [mask_t] if not mask_t is None else None,
1266
+ xstrikes = [xstrikes_t],
1267
+ xguessed_p = None,
1268
+ hard_fit = False,
1269
+ force_linear = force_linear,
1270
+ message_context = lambda : message(False),
1271
+ verbose = Context.quiet
1272
+ )
1273
+ assert not r is None, "Internal error"
1274
+ xdensity = r.xdensities[0]
1275
+ fit = r.fits[0]
1276
+ does_fit = (fit > bid_t - self._eps_price) & (fit < ask_t + self._eps_price)
1277
+ does_fit_msk = does_fit[msk_t]
1278
+ smoothness = self.smoothness if not force_linear else None
1279
+
1280
+ if np.all(does_fit_msk):
1281
+ verbose.write(lambda : f"\r{message()}Soft {'linear' if smoothness is None else f'{smoothness:.2f}-smooth'} per-expiry no-arbitrage fit succeeded within bid/ask. This took {tme}.", end=end)
1282
+ return xdensity, fit
1283
+
1284
+ # hard fit
1285
+ # --------
1286
+
1287
+ r = self.surface_densities(
1288
+ expiries = expiries,
1289
+ variances = variances,
1290
+ strikes = [strikes_t],
1291
+ asks = [ask_t],
1292
+ bids = [bid_t],
1293
+ masks = [mask_t] if not mask_t is None else None,
1294
+ xstrikes = [xstrikes_t],
1295
+ xguessed_p = [xdensity],
1296
+ hard_fit = True,
1297
+ force_linear = force_linear,
1298
+ message_context = lambda : message(False),
1299
+ verbose = verbose
1300
+ )
1301
+
1302
+ if not r is None:
1303
+ fit = r.fits[0]
1304
+ does_fit = (fit > bid_t - self._eps_price) & (fit < ask_t + self._eps_price)
1305
+ does_fit_msk = does_fit[msk_t]
1306
+ assert np.all( does_fit_msk ), "Internal error: hard fit did not fit within bid/ask??"
1307
+ verbose.write(lambda : f"\r{message()}Hard {'linear' if smoothness is None else f'{smoothness:.2f}-smooth'} per-expiry no-arbitrage fit succeeded within bid/ask. This took {tme}.", end=end)
1308
+ return r.xdensities[0], r.fits[0]
1309
+
1310
+ verbose.write(lambda : f"\r{message()}Could not hard fit with {'linear' if smoothness is None else f'{smoothness:.2f}-smooth'} per-expiry no-arbitrage -- using masked soft fit instead which is outside bid/ask for {np.sum(~does_fit_msk)} of {len(does_fit_msk)} options. This took {tme}.")
1311
+ return xdensity, fit
1312
+
1313
+ def make_extended_strikes( self,
1314
+ strikes: np.ndarray,
1315
+ bids: np.ndarray,
1316
+ asks: np.ndarray, *,
1317
+ prev_lower : float|None = None,
1318
+ prev_upper : float|None = None,
1319
+ message_context : str|None = None ) -> tuple[np.ndarray, np.ndarray, str|None]:
1320
+ r"""
1321
+ Utility function to generate an increasing range of extended strikes such that
1322
+ outside points are sufficiently far away, c.f. https://arxiv.org/abs/2601.11209 remark 2.7.
1323
+
1324
+ Essentially, given strikes $K_1,\ldots,K_{n-1}$ and mid-prices $C_1,\ldots,C_n$, we want to find $K_0 < K_1$ and $K_{n+1} > K_n$
1325
+ with call price values equal to intrinsic value such that the boundary conditions
1326
+ $-1 < \frac{C_1 - C_0}{K_1 - K_0}$ and $\frac{C_{n+1} - C_n}{K_{n+1} - K_n} < 0$ are satisfied.
1327
+
1328
+ **Lower strike**
1329
+
1330
+ Let $dC_1 = \frac{C_2 - C_1}{K_2 - K_1}$ be the slope of the line connecting the point $(K_1,C_1)$ to the point $(K_2,C_2)$.
1331
+ Then we want to find $K_0$ with $C_0 = 1 - K_0$ such that:
1332
+ $$
1333
+ -1 <= \frac{ C_1 - C_0 }{ K_1 - K_0 } \leq dC_1 \ .
1334
+ $$
1335
+ If $dC_1$ is not greater than -1, we drop $K_1$ and proceed. Once $dC_1$ is greater than -1, we can chose any strike below
1336
+ $$
1337
+ K_0 \leq \frac{1 - C_1 + K_1 dC_1}{1 + dC_1}
1338
+ $$
1339
+ which is positive. If $K_0$ is non-positive, we will drop $K_1$ from the strike list and proceed to the next strike.
1340
+
1341
+ The actual strike used is $K'_0 := \max\{ K_0/2, K_0 - 2 ( K_1 - K_0 ) \}$.
1342
+
1343
+ The new lower strike will thenn be the minimum of above calculation and ``prev_lower``, if provided.
1344
+
1345
+ **Upper strike**
1346
+
1347
+ Let $dC_{n-1} := \frac{C_n - C_{n-1}}{K_n - K_{n-1}}$ be the slope of the line connecting the point $(K_{n-1},C_{n-1})$ to the point $(K_n,C_n)$.
1348
+ Then we want to find $K_n$ with $C_n = 0$ such that
1349
+ $$
1350
+ dC_{n-1} \leq \frac{ C_{n+1} - C_n }{ K_{n+1} - K_n } \leq 0 \.
1351
+ $$
1352
+ If $dC_{n-1} >= 0$ we drop $K_n$. Once $dC_{n-1}$ is negative, we can chose any strike above
1353
+ $$
1354
+ K_{n+1} \geq K_n - \frac{C_n}{dC_{n-1}} \ .
1355
+ $$
1356
+
1357
+ The actual strike used is $K'_{n+1} := K_n + 2 ( K_{n+1} - K_n )$.
1358
+
1359
+ The new upper strike will then be the maximum of above calculation and ``prev_upper``, if provided.
1360
+
1361
+ Parameters
1362
+ ----------
1363
+ strikes : np.ndarray
1364
+ Array of strikes for the expiry, must be strictly increasing and positive.
1365
+ bids : np.ndarray
1366
+ Array of bid prices for the expiry, must have the same shape as strikes.
1367
+ asks : np.ndarray
1368
+ Array of ask prices for the expiry, must have the same shape as strikes and be strictly greater than bids.
1369
+ prev_lower : float | None, default ``None``
1370
+ Previous lower strike from the previous expiry, if any. The new lower strike will be the minimum of the calculated lower strike and this value, if provided.
1371
+ prev_upper : float | None, default ``None``
1372
+ Previous upper strike from the previous expiry, if any. The new upper strike will be the maximum of the calculated upper strike and this value, if provided.
1373
+ message_context : callable | None, default ``None``
1374
+ Optional callable that returns a string to be used as a header in error messages.
1375
+ This can be used to provide context such as the expiry time and other relevant information.
1376
+
1377
+ Returns
1378
+ -------
1379
+ Extended strikes: tuple[np.ndarray, np.ndarray, str|None]
1380
+ A tuple containing the extended ``xstrikes``, the corresponding ``mask`` to map from input strikes to extended strikes, and an optional ``notice`` to be printed to the user
1381
+ in verbose mode.
1382
+
1383
+ The relation between input strikes, mask, and output "xstrikes" is
1384
+ ```
1385
+ xstrikes[1:-1] == strikes[mask]
1386
+ ```
1387
+ """
1388
+ def message(with_cols : bool = True) -> str:
1389
+ if message_context is None:
1390
+ return ""
1391
+ if callable(message_context):
1392
+ msg = message_context()
1393
+ else:
1394
+ msg = str(message_context)
1395
+ if msg == "":
1396
+ return ""
1397
+ msg = msg[0].upper() + msg[1:]
1398
+ if not with_cols:
1399
+ return msg
1400
+ return msg + ": "
1401
+
1402
+ input_strikes_t = strikes
1403
+ input_bid_t = bids
1404
+ input_ask_t = asks
1405
+ notice = None
1406
+ xstrikes_t = input_strikes_t
1407
+ bid_t = input_bid_t
1408
+ ask_t = input_ask_t
1409
+ mid_t = (input_bid_t + input_ask_t)/2.
1410
+ mask_t = np.ones(input_strikes_t.shape[0], dtype=bool)
1411
+
1412
+ verify_inp( len(xstrikes_t) >= self.min_strikes_per_expiry, f"{message()}At least {self.min_strikes_per_expiry} strikes are required for this expiry, but found {len(xstrikes_t)}.")
1413
+ verify_inp( xstrikes_t.shape == bid_t.shape == ask_t.shape, lambda : f"{message()}Expected strikes, bids and asks to have the same shape for expiry, found {xstrikes_t.shape}, {bid_t.shape}, {ask_t.shape}")
1414
+ verify_inp( np.all( np.diff(xstrikes_t) > 0 ), lambda : f"{message()}Strikes must be strictly increasing; found minimal difference {np.diff(xstrikes_t).min():.3f}" )
1415
+ verify_inp( xstrikes_t[0] > 0., lambda : f"{message()}Lowest strike must be positive; found {xstrikes_t[0]:.3f}" )
1416
+ verify_inp( np.all( ask_t - bid_t >0. ), lambda : f"{message()}All ask prices must be greater than bid prices.")
1417
+
1418
+ # extend strike range with boundary strikes
1419
+ # -----------------------------------------
1420
+ # At K_0 and K_n call prices are intrinsic
1421
+ # -1 <= { C_1 - C_0 }/{ K_1 - K_0 } <= dC_1
1422
+ # Assuming -1 < dC_1 and noting that K_0 < K_1
1423
+ # { 1 - K_0 - C_1) >= dC_1 (K_0 - K_1) =>
1424
+ # 1 - C_1 + K_1 dC_1 >= K_0 (1 + dC_1) =>
1425
+ # K_0 <= (1 - C_1 + K_1 dC_1)/(1 + dC_1)
1426
+ #
1427
+ # Assume that this is violated:
1428
+ # Buy the 0 strike for C_0 (the ask)
1429
+
1430
+ assert self.min_dC_eps > 0., f"Internal error: min_dC_eps {self.min_dC_eps} must be positive."
1431
+ total_input = len(xstrikes_t)
1432
+ N = xstrikes_t.shape[0]
1433
+
1434
+ lower_k = None
1435
+ for ileft in range(N-2):
1436
+ C_0 = mid_t[ileft]
1437
+ C_1 = mid_t[ileft+1]
1438
+ K_0 = xstrikes_t[ileft]
1439
+ K_1 = xstrikes_t[ileft+1]
1440
+ dC_0 = ( C_1 - C_0 )/( K_1 - K_0 )
1441
+ if dC_0+1. > self.min_dC_eps:
1442
+ lower_k = (1 - C_1 + K_1 * dC_0)/(1 + dC_0)
1443
+ if lower_k > 0. and lower_k < K_1:
1444
+ break
1445
+ lower_k = None
1446
+ if ileft == N-2 or lower_k is None:
1447
+ raise RuntimeError(f"{message()}Could not find consistent initial strike for this expiry.")
1448
+ upper_k = None
1449
+ for iright in range(N-2,ileft-1,-1):
1450
+ C_Nm1 = mid_t[iright]
1451
+ C_N = mid_t[iright+1]
1452
+ K_Nm1 = xstrikes_t[iright]
1453
+ K_N = xstrikes_t[iright+1]
1454
+ dC_Nm1 = ( C_Nm1 - C_N )/( K_Nm1 - K_N )
1455
+ if dC_Nm1 < -self.min_dC_eps:
1456
+ upper_k = K_Nm1 - C_Nm1/dC_Nm1
1457
+ if upper_k > K_Nm1:
1458
+ break
1459
+ upper_k = None
1460
+ if iright <= ileft or upper_k is None:
1461
+ raise RuntimeError(f"{message()}Could not find consistent terminal strike for this expiry.")
1462
+
1463
+ if ileft > 0 or iright < N-2:
1464
+ slc = slice( ileft, iright+1 )
1465
+ xstrikes_t = xstrikes_t[slc]
1466
+ bid_t = bid_t[slc]
1467
+ ask_t = ask_t[slc]
1468
+ mask_t[:] = False
1469
+ mask_t[slc] = True
1470
+ assert np.all( xstrikes_t == input_strikes_t[mask_t] ), "Mask error...(2) ?"
1471
+
1472
+ if len(xstrikes_t) < total_input:
1473
+ removed_count = total_input - len(xstrikes_t)
1474
+ notice = lambda removed_count=removed_count, total_input=total_input: f"removed {removed_count} out of {total_input} strikes to ensure -1 < dC/dK[0] and dC/dK[-1] < 0"
1475
+
1476
+ dK0 = K_1 - lower_k
1477
+ lower_k = max( lower_k/2., K_1 - dK0*2. )
1478
+ dkN = upper_k - K_Nm1
1479
+ upper_k = K_Nm1 + dkN*2.
1480
+
1481
+ if lower_k >= 1.:
1482
+ lower_k = 1.-(xstrikes_t[1]-xstrikes_t[0])
1483
+ if upper_k <= 1.:
1484
+ upper_k = 1.+(xstrikes_t[1]-xstrikes_t[0])
1485
+
1486
+ # previous step?
1487
+ lower_k = min(lower_k, prev_lower) if not prev_lower is None else lower_k
1488
+ upper_k = max(upper_k, prev_upper) if not prev_upper is None else upper_k
1489
+ xstrikes_t = np.concatenate(([lower_k], xstrikes_t, [upper_k]))
1490
+
1491
+ assert np.all( bid_t == input_bid_t[mask_t] ), "Mask error...?"
1492
+ assert np.all( ask_t == input_ask_t[mask_t] ), "Mask error...?"
1493
+ assert np.all( xstrikes_t[1:-1] == input_strikes_t[mask_t] ), "Mask error...?"
1494
+ return xstrikes_t, mask_t, notice