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,581 @@
1
+ """
2
+ Daily arbitrage-free fits of WIDB option books
3
+ ==============================================
4
+
5
+ :func:`arb_free_model_day` fits an arbitrage-free surface to the full cleaned book of one day and caches the model
6
+ with its fit statistics; :func:`mk_arb_free_day` returns the day's rows with the fitted prices. The fitter removes
7
+ strikes, and whole expiries, where no arbitrage-free price exists within bid/ask.
8
+
9
+ Example
10
+ -------
11
+ >>> import datetime as dt
12
+ >>> from openqdata.widb.arbfree import fit_config, mk_arb_free_day
13
+ >>>
14
+ >>> rows = mk_arb_free_day("SPX", dt.date(2023, 1, 17), mk_arb_free=fit_config(0.1), override_cache_mode="cacheonly")
15
+ >>> print(rows[["pure_strike", "mask_arb_free", "pure_fit1_price", "pure_fitX_price"]])
16
+
17
+ The batch command fits every business day of a period::
18
+
19
+ python -m openqdata.widb.arbfree SPX --period 2020-05-01 2022-01-31 --smoothness 0.1
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import datetime as dt
24
+ import math
25
+ import warnings
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+ from cdxcore.bs import bs
30
+ from cdxcore.subdir import CacheMode, SubDir
31
+ from cdxcore.uniquehash import named_unique_filename48_8
32
+ from cdxcore.util import fmt_date, fmt_list, verify_inp
33
+ from cdxcore.verbose import Context
34
+
35
+ from openqdata.arbfree.arbfree import ArbFreePricer, MkArbFree
36
+ from openqdata.utils.pd import create_empty_df, restore_object_strings, verify_schema
37
+ from openqdata.widb.day import (
38
+ _GREEK_CALC_EPS,
39
+ _IMPLIED_VOL_CALC_EPS,
40
+ ENRICHED_PER_DAY_FIELDS,
41
+ ENRICHED_PER_EXPIRY_FIELDS,
42
+ SCHEMA_ENRICHED_DAY,
43
+ ExpiryFilter,
44
+ RawDayFilter,
45
+ _processing,
46
+ enrich_day,
47
+ )
48
+
49
+ SCHEMA_ARB_FREE_DAY_EXPIRY = SCHEMA_ENRICHED_DAY | {
50
+ "mask_arb_free": np.dtype("bool"),
51
+ "fit1_vol": np.dtype("float32"),
52
+ "pure_fit1_price": np.dtype("float32"),
53
+ "pure_fit1_delta": np.dtype("float32"),
54
+ "pure_fit1_gamma": np.dtype("float32"),
55
+ "pure_fit1_vega": np.dtype("float32"),
56
+ "pure_fit1_theta": np.dtype("float32"),
57
+ "pure_fit1_dk": np.dtype("float32"),
58
+ }
59
+ """ Fields and their types when arbitrage mode is ``"expiry"``. """
60
+
61
+ SCHEMA_ARB_FREE_DAY_SURFACE = SCHEMA_ARB_FREE_DAY_EXPIRY | {
62
+ "fitX_vol": np.dtype("float32"),
63
+ "pure_fitX_price": np.dtype("float32"),
64
+ "pure_fitX_delta": np.dtype("float32"),
65
+ "pure_fitX_gamma": np.dtype("float32"),
66
+ "pure_fitX_vega": np.dtype("float32"),
67
+ "pure_fitX_theta": np.dtype("float32"),
68
+ "pure_fitX_dk": np.dtype("float32"),
69
+ }
70
+ """ Fields and their types when arbitrage mode is ``"surface"``. """
71
+
72
+
73
+
74
+ def _market_groups(ticker: str, d: dt.date, data: pd.DataFrame):
75
+ """Split enriched rows into per-expiry frames and pure quote arrays, sorted by expiry id."""
76
+ expiry_ids = data["expiry_id"].to_numpy()
77
+ unique_expiry_ids = np.unique(expiry_ids)
78
+ grouped_frames: list[pd.DataFrame] = []
79
+ expiries_d : list[dt.date] = []
80
+ is_ams : list[bool] = []
81
+ expiries: list[float] = []
82
+ strikes: list[np.ndarray] = []
83
+ bids: list[np.ndarray] = []
84
+ asks: list[np.ndarray] = []
85
+
86
+ assert data[data['pure_ask_price']<=data['pure_bid_price']].empty, f"{ticker} {d}: found {len(data[data['pure_ask_price']<=data['pure_bid_price']])} options with ask price below or equal to bid price. These options should have been filtered out by the expiry filter. Please check the enriched day data for details."
87
+
88
+ for expiry_id in unique_expiry_ids:
89
+ group = data.loc[expiry_ids == expiry_id].sort_values("pure_strike", kind="stable").reset_index(drop=True)
90
+ grouped_frames.append(group)
91
+ expiries.append(float(group["tte_y"].iloc[0]))
92
+ expiries_d.append(group["expiry"].iloc[0])
93
+ is_ams.append(group["is_am"].iloc[0])
94
+ strikes.append(group["pure_strike"].to_numpy(dtype=np.float64))
95
+ bids.append(group["pure_bid_price"].to_numpy(dtype=np.float64))
96
+ asks.append(group["pure_ask_price"].to_numpy(dtype=np.float64))
97
+
98
+ if len(expiries) > 1 and np.min( np.diff(expiries) ) <= 0:
99
+ text = ""
100
+ for xid, expiry, date, is_am, ks in zip(unique_expiry_ids, expiries, expiries_d, is_ams, strikes, strict=True):
101
+ text += f"Expiry ID {xid} has expiry {expiry} on date {date} (AM: {is_am}) with {len(ks)} strikes\n"
102
+ warnings.warn("*** Error:\n"+text)
103
+ assert np.min( np.diff(expiries) ) > 0, f"{ticker} {d}: expiries are expected to be strictly increasing."
104
+ return unique_expiry_ids, grouped_frames, np.asarray(expiries, dtype=np.float64), strikes, bids, asks
105
+
106
+
107
+ #: Fit settings of the WIDB benchmark data per smoothness (None is the linear surface); see :func:`fit_config`.
108
+ FIT_SETTINGS = {
109
+ None: dict(mid_fit_weight=1.), # mid fit: as good as the bid/ask fit here, and faster
110
+ 0.1: dict(mid_fit_weight=0.01, reweight_max_iter=4, reweight_min_within=0.9), # bid/ask fit, reweighted on the few days below 90%
111
+ 0.25: dict(mid_fit_weight=1., reweight_max_iter=4, reweight_min_within=0.75), # mid fit, reweighted on days below 75%
112
+ }
113
+
114
+
115
+ def fit_config(smoothness: float | None = None, **overrides) -> MkArbFree:
116
+ """
117
+ The fit configuration of the WIDB benchmark data for a smoothness level.
118
+
119
+ The stored fits are identified by their configuration, so the batch command, the fit statistics and any reader
120
+ must use the same one: ``arb_free_model_day("SPX", d, mk_arb_free=fit_config(0.1))``. The settings per smoothness
121
+ are in :data:`FIT_SETTINGS`; a smoothness not listed there uses the settings of 0.1. ``overrides`` replace
122
+ individual :class:`MkArbFree` fields, for example ``timeout_seconds``.
123
+ """
124
+ smoothness = None if smoothness is None or smoothness == 0. else float(smoothness)
125
+ settings = FIT_SETTINGS.get(smoothness, FIT_SETTINGS[0.1])
126
+ return MkArbFree(**( dict(smoothness=smoothness) | settings | { k: v for k, v in overrides.items() if v is not None } ))
127
+
128
+
129
+ #: A day fit with fewer than this share of quotes within bid/ask is a failure: it raises and is not stored.
130
+ FAIL_MIN_WITHIN = 0.25
131
+
132
+
133
+ def fit_model(ticker: str, d: dt.date, data: pd.DataFrame, mk_arb_free: MkArbFree, verbose: Context = Context.quiet) -> dict:
134
+ """Fit ``mk_arb_free`` to enriched rows and return the model with its fit statistics.
135
+
136
+ Returns a dictionary suitable for HDF5 storage:
137
+
138
+ * ``empty``: whether no expiry could be fitted (then ``model`` is absent).
139
+ * ``model``: :meth:`ArbFreePricer.to_dict`; restore with :meth:`ArbFreePricer.from_dict`.
140
+ * ``stats``: fit statistics on all input quotes, including strikes the fitter masked:
141
+ ``num_options``, ``num_input_expiries``, ``num_expiries``, ``dropped_expiry_ids``,
142
+ ``num_outside`` and ``fraction_outside`` (outside bid/ask), ``mean_excess`` and ``median_excess``
143
+ (conditional on being outside, in half-spreads), ``run_time_expiry`` and ``run_time_surface`` (seconds),
144
+ ``num_surface_fits`` (above 1 if the surface fit was reweighted), ``within_first_fit`` and ``within_kept_fit`` (share of the quotes of the
145
+ retained expiries within bid/ask after the first surface fit and in the fit kept; the gain of the reweighting is their difference).
146
+ Fits stored before these fields existed lack them.
147
+
148
+ The fit fails with :class:`RuntimeError` if the fitter finds no point which satisfies its constraints within
149
+ numerical tolerance, or if fewer than ``FAIL_MIN_WITHIN`` of the quotes end up within bid/ask.
150
+ """
151
+ unique_expiry_ids, _, expiries, strikes, bids, asks = _market_groups(ticker, d, data)
152
+ info = {}
153
+ model = mk_arb_free(expiries=expiries, strikes=strikes, bids=bids, asks=asks,
154
+ message_context=lambda: f"{ticker} {d}", info=info, verbose=verbose)
155
+ kept = [] if model.input_index is None else [int(i) for i in model.input_index]
156
+ stats = dict(
157
+ num_options = int(sum(len(k) for k in strikes)),
158
+ num_input_expiries = int(len(expiries)),
159
+ num_expiries = int(len(model.expiries)),
160
+ dropped_expiry_ids = np.asarray([unique_expiry_ids[i] for i in range(len(expiries)) if i not in kept], dtype=np.int64),
161
+ run_time_expiry = float(model.run_time_expiry or 0.),
162
+ run_time_surface = float(model.run_time_surface or 0.),
163
+ num_surface_fits = int(info.get("num_surface_fits", 0)),
164
+ within_first_fit = float(info.get("within_first_fit", np.nan)),
165
+ within_kept_fit = float(info.get("within_kept_fit", np.nan)),
166
+ )
167
+ if len(model.expiries) == 0:
168
+ return dict(empty=True, stats=stats | dict(num_outside=0, fraction_outside=0., mean_excess=0., median_excess=0.))
169
+ fit = model.compute_market_fit(expiries=expiries, strikes=strikes, bids=bids, asks=asks, and_vols=False)
170
+ errors = np.concatenate(fit.fit_errs)
171
+ stats |= dict(num_outside=int((errors > 0.).sum()), fraction_outside=float(fit.pcnt_fit),
172
+ mean_excess=float(fit.mean_err), median_excess=float(fit.median_err))
173
+ within = 1. - stats["fraction_outside"]
174
+ if within < FAIL_MIN_WITHIN:
175
+ raise RuntimeError(f"{ticker} {d}: fit failed: only {within*100.:.1f}% of quotes are within bid/ask, below the minimum of {FAIL_MIN_WITHIN*100.:g}%.")
176
+ return dict(empty=False, model=model.to_dict(), stats=stats)
177
+
178
+
179
+ def _model_uid(ticker, d, raw_day_filter, expiry_filter, mk_arb_free) -> str:
180
+ return (
181
+ f"model/{named_unique_filename48_8(f'{str(expiry_filter)},{str(raw_day_filter)},{str(mk_arb_free)}', expiry_filter, raw_day_filter, mk_arb_free)}"
182
+ f"/{ticker}/{fmt_date(d)}"
183
+ )
184
+
185
+ @_processing(fmt=SubDir.PYTREE_HDF5).cache(
186
+ "0.1",
187
+ dependencies=[enrich_day, MkArbFree],
188
+ uid=_model_uid,
189
+ exclude_args=["verbose", "enriched_data", "raise_if_bad_day", "refresh_cache"],
190
+ )
191
+ def arb_free_model_day(
192
+ ticker: str,
193
+ d: dt.date,
194
+ enriched_data: pd.DataFrame | None = None,
195
+ *,
196
+ raw_day_filter: RawDayFilter = RawDayFilter(),
197
+ expiry_filter: ExpiryFilter = ExpiryFilter(),
198
+ mk_arb_free: MkArbFree = fit_config(),
199
+ override_cache_mode: CacheMode | None = None,
200
+ raise_if_bad_day: bool = True,
201
+ verbose: Context = Context.all,
202
+ ) -> dict:
203
+ """
204
+ Fitted arbitrage-free model and fit statistics for the full cleaned book of one WIDB day.
205
+
206
+ This is the cached fit behind :func:`mk_arb_free_day`. See :func:`fit_model` for the returned
207
+ dictionary; ``ArbFreePricer.from_dict(result["model"])`` restores the pricer.
208
+ """
209
+ if enriched_data is None:
210
+ enriched_data = enrich_day(ticker, d, raw_day_filter=raw_day_filter, expiry_filter=expiry_filter,
211
+ override_cache_mode=override_cache_mode, raise_if_bad_day=raise_if_bad_day, verbose=verbose)
212
+ if enriched_data is None or enriched_data.empty:
213
+ return dict(empty=True, stats=dict(num_options=0, num_input_expiries=0, num_expiries=0,
214
+ dropped_expiry_ids=np.zeros((0,), dtype=np.int64), run_time_expiry=0., run_time_surface=0.,
215
+ num_outside=0, fraction_outside=0., mean_excess=0., median_excess=0.))
216
+ return fit_model(ticker, d, restore_object_strings(enriched_data, SCHEMA_ENRICHED_DAY), mk_arb_free, verbose)
217
+
218
+
219
+ def _uid(ticker, d, raw_day_filter, expiry_filter, mk_arb_free) -> str:
220
+ return (
221
+ f"arbfree/{named_unique_filename48_8(f'{str(expiry_filter)},{str(raw_day_filter)},{str(mk_arb_free)}', expiry_filter, raw_day_filter, mk_arb_free)}"
222
+ f"/{ticker}/{fmt_date(d)}"
223
+ )
224
+
225
+ @_processing(fmt=SubDir.PANDAS_PARQUET).cache(
226
+ "0.63",
227
+ dependencies=[enrich_day, MkArbFree],
228
+ uid=_uid,
229
+ exclude_args=["verbose", "enriched_data", "raise_if_bad_day", "refresh_cache"],
230
+ )
231
+ def mk_arb_free_day(
232
+ ticker: str,
233
+ d: dt.date,
234
+ enriched_data: pd.DataFrame | None = None,
235
+ *,
236
+ raw_day_filter: RawDayFilter = RawDayFilter(),
237
+ expiry_filter: ExpiryFilter = ExpiryFilter(),
238
+ mk_arb_free: MkArbFree|None = fit_config(),
239
+ override_cache_mode: CacheMode | None = None,
240
+ raise_if_bad_day: bool = True,
241
+ verbose: Context = Context.all,
242
+ ) -> pd.DataFrame:
243
+ """
244
+ Generate an arbitrage-free fit for a single enriched WIDB day.
245
+
246
+ The returned DataFrame keeps the full input-strike rows for retained expiries
247
+ and adds mask/fitted-price/Greek columns aligned to those input strikes.
248
+ Expiries dropped by MkArbFree are removed from the returned frame; masked strikes of retained expiries are kept
249
+ and marked by ``mask_arb_free``.
250
+ The underlying mechanism is described in detail in :class:`MkArbFree`.
251
+
252
+ The schema of the data frame returned depend on the settings in ``mk_arb_free.no_arb_mode``.
253
+
254
+ * ``expiry``: the dataframe has schema :data:`SCHEMA_ARB_FREE_DAY_EXPIRY`. which includes all columns :data:`SCHEMA_ENRICHED_DAY` plus the following additional columns:
255
+
256
+ - ``mask_arb_free``: boolean mask indicating which strikes are active in the fit (True) or were masked (False).
257
+ - ``pure_fit1_price``: fitted arbitrage-free price within bid/ask where ``mask_arb_free`` is True.
258
+ - ``pure_fit1_delta``, ``pure_fit1_gamma``, ``pure_fit1_vega``, ``pure_fit1_theta``, ``pure_fit1_dk``: Greeks corresponding to ``pure_fit1_price``.
259
+
260
+ * ``surface``: the dataframe has schema :data:`SCHEMA_ARB_FREE_DAY_SURFACE`, which includes all columns from ``SCHEMA_ARB_FREE_DAY_EXPIRY`` plus:
261
+
262
+ - ``pure_fitX_price``: price of the arbitrage-free surface. For the linear surface, existence of a ``fitX`` within bid/ask is, up to machine precision, equivalent to the market being free of arbitrage.
263
+ - ``pure_fitX_delta``, ``pure_fitX_gamma``, ``pure_fitX_vega``, ``pure_fitX_theta``, ``pure_fitX_dk``: Greeks corresponding to ``pure_fitX_price``.
264
+
265
+ Returns
266
+ -------
267
+ Result: :class:`pandas.DataFrame`
268
+ The frame is empty if ``raise_if_bad_day`` is False and the day is listed in :data:`bad.BAD`.
269
+ """
270
+ if not enriched_data is None:
271
+ verify_inp( isinstance(enriched_data, pd.DataFrame), f"{ticker} {d}: expected 'enriched_data' to be a pandas DataFrame or None, got {type(enriched_data)}.")
272
+ data = enriched_data
273
+ else:
274
+ data = enrich_day(
275
+ ticker,
276
+ d,
277
+ raw_day_filter=raw_day_filter,
278
+ expiry_filter=expiry_filter,
279
+ override_cache_mode=override_cache_mode,
280
+ raise_if_bad_day=raise_if_bad_day,
281
+ verbose=verbose,
282
+ )
283
+ if data is None:
284
+ assert raise_if_bad_day, "Internal error: empty data should only be returned when 'raise_if_bad_day' is False. Please check the enriched day data for details."
285
+ return None
286
+ del enriched_data
287
+
288
+ if mk_arb_free is None:
289
+ return data
290
+
291
+ verify_inp( mk_arb_free.no_arb_mode in ['expiry', 'surface'], lambda: f"{ticker} {d}: arb_free_day.no_arb_mode must be 'surface' or 'expiry'; found no_arb_mode '{mk_arb_free.no_arb_mode}'." )
292
+ mode_surface = mk_arb_free.no_arb_mode == 'surface'
293
+ expected_schema = SCHEMA_ARB_FREE_DAY_SURFACE if mode_surface else SCHEMA_ARB_FREE_DAY_EXPIRY
294
+
295
+ if data.empty:
296
+ return create_empty_df(expected_schema)
297
+ data = restore_object_strings(data, SCHEMA_ENRICHED_DAY)
298
+ verify_schema(data, SCHEMA_ENRICHED_DAY, lambda: f"{ticker} {d}")
299
+
300
+ fitted = arb_free_model_day(ticker, d, enriched_data=data, raw_day_filter=raw_day_filter, expiry_filter=expiry_filter,
301
+ mk_arb_free=mk_arb_free, override_cache_mode=override_cache_mode,
302
+ raise_if_bad_day=raise_if_bad_day, verbose=verbose(1))
303
+ return fitted_rows(ticker, d, data, fitted, mode_surface=mode_surface, verbose=verbose)
304
+
305
+
306
+ def fitted_rows(ticker: str, d: dt.date, data: pd.DataFrame, fitted: dict, *, mode_surface: bool, verbose: Context = Context.quiet) -> pd.DataFrame:
307
+ """Align a fitted model (see :func:`fit_model`) to the enriched rows it was fitted to."""
308
+ tme = verbose.timer()
309
+ expected_schema = SCHEMA_ARB_FREE_DAY_SURFACE if mode_surface else SCHEMA_ARB_FREE_DAY_EXPIRY
310
+ if fitted["empty"]:
311
+ return create_empty_df(expected_schema)
312
+ arb_result = ArbFreePricer.from_dict(fitted["model"])
313
+ unique_expiry_ids, grouped_frames, _, _, _, _ = _market_groups(ticker, d, data)
314
+
315
+ if len(arb_result.expiries) == 0:
316
+ verbose.write(lambda: f"{ticker} {d}: MkArbFree dropped all expiries. This took {tme}.")
317
+ return create_empty_df(expected_schema)
318
+
319
+ fit1_all = arb_result.fits1
320
+ assert not fit1_all is None, f"Internal error: {ticker} {d}: MkArbFree returned None for fits; expected arrays of shape (num_expiries, num_strikes_per_expiry)."
321
+
322
+ if mode_surface:
323
+ fitx_all = arb_result.fitsX
324
+ assert not fitx_all is None, f"Internal error: {ticker} {d}: MkArbFree returned None for fitsX; expected arrays of shape (num_expiries, num_strikes_per_expiry)."
325
+ else:
326
+ fitx_all = None
327
+
328
+ result_frames: list[pd.DataFrame] = []
329
+ dropped_strikes = 0
330
+ output_indices = list(arb_result.input_index) if arb_result.input_index is not None else slice(None)
331
+
332
+ for output_index, source_index in enumerate(output_indices):
333
+ group = grouped_frames[source_index].copy()
334
+ pure_strike = group["pure_strike"].to_numpy(dtype=np.float64)
335
+ mask_t = np.asarray(arb_result.masks[output_index], dtype=bool)
336
+ fit1_t = np.asarray(fit1_all[output_index], dtype=np.float64)
337
+ fitx_t = np.asarray(fitx_all[output_index], dtype=np.float64) if mode_surface else None
338
+
339
+ assert mask_t.shape == pure_strike.shape, f"Internal error: {ticker} {d}: arb mask shape {mask_t.shape} does not match strike shape {pure_strike.shape}."
340
+ assert fit1_t.shape == pure_strike.shape, f"Internal error: {ticker} {d}: fit1 shape {fit1_t.shape} does not match strike shape {pure_strike.shape}."
341
+ if mode_surface:
342
+ assert fitx_t.shape == pure_strike.shape, f"Internal error: {ticker} {d}: fitX shape {fitx_t.shape} does not match strike shape {pure_strike.shape}."
343
+
344
+ sqrt_t = math.sqrt(float(arb_result.expiries[output_index]))
345
+ fit1_vols = bs.implied(pure_strike, fit1_t, sqrtT=sqrt_t, eps=_IMPLIED_VOL_CALC_EPS)
346
+ fitx_vols = bs.implied(pure_strike, fitx_t, sqrtT=sqrt_t, eps=_IMPLIED_VOL_CALC_EPS) if mode_surface else None
347
+ fit1_greeks = bs(
348
+ k=pure_strike ,
349
+ vol=fit1_vols,
350
+ sqrtT=sqrt_t,
351
+ eps=_GREEK_CALC_EPS,
352
+ what=bs.PRICE | bs.DELTA | bs.GAMMA | bs.VEGA | bs.THETA | bs.DK,
353
+ )
354
+ fitx_greeks = bs(
355
+ k=pure_strike,
356
+ vol=fitx_vols,
357
+ sqrtT=sqrt_t,
358
+ eps=_GREEK_CALC_EPS,
359
+ what=bs.PRICE | bs.DELTA | bs.GAMMA | bs.VEGA | bs.THETA | bs.DK,
360
+ ) if mode_surface else None
361
+
362
+ group["mask_arb_free"] = mask_t.astype(bool)
363
+ group["fit1_vol"] = fit1_vols.astype(np.float32, copy=False)
364
+ group["pure_fit1_price"] = fit1_t.astype(np.float32, copy=False)
365
+ for greek_name, values in fit1_greeks.items():
366
+ group[f"pure_fit1_{greek_name}"] = np.asarray(values, dtype=np.float32)
367
+
368
+ if mode_surface:
369
+ group["fitX_vol"] = fitx_vols.astype(np.float32, copy=False)
370
+ group["pure_fitX_price"] = fitx_t.astype(np.float32, copy=False)
371
+ for greek_name, values in fitx_greeks.items():
372
+ group[f"pure_fitX_{greek_name}"] = np.asarray(values, dtype=np.float32)
373
+
374
+ dropped_strikes += int((~mask_t).sum())
375
+ result_frames.append(group)
376
+
377
+ result = pd.concat(result_frames, axis=0, ignore_index=True)
378
+ result = result.sort_values(["expiry_id", "pure_strike"], kind="stable", ignore_index=True)
379
+
380
+ for column, dtype in expected_schema.items():
381
+ if result[column].dtype != dtype:
382
+ result[column] = result[column].astype(dtype)
383
+
384
+ verify_schema(result, expected_schema, lambda: f"{ticker} {d}")
385
+
386
+ for column in ENRICHED_PER_DAY_FIELDS:
387
+ if result[column].nunique() != 1:
388
+ raise RuntimeError(
389
+ f"Internal error: {ticker} {d}: arb-free DataFrame column '{column}' is expected to have exactly one unique value. Found values: {fmt_list(result[column].unique())}."
390
+ )
391
+
392
+ for column in ENRICHED_PER_EXPIRY_FIELDS:
393
+ values_per_expiry = result.groupby("expiry_id")[column].nunique()
394
+ if (values_per_expiry != 1).any():
395
+ raise RuntimeError(
396
+ f"Internal error: {ticker} {d}: arb-free DataFrame column '{column}' is expected to have exactly one unique value per expiry. Found expiries with multiple values: {fmt_list(values_per_expiry[values_per_expiry != 1].index.tolist())}."
397
+ )
398
+
399
+
400
+ remaining_expiries = sorted( result['expiry'].unique() )
401
+ dropped_expiries = len(unique_expiry_ids) - len(output_indices)
402
+ verbose.write( lambda: f"{ticker} {d}: generated arbitrage-free price surface. Dropped {dropped_expiries} expiries and {dropped_strikes} strikes of the remaining expiries from "+\
403
+ f"{remaining_expiries[0]} to {remaining_expiries[-1]}. This took {tme}.")
404
+ result.attrs['arb_free_timing'] = tme.seconds
405
+ return result
406
+
407
+
408
+ # ================================================================
409
+ # Command-line interface
410
+ # ================================================================
411
+
412
+ import click
413
+
414
+ from openqdata.widb import _cli_defaults
415
+
416
+ #: Environment variables which limit the numerical threads of a worker process.
417
+ THREAD_VARIABLES = ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "RAYON_NUM_THREADS")
418
+
419
+
420
+ def timing_table(passes: list[dict]) -> str:
421
+ """Markdown table of the passes of one batch run: one row per option set, smoothness and time limit."""
422
+ lines = ["| Ticker | Option set | Smoothness | Time limit (s) | Days | Failed | Wall time | Worker time |",
423
+ "|---|---|---:|---:|---:|---:|---:|---:|"]
424
+ for r in passes:
425
+ lines.append(f"| {r['ticker']} | {r['population']} | {0 if r['smoothness'] is None else r['smoothness']:g} | {r['timeout_seconds']:g} | "
426
+ f"{r['days']:,} | {r['failed']:,} | {r['wall_seconds']/3600.:.2f} h | {r['worker_seconds']/3600.:.2f} h |")
427
+ return "\n".join(lines) + "\n"
428
+
429
+
430
+ @click.command()
431
+ @click.argument("tickers", nargs=-1, required=True)
432
+ @click.option("--period",nargs=2, type=click.DateTime(formats=["%Y-%m-%d"]), default=_cli_defaults.period, metavar="START END", help="Period YYYY-MM-DD YYYY-MM-DD")
433
+ @click.option("--date", "only_dates", type=click.DateTime(formats=["%Y-%m-%d"]), multiple=True, help="Fit only this date instead of a period; repeat for several")
434
+ @click.option('--population', 'populations', type=click.Choice(["all", "flt"]), multiple=True, default=("all",), show_default=True,
435
+ help="Option set to fit; repeat for several. 'all': the full book. 'flt': the reduced set (at most 1,000 options; much faster)")
436
+ @click.option('--smoothness', 'smoothnesses', type=float, multiple=True, default=(0.,), show_default=True,
437
+ help="SANOS smoothness eta (e.g. 0.1, 0.25), 0 for the linear surface; repeat for several")
438
+ @click.option('--mid-fit-weight', 'mid_fit_weight', type=float, default=None,
439
+ help="Weight w of the distance from the mid in the fit; 1 is a pure mid fit, a small value fits to the bid/ask [default: the benchmark setting of the smoothness]")
440
+ @click.option('--reweight-max-iter', 'reweight_max_iter', type=int, default=None,
441
+ help="Maximum number of surface fits per day; above 1 the fit is repeated with reweighted quotes [default: the benchmark setting of the smoothness]")
442
+ @click.option('--reweight-min-within', 'reweight_min_within', type=float, default=None,
443
+ help="Reweighting stops once this share of quotes is within bid/ask [default: the benchmark setting of the smoothness]")
444
+ @click.option('--timeout-seconds', 'timeouts', type=float, multiple=True, default=(MkArbFree.timeout_seconds,), show_default=True,
445
+ help="Solver time limit per fit; repeat with longer limits to retry the days which failed")
446
+ @click.option('--exclude-halfdays', 'exclude_halfdays', is_flag=True, help="Exclude NYSE early-close days (included by default)")
447
+ @click.option('--newest-first', 'newest_first', is_flag=True, help="Fit the most recent days first")
448
+ @click.option('--workers', default=_cli_defaults.workers, help='Number of workers', type=int)
449
+ @click.option('--threads', default=2, show_default=True, type=int, help="Numerical threads per worker; workers x threads should not exceed the number of cores")
450
+ @click.option('--threading', is_flag=True, help="Use only threading, no multiprocessing")
451
+ @click.option('--refresh', is_flag=True, help="Recompute and overwrite existing fits")
452
+ @click.option('--report', type=click.Path(dir_okay=False), default=None, help="Write the timing table of this run to this Markdown file")
453
+ def main(tickers : list[str],
454
+ period : list[dt.datetime],
455
+ only_dates : tuple[dt.datetime, ...],
456
+ populations : tuple[str, ...],
457
+ smoothnesses : tuple[float, ...],
458
+ mid_fit_weight : float | None,
459
+ reweight_max_iter : int | None,
460
+ reweight_min_within : float | None,
461
+ timeouts : tuple[float, ...],
462
+ exclude_halfdays : bool,
463
+ newest_first : bool,
464
+ workers : int,
465
+ threads : int,
466
+ threading : bool,
467
+ refresh : bool,
468
+ report : str | None,
469
+ ):
470
+ """
471
+ Fit arbitrage-free surfaces for every business day of a period, or for given dates, and store fitted rows, models and fit statistics.
472
+
473
+ Every combination of ticker, option set and smoothness is one pass over the period, in the order given.
474
+ Completed days are read from the cache, so an interrupted run resumes where it stopped.
475
+ A day that fails does not stop the run. With several time limits, the days which failed are fitted again with
476
+ the next limit. Every remaining failure is reported at the end and the command exits with status 1.
477
+ """
478
+ verify_inp( len(tickers) > 0, "At least one ticker must be specified")
479
+ verify_inp( period is not None and len(period) == 2, "A start and end date must be specified")
480
+ verify_inp( all( t > 0. for t in timeouts ), lambda: f"Time limits must be positive, found {fmt_list(timeouts)}")
481
+ verify_inp( threads > 0, lambda: f"'threads' must be positive, found {threads}")
482
+
483
+ import os
484
+ import sys
485
+ import time
486
+ import traceback
487
+ from pathlib import Path
488
+
489
+ from cdxcore.jcpool import JCPool
490
+
491
+ from openqdata.biz_calendar import DateRange, to_date
492
+ from openqdata.pool import PoolConfig
493
+ from openqdata.widb.bad import BAD
494
+ from openqdata.widb.sanos import fit_sanos_day, fit_sanos_model_day
495
+
496
+ # worker processes inherit the environment: without a limit each one starts a thread per core
497
+ for name in THREAD_VARIABLES:
498
+ os.environ[name] = str(threads)
499
+
500
+ start, end = period
501
+ date_range = DateRange(start=to_date(start), end=to_date(end), exclude_half_days=exclude_halfdays)
502
+ pool_config = PoolConfig(num_workers=workers, threading=threading)
503
+ raw_day_filter = RawDayFilter()
504
+ expiry_filter = ExpiryFilter()
505
+ if only_dates:
506
+ start, end = min(only_dates), max(only_dates)
507
+ date_range = DateRange(start=to_date(start), end=to_date(end), exclude_half_days=False)
508
+ dates = sorted( ( set(to_date(d) for d in only_dates) & set(date_range.get_business_days()) ) - set(BAD.DAYS_ALL) )
509
+ else:
510
+ dates = sorted( set(date_range.get_business_days()) - set(BAD.DAYS_ALL) )
511
+
512
+ verbose = Context.all
513
+ verbose.write(lambda: f"Fitting {fmt_list(tickers)} from {fmt_date(start)} to {fmt_date(end)} {'excluding' if date_range.exclude_half_days else 'including'} half days: {len(dates)} business days.")
514
+ verbose.report(1,lambda: f"Option sets {fmt_list(populations)}; smoothness {fmt_list(smoothnesses)}; solver time limits {fmt_list(timeouts)}s")
515
+ verbose.report(1,lambda: f"Raw Day Filter: {raw_day_filter}")
516
+ verbose.report(1,lambda: f"Expiry filter: {expiry_filter}")
517
+ verbose.report(1,lambda: f"Pool config: {pool_config}, {threads} numerical threads per worker")
518
+
519
+ pool = JCPool(num_workers=pool_config.num_workers, threading=pool_config.threading)
520
+ passes : list[dict] = []
521
+ failures : list[tuple[str, str, float, dt.date, str]] = []
522
+
523
+ def processing( *, ticker, d, population, mk_arb_free, cache_mode ):
524
+ # Returns the time taken and the error, None on success: one bad day must not stop the run.
525
+ t0 = time.time()
526
+ try:
527
+ kwargs = dict(raw_day_filter=raw_day_filter, expiry_filter=expiry_filter, override_cache_mode=cache_mode,
528
+ raise_if_bad_day=False, verbose=Context.quiet, cache_generate_only=True)
529
+ if population == "all":
530
+ arb_free_model_day( ticker, d, mk_arb_free=mk_arb_free, **kwargs )
531
+ mk_arb_free_day( ticker, d, mk_arb_free=mk_arb_free, **kwargs )
532
+ else:
533
+ fit_sanos_model_day( ticker, d, mk_arb_free, **kwargs )
534
+ fit_sanos_day( ticker, d, mk_arb_free, **kwargs )
535
+ return dict(seconds=time.time() - t0, error=None)
536
+ except Exception as error:
537
+ return dict(seconds=time.time() - t0, error=f"{type(error).__name__}: {error}\n{traceback.format_exc()}")
538
+
539
+ for ticker in tickers:
540
+ for population in populations:
541
+ for smoothness in smoothnesses:
542
+ todo, failed = sorted(dates, reverse=newest_first), {}
543
+ for attempt, timeout_seconds in enumerate(timeouts):
544
+ mk_arb_free = fit_config(smoothness, timeout_seconds=timeout_seconds, mid_fit_weight=mid_fit_weight,
545
+ reweight_max_iter=reweight_max_iter, reweight_min_within=reweight_min_within)
546
+ # a refresh recomputes once; the retries only fit what is still missing
547
+ cache_mode = "update" if refresh and attempt == 0 else "on"
548
+ label = f"{ticker} '{population}' smoothness {0 if mk_arb_free.smoothness is None else mk_arb_free.smoothness:g}, time limit {timeout_seconds:g}s"
549
+ failed, worker_seconds = {}, 0.
550
+ with verbose.write_t(lambda: f"\r{label}: {len(todo)} days:", end='') as tme:
551
+ cnt = 0
552
+ jobs = { d: pool.delayed(processing)(ticker=ticker, d=d, population=population, mk_arb_free=mk_arb_free, cache_mode=cache_mode) for d in todo }
553
+ for d, result in pool.parallel( jobs ):
554
+ cnt += 1
555
+ worker_seconds += result['seconds']
556
+ error = result['error']
557
+ if error is not None:
558
+ failed[d] = error
559
+ verbose.write(f"\r*** FAILED {ticker} {fmt_date(d)}: {error.splitlines()[0]}")
560
+ if tme.interval_test(1.):
561
+ verbose.write(f"\r{label}: day {cnt}/{len(todo)} {fmt_date(d)}; {len(failed)} failed. So far this took {tme}...", end='')
562
+ verbose.write(f"\r{label}: {len(todo)} days, {len(failed)} failed. This took {tme}.")
563
+ passes.append(dict(ticker=ticker, population=population, smoothness=mk_arb_free.smoothness, timeout_seconds=timeout_seconds,
564
+ days=len(todo), failed=len(failed), wall_seconds=tme.seconds, worker_seconds=worker_seconds))
565
+ if report is not None:
566
+ Path(report).write_text(timing_table(passes)) # kept up to date: a long run can be read while it runs
567
+ if not failed:
568
+ break
569
+ todo = sorted(failed, reverse=newest_first)
570
+ failures += [ (ticker, population, smoothness, d, error) for d, error in failed.items() ]
571
+
572
+ verbose.write(timing_table(passes))
573
+ if failures:
574
+ verbose.write(f"*** {len(failures)} day(s) FAILED and have no fit:")
575
+ for ticker, population, smoothness, d, error in failures:
576
+ verbose.write(f"*** {ticker} '{population}' smoothness {smoothness:g} {fmt_date(d)}: {error}")
577
+ sys.exit(1)
578
+ verbose.write("All passes completed without failures.")
579
+
580
+ if __name__ == "__main__":
581
+ main()
openqdata/widb/bad.py ADDED
@@ -0,0 +1,69 @@
1
+ """
2
+ Bad data directory
3
+ ==================
4
+
5
+ This file contains all known bad data points:
6
+
7
+ * General bad days
8
+ * Bad days per ticker
9
+ * Bad options
10
+ * Likely last valid date
11
+
12
+ Please update this file as you experience errors in the data.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import datetime as dt
18
+
19
+ import openqdata as openqdata #NOQA
20
+
21
+
22
+ class BAD:
23
+ """
24
+ Container class for BAD data points in various categories.
25
+ """
26
+
27
+ LAST_LIKELY_VALID_DATE = dt.date(2025, 9, 1)
28
+ """ Likely last valid date in the data. This is an estimate based on the most recent data issues. """
29
+
30
+ DAYS_ALL = {
31
+ dt.date(2004, 10, 11), # no zero curve
32
+ dt.date(2004, 11, 11), # no zero curve
33
+ dt.date(2007, 11, 12), # no zero curve
34
+ dt.date(2018, 12, 4), # expiries with zero business days?
35
+ dt.date(2025, 1,8) # expiries with zero business days?
36
+ }
37
+ """ Days where some core information is missing, e.g. zero curves. """
38
+
39
+ DAYS_TICKER = {'SPX': {
40
+ dt.date(2006, 11, 17), # no forward for 1
41
+ dt.date(2012, 11, 17), # no forward for 1
42
+ dt.date(2015, 8, 21) # cannot find arb-free surface
43
+ },
44
+ 'RUT': {
45
+ dt.date(2009, 2, 20), # no forward for 1
46
+ },
47
+ 'NDX': {
48
+ #dt.date(2012, 4, 4), # suspicious forward prices in fwd_tbl, min=0.002745 spot=2745.0
49
+ }
50
+ }
51
+ """ Days where data per ticker are missing or are faulty. """
52
+
53
+ OPTIONS = {\
54
+ 'SPX' : {'SPX 291221C400000','SPX 261218C200000','SPX 301220C400000',
55
+ 'SPZ.OT', 'SPZ.CT', # invalid implied forward
56
+ 'JXB.OT', 'JXB.CT', # invalid implied forward
57
+ 'JXB.BT', 'JXB.NT', # invalid implied forward
58
+ }
59
+ }
60
+ """ Specific options to exclude due to data issues. """
61
+
62
+ OPTIONS_BY_DATE = {
63
+ # (ticker, date): set of option symbols to exclude
64
+ 'SPX': {
65
+ dt.date(2024, 5, 6): {'SPX 291221C400000'},
66
+ }
67
+ }
68
+ """ Options to exclude by date and ticker. """
69
+