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
openqdata/widb/day.py ADDED
@@ -0,0 +1,1098 @@
1
+ """
2
+ Generating one day of WRDS Option Metrics data for one ticker
3
+ =============================================================
4
+
5
+ Key functions:
6
+
7
+ * :func:`collect_raw_day` - Collect raw option data with minimal analytics for a ticker and date
8
+ * :func:`enrich_day` - Enrich raw data with implied volatilities, greeks, and synthetic call options
9
+
10
+ Summary
11
+ -------
12
+ This module provides tools to process daily option data from WRDS Option Metrics (IvyDB):
13
+
14
+ 1. **collect_raw_day**: Downloads spot, forward, discount factor, and option data. Cleans bad options
15
+ and computes business days to expiry and implied discount factors. Returns a raw DataFrame.
16
+
17
+ 2. **enrich_day**: Builds on raw data by computing implied forwards from put-call parity, synthetic
18
+ minimal-spread call options, implied volatilities, and option greeks (delta, gamma, vega, theta).
19
+
20
+ Both functions use filtering configurations to control data quality and processing parameters.
21
+
22
+ Usage Example
23
+ -------------
24
+ >>> from openqdata.widb.day import collect_raw_day, enrich_day, RawDayFilter, ExpiryFilter
25
+ >>> from openqdata.biz_calendar import to_date
26
+ >>> from cdxcore.verbose import Context
27
+ >>> import datetime as dt
28
+ >>>
29
+ >>> # Define date and filters
30
+ >>> d = to_date("2022-01-03")
31
+ >>> ticker = "SPX"
32
+ >>> raw_filter = RawDayFilter() # the benchmark filters; other settings are other cache entries
33
+ >>> enriched_filter = ExpiryFilter()
34
+ >>>
35
+ >>> # Read cached days; drop override_cache_mode to download and compute missing ones
36
+ >>> raw_data = collect_raw_day(ticker, d, raw_filter, override_cache_mode="cacheonly", verbose=Context())
37
+ >>> enriched_data = enrich_day(ticker, d, raw_data, raw_day_filter=raw_filter,
38
+ ... expiry_filter=enriched_filter, override_cache_mode="cacheonly", verbose=Context())
39
+ >>>
40
+ >>> # Access results
41
+ >>> print(enriched_data[['strike', 'fwd', 'ask_vol', 'bid_vol', 'pure_ask_delta']].head())
42
+
43
+ This file's ``main`` can also be used to generate data manually:
44
+
45
+ ::
46
+
47
+ python -m openqdata.widb.day SPX RUT NDX --period 2020-05-01 2022-01-31
48
+
49
+ """
50
+ from __future__ import annotations
51
+
52
+ import datetime as dt
53
+ import math as math
54
+ import warnings
55
+ from dataclasses import dataclass
56
+
57
+ import numpy as np
58
+ import pandas as pd
59
+ from cdxcore.bs import bs
60
+ from cdxcore.err import verify, verify_inp
61
+ from cdxcore.pretty import PrettyObject
62
+ from cdxcore.subdir import CacheMode, SubDir
63
+ from cdxcore.uniquehash import named_unique_filename48_8
64
+ from cdxcore.util import fmt_date, fmt_list
65
+ from cdxcore.verbose import Context
66
+ from cdxcore.version import version
67
+ from scipy.optimize import linprog
68
+
69
+ from openqdata.biz_calendar import (
70
+ AM_EXIRY_SUBTRACT,
71
+ DAYS_PER_YEAR,
72
+ NMS5,
73
+ DateRange,
74
+ count_business_days_between,
75
+ prev_business_day,
76
+ to_date,
77
+ )
78
+ from openqdata.pool import PoolConfig
79
+ from openqdata.utils.pd import create_empty_df, restore_object_strings, verify_schema
80
+ from openqdata.widb import WIDBClient, interpolate_zero_curve
81
+ from openqdata.widb.bad import BAD
82
+
83
+ _processing = WIDBClient.locations.processed("day",fmt=SubDir.PANDAS_PARQUET)
84
+ _IMPLIED_VOL_CALC_EPS = 1E-8
85
+ _GREEK_CALC_EPS = 1E-8
86
+ _MIN_IMPLIED_VOL = 0.01
87
+ _MAX_IMPLIED_VOL = 5.
88
+
89
+ # ---------------------------------------------------------------------------
90
+ # Raw data, day
91
+ # Minimal analytics and clean up.
92
+ # ---------------------------------------------------------------------------
93
+
94
+ SCHEMA_RAW_DAY = {
95
+ 'ticker' : np.dtype('O'),
96
+ 'date' : np.dtype("datetime64[ms]"), # [D] not supported in storage
97
+ 'spot' : np.float32,
98
+ 'spot_prev' : np.float32,
99
+ 'call_symbol' : np.dtype("O"),
100
+ 'put_symbol' : np.dtype("O"),
101
+ 'call_opt_id' : np.int32,
102
+ 'put_opt_id' : np.int32,
103
+ 'expiry_id' : np.int32,
104
+ 'is_american' : np.bool_,
105
+ 'is_am' : np.bool_,
106
+ 'strike' : np.float32,
107
+ 'fwd_ref' : np.float32,
108
+ 'df' : np.float32,
109
+ 'expiry' : np.dtype("datetime64[ms]"), # [D] not supported in storage``
110
+ 'bdte' : np.float32, # this is a float because of AM options.
111
+ 'tte_y' : np.float32,
112
+ 'mkt_call_ask' : np.float32,
113
+ 'mkt_call_bid' : np.float32,
114
+ 'mkt_call_log_volume' : np.float32,
115
+ 'mkt_call_log_open_interest' : np.float32,
116
+ 'mkt_put_ask' : np.float32,
117
+ 'mkt_put_bid' : np.float32,
118
+ 'mkt_put_log_volume' : np.float32,
119
+ 'mkt_put_log_open_interest' : np.float32,
120
+ }
121
+
122
+ RAW_PER_DAY_FIELDS = {'ticker','date','spot','spot_prev'}
123
+ RAW_PER_EXPIRY_FIELDS = {'expiry_id','expiry','bdte','tte_y','is_am','fwd_ref','df'}
124
+
125
+ IRREGULAR_EXPIRES = {
126
+ dt.date(2025,1,9) # SPX 2025-01-10 expiry was announced on 2025-01-09, which is the same day as the 2025-01-10 expiry, leading to data issues. We consider this an irregular expiry and drop it by default. If you want to keep it, please set RawDayFilter.drop_irregular_expiries to False and add the date to the BAD data sets if you confirm the data quality is sufficient.
127
+ }
128
+
129
+ @version("0.5")
130
+ @dataclass(frozen=True)
131
+ class RawDayFilter:
132
+ min_bid : float = 0.011 # minimum bid value, typically above one tick.
133
+ drop_irregular_expiries : bool = True # drop irregular expiries, ie holidays which were announced shortly
134
+
135
+ def __post_init__(self):
136
+ verify_inp(self.min_bid >= 0., lambda : f"'min_bid' must be non-negative, found {self.min_bid:.3f}")
137
+
138
+ def __str__(self):#by convention use a some what readable string with comma separated key=value pairs
139
+ return f"bid={self.min_bid:.3f}"
140
+
141
+ @_processing(fmt=SubDir.PANDAS_PARQUET).cache(
142
+ "0.7", # 0.8 only restored object string dtypes for pandas 3; enrich_day restores them on input
143
+ dependencies=[interpolate_zero_curve, WIDBClient],
144
+ uid=lambda ticker, d, raw_day_filter : f"raw/{named_unique_filename48_8(str(raw_day_filter),raw_day_filter)}/{ticker}/{fmt_date(d)}",
145
+ exclude_args=['verbose','raise_if_bad_day'])
146
+ def collect_raw_day( ticker : str,
147
+ d : dt.date,
148
+ raw_day_filter : RawDayFilter, *,
149
+ raise_if_bad_day : bool = True,
150
+ verbose : Context = Context.all, secid : int|None = None ) -> pd.DataFrame:
151
+ """
152
+ Collect raw data with minimal analytics for a given ticker and date.
153
+
154
+ The function returns a panda data frame with columns :attr:`SCHEMA_RAW_DAY`.
155
+
156
+ The function:
157
+
158
+ * Downloads spot, forward, discount and option data.
159
+ * Removes and bad days/tickers/options using :attr:`openqdata.widb.bad.BAD`.
160
+ * Removes options with same-day expiry, missing quotes, bids at or below the bid floor, locked or crossed quotes, and bad settlement (ss_flag != '0').
161
+ By default the function also removed irregular expiries, which are holidays that were announced shortly before the expiry date, leading to data issues.
162
+ * Computes the implied discount factor from the zero curve and the reference forward price from the forward table (which is unreliable; it is stored as ``fwd_ref`` and not used for fitting).
163
+ * Computes business days to expiry and a unique expiry ID (which includes AM/PM).
164
+
165
+ Typically the result of this function is processed with :func:`enrich_day`.
166
+
167
+ Parameters
168
+ ----------
169
+ ticker : str
170
+ Ticker symbol, e.g. "SPX"
171
+ d : :class:`datetime.date`
172
+ Date for which to collect data
173
+ raw_day_filter : :class:`RawDayFilter`
174
+ Configuration for data collection
175
+ raise_if_bad_day : bool, default ``True``
176
+ If ``True``, raises an error if the date is in the BAD data sets. If ``False``, returns an empty data set instead. (In no other condition will an empty data set returned)
177
+ verbose : :class:`cdxcore.verbose.Context`
178
+ Verbose context for logging
179
+
180
+ Returns
181
+ -------
182
+ Daily data: :class:`pandas.DataFrame`
183
+ Cleaned DataFrame with all relevant data for the given ticker and date, with the schema :attr:`SCHEMA_RAW_DAY`.
184
+ This data set is not empty unless ``raise_if_bad_day`` is False and the date/ticker is in the BAD data sets.
185
+
186
+ Raises
187
+ ------
188
+ Not found: :class:`LookupError`
189
+ If no data was downloaded from IvyDB for the given ticker and date.
190
+ No data: :class:`EOFError`
191
+ If no data was available for the given ticker and date.
192
+ Bad day: :class:`IndexError`
193
+ If this date and ticker are known to have bad data; see :class:`openqdata.widb.bad.BAD` for details.
194
+ Bad data: :class:`RuntimeError`
195
+ If data was downloaded but found to be bad after basic cleaning steps.
196
+ This can happen for example if the forward price is highly suspicious, or if all options had zero or NA bid prices. Please check the date range and calendar settings,
197
+ and consider adding the date/ticker to the BAD data sets if the issue is confirmed.
198
+ """
199
+ verify_inp(isinstance(raw_day_filter, RawDayFilter), lambda : f"'raw_day_filter' must be an instance of RawDayFilter, found {type(raw_day_filter)}")
200
+
201
+ if d >= BAD.LAST_LIKELY_VALID_DATE:
202
+ raise ValueError(f"{d} is on or after the BAD.LAST_LIKELY_VALID_DATE ({BAD.LAST_LIKELY_VALID_DATE}). Data for this date is likely to be missing from Option Metrics. "+\
203
+ "If you are sure this is not the case, please update widb/bad.py.")
204
+
205
+ if d in BAD.DAYS_ALL:
206
+ if not raise_if_bad_day:
207
+ return create_empty_df(SCHEMA_RAW_DAY)
208
+ raise IndexError(f"{d} is in the BAD.DAYS_ALL set. No data will be downloaded for this date. Please check the date range and calendar settings. BAD.DAYS_ALL={BAD.DAYS_ALL}")
209
+ if d in BAD.DAYS_TICKER.get(ticker, set()):
210
+ if not raise_if_bad_day:
211
+ return create_empty_df(SCHEMA_RAW_DAY)
212
+ raise IndexError(f"{d} is in the BAD.DAYS_TICKER set for {ticker}. No data will be downloaded for this date. Please check the date range and calendar settings. BAD.DAYS_TICKER[{ticker}]={BAD.DAYS_TICKER.get(ticker, set())}")
213
+
214
+ conn = WIDBClient()
215
+ secid = conn.lookup_secid(ticker)
216
+
217
+ with verbose.write_t(f"Collecting raw market data for {ticker} on {d}."):
218
+ try:
219
+ spot = conn.spot_price(secid, d, verbose=verbose(1))
220
+ except LookupError as e:
221
+ raise LookupError(f"Failed to fetch spot price for {ticker} on {d}. "+\
222
+ f"This likely means either the corresponding secid {secid} is not covered by Option Metrics, or {d} is not a business day for this underlying. Please check the date range and calendar settings.") from e
223
+
224
+ try:
225
+ prev_d = prev_business_day(d, count_start=False)
226
+ spot_d = conn.spot_price(secid, prev_d, verbose=verbose(1))
227
+ except LookupError as e:
228
+ raise LookupError(f"Failed to fetch spot price for {ticker} on previous business day {prev_d} (relative to {d}).") from e
229
+
230
+ zero_curve = conn.zero_curve(d, verbose=verbose(1))
231
+ opts_pd = conn.options(secid, d, verbose=verbose(1))
232
+ fwd_table = conn.forwards(secid, d, verbose=verbose(1))
233
+
234
+ assert isinstance(zero_curve, pd.DataFrame), f"Internal error: expected zero_curve to be a pandas DataFrame, found {type(zero_curve)}"
235
+ assert isinstance(opts_pd, pd.DataFrame), f"Internal error: expected opts_pd to be a pandas DataFrame, found {type(opts_pd)}"
236
+ assert isinstance(fwd_table, pd.DataFrame), f"Internal error: expected fwd_table to be a pandas DataFrame, found {type(fwd_table)}"
237
+
238
+ if opts_pd.empty:
239
+ raise EOFError(f"No option data found for {ticker} on {d}. Please check the date range and calendar settings.")
240
+ if zero_curve.empty:
241
+ raise EOFError(f"No zero-curve data for {d}")
242
+ if fwd_table.empty:
243
+ raise EOFError(f"No forward price data for {ticker} on {d}")
244
+
245
+ # Remove bad options
246
+ # ------------------
247
+ # exclude known bad options, either in totality (by symbol) or per date
248
+
249
+ status_removed = []
250
+ n_total = len(opts_pd)
251
+
252
+ def remove_bad( status_removed, opts_pd ):
253
+ bad_options = BAD.OPTIONS.get(ticker,set()) | BAD.OPTIONS_BY_DATE.get(ticker,{}).get(d, set())
254
+ if len(bad_options) > 0:
255
+ n_before = len(opts_pd)
256
+ opts_pd = opts_pd.loc[~opts_pd["symbol"].astype(str).isin(bad_options)].copy()
257
+ n_removed = n_before - len(opts_pd)
258
+ if opts_pd.empty:
259
+ raise EOFError(f"No option data found for {ticker} on {d} after having removed {n_removed} bad options {fmt_list(sorted(bad_options))}. Please check BAD.OPTIONS and the date range.")
260
+ if n_removed > 0:
261
+ status_removed.append(f"{n_removed}/{n_before} 'bad' options")
262
+ return status_removed, opts_pd
263
+ status_removed, opts_pd = remove_bad(status_removed, opts_pd)
264
+
265
+ # Remove same day expiry
266
+ # ----------------------
267
+
268
+ def remove_same_day_expiry( status_removed, opts_pd ):
269
+ opts_pd['exdate'] = pd.to_datetime(opts_pd['exdate']).dt.date
270
+ same_day_expiry_mask = opts_pd['exdate'] == d
271
+ if same_day_expiry_mask.any():
272
+ n_before = len(opts_pd)
273
+ opts_pd = opts_pd.loc[~same_day_expiry_mask].copy()
274
+ n_removed = n_before - len(opts_pd)
275
+ if opts_pd.empty:
276
+ raise EOFError(f"{ticker} {d}: all option rows expired today and were dropped.")
277
+ if n_removed > 0:
278
+ status_removed.append(f"{n_removed}/{n_before} options with same-day expiry")
279
+ return status_removed, opts_pd
280
+ status_removed, opts_pd = remove_same_day_expiry(status_removed, opts_pd)
281
+
282
+ def remove_irregular_expiries( status_removed, opts_pd ):
283
+ if raw_day_filter.drop_irregular_expiries:
284
+ opts_pd['exdate'] = pd.to_datetime(opts_pd['exdate']).dt.date
285
+ irregular_expiry_mask = opts_pd['exdate'].isin(IRREGULAR_EXPIRES)
286
+ if irregular_expiry_mask.any():
287
+ n_before = len(opts_pd)
288
+ opts_pd = opts_pd.loc[~irregular_expiry_mask].copy()
289
+ n_removed = n_before - len(opts_pd)
290
+ if opts_pd.empty:
291
+ raise EOFError(f"{ticker} {d}: all option rows had irregular expiries and were dropped.")
292
+ if n_removed > 0:
293
+ status_removed.append(f"{n_removed}/{n_before} options with irregular expiries")
294
+ return status_removed, opts_pd
295
+
296
+ status_removed, opts_pd = remove_irregular_expiries(status_removed, opts_pd)
297
+
298
+ # remove NA quotes
299
+ # ----------------
300
+
301
+ def remove_na_quotes( status_removed, opts_pd ):
302
+ na_quotes = opts_pd["best_bid"].isna() | opts_pd["best_offer"].isna()
303
+ if na_quotes.any():
304
+ n_before = len(opts_pd)
305
+ opts_pd = opts_pd.loc[~na_quotes].copy()
306
+ n_removed = n_before - len(opts_pd)
307
+ if opts_pd.empty:
308
+ raise EOFError(f"No option data found for {ticker} on {d} after removing {n_removed}/{n_before} options with NA bid or ask. Please check the date range and calendar settings.")
309
+ if n_removed > 0:
310
+ status_removed.append(f"{n_removed}/{n_before} options with NA bid or ask")
311
+ return status_removed, opts_pd
312
+ status_removed, opts_pd = remove_na_quotes(status_removed, opts_pd)
313
+
314
+ # remove crossed quotes
315
+ # ---------------------
316
+
317
+ def remove_crossed_quotes( status_removed, opts_pd ):
318
+ crossed_quotes = (
319
+ ( opts_pd["best_bid"].fillna(0.0).astype(float)
320
+ >= opts_pd["best_offer"].fillna(0.0).astype(float) )
321
+ )
322
+ if crossed_quotes.any():
323
+ n_before = len(opts_pd)
324
+ opts_pd = opts_pd.loc[~crossed_quotes].copy()
325
+ n_removed = n_before - len(opts_pd)
326
+ if opts_pd.empty:
327
+ raise EOFError(
328
+ f"No option data found for {ticker} on {d} after removing {n_removed}/{n_before} options with bid >= ask."
329
+ )
330
+ if n_removed > 0:
331
+ status_removed.append(f"{n_removed}/{n_before} options with bid >= ask")
332
+ return status_removed, opts_pd
333
+ status_removed, opts_pd = remove_crossed_quotes(status_removed, opts_pd)
334
+
335
+ # remove zero quotes
336
+ # ------------------
337
+
338
+ def remove_zero( status_removed, opts_pd ):
339
+ zero_quotes = (
340
+ opts_pd["best_bid"].fillna(0.0).astype(float) <= raw_day_filter.min_bid
341
+ )
342
+ if zero_quotes.any():
343
+ n_before = len(opts_pd)
344
+ opts_pd = opts_pd.loc[~zero_quotes].copy()
345
+ n_removed = n_before - len(opts_pd)
346
+ if opts_pd.empty:
347
+ raise EOFError(
348
+ f"No option data found for {ticker} on {d} after removing {n_removed}/{n_before} options with bid <= {raw_day_filter.min_bid}."
349
+ )
350
+ if n_removed > 0:
351
+ status_removed.append(f"{n_removed}/{n_before} options with bid <= {raw_day_filter.min_bid}")
352
+ return status_removed, opts_pd
353
+ status_removed, opts_pd = remove_zero(status_removed, opts_pd)
354
+
355
+ # remove bad settlement
356
+ # ---------------------
357
+
358
+ def remove_bad_ss( status_removed, opts_pd ):
359
+ n_ss_bad = opts_pd['ss_flag'].values != "0"
360
+ if n_ss_bad.any():
361
+ n_before = len(opts_pd)
362
+ opts_pd = opts_pd.loc[~n_ss_bad].copy()#
363
+ n_removed = n_before - len(opts_pd)
364
+ if opts_pd.empty:
365
+ raise EOFError(
366
+ f"No option data found for {ticker} on {d} after removing {n_removed}/{n_before} options with ss_flag != '0'."
367
+ )
368
+ if n_removed > 0:
369
+ status_removed.append(f"{n_removed}/{n_before} options with bad settlement (ss_flag != '0')")
370
+ return status_removed, opts_pd
371
+ status_removed, opts_pd = remove_bad_ss(status_removed, opts_pd)
372
+
373
+ # implied df
374
+ # ----------
375
+
376
+ def df_ref( opts_pd, zero_curve ):
377
+ opts_pd = opts_pd.assign(
378
+ discount_factor_ref=lambda frame: interpolate_zero_curve(
379
+ zero_curve,
380
+ np.array(
381
+ [
382
+ ( pd.Timestamp(exdate).date() - d).days
383
+ for exdate in frame["exdate"]
384
+ ],
385
+ dtype=float,
386
+ ),
387
+ ))
388
+ assert np.min( opts_pd["discount_factor_ref"].values) > 0., f"Internal error {ticker} {d}: all implied discount factors must be positive"
389
+ return opts_pd
390
+ opts_pd = df_ref(opts_pd, zero_curve)
391
+
392
+ # computed implied forward
393
+ # ------------------------
394
+
395
+ def forward_ref( opts_pd, fwd_table ):
396
+ # Forward prices by expiry (and AM/PM settlement).
397
+ # fwd_table is small (one row per expiry/settlement), opts_pd is large.
398
+ # Use a MultiIndex reindex (O(n)) rather than a per-row lookup.
399
+ # Note that IvyDB forward prices are highyl suspicious.
400
+ # We treat them as "forward_ref" only
401
+ assert not fwd_table.empty, "Internal error"
402
+ if "am_settlement" not in fwd_table.columns:
403
+ fwd_table["am_settlement"] = 0.0
404
+ # Keep only what we need for mapping (avoids dtype edge-cases/warnings).
405
+ fwd_table["exdate"] = pd.to_datetime(fwd_table["exdate"]).dt.date
406
+ fwd_table["am_settlement"] = fwd_table["am_settlement"].fillna(0.0).astype(float)
407
+ fwd_table["forward_price"] = fwd_table["forward_price"].astype(float)
408
+
409
+ # remove today since that day was removed also from the options table
410
+ fwd_table = fwd_table.loc[fwd_table["exdate"] != d]
411
+ bad_forward_mask = fwd_table["forward_price"] == spot / 1_000_000.0
412
+ if bad_forward_mask.any():
413
+ w = f"{ticker} {d}: found {bad_forward_mask.sum()} forward_ref values equal to spot/1_000_000 ({spot/1_000_000.0}). Replacing those with spot ({spot})."
414
+ verbose.write(fwd_table)
415
+ verbose.write(w)
416
+ warnings.warn(w)
417
+ fwd_table.loc[bad_forward_mask, "forward_price"] = float(spot)
418
+
419
+ if (fwd_table['forward_price'].min() < spot/2.) or (fwd_table['forward_price'].max() > spot*2.):
420
+ err = f"{ticker} {d}: suspicious forward prices in fwd_table, min={fwd_table['forward_price'].min()}, max={fwd_table['forward_price'].max()} spot={spot}. Fix or add the date/expiry to the BAD data sets."
421
+ verbose.write(err)
422
+ verbose.write(fwd_table)
423
+ raise RuntimeError(err)
424
+
425
+ # Enforce one forward per (exdate, am_settlement)
426
+ dup_mask = fwd_table.duplicated(subset=["exdate", "am_settlement"], keep=False)
427
+ if dup_mask.any():
428
+ dup_keys = (
429
+ fwd_table.loc[dup_mask, ["exdate", "am_settlement"]]
430
+ .drop_duplicates()
431
+ .head(10)
432
+ .to_records(index=False)
433
+ .tolist()
434
+ )
435
+ raise RuntimeError(
436
+ f"{ticker} {d}: forward table has duplicate keys (exdate, am_settlement). "
437
+ f"Expected exactly one forward per key. Sample duplicates: {dup_keys}. Fix or add the date/expiry to the BAD data sets."
438
+ )
439
+
440
+ # write forward_ref into option table
441
+ fwd_ref_by_key = fwd_table.set_index(["exdate", "am_settlement"])["forward_price"].astype(float)
442
+ opts_pd["forward_ref"] = fwd_ref_by_key.reindex(
443
+ pd.MultiIndex.from_frame(opts_pd[["exdate", "am_settlement"]], names=["exdate", "am_settlement"])
444
+ ).to_numpy(dtype=float)
445
+
446
+ return opts_pd
447
+ opts_pd = forward_ref(opts_pd, fwd_table)
448
+
449
+ # Enrich
450
+ # --------------
451
+
452
+ def enrich( opts_pd ):
453
+ opts_pd["log_volume"] = np.log10(1+opts_pd["volume"].fillna(0.0).astype(float))
454
+ opts_pd["log_open_interest"] = np.log10(1+opts_pd["open_interest"].fillna(0.0).astype(float))
455
+ opts_pd['is_call'] = opts_pd["cp_flag"].astype("string").str.upper().eq("C")
456
+ opts_pd['is_american'] = opts_pd["exercise_style"].fillna("E").astype("string").str.upper().eq("A")
457
+ opts_pd['is_am'] = opts_pd["am_settlement"].fillna(0.0).astype(float) == 1.0
458
+ opts_pd['strike'] = opts_pd["strike_price"].astype(float)
459
+
460
+ opts_pd = opts_pd.drop(columns=["volume", "open_interest", "cp_flag", "exercise_style", "am_settlement", "strike_price"])
461
+
462
+ # find opt calls for the same exdate, am_settlement, strike
463
+ opt_calls = opts_pd[opts_pd["is_call"]].copy()
464
+ opt_puts = opts_pd[~opts_pd["is_call"]].copy()
465
+ opt_calls = opt_calls.sort_values(by=["exdate", "is_am", "strike", "is_american"])
466
+ opt_puts = opt_puts.sort_values(by=["exdate", "is_am", "strike", "is_american"])
467
+ del opts_pd
468
+
469
+ opt_calls = opt_calls.rename(columns={
470
+ "symbol": "call_symbol",
471
+ "optionid": "call_opt_id",
472
+ "best_bid": "call_bid",
473
+ "best_offer": "call_ask",
474
+ "log_volume": "call_log_volume",
475
+ "log_open_interest": "call_log_open_interest",
476
+ })
477
+ opt_puts = opt_puts.rename(columns={
478
+ "symbol": "put_symbol",
479
+ "optionid": "put_opt_id",
480
+ "best_bid": "put_bid",
481
+ "best_offer": "put_ask",
482
+ "log_volume": "put_log_volume",
483
+ "log_open_interest": "put_log_open_interest",
484
+ })
485
+ opt_calls = opt_calls[["exdate", "is_am", "strike", "is_american", "call_symbol", "call_opt_id", "call_bid", "call_ask", "call_log_volume", "call_log_open_interest"]+\
486
+ ["discount_factor_ref", "forward_ref"]]
487
+ opt_puts = opt_puts[["exdate", "is_am", "strike", "is_american", "put_symbol", "put_opt_id", "put_bid", "put_ask", "put_log_volume", "put_log_open_interest"]]
488
+
489
+ opts_pd = pd.merge(
490
+ opt_calls,
491
+ opt_puts,
492
+ on=["exdate", "is_am", "is_american", "strike"],
493
+ suffixes=("", ""),
494
+ )
495
+
496
+ # write into a "dict"
497
+ # then convert to panda
498
+
499
+ r = PrettyObject()
500
+ r.spot = np.float32(spot)
501
+ r.spot_prev = np.float32(spot_d)
502
+ r.date = np.array(d, dtype="datetime64[ms]")
503
+ r.ticker = ticker
504
+ r.call_symbol = opts_pd["call_symbol"].astype(str).values.tolist()
505
+ r.put_symbol = opts_pd["put_symbol"].astype(str).values.tolist()
506
+ r.call_opt_id = opts_pd["call_opt_id"].to_numpy(dtype=np.int32)
507
+ r.put_opt_id = opts_pd["put_opt_id"].to_numpy(dtype=np.int32)
508
+ r.is_american = opts_pd["is_american"].to_numpy(dtype=bool)
509
+ r.is_am = opts_pd["is_am"].to_numpy(dtype=bool)
510
+ r.expiry = np.array(opts_pd["exdate"], dtype="datetime64[ms]")
511
+ r.strike = opts_pd["strike"].values.astype(np.float32)
512
+ r.fwd_ref = opts_pd["forward_ref"].values.astype(np.float32)
513
+ r.df = opts_pd["discount_factor_ref"].values.astype(np.float32)
514
+
515
+ r.mkt_call_bid = opts_pd["call_bid"].values.astype(np.float32)
516
+ r.mkt_put_bid = opts_pd["put_bid"].values.astype(np.float32)
517
+ r.mkt_call_ask = opts_pd["call_ask"].values.astype(np.float32)
518
+ r.mkt_put_ask = opts_pd["put_ask"].values.astype(np.float32)
519
+ r.mkt_call_log_volume = opts_pd["call_log_volume"].values.astype(np.float32)
520
+ r.mkt_put_log_volume = opts_pd["put_log_volume"].values.astype(np.float32)
521
+ r.mkt_call_log_open_interest = opts_pd["call_log_open_interest"].values.astype(np.float32)
522
+ r.mkt_put_log_open_interest = opts_pd["put_log_open_interest"].values.astype(np.float32)
523
+
524
+ # Option ID as string symbol
525
+ expiry_dates = pd.to_datetime(r.expiry)
526
+ r.expiry_id = (
527
+ expiry_dates.year * 100000
528
+ + expiry_dates.month * 1000
529
+ + expiry_dates.day * 10
530
+ + np.where(r.is_am, 0, 1)
531
+ ).astype(np.int32)
532
+
533
+ r.bdte = count_business_days_between(d, expiry_dates.to_numpy(dtype="datetime64[D]")) # returns integers
534
+
535
+ if np.min(r.bdte) <= 0:
536
+ # historically end of month expiries might fall on a Saturday AM
537
+ # we check that if BDTE is zero, those are the cases
538
+ bad_expiries = r.expiry[r.bdte <= 0]
539
+ bad_is_am = r.is_am[r.bdte <= 0]
540
+ bad_bdte = r.bdte[r.bdte <= 0]
541
+
542
+ for be, bam, bb in zip(bad_expiries, bad_is_am, bad_bdte, strict=True):
543
+ be = to_date(be)
544
+ assert bb == 0, f"Internal error: expected non-positive business days to expiry to be exactly zero, found {bb} for expiry {be} with is_am={bam}. Please contact the authors with an example."
545
+ assert be.weekday() == 5, f"Internal error: expected bad expiry {be} to be a Saturday, found weekday {be.weekday()}. Please contact the authors with an example."
546
+ assert bam == True, f"Internal error: expected bad expiry {be} to be an AM settlement, found is_am={bam}. Please contact the authors with an example."
547
+
548
+ r.bdte = np.clip( r.bdte.astype(np.float32) - np.where(r.is_am, AM_EXIRY_SUBTRACT, 0.0), min=0. ).astype(np.float32)
549
+ r.tte_y = r.bdte / DAYS_PER_YEAR
550
+ return pd.DataFrame(dict(r))
551
+
552
+ result = restore_object_strings(enrich(opts_pd), SCHEMA_RAW_DAY)
553
+ verify_schema(result, SCHEMA_RAW_DAY, lambda : f"{ticker} {d}")
554
+
555
+ # check that common fields are so.
556
+ for c in RAW_PER_DAY_FIELDS:
557
+ column_data = result[c]
558
+ if not (column_data.nunique() == 1):
559
+ raise RuntimeError(f"Internal error: {ticker} {d}: enriched DataFrame column '{c}' is expected to have exactly one unique value, found {column_data.nunique()}. Please contact the authors with an example.")
560
+
561
+ for c in RAW_PER_EXPIRY_FIELDS:
562
+ grouped_unique = result.groupby("expiry_id", sort=False)[c].nunique(dropna=False)
563
+ if not (grouped_unique == 1).all():
564
+ bad_expiry_ids = grouped_unique[grouped_unique != 1].index.tolist()[:10]
565
+ raise RuntimeError(f"Internal error: {ticker} {d}: enriched DataFrame column '{c}' is expected to have a single value within each expiry_id, but this failed for expiry_id values {bad_expiry_ids}. Please contact the authors with an example.")
566
+
567
+ verbose.write(f"{ticker} {d}: collected {len(result)}/{n_total} options. Removed: {fmt_list(status_removed) if len(status_removed) > 0 else 'none'}.")
568
+ return result
569
+
570
+ # ---------------------------------------------------------------------------
571
+ # Enriched data, day
572
+ # Optimal forward computation, implied volatilities, (pure) greeks.
573
+ # Also translates everything in calls.
574
+ # ---------------------------------------------------------------------------
575
+
576
+ SCHEMA_ENRICHED_DAY = SCHEMA_RAW_DAY | {
577
+ 'fwd' : np.dtype("float32"), # implied forward from put-call parity
578
+ 'nms' : np.dtype("float32"), # normalized log-moneyness using :class:`NMS5`
579
+ 'nms_atm' : np.dtype("float32"), # normalized log-moneyness using :class:`NMS5` with the ATM volatility
580
+ 'call_ask' : np.dtype("float32"), # implied from pure call after implied vol fitting
581
+ 'call_bid' : np.dtype("float32"), # implied from pure call after implied vol fitting
582
+ 'ask_vol' : np.dtype("float32"),
583
+ 'bid_vol' : np.dtype("float32"),
584
+ 'log_volume' : np.dtype("float32"),
585
+ 'log_open_interest' : np.dtype("float32"),
586
+ 'pure_strike' : np.dtype("float32"),
587
+ 'pure_ask_price' : np.dtype("float32"),
588
+ 'pure_bid_price' : np.dtype("float32"),
589
+ 'pure_ask_delta' : np.dtype("float32"),
590
+ 'pure_bid_delta' : np.dtype("float32"),
591
+ 'pure_ask_gamma' : np.dtype("float32"),
592
+ 'pure_bid_gamma' : np.dtype("float32"),
593
+ 'pure_bid_vega' : np.dtype("float32"),
594
+ 'pure_ask_vega' : np.dtype("float32"),
595
+ 'pure_bid_theta' : np.dtype("float32"),
596
+ 'pure_ask_theta' : np.dtype("float32"),
597
+ 'pure_ask_dk' : np.dtype("float32"),
598
+ 'pure_bid_dk' : np.dtype("float32")
599
+ }
600
+
601
+ ENRICHED_PER_DAY_FIELDS = RAW_PER_DAY_FIELDS
602
+ ENRICHED_PER_EXPIRY_FIELDS = RAW_PER_EXPIRY_FIELDS|{'fwd'}
603
+
604
+ @version("0.6")
605
+ @dataclass(frozen=True)
606
+ class ExpiryFilter:
607
+ """ How to filter expiries to be able to compute implied forwards """
608
+ num_min_either_traded : int = 10 # Drop expiries with less than this number of either calls or puts traded for a given strike.
609
+ num_min_both_traded : int = 4 # Drop expiries with less than this number of both calls and puts traded for a given strike.q
610
+ min_pure_spread : float = 1E-6
611
+ min_implied_vol : float = 0.01
612
+ max_implied_vol : float = 5.0
613
+
614
+ def __post_init__(self):
615
+ verify_inp(self.num_min_either_traded >= 0, lambda : f"'num_min_either_traded' must be non-negative, found {self.num_min_either_traded}")
616
+ verify_inp(self.num_min_both_traded >= 0, lambda : f"'num_min_both_traded' must be non-negative, found {self.num_min_both_traded}")
617
+ verify_inp(self.min_pure_spread > 0, lambda : f"'min_pure_spread' must be positive, found {self.min_pure_spread}")
618
+ verify_inp(self.min_implied_vol > 0, lambda : f"'min_implied_vol' must be positive, found {self.min_implied_vol}")
619
+ verify_inp(self.max_implied_vol > self.min_implied_vol, lambda : f"'max_implied_vol' must be greater than 'min_implied_vol', found max_implied_vol={self.max_implied_vol} and min_implied_vol={self.min_implied_vol}")
620
+
621
+ def __str__(self):#by convention use a some what readable string with comma separated key=value pairs
622
+ return f"nat,eth={self.num_min_either_traded},bth={self.num_min_both_traded},mps={self.min_pure_spread},miv={self.min_implied_vol},xiv={self.max_implied_vol}"
623
+
624
+ def __unique_hash__(self, unique_hash, debug_trace) -> tuple[str, dict]:
625
+ # Preserve the former normalize=False encoding for existing cache IDs.
626
+ return type(self).__qualname__, vars(self) | {"normalize": False}
627
+
628
+ #: Expiries at least this many business days out may have their discount factor implied from put-call parity.
629
+ IMPLIED_DISCOUNT_MIN_BDTE = 126.
630
+
631
+
632
+ @version("1.0")
633
+ def consistent_discount_factor(strikes: np.ndarray, lower: np.ndarray, upper: np.ndarray, discount: float) -> float:
634
+ """Move ``discount`` into the range of discount factors for which one forward reconciles every strike.
635
+
636
+ Put-call parity bounds ``C - P = D*(F - K)`` per strike to ``[lower, upper]``, with
637
+ ``lower = C_bid - P_ask`` and ``upper = C_ask - P_bid`` in cash units. For a given discount factor ``D``
638
+ a common forward exists if and only if ``D`` lies in an interval ``[D_min, D_max]`` determined by the
639
+ quotes (a two-variable linear program in ``D*F`` and ``D``). If ``discount`` lies in it, or no ``D`` makes
640
+ the quotes consistent, ``discount`` is returned unchanged; otherwise the nearest point just inside the
641
+ interval is returned.
642
+ """
643
+ strikes = np.asarray(strikes, dtype=np.float64)
644
+ lower = np.asarray(lower, dtype=np.float64)
645
+ upper = np.asarray(upper, dtype=np.float64)
646
+ valid = np.isfinite(strikes) & np.isfinite(lower) & np.isfinite(upper) & (lower <= upper)
647
+ if valid.sum() < 2:
648
+ return float(discount)
649
+ k, lo, hi = strikes[valid], lower[valid], upper[valid]
650
+ # variables (A, D) with A = D*F: lo <= A - D*K <= hi
651
+ a_ub = np.vstack([np.c_[-np.ones_like(k), k], np.c_[np.ones_like(k), -k]])
652
+ b_ub = np.r_[-lo, hi]
653
+ bounds = []
654
+ for sign in (1., -1.):
655
+ res = linprog(c=[0., sign], A_ub=a_ub, b_ub=b_ub, bounds=[(None, None), (0., 2.)], method="highs")
656
+ if res.status != 0:
657
+ return float(discount)
658
+ bounds.append(float(res.x[1]))
659
+ d_min, d_max = bounds
660
+ if d_min <= discount <= d_max:
661
+ return float(discount)
662
+ # just inside the interval, so that the forward window is non-empty despite rounding
663
+ margin = 1e-3 * (d_max - d_min)
664
+ return float(min(max(discount, d_min + margin), d_max - margin))
665
+
666
+
667
+ @version("2.0")
668
+ def consistent_forward(lower: np.ndarray, upper: np.ndarray, estimate: float) -> float:
669
+ """Move ``estimate`` into the forward range consistent with every strike, if one exists.
670
+
671
+ Each strike's put-call parity bounds the (discounted) forward to ``[lower, upper]``, with
672
+ ``lower = C_bid - P_ask + DF*K`` and ``upper = C_ask - P_bid + DF*K``. If all these intervals
673
+ overlap, the estimate is clipped into their intersection, so that every strike's call quote and
674
+ put-parity quote are consistent. If they do not overlap, no forward reconciles all strikes and the
675
+ estimate is returned unchanged. (Maximizing the number of reconciled strikes instead was tested on
676
+ every cached SPX day: it let sparse long-dated wing quotes move the forward by up to 2%.)
677
+ """
678
+ lower = np.asarray(lower, dtype=np.float64)
679
+ upper = np.asarray(upper, dtype=np.float64)
680
+ assert lower.shape == upper.shape and lower.ndim == 1, f"Expected matching vectors, found {lower.shape} and {upper.shape}"
681
+ valid = np.isfinite(lower) & np.isfinite(upper) & (lower <= upper)
682
+ if not np.any(valid):
683
+ return float(estimate)
684
+ low, high = float(lower[valid].max()), float(upper[valid].min())
685
+ if low > high:
686
+ return float(estimate)
687
+ return float(min(max(estimate, low), high))
688
+
689
+ def _uid(ticker, d, raw_day_filter, expiry_filter) -> str:
690
+ return f"enrich/{named_unique_filename48_8(f'{str(expiry_filter)},{str(raw_day_filter)}',expiry_filter,raw_day_filter)}"+\
691
+ f"/{ticker}/{fmt_date(d)}"
692
+
693
+ @_processing(fmt=SubDir.PANDAS_PARQUET).cache(
694
+ "0.11",
695
+ dependencies=[collect_raw_day, ExpiryFilter, consistent_forward, consistent_discount_factor],
696
+ uid=_uid,
697
+ exclude_args=['verbose','raw_data','raise_if_bad_day','refresh_cache'])
698
+ def enrich_day( ticker : str, d : dt.date, raw_data : pd.DataFrame|None = None, *,
699
+ raw_day_filter : RawDayFilter = RawDayFilter(),
700
+ expiry_filter : ExpiryFilter = ExpiryFilter(),
701
+ override_cache_mode : CacheMode|None = None,
702
+ raise_if_bad_day : bool = True,
703
+ verbose : Context = Context.all ) -> pd.DataFrame:
704
+ """
705
+ Enrich a day's data.
706
+
707
+ * Compute synthetic minimal spread call options.
708
+ * Compute an implied forward from inverse-spread weighted bid/ask call prices.
709
+ * Compute implied volatilities and (pure) greeks.
710
+
711
+ The returned daya data frame has the schema :attr:`SCHEMA_ENRICHED_DAY`, which includes all columns from :attr:`SCHEMA_RAW_DAY`.
712
+
713
+ Parameters
714
+ ----------
715
+ ticker : str
716
+ Ticker symbol, e.g. "SPX"
717
+ d : :class:`datetime.date`
718
+ Date for which to collect data
719
+ raw_data : :class:`pandas.DataFrame` | None, default ``None``
720
+ Raw data for the given ticker and date. If ``None``, data will be generated
721
+ using :func:`collect_raw_day`.
722
+ raw_day_filter : :class:`RawDayFilter`
723
+ Configuration for data collection
724
+ expiry_filter : :class:`ExpiryFilter`
725
+ Filter for expiries to be able to compute implied forwards
726
+ override_cache_mode : :class:`CacheMode` | None, default ``None``
727
+ If not ``None``, overrides the cache mode for the raw day data. Set to ``"update"`` to
728
+ refresh the underlying raw cache.
729
+ raise_if_bad_day : bool, default ``True``
730
+ If ``True``, raises an error if the date is in the BAD data sets.
731
+ If ``False``, returns an empty data set instead. (In no other condition will an empty data set be returned)
732
+ verbose : :class:`cdxcore.verbose.Context`
733
+ Verbose context for logging
734
+
735
+ Returns
736
+ -------
737
+ Daily data: :class:`pandas.DataFrame`
738
+ Cleaned DataFrame with all relevant data for the given ticker and date, creating the schema :attr:`SCHEMA_ENRICHED_DAY`.
739
+
740
+ Raises
741
+ ------
742
+ Not found: :class:`LookupError`
743
+ If no data was downloaded from IvyDB for the given ticker and date.
744
+ No data: :class:`EOFError`
745
+ If no data was available for the given ticker and date.
746
+ Bad day: :class:`IndexError`
747
+ If this date and ticker are known to have bad data; see :class:`openqdata.widb.bad.BAD` for details.
748
+ Bad data: :class:`RuntimeError`
749
+ If data was downloaded but found to be bad after basic cleaning steps.
750
+ This can happen for example if the forward price is highly suspicious, or if all options had zero or NA bid prices. Please check the date range and calendar settings,
751
+ and consider adding the date/ticker to the BAD data sets if the issue is confirmed.
752
+ """
753
+ if not raw_data is None:
754
+ verify_inp( isinstance(raw_data, pd.DataFrame), lambda : f"Expected raw_data to be a pandas DataFrame or None, found {type(raw_data)}")
755
+ data = raw_data
756
+ else:
757
+ data = collect_raw_day(ticker, d, raw_day_filter, verbose=verbose, override_cache_mode=override_cache_mode, raise_if_bad_day = raise_if_bad_day)
758
+ del raw_data
759
+
760
+ if data.empty:
761
+ return create_empty_df(SCHEMA_ENRICHED_DAY)
762
+ data = restore_object_strings(data, SCHEMA_RAW_DAY)
763
+ verify_schema(data, SCHEMA_RAW_DAY, lambda : f"{ticker} {d}")
764
+
765
+ expiry_ids = data["expiry_id"].to_numpy()
766
+ unq_ids = np.unique(expiry_ids)
767
+ num_total = len(data)
768
+ num_expiries = len(unq_ids)
769
+
770
+ put_log_vol = data['mkt_put_log_volume'].to_numpy().astype(np.float64)
771
+ call_log_vol = data['mkt_call_log_volume'].to_numpy().astype(np.float64)
772
+ put_log_oi = data['mkt_put_log_open_interest'].to_numpy().astype(np.float64)
773
+ call_log_oi = data['mkt_call_log_open_interest'].to_numpy().astype(np.float64)
774
+
775
+ either_cp = (put_log_vol>0)|(call_log_vol>0)
776
+ both_cp = (put_log_vol>0)&(call_log_vol>0)
777
+ df_ref = data['df'].to_numpy().astype(np.float64)
778
+ strike = data['strike'].to_numpy().astype(np.float64)
779
+ expiries = data['expiry'].to_numpy()
780
+ is_am = data['is_am'].to_numpy()
781
+
782
+ mkt_call_ask = data['mkt_call_ask'].to_numpy().astype(np.float64)
783
+ mkt_call_bid = data['mkt_call_bid'].to_numpy().astype(np.float64)
784
+ mkt_put_ask = data['mkt_put_ask'].to_numpy().astype(np.float64)
785
+ mkt_put_bid = data['mkt_put_bid'].to_numpy().astype(np.float64)
786
+
787
+ dffwd_ask = ( mkt_call_ask - mkt_put_bid ) + df_ref*strike # C-P=DF(FWD-strike)
788
+ dffwd_bid = ( mkt_call_bid - mkt_put_ask ) + df_ref*strike
789
+ dffwd_mid = 0.5*(dffwd_ask + dffwd_bid)
790
+ dffwd_wght = np.where( both_cp, 1./np.maximum( dffwd_ask - dffwd_bid, 0.001 ), 0. )
791
+
792
+ # compute dffwd_mean grouped by expiry_id
793
+ arrays = PrettyObject()
794
+ arrays.fwd = np.zeros_like( dffwd_ask, dtype=np.float32 )
795
+ arrays.nms = np.zeros_like( dffwd_ask, dtype=np.float32 )
796
+ arrays.nms_atm = np.zeros_like( dffwd_ask, dtype=np.float32 )
797
+ arrays.is_valid = np.zeros_like( arrays.fwd, dtype=bool )
798
+ arrays.call_ask = np.zeros_like( arrays.fwd, dtype=np.float32 )
799
+ arrays.call_bid = np.zeros_like( arrays.fwd, dtype=np.float32 )
800
+ arrays.ask_vol = np.zeros_like( arrays.fwd, dtype=np.float32 )
801
+ arrays.bid_vol = np.zeros_like( arrays.fwd, dtype=np.float32 )
802
+ arrays.log_volume = np.log10( np.pow(10.,call_log_vol.astype(np.float64))+np.pow(10.,put_log_vol.astype(np.float64))-1 ).astype(np.float32)
803
+ arrays.log_open_interest = np.log10( np.pow(10.,call_log_oi.astype(np.float64))+np.pow(10.,put_log_oi.astype(np.float64))-1 ).astype(np.float32)
804
+ arrays.pure_strike = np.zeros_like( arrays.fwd, dtype=np.float32 )
805
+ arrays.pure_ask_price = np.zeros_like( arrays.fwd, dtype=np.float32 )
806
+ arrays.pure_bid_price = np.zeros_like( arrays.fwd, dtype=np.float32 )
807
+ arrays.pure_ask_delta = np.zeros_like( arrays.fwd, dtype=np.float32 )
808
+ arrays.pure_bid_delta = np.zeros_like( arrays.fwd, dtype=np.float32 )
809
+ arrays.pure_ask_gamma = np.zeros_like( arrays.fwd, dtype=np.float32 )
810
+ arrays.pure_bid_gamma = np.zeros_like( arrays.fwd, dtype=np.float32 )
811
+ arrays.pure_bid_vega = np.zeros_like( arrays.fwd, dtype=np.float32 )
812
+ arrays.pure_ask_vega = np.zeros_like( arrays.fwd, dtype=np.float32 )
813
+ arrays.pure_bid_theta = np.zeros_like( arrays.fwd, dtype=np.float32 )
814
+ arrays.pure_ask_theta = np.zeros_like( arrays.fwd, dtype=np.float32 )
815
+ arrays.pure_ask_dk = np.zeros_like( arrays.fwd, dtype=np.float32 )
816
+ arrays.pure_bid_dk = np.zeros_like( arrays.fwd, dtype=np.float32 )
817
+
818
+ # project
819
+ dropped_expiries = []
820
+ dropped_strikes = []
821
+ num_dropped_strikes = 0
822
+
823
+ for expiry_id in unq_ids:
824
+ mask = expiry_ids == expiry_id
825
+ iexpory = expiries[mask][0]
826
+ iiam = is_am[mask][0]
827
+ strid = f"{fmt_date(to_date(iexpory))}{'am' if iiam else 'pm'}"
828
+ is_valid = arrays.is_valid[mask] # starts False
829
+
830
+ if np.sum( both_cp[mask] ) < expiry_filter.num_min_both_traded:
831
+ dropped_expiries.append(f"{strid} (insufficient traded strikes)")
832
+ continue
833
+ if np.sum(either_cp[mask]) < expiry_filter.num_min_either_traded:
834
+ dropped_expiries.append(f"{strid} (insufficient traded options)")
835
+ continue
836
+ # From about six months out the zero-curve discount factor can be inconsistent with the quotes'
837
+ # own put-call parity rate; move it only as far as needed for one forward to reconcile every strike.
838
+ if data['bdte'].to_numpy()[mask][0] >= IMPLIED_DISCOUNT_MIN_BDTE:
839
+ k_t = strike[mask]
840
+ implied = consistent_discount_factor(k_t, (mkt_call_bid - mkt_put_ask)[mask], (mkt_call_ask - mkt_put_bid)[mask], df_ref[mask][0])
841
+ if implied != df_ref[mask][0]:
842
+ df_ref[mask] = implied
843
+ dffwd_ask[mask] = (mkt_call_ask - mkt_put_bid)[mask] + implied*k_t
844
+ dffwd_bid[mask] = (mkt_call_bid - mkt_put_ask)[mask] + implied*k_t
845
+ dffwd_mid[mask] = 0.5*(dffwd_ask[mask] + dffwd_bid[mask]) # spreads, hence weights, are unchanged
846
+ dffwd_t = np.sum(dffwd_mid[mask] * dffwd_wght[mask]) / np.sum(dffwd_wght[mask]) # weighted forward for this expiry_id
847
+ # Wide wing quotes can pull the weighted mean just outside the range where every strike's call
848
+ # and put-parity bands overlap; if that range exists, move the forward into it.
849
+ dffwd_t = consistent_forward(dffwd_bid[mask], dffwd_ask[mask], dffwd_t)
850
+ if np.min(dffwd_t) < 1E-6:
851
+ dropped_expiries.append(f"{strid} (cannot compute implied forward)")
852
+ continue
853
+
854
+ df_t = df_ref[mask][0] # same for all rows
855
+ fwd_t = dffwd_t / df_t
856
+ tte_yt = data['tte_y'].to_numpy()[mask][0]
857
+ sqrtT_t = math.sqrt(tte_yt)
858
+ arrays.fwd[mask] = fwd_t
859
+ is_valid[:] = True
860
+
861
+ # synthetic call price from put-call parity using the projected forward, for comparison with the market call price.
862
+ sy_call_ask = mkt_put_ask[mask] + dffwd_t - df_t * strike[mask]
863
+ sy_call_bid = mkt_put_bid[mask] + dffwd_t - df_t * strike[mask]
864
+
865
+ sy_call_spread = sy_call_ask - sy_call_bid
866
+ bad_options = (sy_call_ask <= 0.) | (sy_call_bid <= 0.) | (sy_call_spread < expiry_filter.min_pure_spread*dffwd_t)
867
+ issues = ""
868
+ if np.any(bad_options):
869
+ issues = f"{np.sum(bad_options)} strikes with p/c issues; "
870
+ num_dropped_strikes += np.sum(bad_options)
871
+ is_valid[:] &= ~bad_options
872
+
873
+ call_mid = 0.5 * ( np.minimum( sy_call_ask, mkt_call_ask[mask]) + np.maximum( sy_call_bid, mkt_call_bid[mask]) )
874
+ call_spread = np.minimum( mkt_call_ask[mask] - mkt_call_bid[mask], sy_call_ask - sy_call_bid )
875
+ new_call_ask = call_mid + 0.5*call_spread
876
+ new_call_bid = call_mid - 0.5*call_spread
877
+ pure_strike = strike[mask] / fwd_t
878
+ pure_call_ask = new_call_ask / dffwd_t
879
+ pure_call_bid = new_call_bid / dffwd_t
880
+ bad_options = (pure_call_ask - pure_call_bid) < expiry_filter.min_pure_spread
881
+ if np.any(bad_options):
882
+ issues = issues + f"{np.sum(bad_options)} strikes with invalid spread; "
883
+ num_dropped_strikes += np.sum(bad_options)
884
+ is_valid[:] &= ~bad_options
885
+
886
+ if not np.any(is_valid):
887
+ dropped_expiries.append(f"{strid} (too many serious forward/prices issues to recover)")
888
+ is_valid[:] = False
889
+ continue
890
+ if np.sum( both_cp[mask][is_valid] ) < expiry_filter.num_min_both_traded:
891
+ dropped_expiries.append(f"{strid} (insufficient traded strikes post filtering)")
892
+ is_valid[:] = False
893
+ continue
894
+ if np.sum(either_cp[mask][is_valid]) < expiry_filter.num_min_either_traded:
895
+ dropped_expiries.append(f"{strid} (insufficient traded options post filtering)")
896
+ is_valid[:] = False
897
+ continue
898
+
899
+ # implied vol calculation will be within 10% of spread
900
+ # which means that bid should remain below ask.
901
+ # However, for extreme options the implied vol calculation
902
+ # may reach a boundary. In this case bid/ask spreads
903
+ # are not guranteed to be preserved.
904
+
905
+ spread = pure_call_ask - pure_call_bid
906
+ price_tol = np.minimum( spread*0.1, 1E-6)
907
+ ask_vols = bs.implied( pure_strike, pure_call_ask, sqrtT = sqrtT_t,
908
+ price_tol=price_tol,
909
+ mask=is_valid,
910
+ eps=_IMPLIED_VOL_CALC_EPS,
911
+ vol_min=expiry_filter.min_implied_vol,
912
+ vol_max=expiry_filter.max_implied_vol )
913
+ bid_vols = bs.implied( pure_strike, pure_call_bid, sqrtT = sqrtT_t,
914
+ price_tol=price_tol,
915
+ mask=is_valid,
916
+ eps=_IMPLIED_VOL_CALC_EPS,
917
+ vol_min=expiry_filter.min_implied_vol,
918
+ vol_max=expiry_filter.max_implied_vol )
919
+ atm_vol = np.interp( 1., pure_strike, (ask_vols+bid_vols)*0.5 )
920
+ ask_vols[~is_valid] = expiry_filter.min_implied_vol*1.1
921
+ bid_vols[~is_valid] = expiry_filter.min_implied_vol
922
+
923
+ arrays.pure_strike[mask] = pure_strike
924
+ arrays.ask_vol[mask] = ask_vols
925
+ arrays.bid_vol[mask] = bid_vols
926
+
927
+ bid_greeks = bs( k=pure_strike, vol=bid_vols, sqrtT = sqrtT_t, eps=_GREEK_CALC_EPS, what=bs.PRICE|bs.DELTA|bs.GAMMA|bs.VEGA|bs.THETA|bs.DK )
928
+ ask_greeks = bs( k=pure_strike, vol=ask_vols, sqrtT = sqrtT_t, eps=_GREEK_CALC_EPS, what=bs.PRICE|bs.DELTA|bs.GAMMA|bs.VEGA|bs.THETA|bs.DK )
929
+
930
+ diff_del = 0
931
+ ask_diff = ask_greeks.price - pure_call_ask
932
+ diff_err =( np.abs(ask_diff) > price_tol*1.1 ) & is_valid
933
+ if np.any(diff_err):
934
+ ask_vol_at_err = ask_vols[diff_err]
935
+ bnd_vol = ( ask_vol_at_err == expiry_filter.min_implied_vol ) | ( ask_vol_at_err == expiry_filter.max_implied_vol )
936
+ assert np.all(bnd_vol), f"Internal error: {ticker} {d}: found {np.sum(diff_err)} options with implied vol calculation errors above tolerance, but not at the boundaries. Please contact the authors with an example."
937
+ diff_del = np.sum(diff_err)
938
+ is_valid &= ~diff_err
939
+
940
+ bid_diff = bid_greeks.price - pure_call_bid
941
+ diff_err = (np.abs(bid_diff) > price_tol*1.1) & is_valid
942
+ if np.any(diff_err):
943
+ bid_vol_at_err = bid_vols[diff_err]
944
+ bnd_vol = ( bid_vol_at_err == expiry_filter.min_implied_vol ) | ( bid_vol_at_err == expiry_filter.max_implied_vol )
945
+ assert np.all(bnd_vol), f"Internal error: {ticker} {d}: found {np.sum(diff_err)} options with implied vol calculation errors above tolerance, but not at the boundaries. Please contact the authors with an example."
946
+ diff_del += np.sum(diff_err)
947
+ is_valid &= ~diff_err
948
+
949
+ if diff_del>0:
950
+ issues = issues + f"{diff_del} strikes at implied vol boundaries; "
951
+ num_dropped_strikes += diff_del
952
+
953
+ # copy residual over
954
+
955
+ def copy(which, src):
956
+ for k,v in src.items():
957
+ v[~is_valid] = 0.0
958
+ arrays[f"pure_{which}_{k}"][mask] = v
959
+ copy("bid", bid_greeks)
960
+ copy("ask", ask_greeks)
961
+
962
+ arrays.call_ask[mask] = ask_greeks.price * dffwd_t
963
+ arrays.call_bid[mask] = bid_greeks.price * dffwd_t
964
+ arrays.nms[mask] = NMS5.to_nms( pure_strike, tte_yt )
965
+ arrays.nms_atm[mask] = NMS5.to_nms( pure_strike, tte_yt, vol=atm_vol )
966
+
967
+ assert np.all(arrays.call_bid[mask][is_valid] > 0.), f"Internal error: {ticker} {d}: found non-positive call bid price after enrichment for expiry {strid}. Please contact the authors with an example."
968
+ assert np.all(arrays.call_ask[mask][is_valid] > arrays.call_bid[mask][is_valid]), f"Internal error: {ticker} {d}: found non-positive bid-ask spread {strid}. Please contact the authors with an example."
969
+
970
+ assert np.any( is_valid ), "Internal error: no valid options found after enrichment."
971
+ arrays.is_valid[mask] = is_valid ##??? why do I need to do that???
972
+ assert np.all( is_valid == arrays.is_valid[mask] ), "Internal error: mismatch between is_valid and arrays.is_valid"
973
+
974
+ if len(issues) > 0:
975
+ dropped_strikes.append(f"{fmt_date(to_date(iexpory))}{'am' if iiam else 'pm'} (Dropped {issues[:-2]}: {np.sum(is_valid)}/{len(is_valid)} strikes left)")
976
+
977
+ data = data.copy(deep=False)
978
+
979
+ # drop anything?
980
+ drop = set(data.columns) - set(SCHEMA_ENRICHED_DAY)
981
+ if len(drop) > 0:
982
+ data = data.drop(columns=drop)
983
+
984
+ arrays.df = df_ref.astype(np.float32) # discount factors, implied from parity where adjusted
985
+
986
+ # copy over
987
+ for r, v in arrays.items():
988
+ data[r] = v
989
+ # keep valid rows only; 'is_valid' is a working column and not part of SCHEMA_ENRICHED_DAY
990
+ data = data.loc[data["is_valid"]].drop(columns="is_valid")
991
+
992
+ df_bad = data[data['pure_ask_price']<=data['pure_bid_price']]
993
+ verify(df_bad.empty, lambda: f"Internal error: {ticker} {d}: found {len(df_bad)} options with pure ask price at or below pure bid price -- this should not happen here: "
994
+ f"{df_bad[['expiry_id', 'strike', 'pure_ask_price', 'pure_bid_price']].head().to_dict('records')}")
995
+
996
+ num_expires_left = data["expiry_id"].nunique()
997
+ if len(dropped_expiries) > 0:
998
+ dropped_expiries = f"Dropped the following {len(dropped_expiries)} of {num_expiries} input expiries: {fmt_list(dropped_expiries)}. "
999
+ if len(dropped_strikes) > 0:
1000
+ dropped_strikes = f"Dropped {num_dropped_strikes} strikes among the remaining {num_expires_left} expiries: {fmt_list(dropped_strikes)}. "
1001
+
1002
+ data = restore_object_strings(data, SCHEMA_ENRICHED_DAY)
1003
+ verify_schema(data, SCHEMA_ENRICHED_DAY, lambda : f"{ticker} {d}")
1004
+
1005
+ if data.empty:
1006
+ verbose.write(lambda : f"{ticker} {d}: no valid options found after enrichment:")
1007
+ for de in dropped_expiries:
1008
+ verbose.report(2,de)
1009
+ for ds in dropped_strikes:
1010
+ verbose.report(2,ds)
1011
+ if raise_if_bad_day:
1012
+ assert len(dropped_expiries) > 0 or len(dropped_strikes) > 0, "Internal error -- No info??"
1013
+ raise RuntimeError(f"Internal error: {ticker} {d}: no valid options found after enrichment.")
1014
+ warnings.warn(f"{ticker} {d}: no valid options found after enrichment:{dropped_expiries}{dropped_strikes}")
1015
+ return data
1016
+
1017
+ # check that common fields are so.
1018
+ for c in ENRICHED_PER_DAY_FIELDS:
1019
+ column_data = data[c]
1020
+ if not (column_data.nunique() == 1):
1021
+ raise RuntimeError(f"Internal error: {ticker} {d}: enriched DataFrame column '{c}' is expected to have exactly one unique value, found {column_data.nunique()}. Please contact the authors with an example.")
1022
+
1023
+ num_expiries = data["expiry_id"].nunique()
1024
+ for c in ENRICHED_PER_EXPIRY_FIELDS:
1025
+ grouped_unique = data.groupby("expiry_id", sort=False)[c].nunique(dropna=False)
1026
+ if not (grouped_unique == 1).all():
1027
+ bad_expiry_ids = grouped_unique[grouped_unique != 1].index.tolist()[:10]
1028
+ raise RuntimeError(f"Internal error: {ticker} {d}: enriched DataFrame column '{c}' is expected to have a single value within each expiry_id, but this failed for expiry_id values {bad_expiry_ids}. Please contact the authors with an example.")
1029
+
1030
+ verbose.write(lambda : f"{ticker} {d}: Enriched {len(data)} of {num_total} raw options across {num_expires_left} of {num_expiries} input expiries.")
1031
+ if len(dropped_expiries) > 0:
1032
+ verbose.report(1,dropped_expiries)
1033
+ if len(dropped_strikes) > 0:
1034
+ verbose.report(1,dropped_strikes)
1035
+ return data
1036
+
1037
+ # ================================================================
1038
+ # Command-line interface
1039
+ # ================================================================
1040
+
1041
+ import click
1042
+
1043
+ from openqdata.widb import _cli_defaults
1044
+
1045
+
1046
+ @click.command()
1047
+ @click.argument("tickers", nargs=-1, required=True)
1048
+ @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")
1049
+ @click.option('--exclude-halfdays', 'exclude_halfdays', is_flag=True, help="Exclude NYSE early-close days (included by default)")
1050
+ @click.option('--workers', default=_cli_defaults.workers, help='Number of workers', type=int)
1051
+ @click.option('--threading', is_flag=True, help="Use only threading, no multiprocessing")
1052
+ @click.option('--refresh', is_flag=True, help="Refresh data (this will only refresh the top level files)")
1053
+
1054
+ def main(tickers : list[str],
1055
+ period : list[dt.datetime],
1056
+ exclude_halfdays : bool,
1057
+ workers : int,
1058
+ threading : bool,
1059
+ refresh : bool):
1060
+
1061
+ verify_inp( len(tickers) > 0, "At least one ticker must be specified")
1062
+ verify_inp( period is not None and len(period) == 2, "A start and end date must be specified")
1063
+
1064
+ from cdxcore.jcpool import JCPool
1065
+
1066
+ start, end = period
1067
+ date_range = DateRange(start=to_date(start), end=to_date(end), exclude_half_days=exclude_halfdays)
1068
+ pool_config = PoolConfig(num_workers=workers, threading=threading)
1069
+ raw_day_filter = RawDayFilter()
1070
+ expiry_filter = ExpiryFilter()
1071
+ dates = sorted( set(date_range.get_business_days())-set(BAD.DAYS_ALL) )
1072
+
1073
+ verbose = Context.all
1074
+ verbose.write(lambda: f"Enriching data for tickers {fmt_list(tickers)} from {fmt_date(start)} to {fmt_date(end)} {'excluding' if date_range.exclude_half_days else 'including'} half days. Total business days: {len(dates)}.")
1075
+ verbose.report(1,lambda: f"Raw Day Filter: {raw_day_filter}")
1076
+ verbose.report(1,lambda: f"Expiry filter: {expiry_filter}")
1077
+ verbose.report(1,lambda: f"Pool config: {pool_config}")
1078
+
1079
+ pool = JCPool(num_workers=pool_config.num_workers, threading=pool_config.threading)
1080
+
1081
+ for it, ticker in enumerate(tickers):
1082
+
1083
+ def processing( ticker, d, raw_day_filter, expiry_filter, refresh ):
1084
+ enrich_day( ticker=ticker, d=d, raw_day_filter=raw_day_filter, expiry_filter=expiry_filter, override_cache_mode="update" if refresh else "on", raise_if_bad_day=False, verbose=Context.quiet, cache_generate_only=True )
1085
+ return 0
1086
+
1087
+ with verbose.write_t(lambda: f"\rProcessing ticker {it+1}/{len(tickers)} {ticker} from {fmt_date(date_range.start)} to {fmt_date(date_range.end)}:", end='') as tme:
1088
+ cnt = 0
1089
+ for d, _ in pool.parallel( { d: pool.delayed(processing)(ticker, d, raw_day_filter, expiry_filter, refresh) for d in dates } ):
1090
+ cnt += 1
1091
+ if tme.interval_test(1.):
1092
+ verbose.write(f"\rProcessing ticker {it+1}/{len(tickers)} '{ticker}' date {cnt}/{len(dates)} {fmt_date(d)}. So far this took {tme}...", end='')
1093
+ verbose.write(f"\rProcessed ticker {it+1}/{len(tickers)} '{ticker}' for all {len(dates)} dates. This took {tme}.")
1094
+
1095
+ verbose.write(f"All {len(tickers)} tickers processed.")
1096
+
1097
+ if __name__ == "__main__":
1098
+ main()