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,328 @@
1
+ """
2
+ Fit statistics of the WIDB benchmark data
3
+ =========================================
4
+
5
+ Collects the daily fits cached by ``python -m openqdata.widb.arbfree`` and produces the summary tables and the
6
+ time-series figures shown in the documentation::
7
+
8
+ python -m openqdata.widb.fitstats SPX --period 2005-01-03 2025-08-29 --out docs/figures
9
+
10
+ Nothing is fitted here: every model is read from the cache, and a day without a cached fit is an error unless
11
+ ``--skip-missing`` is given.
12
+
13
+ A model is fitted to one of two option sets, the full cleaned book (``all``) or the reduced selection of at most
14
+ 1,000 options (``flt``). The share of quotes within bid/ask depends on the set it is measured on, so every model
15
+ is evaluated on both sets and the two are reported separately.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import datetime as dt
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+ from cdxcore.subdir import CacheMustExistError
25
+ from cdxcore.util import verify_inp
26
+ from cdxcore.verbose import Context
27
+
28
+ from openqdata.arbfree.arbfree import ArbFreePricer, MkArbFree
29
+ from openqdata.biz_calendar import DateRange
30
+ from openqdata.widb.arbfree import _market_groups, arb_free_model_day, fit_config
31
+ from openqdata.widb.bad import BAD
32
+ from openqdata.widb.day import ExpiryFilter, RawDayFilter, enrich_day
33
+ from openqdata.widb.options_filter import OptionsFilter, filter_options_day
34
+ from openqdata.widb.sanos import fit_sanos_model_day
35
+
36
+ #: Option sets: a model is fitted to one of them and evaluated on both.
37
+ SETS = {"all": "full book", "flt": "reduced set"}
38
+
39
+ #: Columns of :func:`fit_statistics`.
40
+ COLUMNS = ["num_options", "num_input_expiries", "num_expiries", "num_dropped_expiries",
41
+ "within_all_percent", "within_flt_percent", "mean_excess", "median_excess", "fit_seconds", "num_surface_fits", "within_first_fit_percent"]
42
+
43
+
44
+ def _within_percent(model: ArbFreePricer, ticker: str, d: dt.date, rows: pd.DataFrame | None) -> float:
45
+ """Percentage of the quotes in ``rows`` whose fitted call lies within the fitted call bid/ask."""
46
+ if rows is None or rows.empty:
47
+ return np.nan
48
+ _, _, expiries, strikes, bids, asks = _market_groups(ticker, d, rows)
49
+ return 100. * (1. - float(model.compute_market_fit(expiries=expiries, strikes=strikes, bids=bids, asks=asks, and_vols=False).pcnt_fit))
50
+
51
+
52
+ def fit_statistics_day(ticker: str, d: dt.date, *,
53
+ population: str = "all",
54
+ mk_arb_free: MkArbFree = fit_config(),
55
+ raw_day_filter: RawDayFilter = RawDayFilter(),
56
+ expiry_filter: ExpiryFilter = ExpiryFilter(),
57
+ options_filter: OptionsFilter = OptionsFilter(normalize=False)) -> dict:
58
+ """
59
+ Fit statistics of the cached model of one day; see :func:`fit_statistics` for the fields.
60
+
61
+ Raises :class:`cdxcore.subdir.CacheMustExistError` if the fit or the quotes it is evaluated on are not cached.
62
+ """
63
+ kwargs = dict(raw_day_filter=raw_day_filter, expiry_filter=expiry_filter, override_cache_mode="cacheonly")
64
+ if population == "all":
65
+ fitted = arb_free_model_day(ticker, d, mk_arb_free=mk_arb_free, **kwargs)
66
+ else:
67
+ fitted = fit_sanos_model_day(ticker, d, mk_arb_free, options_filter=options_filter, **kwargs)
68
+ stats, empty = fitted["stats"], bool(fitted["empty"])
69
+ within = dict(all=np.nan, flt=np.nan)
70
+ if not empty:
71
+ model = ArbFreePricer.from_dict(fitted["model"])
72
+ quotes = dict(all=enrich_day(ticker, d, **kwargs),
73
+ flt=filter_options_day(ticker, d, mk_arb_free=fit_config(), options_filter=options_filter,
74
+ verbose=Context.quiet, **kwargs))
75
+ within = {name: _within_percent(model, ticker, d, rows) for name, rows in quotes.items()}
76
+ return dict(
77
+ num_options=int(stats["num_options"]),
78
+ num_input_expiries=int(stats["num_input_expiries"]),
79
+ num_expiries=int(stats["num_expiries"]),
80
+ num_dropped_expiries=int(len(stats["dropped_expiry_ids"])),
81
+ within_all_percent=within["all"],
82
+ within_flt_percent=within["flt"],
83
+ mean_excess=np.nan if empty else float(stats["mean_excess"]),
84
+ median_excess=np.nan if empty else float(stats["median_excess"]),
85
+ fit_seconds=np.nan if empty else float(stats["run_time_expiry"]) + float(stats["run_time_surface"]),
86
+ num_surface_fits=int(stats.get("num_surface_fits", 1)), # fits stored before the field existed count as a single fit
87
+ within_first_fit_percent=100. * float(stats.get("within_first_fit", np.nan)),
88
+ )
89
+
90
+
91
+ def fit_statistics(ticker: str, date_range: DateRange, *,
92
+ population: str = "all",
93
+ mk_arb_free: MkArbFree = fit_config(),
94
+ raw_day_filter: RawDayFilter = RawDayFilter(),
95
+ expiry_filter: ExpiryFilter = ExpiryFilter(),
96
+ options_filter: OptionsFilter = OptionsFilter(normalize=False),
97
+ skip_missing: bool = False,
98
+ workers: int = 1) -> pd.DataFrame:
99
+ """
100
+ Daily fit statistics from the cached fits to one option set (``population``) with one configuration.
101
+
102
+ Returns one row per business day in ``date_range`` (bad days excluded), indexed by date:
103
+
104
+ * ``num_options``: paired call/put observations fitted.
105
+ * ``num_input_expiries``, ``num_expiries``, ``num_dropped_expiries``: expiries offered, fitted and dropped.
106
+ * ``within_all_percent``, ``within_flt_percent``: percentage of the observations of the full book and of the
107
+ reduced set whose fitted call lies within the fitted call bid/ask. The model is the same in both columns;
108
+ only the quotes it is measured on differ.
109
+ * ``mean_excess``, ``median_excess``: distance outside bid/ask in half-spreads, over the fitted observations
110
+ which are outside (zero if there are none).
111
+ * ``fit_seconds``: solver time of the per-expiry and surface fits.
112
+ * ``num_surface_fits``: number of surface fits; above 1 if the fit was reweighted to raise the share within bid/ask.
113
+ * ``within_first_fit_percent``: percentage of the quotes of the retained expiries within bid/ask after the first surface fit, so
114
+ before any reweighting (NaN for fits stored before it was recorded).
115
+
116
+ Days without any fitted expiry have ``num_expiries == 0`` and NaN statistics. A day without a cached
117
+ fit raises :class:`LookupError` unless ``skip_missing`` is set, in which case it is left out.
118
+ """
119
+ verify_inp(population in SETS, lambda: f"'population' must be one of {list(SETS)}, found {population!r}")
120
+ days = sorted(set(date_range.get_business_days()) - set(BAD.DAYS_ALL) - BAD.DAYS_TICKER.get(ticker, set()))
121
+
122
+ def day(d):
123
+ try:
124
+ return fit_statistics_day(ticker, d, population=population, mk_arb_free=mk_arb_free, raw_day_filter=raw_day_filter,
125
+ expiry_filter=expiry_filter, options_filter=options_filter)
126
+ except CacheMustExistError:
127
+ return None
128
+
129
+ if workers > 1:
130
+ from cdxcore.jcpool import JCPool
131
+ pool = JCPool(num_workers=workers)
132
+ rows = dict(pool.parallel({d: pool.delayed(day)(d) for d in days}))
133
+ else:
134
+ rows = {d: day(d) for d in days}
135
+ missing = [d for d in days if rows[d] is None]
136
+ if missing and not skip_missing:
137
+ raise LookupError(f"{ticker} {population} {mk_arb_free}: {len(missing)} of {len(days)} days have no cached fit, "
138
+ f"first {missing[0]}, last {missing[-1]}. Run 'python -m openqdata.widb.arbfree' for them first.")
139
+ frame = pd.DataFrame.from_dict({d: rows[d] for d in days if rows[d] is not None}, orient="index", columns=COLUMNS)
140
+ frame.index.name = "date"
141
+ return frame
142
+
143
+
144
+ def summarize(stats: pd.DataFrame) -> dict:
145
+ """Summary of :func:`fit_statistics` over days with a fit: each day counts once, whatever its size."""
146
+ fitted = stats.loc[stats.num_expiries > 0]
147
+ return dict(
148
+ dates=int(len(stats)),
149
+ dates_without_fit=int(len(stats) - len(fitted)),
150
+ mean_within_all_percent=float(fitted.within_all_percent.mean()),
151
+ mean_within_flt_percent=float(fitted.within_flt_percent.mean()),
152
+ mean_excess=float(fitted.mean_excess.mean()),
153
+ median_of_median_excess=float(fitted.median_excess.median()),
154
+ median_fit_seconds=float(fitted.fit_seconds.median()),
155
+ median_options=float(fitted.num_options.median()),
156
+ dates_reweighted=int((fitted.num_surface_fits > 1).sum()),
157
+ )
158
+
159
+
160
+ def _eta(smoothness: float | None) -> str:
161
+ return f"{0 if smoothness is None else smoothness:g}"
162
+
163
+
164
+ def summary_table(summaries: dict[tuple[str, float | None], dict]) -> str:
165
+ """
166
+ Markdown tables of :func:`summarize` results keyed by ``(population, smoothness)``.
167
+
168
+ The share within bid/ask gets one table per option set it is measured on, with the models fitted to the full
169
+ book and to the reduced set side by side. A last table has the statistics of each fit on its own input.
170
+ """
171
+ populations = [p for p in SETS if any(key[0] == p for key in summaries)]
172
+ smoothnesses = list(dict.fromkeys(key[1] for key in summaries))
173
+ lines = []
174
+ for evaluated in SETS:
175
+ lines += [f"**Quotes of the {SETS[evaluated]} within bid/ask (mean daily)**", "",
176
+ "| Smoothness | " + " | ".join(f"Model fitted to the {SETS[p]}" for p in populations) + " |",
177
+ "|---:|" + "---:|" * len(populations)]
178
+ for smoothness in smoothnesses:
179
+ cells = [f"{summaries[(p, smoothness)][f'mean_within_{evaluated}_percent']:.2f}%" if (p, smoothness) in summaries else ""
180
+ for p in populations]
181
+ lines.append(f"| {_eta(smoothness)} | " + " | ".join(cells) + " |")
182
+ lines.append("")
183
+ lines += ["**Each fit on the quotes it was fitted to**", "",
184
+ "| Fitted to | Smoothness | Dates | Without fit | Reweighted | Excess outside, half-spreads (mean daily) | Median daily median excess "
185
+ "| Median fit time (s) | Median options |",
186
+ "|---|---:|---:|---:|---:|---:|---:|---:|---:|"]
187
+ for (population, smoothness), s in summaries.items():
188
+ lines.append(f"| {SETS[population]} | {_eta(smoothness)} | {s['dates']:,} | {s['dates_without_fit']:,} | {s['dates_reweighted']:,} | {s['mean_excess']:.3f} | "
189
+ f"{s['median_of_median_excess']:.3f} | {s['median_fit_seconds']:.2f} | {s['median_options']:,.0f} |")
190
+ return "\n".join(lines) + "\n"
191
+
192
+
193
+ #: Colours of the time series: days fitted once, and days where the reweighted fits ran.
194
+ COLOR_SINGLE_FIT, COLOR_REWEIGHTED = "#2a78d6", "#eb6834"
195
+
196
+ #: Upper limit of the excess axis in :func:`plot_fit_scope`, in half-spreads.
197
+ EXCESS_AXIS_CAP = 10.
198
+
199
+ #: Colours of the two option sets in :func:`plot_fit_scope`.
200
+ COLOR_SET = {"all": "#2a78d6", "flt": "#1baf7a"}
201
+
202
+
203
+ def plot_fit_scope(stats: dict[str, dict[float | None, pd.DataFrame]], title: str, path: Path) -> None:
204
+ """
205
+ Each fit measured on the quotes it was fitted to: the full-book models on the full book, the reduced-set models on
206
+ the reduced set. One column per smoothness; rows: within bid/ask and mean excess. Reweighted days are marked.
207
+
208
+ ``stats`` maps the option set ("all", "flt") to the :func:`fit_statistics` frames by smoothness.
209
+ """
210
+ import matplotlib
211
+ matplotlib.use("Agg")
212
+ import matplotlib.pyplot as plt
213
+ from matplotlib.lines import Line2D
214
+
215
+ smoothnesses = list(dict.fromkeys(s for frames in stats.values() for s in frames))
216
+ fig, axs = plt.subplots(2, len(smoothnesses), figsize=(6 * len(smoothnesses), 7), sharex=True, sharey="row", squeeze=False)
217
+ for c, smoothness in enumerate(smoothnesses):
218
+ axs[0, c].set_title(f"Smoothness {_eta(smoothness)}")
219
+ for population, frames in stats.items():
220
+ if smoothness not in frames:
221
+ continue
222
+ frame = frames[smoothness]
223
+ dates = pd.to_datetime(frame.index)
224
+ reweighted = (frame["num_surface_fits"] > 1).to_numpy()
225
+ for r, column in enumerate((f"within_{population}_percent", "mean_excess")):
226
+ axs[r, c].plot(dates, frame[column], linewidth=.6, color=COLOR_SET[population], zorder=2)
227
+ if reweighted.any():
228
+ axs[r, c].scatter(dates[reweighted], frame[column].to_numpy()[reweighted], s=5, color=COLOR_REWEIGHTED, linewidths=0, zorder=3)
229
+ for r in range(2):
230
+ axs[r, c].grid(alpha=.3)
231
+ axs[0, 0].set_ylabel("Within bid/ask, own quotes (%)")
232
+ axs[1, 0].set_ylabel(f"Mean excess, own quotes\n(half-spreads, axis capped at {EXCESS_AXIS_CAP:g})")
233
+ axs[0, 0].set_ylim(0, 100)
234
+ axs[1, 0].set_ylim(0, EXCESS_AXIS_CAP) # a handful of days with one or two far misses would flatten everything else
235
+ fig.suptitle(title, fontsize=14)
236
+ fig.legend(handles=[Line2D([], [], color=COLOR_SET[p], linewidth=1.5, label=f"fitted to and measured on the {SETS[p]}") for p in stats] +
237
+ [Line2D([], [], color=COLOR_REWEIGHTED, marker="o", markersize=5, linestyle="", label="days with reweighted fits")],
238
+ loc="lower center", ncols=len(stats) + 1, frameon=False)
239
+ fig.autofmt_xdate()
240
+ fig.tight_layout(rect=(0., .05, 1., .97))
241
+ fig.savefig(path, dpi=150)
242
+ plt.close(fig)
243
+
244
+
245
+ def plot_time_series(stats_by_smoothness: dict[float | None, pd.DataFrame], title: str, path: Path) -> None:
246
+ """
247
+ One column per smoothness; rows: within bid/ask on each option set, mean and median excess, fit time, options.
248
+
249
+ Days whose surface fit was reweighted are marked in a second colour.
250
+ """
251
+ import matplotlib
252
+ matplotlib.use("Agg")
253
+ import matplotlib.pyplot as plt
254
+ from matplotlib.lines import Line2D
255
+
256
+ panels = [("within_all_percent", "Within bid/ask: full book (%)"), ("within_flt_percent", "Within bid/ask: reduced set (%)"),
257
+ ("mean_excess", "Mean excess (half-spreads)"), ("median_excess", "Median excess (half-spreads)"),
258
+ ("fit_seconds", "Fit time (seconds)"), ("num_options", "Paired options fitted")]
259
+ columns = list(stats_by_smoothness.items())
260
+ fig, axs = plt.subplots(len(panels), len(columns), figsize=(6 * len(columns), 3 * len(panels)),
261
+ sharex=True, sharey="row", squeeze=False)
262
+ any_reweighted = False
263
+ for c, (smoothness, stats) in enumerate(columns):
264
+ dates = pd.to_datetime(stats.index)
265
+ reweighted = (stats["num_surface_fits"] > 1).to_numpy()
266
+ any_reweighted |= bool(reweighted.any())
267
+ axs[0, c].set_title(f"Smoothness {_eta(smoothness)}" + (f": {int(reweighted.sum()):,} of {len(stats):,} days reweighted" if reweighted.any() else ""))
268
+ for r, (column, label) in enumerate(panels):
269
+ axs[r, c].plot(dates, stats[column], linewidth=.6, color=COLOR_SINGLE_FIT, zorder=2)
270
+ if reweighted.any():
271
+ axs[r, c].scatter(dates[reweighted], stats[column].to_numpy()[reweighted], s=5, color=COLOR_REWEIGHTED, linewidths=0, zorder=3)
272
+ axs[r, c].grid(alpha=.3)
273
+ if c == 0:
274
+ axs[r, c].set_ylabel(label)
275
+ for r in (0, 1):
276
+ axs[r, 0].set_ylim(0, 100)
277
+ fig.suptitle(title, fontsize=14)
278
+ if any_reweighted:
279
+ fig.legend(handles=[Line2D([], [], color=COLOR_SINGLE_FIT, linewidth=1.5, label="daily fits"),
280
+ Line2D([], [], color=COLOR_REWEIGHTED, marker="o", markersize=5, linestyle="", label="days with reweighted fits")],
281
+ loc="upper right", ncols=2, frameon=False)
282
+ fig.autofmt_xdate()
283
+ fig.tight_layout(rect=(0., 0., 1., .98))
284
+ fig.savefig(path, dpi=150)
285
+ plt.close(fig)
286
+
287
+
288
+ # ================================================================
289
+ # Command-line interface
290
+ # ================================================================
291
+
292
+ import click
293
+
294
+ from openqdata.widb import _cli_defaults
295
+
296
+
297
+ @click.command()
298
+ @click.argument("ticker")
299
+ @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")
300
+ @click.option("--out", type=click.Path(file_okay=False, path_type=Path), required=True, help="Directory for the tables and figures")
301
+ @click.option("--smoothness", "smoothnesses", type=float, multiple=True, default=(0., .1, .25), show_default=True, help="Smoothness levels; 0 is the linear surface")
302
+ @click.option("--population", "populations", type=click.Choice(list(SETS)), multiple=True, default=tuple(SETS), show_default=True, help="Option sets whose fits are read; repeat for both")
303
+ @click.option("--exclude-halfdays", "exclude_halfdays", is_flag=True, help="Exclude NYSE early-close days (included by default)")
304
+ @click.option("--skip-missing", is_flag=True, help="Leave out days without a cached fit instead of failing")
305
+ @click.option("--workers", default=_cli_defaults.workers, type=int, help="Number of workers")
306
+ def main(ticker: str, period: list[dt.datetime], out: Path, smoothnesses: tuple[float, ...], populations: tuple[str, ...], exclude_halfdays: bool, skip_missing: bool, workers: int):
307
+ """Write the fit-statistics tables and time-series figures of TICKER from the cached fits."""
308
+ date_range = DateRange(start=period[0].date(), end=period[1].date(), exclude_half_days=exclude_halfdays)
309
+ out.mkdir(parents=True, exist_ok=True)
310
+ summaries, all_stats = {}, {}
311
+ for population in populations:
312
+ by_smoothness = all_stats.setdefault(population, {})
313
+ for smoothness in smoothnesses:
314
+ config = fit_config(smoothness)
315
+ stats = fit_statistics(ticker, date_range, population=population, mk_arb_free=config, skip_missing=skip_missing, workers=workers)
316
+ stats.to_csv(out / f"{ticker.lower()}-fit-statistics-{population}-{_eta(config.smoothness)}.csv")
317
+ by_smoothness[config.smoothness] = stats
318
+ summaries[(population, config.smoothness)] = summarize(stats)
319
+ plot_time_series(by_smoothness, f"{ticker}: daily fits to the {SETS[population]}", out / f"{ticker.lower()}-fit-statistics-{population}.png")
320
+ if len(all_stats) > 1:
321
+ plot_fit_scope(all_stats, f"{ticker}: each fit on the quotes it was fitted to", out / f"{ticker.lower()}-fit-statistics-scope.png")
322
+ table = summary_table(summaries)
323
+ (out / f"{ticker.lower()}-fit-statistics.md").write_text(table)
324
+ click.echo(table)
325
+
326
+
327
+ if __name__ == "__main__":
328
+ main()
@@ -0,0 +1,338 @@
1
+ """
2
+ Options Filter
3
+ ==============
4
+
5
+ Provides daily option data subject to some filter and optional normalization.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import datetime as dt
10
+ import math as math
11
+ import warnings as warnings
12
+ from dataclasses import dataclass
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+ from cdxcore.err import verify_inp
17
+ from cdxcore.subdir import CacheMode
18
+ from cdxcore.uniquehash import named_unique_filename48_8
19
+ from cdxcore.util import fmt_dict, fmt_list
20
+ from cdxcore.verbose import Context
21
+ from cdxcore.version import version
22
+
23
+ from openqdata.utils.pd import create_empty_df, restore_object_strings, verify_schema
24
+ from openqdata.widb.arbfree import (
25
+ SCHEMA_ARB_FREE_DAY_EXPIRY,
26
+ SCHEMA_ARB_FREE_DAY_SURFACE,
27
+ MkArbFree,
28
+ fit_config,
29
+ mk_arb_free_day,
30
+ )
31
+ from openqdata.widb.day import (
32
+ SCHEMA_ENRICHED_DAY,
33
+ ExpiryFilter,
34
+ RawDayFilter,
35
+ SubDir,
36
+ _processing,
37
+ enrich_day,
38
+ )
39
+
40
+ # ======================================================================
41
+ # Sample days for a given ticker
42
+ # ======================================================================
43
+
44
+ @version("0.63")
45
+ @dataclass(frozen=True)
46
+ class OptionsFilter:
47
+ """
48
+ Create a time series with a maximum number of valid options per time step.
49
+ """
50
+ normalize : bool = True # Normalize output data:
51
+ # * Drop ``spot``
52
+ # * Add ``spot_ret``: the return of the spot price compared to the previous day, i.e. ``spot / spot_prev - 1``.
53
+ # * Divide the following fields by spot: ``spot_prev``, ``call_ask``, ``call_bid``, ``fwd``, ``strike``, ``mkt_call_bid``, ``mkt_put_bid``, ``mkt_call_ask``, ``mkt_put_ask``.
54
+ max_num_options: int = 1000 #: Maximum number of options per day. If more remain after all other filters, ten per expiry are reserved and the rest is filled with the smallest ``abs(nms)``.
55
+ max_business_days_to_expiry: int = 252*3 #: Maximum business days to expiry.
56
+ max_nms: float|tuple[float,float] = (-5.,2.) #: Maximum |NMS5| or a tuple with NMS5_lower<0<NMS5_upper.
57
+ nms_use_atm : bool = True #: Whether to use NMS5 with the ATM volatility instead of the actual NMS5.
58
+ min_log_volume: float = 1.0 #: Minimum log volume.
59
+ min_log_open_interest: float = 1.0 #: Minimum log open interest.
60
+ remove_am: bool = False #: Whether to remove options that settled at the AM price.
61
+ min_opt_per_expiry: int = 10 #: Minimum number of options per expiry. This is applied *before* the max_num_options filter, and can lead to fewer than max_num_options being returned if there are many expiries with few options.
62
+
63
+ def __post_init__(self):
64
+ verify_inp(self.max_num_options >= 10, lambda : f"'max_num_options' must be at least 10, found {self.max_num_options}")
65
+ verify_inp(self.max_business_days_to_expiry > 0, lambda : f"'max_business_days_to_expiry' must be positive, found {self.max_business_days_to_expiry}")
66
+ if isinstance(self.max_nms, tuple):
67
+ verify_inp(len(self.max_nms) == 2, lambda : f"'max_nms' tuple must have length 2, found {len(self.max_nms)}")
68
+ verify_inp(self.max_nms[0] < 0 < self.max_nms[1], lambda : f"'max_nms' tuple must have negative first element and positive second element, found {self.max_nms}")
69
+ else:
70
+ verify_inp(self.max_nms > 0, lambda : f"'max_nms' must be positive, found {self.max_nms}")
71
+ verify_inp(self.min_log_volume >= 0, lambda : f"'min_log_volume' must be non-negative, found {self.min_log_volume}")
72
+ verify_inp(self.min_log_open_interest >= 0, lambda : f"'min_log_open_interest' must be non-negative, found {self.min_log_open_interest}")
73
+ verify_inp(self.min_opt_per_expiry > 0, lambda : f"'min_opt_per_expiry' must be positive, found {self.min_opt_per_expiry}")
74
+
75
+ def __str__(self):#by convention use a some what readable string with comma separated key=value pairs
76
+ return f"nopt={self.max_num_options},bdte={self.max_business_days_to_expiry},nms{'at' if self.nms_use_atm else ''}={self.max_nms},lvolu={self.min_log_volume},loi={self.min_log_open_interest},rmam={self.remove_am},mxpp={self.min_opt_per_expiry}"
77
+
78
+ def _filter(self, ticker : str, d : dt.date, df : pd.DataFrame) -> pd.DataFrame:
79
+ """
80
+ Filter data frame
81
+ """
82
+
83
+ assert set(df.columns) >= set(SCHEMA_ENRICHED_DAY), f"Internal error {ticker} {d}: DataFrame has missing columns. Missing: {fmt_list(set(SCHEMA_ENRICHED_DAY) - set(df.columns))}. Please contact the authors with an example."
84
+ assert not df.isna().any().any(), f"Internal error {ticker} {d}: filter resulted in NaN values. Please contact the authors with an example."
85
+
86
+ assert not df.empty, "Internal error - this should have been filtered earlier"
87
+ df = df[df['bdte'] <= self.max_business_days_to_expiry]
88
+
89
+ if self.normalize:
90
+ df = normalize_day(ticker, d, df)
91
+
92
+ min_nms = -self.max_nms if isinstance(self.max_nms, (int, float)) else self.max_nms[0]
93
+ max_nms = self.max_nms if isinstance(self.max_nms, (int, float)) else self.max_nms[1]
94
+
95
+ if self.nms_use_atm:
96
+ df = df[(df['nms_atm'] >= min_nms) & (df['nms_atm'] <= max_nms)]
97
+ else:
98
+ df = df[(df['nms'] >= min_nms) & (df['nms'] <= max_nms)]
99
+ df = df[df['log_volume'] >= self.min_log_volume] if self.min_log_volume > 0. else df
100
+ df = df[df['log_open_interest'] >= self.min_log_open_interest] if self.min_log_open_interest > 0. else df
101
+ if self.remove_am:
102
+ df = df[~df['is_am']]
103
+
104
+ # filter expiries
105
+ if not df.empty:
106
+ expiry_counts = df['expiry_id'].value_counts()
107
+ valid_expiries = expiry_counts[expiry_counts >= self.min_opt_per_expiry].index
108
+ df = df[df['expiry_id'].isin(valid_expiries)]
109
+ if df.empty:
110
+ expiry_counts = expiry_counts.to_dict()
111
+ expiry_counts = { d: expiry_counts[d] for d in sorted(expiry_counts) }
112
+ warnings.warn(f"{ticker} {d}: after filtering no expiry had the minimum of {self.min_opt_per_expiry} options per expiry left. This means this sample is not eligible. Here are the options per filtered expiry: {fmt_dict(expiry_counts)}.")
113
+ return df
114
+
115
+ # remove excess options while keeping min_opt_per_expiry per expiry, and the closes to ATM
116
+ if not df.empty and len(df) > self.max_num_options:
117
+ nms = df['nms'].to_numpy()
118
+ abs_nms = np.abs(nms)
119
+
120
+ # Reuse per-expiry positional indices instead of repeatedly filtering the full frame.
121
+ reserved_positions = []
122
+ remaining_positions = []
123
+
124
+ for expiry_id, expiry_positions in df.groupby('expiry_id', sort=False).indices.items():
125
+ expiry_positions = np.asarray(expiry_positions, dtype=np.intp)
126
+
127
+ assert len(expiry_positions) >= self.min_opt_per_expiry, f"Internal error: expiry_id {expiry_id} has fewer options than 'min_opt_per_expiry' after filtering. This should not happen, as we already filtered out expiries with too few options. Please contact the authors with an example."
128
+ if len(expiry_positions) == self.min_opt_per_expiry:
129
+ reserved_positions.append(expiry_positions)
130
+ continue
131
+
132
+ expiry_nms = nms[expiry_positions]
133
+ selected_mask = np.zeros((len(expiry_positions),), dtype=bool)
134
+ selected_positions = []
135
+
136
+ # Add smallest positive NMS.
137
+ pos_local = np.flatnonzero(expiry_nms > 0.)
138
+ if len(pos_local) > 0:
139
+ best_pos_local = pos_local[np.argmin(expiry_nms[pos_local])]
140
+ selected_mask[best_pos_local] = True
141
+ selected_positions.append(expiry_positions[best_pos_local:best_pos_local+1])
142
+
143
+ # Add highest negative NMS.
144
+ neg_local = np.flatnonzero(expiry_nms < 0.)
145
+ if len(neg_local) > 0:
146
+ best_neg_local = neg_local[np.argmax(expiry_nms[neg_local])]
147
+ if not selected_mask[best_neg_local]:
148
+ selected_mask[best_neg_local] = True
149
+ selected_positions.append(expiry_positions[best_neg_local:best_neg_local+1])
150
+
151
+ # Add (min_opt_per_expiry - 2) remaining options with smallest abs(NMS).
152
+ remaining_count = self.min_opt_per_expiry - np.sum(selected_mask)
153
+ if remaining_count > 0:
154
+ remaining_local = np.flatnonzero(~selected_mask)
155
+ if len(remaining_local) > 0:
156
+ remaining_order = remaining_local[np.argsort(abs_nms[expiry_positions[remaining_local]], kind='stable')]
157
+ extra_local = remaining_order[:remaining_count]
158
+ selected_mask[extra_local] = True
159
+ selected_positions.append(expiry_positions[extra_local])
160
+
161
+ reserved_positions.append(np.concatenate(selected_positions) if selected_positions else np.empty((0,), dtype=np.intp))
162
+
163
+ expiry_remaining = expiry_positions[~selected_mask]
164
+ if len(expiry_remaining) > 0:
165
+ remaining_positions.append(expiry_remaining)
166
+
167
+ reserved_positions = np.concatenate(reserved_positions) if reserved_positions else np.empty((0,), dtype=np.intp)
168
+ remaining_positions = np.concatenate(remaining_positions) if remaining_positions else np.empty((0,), dtype=np.intp)
169
+
170
+ # Sort remaining by abs_nms and limit.
171
+ remaining_slots = max(0, self.max_num_options - len(reserved_positions))
172
+ if remaining_slots > 0 and len(remaining_positions) > 0:
173
+ remaining_positions = remaining_positions[np.argsort(abs_nms[remaining_positions], kind='stable')[:remaining_slots]]
174
+ else:
175
+ remaining_positions = np.empty((0,), dtype=np.intp)
176
+
177
+ # Combine reserved and remaining.
178
+ df = df.iloc[np.concatenate([reserved_positions, remaining_positions])]
179
+ assert len(df) <= self.max_num_options, f"Internal error {ticker} {d}: after filtering by max_num_options, the number of options exceeds max_num_options. Please contact the authors with an example."
180
+
181
+ if df.empty:
182
+ raise RuntimeError(f"Internal error {ticker} {d}: filter resulted in an empty data set. Please contact the authors with an example.")
183
+ assert not df.isna().any().any(), f"Internal error {ticker} {d}: filter resulted in NaN values. Please contact the authors with an example."
184
+
185
+ return df
186
+
187
+ @version("0.3", dependencies=[enrich_day] )
188
+ def normalize_day(ticker : str, d : dt.date, df : pd.DataFrame) -> pd.DataFrame:
189
+ """
190
+ Create a normalized version of a day.
191
+
192
+ * Drop ``spot``
193
+ * Add ``spot_ret``: the return of the spot price compared to the previous day, i.e. ``spot / spot_prev - 1``.
194
+ * Divide the following fields by spot: ``spot_prev``, ``call_ask``, ``call_bid``, ``fwd``, ``strike``, ``mkt_call_bid``, ``mkt_put_bid``, ``mkt_call_ask``, ``mkt_put_ask``.
195
+ """
196
+ df = df.copy()
197
+ spot = df['spot'].to_numpy()
198
+ spot_prev = df['spot_prev'].to_numpy()
199
+
200
+ if np.min(spot) <= 0.:
201
+ raise ValueError(f"{ticker} {d}: Expected positive spot, got {np.min(spot):.4g} for ticker {ticker}.")
202
+ if np.min(spot_prev) <= 0.:
203
+ raise ValueError(f"{ticker} {d}: Expected positive spot_prev, got {np.min(spot_prev):.4g} for ticker {ticker}.")
204
+
205
+ df = df.drop(columns="spot")
206
+ df['spot_ret'] = spot / spot_prev - 1.
207
+ df['spot_ref'] = spot
208
+ df['spot_prev'] /= spot
209
+ df['call_ask'] /= spot
210
+ df['call_bid'] /= spot
211
+ df['fwd'] /= spot
212
+ df['strike'] /= spot
213
+
214
+ df['mkt_call_bid'] /= spot
215
+ df['mkt_put_bid'] /= spot
216
+ df['mkt_call_ask'] /= spot
217
+ df['mkt_put_ask'] /= spot
218
+ return df
219
+
220
+ def SCHEMA_OPTION_DAY( mk_arb_free: MkArbFree|None, normalized : bool ) -> list[str]:
221
+ """
222
+ Returns the schema for an option day series object depending on the :class:`MkArbFree` configuration and whether it is normalized or not.
223
+ """
224
+ if mk_arb_free is None:
225
+ source_schema = SCHEMA_ENRICHED_DAY
226
+ elif mk_arb_free.no_arb_mode == "expiry":
227
+ source_schema = SCHEMA_ARB_FREE_DAY_EXPIRY
228
+ elif mk_arb_free.no_arb_mode == "surface":
229
+ source_schema = SCHEMA_ARB_FREE_DAY_SURFACE
230
+ else:
231
+ raise ValueError(f"Unknown no_arb_mode: {mk_arb_free.no_arb_mode}")
232
+
233
+ if normalized:
234
+ source_schema = dict(source_schema)
235
+ del source_schema['spot']
236
+ source_schema['spot_ref'] = np.float32
237
+ source_schema['spot_ret'] = np.float32
238
+
239
+ return source_schema
240
+
241
+ @version( "0.3", dependencies=[enrich_day, mk_arb_free_day, OptionsFilter, normalize_day] )
242
+ def filter_options_day(
243
+ ticker: str,
244
+ d: dt.date,
245
+ source_data : pd.DataFrame | None = None,
246
+ *,
247
+ raw_day_filter: RawDayFilter = RawDayFilter(),
248
+ expiry_filter: ExpiryFilter = ExpiryFilter(),
249
+ mk_arb_free: MkArbFree = fit_config(),
250
+ options_filter : OptionsFilter = OptionsFilter(),
251
+ # operational
252
+ raise_if_bad_day: bool = True,
253
+ # pass on caching parameters
254
+ override_cache_mode: CacheMode | None = None,
255
+ cache_generate_only : bool = False,
256
+ # verbose
257
+ verbose: Context = Context.all,
258
+ ) -> pd.DataFrame | tuple[pd.DataFrame, dict]:
259
+ """
260
+ Filter options according to ``options_filter``.
261
+
262
+ This includes filtering by moneyness, time to expiry, volume, open interest, and other criteria defined in :class:`OptionsFilter`.
263
+ This function itself is not cached, but it since it is basically a thin layer on top of :func:`mk_arb_free_day` and the filtering logic is fast,
264
+ caching is implicit.
265
+ """
266
+ verify_inp(isinstance(options_filter, OptionsFilter), lambda : f"'options_filter' must be an instance of OptionsFilter, found {type(options_filter)}")
267
+ verify_inp(mk_arb_free is None or isinstance(mk_arb_free, MkArbFree), lambda : f"'mk_arb_free' must be None or an instance of MkArbFree, found {type(mk_arb_free)}")
268
+ verify_inp(isinstance(raw_day_filter, RawDayFilter), lambda : f"'raw_day_filter' must be an instance of RawDayFilter, found {type(raw_day_filter)}")
269
+ verify_inp(isinstance(expiry_filter, ExpiryFilter), lambda : f"'expiry_filter' must be an instance of ExpiryFilter, found {type(expiry_filter)}")
270
+
271
+ schema = SCHEMA_OPTION_DAY(mk_arb_free, options_filter.normalize)
272
+
273
+ if not source_data is None:
274
+ verify_inp( isinstance(source_data, pd.DataFrame), f"{ticker} {d}: expected 'source_data' to be a pandas DataFrame or None, got {type(source_data)}.")
275
+ data = source_data
276
+ else:
277
+ data = mk_arb_free_day(
278
+ ticker=ticker, d=d,
279
+ raw_day_filter=raw_day_filter,
280
+ expiry_filter=expiry_filter,
281
+ mk_arb_free=mk_arb_free,
282
+ raise_if_bad_day=raise_if_bad_day,
283
+ verbose=verbose,
284
+ # pass on caching parameters
285
+ override_cache_mode=override_cache_mode,
286
+ cache_generate_only=cache_generate_only )
287
+
288
+ if data is None:
289
+ 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."
290
+ return None
291
+
292
+ if data.empty:
293
+ return create_empty_df(schema)
294
+
295
+ data = options_filter._filter(ticker, d, data)
296
+ data = restore_object_strings(data, schema)
297
+ verify_schema(data, schema, lambda : f"{ticker} {d}")
298
+ return data
299
+
300
+ @_processing(fmt=SubDir.PICKLE).cache(
301
+ "0.1",
302
+ dependencies=[filter_options_day],
303
+ uid=lambda ticker, d, raw_day_filter, expiry_filter, mk_arb_free, options_filter :\
304
+ f"options/{named_unique_filename48_8(f'{str(expiry_filter)},{str(raw_day_filter)},{str(mk_arb_free)},{str(options_filter)}', expiry_filter, raw_day_filter, mk_arb_free, options_filter)}"+\
305
+ f"/{ticker}/{d}"
306
+ )
307
+ def _filter_options_day_num_options( *,
308
+ ticker: str,
309
+ d: dt.date,
310
+ raw_day_filter: RawDayFilter = RawDayFilter(),
311
+ expiry_filter: ExpiryFilter = ExpiryFilter(),
312
+ mk_arb_free: MkArbFree = fit_config(),
313
+ options_filter : OptionsFilter = OptionsFilter(),
314
+ # operational
315
+ raise_if_bad_day: bool = True,
316
+ # pass on caching parameters
317
+ override_cache_mode: CacheMode | None = None,
318
+ cache_generate_only : bool = False,
319
+ # verbose
320
+ verbose: Context|None = Context.quiet
321
+ ) -> int:
322
+ """
323
+ Dummy wrapper around :func:`filter_options_day` to cache the number of options after filtering.
324
+ """
325
+ r = filter_options_day(
326
+ ticker=ticker, d=d,
327
+ raw_day_filter=raw_day_filter, expiry_filter=expiry_filter, mk_arb_free=mk_arb_free, options_filter=options_filter,
328
+ raise_if_bad_day=raise_if_bad_day,
329
+ override_cache_mode=override_cache_mode, cache_generate_only=cache_generate_only,
330
+ verbose=verbose if not verbose is None else Context.quiet
331
+ )
332
+ return len(r) if not r is None else None
333
+
334
+
335
+ if __name__ == "__main__":
336
+ from openqdata.cli import run_module
337
+
338
+ run_module(globals())