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,610 @@
1
+ """
2
+ openqdata.massive.options.contracts
3
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4
+
5
+ Managing contract information per underyling.
6
+ The main functions in this module are:
7
+
8
+ * :func:`filter_contracts`
9
+ * :func:`filter_contracts_between`
10
+
11
+ Each retrieves, filters, and caches contrats for a given underlying.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import warnings as warnings
17
+ from dataclasses import dataclass
18
+ from datetime import date, datetime
19
+
20
+ import polars as pl
21
+ from cdxcore.err import verify
22
+ from cdxcore.jcpool import JCPool
23
+ from cdxcore.pretty import PrettyObject
24
+ from cdxcore.uniquehash import named_unique_filename48_8
25
+ from cdxcore.util import TrackTime, fmt_date, fmt_digits, fmt_list
26
+ from cdxcore.verbose import Context
27
+ from cdxcore.version import version
28
+
29
+ from openqdata.biz_calendar import (
30
+ DAYS_PER_YEAR,
31
+ NMS,
32
+ NMS5,
33
+ DateRange,
34
+ add_business_days,
35
+ count_business_days_between,
36
+ )
37
+ from openqdata.massive import MassiveClient, SubDir
38
+ from openqdata.pool import PoolConfig
39
+
40
+ _cache = MassiveClient.locations.processed("contracts", fmt=SubDir.POLARS_PARQUET)
41
+
42
+ # -----------------------------
43
+ # Rejection codes
44
+ # -----------------------------
45
+
46
+
47
+ class REJECTED:
48
+ """ Reasons why a contract was rejected from the final list """
49
+ USED = 0 # contract is used (not rejected)
50
+ EXPIRY = 1 # contract expires too far in the future (days_to_exp > contracts_filter.max_dte)
51
+ MONEYNESS = 2 # contract is too far out of the money (nms > contracts_filter.max_mns)
52
+ VOLUME = 3 # contract had insufficient volume traded the previous day (this is cash volume)
53
+ PREV_VOLUME_MISSING = -1 # prev day volume data (for filtering) is missing.
54
+ PREV_NO_QUOTES_OR_TRADES = -2 # no trades and no quote data on the previous day (assuming we won't trade tickers if neither quotes nor trades are available)
55
+ NO_TODAY_QUOTES = -3 # no quotes today (assuming we won't trade until we saw a quote)
56
+ NO_TODAY_TRADES = -4 # no trades today (if contracts_filter.drop_no_trades_today is True)
57
+
58
+ SCHEMA = {
59
+ "approx_cash_vol_prev_k": pl.Float32, # previous day cash volume in thousands of USD (contracts * shares_per_contract * mid(open, close) / 1000)
60
+ "approx_cash_vol_today_k": pl.Float32, # today cash volume in thousands of USD (contracts * shares_per_contract * mid(open, close) / 1000)
61
+ "cfi": pl.String, # cfi indetifier, e.g. "OC" for option contract
62
+ "contract_type": pl.String, # contract type, e.g. "call" or "put"
63
+ "days_to_exp": pl.Int16, # full business days to expiry (that means 0DTE have 0 here)
64
+ "exercise_style": pl.String, # exercise style, e.g. "AMERICAN" or "EUROPEAN"
65
+ "exp_date": pl.Date, # expiration date of the contract
66
+ "date": pl.Date, # today
67
+ "prev_bus_date": pl.Date, # previous business day (used for volume filtering, previous spot etc)
68
+ "primary_exchange": pl.String, # https://massive.com/docs/rest/options/contracts/contract-overview
69
+ "reject_code": pl.Int8, # Why this option was flagged as rejected; c.f. :class:`REJECTED` for possible values and their meaning
70
+ "nms": pl.Float32, # :class:`NMS`-computed normalized strike
71
+ "nms5": pl.Float32, # :class:`NMS5`-computed normalized strike
72
+ "shares_per_contract": pl.Int32, # Shares per contract, usually 100; option prices are per share, so cash volume multiplies by it
73
+ "spot_adj_prev_close": pl.Float32, # Previous close adjusted spot price (i.e. previous close adjusted for stock splits and dividends to match today's unadjusted price, which is the relevant price for moneyness and volume filtering)
74
+ "spot_prev_close": pl.Float32, # Previous close unadjusted spot price
75
+ "spot_close": pl.Float32, # Today's close unadjusted spot price
76
+ "spot_open": pl.Float32, # Today's open unadjusted spot price
77
+ "spot_adj_close": pl.Float32, # Today's close adjusted spot price (i.e. today's close adjusted for stock splits and dividends to match previous close)
78
+ "spot_ref_prev_close": pl.Float32, # Reference previous close spot price, adjusted to today's spot. This can be used to scale today's prices without look-ahead bias.
79
+ "strike_price": pl.Float32, # Strike price of the option
80
+ "ticker": pl.String, # Option ticker symbol
81
+ "underlying_ticker": pl.String, # Underlying asset ticker symbol
82
+ "has_prev_quotes": pl.Boolean, # Whether previous day quotes are available
83
+ "has_prev_trades": pl.Boolean, # Whether previous day trades are available
84
+ "has_today_quotes": pl.Boolean, # Whether today's quotes are available
85
+ "has_today_trades": pl.Boolean, # Whether today's trades are available
86
+ "opt_open": pl.Float32, # Unadjusted option open price today if available
87
+ "opt_close": pl.Float32, # Unadjusted option close price today if available
88
+ "opt_prev_open": pl.Float32, # Unadjusted option open price previous day if available
89
+ "opt_prev_close": pl.Float32, # Unadjusted option close price previous day if available
90
+ }
91
+ """ Schema of the :class:`polars.DataFrame` returned by :func:`filter_contracts` and :func:`filter_contracts_between`.
92
+ See also `massive documentation <https://massive.com/docs/rest/options/contracts/contract-overview>`_ for the original field definitions.
93
+ """
94
+
95
+ # -----------------------------
96
+ # Config
97
+ # -----------------------------
98
+
99
+
100
+ @version("0.11")
101
+ @dataclass(frozen=True)
102
+ class ContractsFilter:
103
+ """
104
+ Configuration on to filter the options retrieved via :func:`filter_contracts` and :func:`filter_contracts_between`.
105
+ """
106
+ max_dte: int = 7 #: In business days
107
+ max_mns: float|None = 2.0 #: Maximum absolute normalized strike, i.e. $| log(K/S_\mathrm{prev})*sqrt((1+e)/(T+e)/0.1 | ~ | log(K/S_\mathrm{prev})/(0.1*sqrt(T)) |$, where $S_\mathrm{prev}$ is the previous close adjusted for stock splits and dividends to match today's unadjusted price, and T is time to expiry in years. Here $e$ is one hour. This is a measure of moneyness that accounts for both distance to the money and time to expiry.
108
+ max_mns5 : float|None = None #: Maximum normalized strike, i.e. $| log(K/S_\mathrm{prev})*sqrt((1+g)/(T+g)/0.1 |$, where $S_\mathrm{prev}$ is the previous close adjusted for stock splits and dividends to match today's unadjusted price, and T is time to expiry in years. Here $g$ is five days which tends to make this measure more robust than NMS alone. This is a measure of moneyness that accounts for both distance to the money and time to expiry.
109
+ min_opt_vol_k: float = 0.0 #: Previous-day approx cash vol threshold (USD 1000's)
110
+
111
+ def __str__(self):
112
+ return (
113
+ f"max_dte={self.max_dte}"+\
114
+ ('' if self.max_mns is None else f',max_mns={self.max_mns:.3g}')+
115
+ ('' if self.max_mns5 is None else f',max_mns5={self.max_mns5:.3g}')+
116
+ f',min_opt_vol_k={self.min_opt_vol_k:.3g}'
117
+ )
118
+
119
+ # -----------------------------
120
+ # Core filtering logic
121
+ # -----------------------------
122
+
123
+ @_cache(fmt=SubDir.POLARS_PARQUET).cache(
124
+ "0.27",
125
+ dependencies=[
126
+ MassiveClient.list_all_contracts_expiring_after_day,
127
+ MassiveClient.fetch_day_summary,
128
+ ContractsFilter,
129
+ ],
130
+ uid=lambda underlying, d, contracts_filter, exclude_half_days, drop_no_trades_today: (
131
+ f"{named_unique_filename48_8(f"{contracts_filter} {'xch' if exclude_half_days else ''} {'dnt' if drop_no_trades_today else ''}", contracts_filter, exclude_half_days, drop_no_trades_today)}/{underlying}/contracts/{d}"
132
+ ),
133
+ exclude_args=["pool_config", "client", "verbose"],
134
+ )
135
+ def filter_contracts(
136
+ underlying: str,
137
+ d: date,
138
+ contracts_filter: ContractsFilter,
139
+ exclude_half_days: bool,
140
+ *,
141
+ drop_no_trades_today: bool = False,
142
+ pool_config: PoolConfig|JCPool = PoolConfig(),
143
+ verbose: Context = Context.quiet,
144
+ ) -> pl.DataFrame:
145
+ r"""
146
+ Filters and processes option contracts for a given underlying on a given date.
147
+
148
+ Applies filtering rules based on expiry, moneyness, and trading volume, and returns
149
+ a data frame with enriched contract information including reject codes and calculated metrics. This function also computes
150
+ a correctly cash-valued adjused ``spot_ref_prev_close`` which can be used as non-forward looking normalizer
151
+ for all cash values "today".
152
+
153
+ Filtering Rules implemented in :class:`ContractsFilter`:
154
+
155
+ 1. Expiry filter: business days to expiry in ``[0, contracts_filter.max_dte]``.
156
+ 2. Moneyness filter: $|\log(K/S_{prev})|/\sqrt{T}/0.1$ <= contracts_filter.max_mns where ``T = days_to_exp / DAYS_PER_YEAR``.
157
+ 3. Volume filter (previous day): ``approx_cash_vol_prev_k >= contracts_filter.min_opt_vol_k`` (in 1000$).
158
+
159
+ The returned :class:`polars.DataFrame` includes all contracts, with a "reject_code" column indicating the reason for rejection based on the above rules.
160
+ To obtain the filtered options, use::
161
+
162
+ from openqdata.massive.options.contracts import filter_contracts, ContractsFilter, REJECTED
163
+ df = filter_contracts(...).filter(pl.col("reject_code") == REJECTED.USED)
164
+
165
+ **Performance Warning**
166
+
167
+ This function downloads the adjusted and unadjusted daily data, and trade and quote activity for each option.
168
+ That is much slower than just obtaining the list of contracts.
169
+
170
+ Parameters
171
+ ----------
172
+ underlying : str
173
+ The underlying ticker symbol.
174
+ d : date
175
+ The date for which to retrieve contracts.
176
+ contracts_filter : :class:`ContractsFilter`
177
+ Filter configuration specifying max_dte, max_mns, and min_opt_vol_k thresholds.
178
+ exclude_half_days : bool
179
+ If True, exclude half trading days when calculating business days to expiry.
180
+ This parameter is not contained in :class:`ContractsFilter` because it is
181
+ structural to the model development.
182
+ drop_no_trades_today : bool, default ``False``
183
+ If True, drop options which do not trade 'today'.
184
+ This parameter is not contained in :class:`ContractsFilter` because it is
185
+ structural to the model development. In particular, the model logic must
186
+ be such this feature is not forward-looking (for example by ensuring any
187
+ model analytics only start once the first trade was observed).
188
+ pool_config : PoolConfig, optional
189
+ Configuration for thread pool processing. Defaults to PoolConfig().
190
+ verbose : Context, optional
191
+ Verbosity context for logging. Defaults to Context.quiet.
192
+
193
+ Returns
194
+ -------
195
+ Result: :class:`polars.DataFrame`
196
+ Data frame with schema :data:`SCHEMA` of filtered contracts with added fields:
197
+
198
+ - reject_code (int): Rejection reason code
199
+ - spot_prev_close (float): Previous close unadjusted spot price
200
+ - nms (float): Scaled moneyness metric using :class:`NMS`
201
+ - nms5 (float): Scaled moneyness metric using :class:`NMS5`
202
+ - approx_cash_vol_prev_k (float): Previous day approx cash volume (USD thousands): contracts times shares per contract times the mean of open and close
203
+ - approx_cash_vol_today_k (float): Today approx cash volume (USD thousands), likewise
204
+ - days_to_exp (int): Business days to expiration
205
+ - spot_ref_prev_close (float): Previous close adjusted to match today's spot
206
+
207
+ """
208
+ client = MassiveClient()
209
+
210
+ """
211
+ Handle stock splits:
212
+ Assume stock of 1000 was split 10:1 into 100.
213
+ Strike today 99 is now 9.9, but the previous close was 100, so the moneyness is 0.1/0.1 = 1.0 instead of 0.01/0.1 = 0.1.
214
+ We therefore scale yesterday's adjusted close with today's adjustment factor.
215
+
216
+ F_today = unadjusted / adjusted
217
+ prev_close = adjusted_prev_close * F_today
218
+ """
219
+
220
+ context = PrettyObject()
221
+ context.prev_d = add_business_days( d, -1, exclude_half_days=exclude_half_days ) # previous business day (NB: if d is a Monday then this is the previous Friday, so we correctly skip the weekend)
222
+ context.close_adj_prev = client.fetch_day_summary( underlying, context.prev_d, adjusted=True, can_be_none=False )["close"]
223
+ context.close_unadj_prev = client.fetch_day_summary( underlying, context.prev_d, adjusted=False, can_be_none=False )["close"]
224
+ context.close_adj = client.fetch_day_summary(underlying, d, adjusted=True, can_be_none=False)[ "close" ]
225
+ ocv_today_unadj = client.fetch_day_summary(underlying, d, adjusted=False, can_be_none=False)
226
+ context.close_unadj = ocv_today_unadj["close"]
227
+ context.open_unadj = ocv_today_unadj["open"]
228
+ F_today = context.close_unadj / context.close_adj
229
+ context.ref_prev_close = context.close_adj_prev * F_today
230
+
231
+ with verbose.write_t(lambda: f"\rFetching all contracts for {underlying} expiring on or after {d}... ", end="" ) as tme:
232
+ all_contracts = client.list_all_contracts_expiring_after_day( underlying, d, max_dte=contracts_filter.max_dte )
233
+ all_contracts = pl.DataFrame(all_contracts, schema={
234
+ 'cfi': pl.String,
235
+ 'contract_type': pl.String,
236
+ 'exercise_style': pl.String,
237
+ 'expiration_date': pl.String, # will be parsed to date later
238
+ 'primary_exchange': pl.String,
239
+ 'shares_per_contract': pl.Int32,
240
+ 'strike_price': pl.Float32,
241
+ 'ticker': pl.String,
242
+ 'underlying_ticker': pl.String,
243
+ })
244
+ expected_columns = {'cfi',
245
+ 'contract_type', 'exercise_style',
246
+ 'expiration_date',
247
+ 'primary_exchange',
248
+ 'shares_per_contract',
249
+ 'strike_price',
250
+ 'ticker',
251
+ 'underlying_ticker'}
252
+ assert set(all_contracts.columns) >= expected_columns, f"{underlying} {d}: Missing expected columns in contracts data: {expected_columns - set(all_contracts.columns)}. This is unexpected, please investigate."
253
+ if len(all_contracts) == 0:
254
+ raise RuntimeError(f"{underlying} {d}: No contracts found with expiries on or after {d}.")
255
+ verbose.write(lambda: f"found {len(all_contracts)} contracts with expories form This took {tme}.", head=False)
256
+
257
+ all_contracts = all_contracts.with_columns(
258
+ pl.col("expiration_date").str.strptime(pl.Date, "%Y-%m-%d", strict=True).alias("exp_date"),
259
+ pl.lit(d).alias("date"),
260
+ pl.lit(context.prev_d).alias("prev_bus_date"),
261
+ pl.lit(REJECTED.USED).alias("reject_code").cast(pl.Int8), # assume used unless rejected
262
+ pl.lit(context.close_adj_prev).alias("spot_adj_prev_close"),
263
+ pl.lit(context.close_unadj_prev).alias("spot_prev_close"),
264
+ pl.lit(context.close_unadj).alias("spot_close"),
265
+ pl.lit(context.open_unadj).alias("spot_open"),
266
+ pl.lit(context.close_adj).alias("spot_adj_close"),
267
+ pl.lit(context.ref_prev_close).alias("spot_ref_prev_close") # this is the previous close, adjusted to match today's unadjusted spot
268
+ ).with_columns(
269
+ pl.col("exp_date").map_batches(
270
+ lambda exp_dates: pl.Series([
271
+ count_business_days_between(d, exp_date, exclude_half_days=exclude_half_days)
272
+ for exp_date in exp_dates
273
+ ])
274
+ ).alias("days_to_exp")
275
+ ).drop("expiration_date", "underlying_ticker")
276
+
277
+ neg_dte = all_contracts.filter(pl.col("days_to_exp") < 0)
278
+ if len(neg_dte) > 0:
279
+ raise RuntimeError(f"{underlying} {d}: found negative business days to expiry for dates {sorted(fmt_list(neg_dte['exp_date'].unique().to_list()))}. This should have been excluded by the Massive request filter.")
280
+
281
+ days_to_exp = all_contracts["days_to_exp"].cast(pl.Float32).to_numpy()
282
+ K = all_contracts["strike_price"].cast(pl.Float32).to_numpy()
283
+ T = (days_to_exp + 1) / DAYS_PER_YEAR
284
+ nms = NMS.to_nms(K / context.ref_prev_close, T)
285
+ nms5 = NMS5.to_nms(K / context.ref_prev_close, T)
286
+ rejected = all_contracts['reject_code'].to_numpy()
287
+
288
+ import numpy as np
289
+ rejected = np.where( days_to_exp > contracts_filter.max_dte, REJECTED.EXPIRY, rejected )
290
+ if not contracts_filter.max_mns is None:
291
+ rejected = np.where( (np.abs(nms) > contracts_filter.max_mns) & ~np.isnan(nms) & (rejected == REJECTED.USED), REJECTED.MONEYNESS, rejected )
292
+ if not contracts_filter.max_mns5 is None:
293
+ rejected = np.where( (np.abs(nms5) > contracts_filter.max_mns5) & ~np.isnan(nms5) & (rejected == REJECTED.USED), REJECTED.MONEYNESS, rejected )
294
+
295
+ all_contracts = all_contracts.with_columns(
296
+ pl.Series(rejected).alias("reject_code"),
297
+ pl.Series(nms).cast(pl.Float32).alias("nms"),
298
+ pl.Series(nms5).cast(pl.Float32).alias("nms5"),
299
+ )
300
+
301
+ # per-option data
302
+ # ---------------
303
+
304
+ def fetch_option_data( opt_ticker, shares_per_contract, d, prev_d, drop_no_trades_today ):
305
+
306
+ timing = TrackTime("Process")
307
+ c = dict(opt_ticker=opt_ticker, reject_code=REJECTED.USED) # start with used and change to rejected if any check fails
308
+ client = MassiveClient()
309
+
310
+ def approx_cash_vol_k(oc: dict) -> float:
311
+ # option prices are per share; volume is in contracts
312
+ opx, cpx, vol = oc["open"], oc["close"], oc["volume"]
313
+ return float(vol) * float(shares_per_contract) * 0.5 * (float(opx) + float(cpx)) / 1000.0
314
+
315
+ # ---- volume filter first: cheapest check that rejects the most contracts
316
+ with timing("Fetch open close volume prev"):
317
+ oc_prev = client.fetch_day_summary( opt_ticker, prev_d, adjusted=False, can_be_none=True )
318
+ c["approx_cash_vol_prev_k"] = approx_cash_vol_k(oc_prev) if not oc_prev is None else None
319
+
320
+ # ---- prev quotes/trades check
321
+ with timing("Fetch quotes & trades"):
322
+ has_prev_quotes, has_prev_trades = client.has_any_quotes_or_trades( opt_ticker, prev_d )
323
+ c["has_prev_quotes"] = has_prev_quotes
324
+ c["has_prev_trades"] = has_prev_trades
325
+
326
+ # ---- today quotes check
327
+ with timing("Fetch quotes & trades"):
328
+ has_today_quotes, has_today_trades = client.has_any_quotes_or_trades(opt_ticker, d)
329
+ c["has_today_quotes"] = has_today_quotes
330
+ c["has_today_trades"] = has_today_trades
331
+
332
+ # ---- today volume (diagnostic only, not used for rejection)
333
+ with timing("Fetch open close volume today"):
334
+ oc_today = client.fetch_day_summary(opt_ticker, d, adjusted=False, can_be_none=True)
335
+ assert not oc_today is None or not has_today_trades, f"If there are trades today, there should be a day summary with volume data. This is unexpected, please investigate: opt_ticker={opt_ticker}, d={d}, has_today_trades={has_today_trades}"
336
+ with timing("Fetch open close volume yesterday"):
337
+ oc_yesterday = None
338
+ try:
339
+ oc_yesterday = client.fetch_day_summary(opt_ticker, prev_d, adjusted=False, can_be_none=False) if has_prev_trades else None
340
+ except Exception as e:
341
+ if has_prev_trades:
342
+ raise type(e)(f"Failed to fetch yesterday's open/close/volume for {opt_ticker} on {prev_d}: {e} despite has_prev_trades={has_prev_trades}") from e
343
+
344
+ c["approx_cash_vol_today_k"] = approx_cash_vol_k(oc_today) if not oc_today is None else None
345
+ c['opt_open'] = oc_today['open'] if not oc_today is None else None
346
+ c['opt_close'] = oc_today['close'] if not oc_today is None else None
347
+ c['opt_prev_open'] = oc_yesterday['open'] if oc_yesterday is not None else None
348
+ c['opt_prev_close'] = oc_yesterday['close'] if oc_yesterday is not None else None
349
+
350
+ if not has_prev_quotes or not has_prev_trades:
351
+ c["reject_code"] = REJECTED.PREV_NO_QUOTES_OR_TRADES
352
+
353
+ elif oc_prev is None:
354
+ c["reject_code"] = REJECTED.PREV_VOLUME_MISSING
355
+
356
+ elif c["approx_cash_vol_prev_k"] < contracts_filter.min_opt_vol_k:
357
+ c["reject_code"] = REJECTED.VOLUME
358
+
359
+ elif not has_today_quotes:
360
+ c["reject_code"] = REJECTED.NO_TODAY_QUOTES
361
+
362
+ elif not has_today_trades and drop_no_trades_today:
363
+ c["reject_code"] = REJECTED.NO_TODAY_TRADES
364
+
365
+ return opt_ticker, c, timing
366
+
367
+ used = all_contracts.filter(pl.col("reject_code") == REJECTED.USED)
368
+ opt_tickers = used["ticker"].to_list()
369
+ shares = used["shares_per_contract"].to_list()
370
+ bad = [t for t, s in zip(opt_tickers, shares, strict=True) if s is None or s <= 0]
371
+ verify(not bad, lambda: f"{underlying} {d}: contracts without a positive shares_per_contract: {bad[:5]}")
372
+
373
+ jcpool = pool_config.pool()
374
+ used_ticker_data = []
375
+ tme = verbose.timer()
376
+ timing = None
377
+ for opt_ticker, opt_data, ctiming in jcpool.parallel( jcpool.delayed(fetch_option_data)(opt_ticker, n_shares, d, prev_d=context.prev_d, drop_no_trades_today=drop_no_trades_today ) for opt_ticker, n_shares in zip(opt_tickers, shares, strict=True) ):
378
+ timing = ctiming if timing is None else (timing.add(ctiming))
379
+ if tme.interval_test(1):
380
+ verbose.report( 1, lambda: f"\rFiltering {len(used_ticker_data) + 1}/{len(all_contracts)} contracts: {int((len(used_ticker_data) + 1) * 100 // len(all_contracts))}%: {opt_ticker}...", end="" )
381
+ used_ticker_data.append(opt_data)
382
+ # With no contract left after the static filters, every contract is still returned with its reject code.
383
+
384
+ expted_schema = {'opt_ticker':pl.String,
385
+ 'reject_code':pl.Int8,
386
+ 'approx_cash_vol_prev_k':pl.Float64,
387
+ 'approx_cash_vol_today_k':pl.Float64,
388
+ 'has_prev_quotes':pl.Boolean,
389
+ 'has_prev_trades':pl.Boolean,
390
+ 'has_today_quotes':pl.Boolean,
391
+ 'has_today_trades':pl.Boolean,
392
+ 'opt_open':pl.Float64,
393
+ 'opt_close':pl.Float64,
394
+ 'opt_prev_open':pl.Float64,
395
+ 'opt_prev_close':pl.Float64}
396
+ used_ticker_data = pl.DataFrame(used_ticker_data, schema=expted_schema, infer_schema_length=None)
397
+ assert set(used_ticker_data.columns) == set(expted_schema), f"{underlying} {d}: Missing expected columns in used ticker data: {set(expted_schema) - set(used_ticker_data.columns)}. This is unexpected, please investigate."
398
+
399
+ all_contracts = all_contracts.join( used_ticker_data, left_on="ticker", right_on="opt_ticker", how="left" )
400
+ assert "reject_code_right" in all_contracts.columns, f"{underlying} {d}: Missing 'reject_code_right' column in all_contracts after join. This is unexpected, please investigate."
401
+ assert not "opt_ticker" in all_contracts.columns, f"{underlying} {d}: 'opt_ticker' column should not be in all_contracts after join. This is unexpected, please investigate."
402
+
403
+ all_contracts = all_contracts.with_columns(
404
+ pl.when(pl.col("reject_code_right").is_not_null())
405
+ .then(pl.col("reject_code_right"))
406
+ .otherwise(pl.col("reject_code"))
407
+ .alias("reject_code"),
408
+ pl.lit(underlying).alias("underlying_ticker")
409
+ ).drop("reject_code_right")
410
+
411
+ assert set(all_contracts.columns) >= set(SCHEMA.keys()), f"DataFrame is missing columns from SCHEMA: {sorted(set(SCHEMA.keys()) - set(all_contracts.columns))}"
412
+ assert set(SCHEMA.keys()) >= set(all_contracts.columns) >= set(SCHEMA.keys()), f"DataFrame has superfluous columns: {sorted(set(all_contracts.columns) - set(SCHEMA.keys()))}"
413
+ all_contracts = all_contracts.with_columns([pl.col(col).cast(dtype) for col, dtype in SCHEMA.items()])
414
+
415
+ all_contracts = all_contracts.sort("exp_date","strike_price","contract_type")
416
+ active = all_contracts.filter(pl.col("reject_code") == REJECTED.USED)
417
+
418
+
419
+ timestr = ""
420
+ for topic, tinfo in (timing.items() if timing is not None else []):
421
+ timestr += f"{topic}: {tinfo.average_lap_seconds:.2f}s, "
422
+ timestr = timestr[:-2]
423
+
424
+ all_expiries = all_contracts["exp_date"].unique().to_list()
425
+
426
+ verbose.write(
427
+ lambda: (
428
+ f"\rFiltered {fmt_digits(len(all_contracts))} contacts for {underlying} on {fmt_date(d)}, "
429
+ + f"yielding {fmt_digits(active.height)} active contracts. This took {tme}. "
430
+ + (f"Found {len(all_expiries)} expiries ranging from {min(all_expiries)} to {max(all_expiries)}. " if len(all_expiries) > 0 else "Found no expiries. ")
431
+ + f"Timing: {timestr}."
432
+ ),
433
+ head=False,
434
+ )
435
+ return all_contracts
436
+
437
+ @_cache(fmt=SubDir.POLARS_PARQUET).cache(
438
+ "0.2",
439
+ dependencies=[filter_contracts],
440
+ uid=lambda ticker, date_range, contracts_filter: (
441
+ f"{named_unique_filename48_8(str(contracts_filter), contracts_filter, date_range.exclude_half_days)}/{ticker}/contracts/{date_range}"
442
+ ),
443
+ exclude_args=["pool_config", "client", "verbose", "refresh"],
444
+ )
445
+ def filter_contracts_between(
446
+ ticker: str,
447
+ date_range: DateRange,
448
+ contracts_filter: ContractsFilter,
449
+ *,
450
+ refresh: bool = False,
451
+ pool_config: PoolConfig = PoolConfig(),
452
+ verbose: Context = Context.quiet,
453
+ ) -> pl.DataFrame:
454
+ """
455
+ Filter option contracts for a given underlying ticker between start and end for a given ticker.
456
+
457
+ Parameters
458
+ ----------
459
+ ticker : str
460
+ Underlying ticker symbol, e.g. "AAPL" for Apple.
461
+ date_range : :class:`openqdata.biz_calenddar.DateRange`
462
+ Date range for which to filter contracts. Only contracts with expiration_date >= date_range.start and expiration_date <= date_range.end are returned.
463
+ contracts_filter : :class:`openqdata.massive.options.ContractsFilter`
464
+ Filter parameters for contract filtering. See :class:`ContractsFilter` for details.
465
+ refresh : bool, default False
466
+ If True, refresh data (this will only refresh the top level files, i.e. the files for individual dates, but it will not refresh the cached results of individual contracts).
467
+ pool_config : :class:`openqdata.massive.options.PoolConfig`, default ``PoolConfig()``
468
+ Configuration for parallel processing. See :class:`PoolConfig` for details.
469
+ verbose : :class:`openqdata.massive.options.Context`, default ``Context.quiet``
470
+ Verbose context for logging. See :class:`Context` for details.
471
+
472
+ Returns
473
+ -------
474
+ pl.DataFrame
475
+ DataFrame with filtered contracts for each date in the date range. The DataFrame has the same schema as the output of :func:`filter_contracts`, with an additional column "date" indicating the date for which the contracts were filtered.
476
+ """
477
+
478
+ dfs = []
479
+ dates = date_range.get_business_days()
480
+ tme = verbose.timer()
481
+ for id, d in enumerate(dates):
482
+ if tme.interval_test(1):
483
+ verbose.write(
484
+ lambda: (
485
+ f"\rFiltering contracts for {ticker} on {fmt_date(d)} ... {int(id * 100 // len(dates))}% done."
486
+ )
487
+ )
488
+ df = filter_contracts(
489
+ ticker,
490
+ d,
491
+ contracts_filter=contracts_filter,
492
+ exclude_half_days=date_range.exclude_half_days,
493
+ pool_config=pool_config,
494
+ override_cache_mode="update" if refresh else None,
495
+ verbose=verbose(1),
496
+ )
497
+ if df is None:
498
+ continue
499
+ if not "correction" in df.columns:
500
+ df = df.with_columns(pl.lit(None).alias("correction"))
501
+
502
+ existing_cols = set(df.columns) & set(SCHEMA.keys())
503
+ df = df.select(existing_cols)
504
+
505
+ for col, dtype in SCHEMA.items():
506
+ if col not in existing_cols:
507
+ df = df.with_columns(pl.lit(None).alias(col).cast(dtype))
508
+ else:
509
+ df = df.with_columns(pl.col(col).cast(dtype))
510
+ dfs.append(df)
511
+
512
+ if len(dfs) == 0:
513
+ raise RuntimeError(
514
+ f"No contracts found for {ticker} from {fmt_date(date_range.start)} to {fmt_date(date_range.end)}"
515
+ )
516
+
517
+ with verbose.write_t(
518
+ lambda: (
519
+ f"Concatenating {len(dfs)} contracts for {ticker} from {fmt_date(date_range.start)} to {fmt_date(date_range.end)}... "
520
+ ),
521
+ end="",
522
+ ) as tme:
523
+ dfs = pl.concat(dfs)
524
+ verbose.write(lambda: f"done. This took {tme}.")
525
+ return dfs
526
+
527
+
528
+ # ================================================================
529
+ # Command-line interface
530
+ # python -m curve_bins -tickers TSLA AAPL GS JPM NVDA -etfs
531
+ # ================================================================
532
+
533
+ import click
534
+ from cdxcore.err import verify_inp
535
+
536
+ from openqdata.biz_calendar import to_date
537
+ from openqdata.massive import _cli_defaults
538
+
539
+
540
+ @click.command()
541
+ @click.argument("tickers", nargs=-1, required=True)
542
+ @click.option(
543
+ "--period",
544
+ nargs=2,
545
+ type=click.DateTime(formats=["%Y-%m-%d"]),
546
+ default=_cli_defaults.period,
547
+ metavar="START END",
548
+ help="Period YYYY-MM-DD YYYY-MM-DD",
549
+ )
550
+ @click.option("--halfdays", is_flag=True, help="Include half days")
551
+ @click.option("--workers", default=_cli_defaults.workers, help="Number of workers", type=int)
552
+ @click.option("--threading", is_flag=True, help="Use only threading, no multiprocessing")
553
+ @click.option(
554
+ "--refresh", is_flag=True, help="Refresh data (this will only refresh the top level files)"
555
+ )
556
+ @click.option("--quiet", is_flag=True, help="Quiet mode, no logging")
557
+ @click.option("--max_dte", default=25, help="Maximum business days to expiry", type=int)
558
+ @click.option("--max_nms", default=3.0, help="Maximum normalized moneyness", type=float)
559
+ @click.option(
560
+ "--min_opt", default=25, help="Minimum traded option volume in thousand $", type=float
561
+ )
562
+ def main(
563
+ tickers: list[str],
564
+ period: list[datetime.datetime],
565
+ halfdays: bool,
566
+ workers: int,
567
+ threading: bool,
568
+ quiet: bool,
569
+ refresh: bool,
570
+ max_dte: int,
571
+ max_nms: float,
572
+ min_opt: float,
573
+ ):
574
+ verify_inp(len(tickers) > 0, "At least one ticker must be specified")
575
+ verify_inp(period is not None and len(period) == 2, "A start and end date must be specified")
576
+
577
+ start, end = period
578
+
579
+ date_range = DateRange(start=to_date(start), end=to_date(end), exclude_half_days=not halfdays)
580
+ pool_config = PoolConfig(num_workers=workers, threading=threading)
581
+ contracts_filter = ContractsFilter(max_dte=max_dte, max_mns=max_nms, min_opt_vol_k=min_opt)
582
+
583
+ verbose = Context.all
584
+ verbose.write(
585
+ lambda: (
586
+ f"Filtering contracts for tickers {fmt_list(tickers)} from {fmt_date(start)} to {fmt_date(end)}, "
587
+ + f"with half days {'included' if halfdays else 'excluded'}, using filter {contracts_filter}, with {pool_config.num_workers} {'threads' if pool_config.threading else 'processes'}."
588
+ )
589
+ )
590
+ for it, ticker in enumerate(tickers):
591
+ verbose.write(
592
+ lambda: (
593
+ f"\rProcessing {fmt_digits(len(tickers))} tickers: {int(it * 100 // len(tickers))}% done. Now processing {ticker} from {fmt_date(start)} to {fmt_date(end)}."
594
+ )
595
+ )
596
+ _ = filter_contracts_between(
597
+ ticker,
598
+ date_range,
599
+ contracts_filter=contracts_filter,
600
+ cache_generate_only=not refresh,
601
+ override_cache_mode="update" if refresh else None,
602
+ refresh=refresh,
603
+ pool_config=pool_config,
604
+ verbose=verbose(1),
605
+ )
606
+ verbose.write("All done")
607
+
608
+
609
+ if __name__ == "__main__":
610
+ main()