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,242 @@
1
+ """
2
+ openqdata.massive.expiries
3
+
4
+ Per-ticker option expiry flags via the Massive API.
5
+
6
+ For each trading day, checks whether ANY option on the underlying expires on that day
7
+ and classifies it (MONTHLY, QUAD_WITCHING, etc.).
8
+
9
+ The :func:`ticker_expiries` function uses an incremental cache: it only fetches the
10
+ dates that are not already stored, so repeated calls for overlapping date ranges are
11
+ cheap.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from datetime import date
17
+
18
+ import polars as pl
19
+ from cdxcore.err import verify
20
+ from cdxcore.jcpool import JCPool
21
+ from cdxcore.util import fmt_date
22
+ from cdxcore.verbose import Context
23
+ from cdxcore.version import version
24
+
25
+ from openqdata.biz_calendar import prev_business_day
26
+ from openqdata.massive import MassiveClient
27
+ from openqdata.tickers import _locations_tickers
28
+ from openqdata.tickers.ticker_calendar import EXPIRY
29
+
30
+ _expiries_cache = _locations_tickers
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Calendar classification (pure Polars, no API)
34
+ # ---------------------------------------------------------------------------
35
+
36
+
37
+ @version("0.1")
38
+ def _third_friday_expr() -> pl.Expr:
39
+ """Calendar third Friday for the month containing the ``date`` column."""
40
+ d = pl.col("date")
41
+ m_start = d.dt.month_start()
42
+ wd0 = m_start.dt.weekday()
43
+ off = (pl.lit(5) - wd0 + pl.lit(7)) % pl.lit(7) # Polars ISO weekday: Fri=5
44
+ first_friday = m_start + off * pl.duration(days=1)
45
+ return first_friday + pl.duration(days=14)
46
+
47
+
48
+ @version("0.2", dependencies=[_third_friday_expr, prev_business_day])
49
+ def classify_expiry(df: pl.DataFrame) -> pl.DataFrame:
50
+ """
51
+ Add ``has_expiry`` (Int8, values from :class:`openqdata.tickers.ticker_calendar.EXPIRY`)
52
+ to a DataFrame that contains a ``date`` column.
53
+
54
+ The classification is purely calendar-based and does not depend on which other dates are
55
+ present in ``df``. The standard monthly expiry is the third Friday of the month or, if that
56
+ is not an NYSE business day, the last business day before it.
57
+
58
+ * :attr:`EXPIRY.QUAD_WITCHING`: standard monthly expiry in Mar/Jun/Sep/Dec
59
+ * :attr:`EXPIRY.MONTHLY`: standard monthly expiry in other months
60
+ * :attr:`EXPIRY.NONE`: any other date
61
+ """
62
+ verify("date" in df.columns, "df must contain a 'date' column")
63
+
64
+ df0 = df.with_columns(pl.col("date").cast(pl.Date))
65
+ months = (
66
+ df0.select(_third_friday_expr().alias("_third_friday"))
67
+ .unique()
68
+ .drop_nulls()
69
+ )
70
+ monthly = pl.DataFrame(
71
+ {
72
+ "_third_friday": months["_third_friday"],
73
+ "_monthly_expiry_date": pl.Series(
74
+ [prev_business_day(d, count_start=True) for d in months["_third_friday"].to_list()],
75
+ dtype=pl.Date,
76
+ ),
77
+ },
78
+ schema={"_third_friday": pl.Date, "_monthly_expiry_date": pl.Date},
79
+ )
80
+
81
+ df1 = df0.with_columns(_third_friday_expr().alias("_third_friday")).join(
82
+ monthly, on="_third_friday", how="left"
83
+ )
84
+ is_monthly = pl.col("date") == pl.col("_monthly_expiry_date")
85
+ is_qtr = pl.col("date").dt.month().is_in([3, 6, 9, 12])
86
+
87
+ return df1.with_columns(
88
+ pl.when(is_monthly & is_qtr)
89
+ .then(pl.lit(int(EXPIRY.QUAD_WITCHING)))
90
+ .when(is_monthly)
91
+ .then(pl.lit(int(EXPIRY.MONTHLY)))
92
+ .otherwise(pl.lit(int(EXPIRY.NONE)))
93
+ .cast(pl.Int8)
94
+ .alias("has_expiry")
95
+ ).drop(["_third_friday", "_monthly_expiry_date"])
96
+
97
+
98
+ # ---------------------------------------------------------------------------
99
+ # Per-day API check
100
+ # ---------------------------------------------------------------------------
101
+
102
+
103
+ @version("0.2", dependencies=[classify_expiry, MassiveClient])
104
+ def ticker_expiries_day(ticker: str, dt: date) -> tuple[date, int | None]:
105
+ """
106
+ Check via the Massive API whether any option on ``ticker`` expires on ``dt``.
107
+
108
+ Returns
109
+ -------
110
+ (dt, expiry_code)
111
+ ``expiry_code`` is an :class:`EXPIRY` int value, or ``None`` if no options expire.
112
+ """
113
+ client = MassiveClient()
114
+ url = f"{MassiveClient.BASE_URL}/v3/reference/options/contracts"
115
+ params = {
116
+ "underlying_ticker": ticker,
117
+ "expiration_date.gte": dt.strftime("%Y-%m-%d"),
118
+ "expiration_date.lte": dt.strftime("%Y-%m-%d"),
119
+ "limit": 1000,
120
+ "order": "asc",
121
+ "expired": True,
122
+ "sort": "expiration_date",
123
+ "as_of": dt.strftime("%Y-%m-%d"),
124
+ }
125
+ res = client.paginate(url, params)
126
+ if not res:
127
+ return dt, None
128
+
129
+ expiring = {
130
+ r.get("expiration_date") for r in res if isinstance(r, dict)
131
+ }
132
+ if dt.strftime("%Y-%m-%d") not in expiring:
133
+ return dt, None
134
+
135
+ # Options expire on ``dt``: mechanical monthly/quarterly expiries keep their code,
136
+ # every other expiry (weeklies, 0DTE, ...) is STANDARD.
137
+ code = int(classify_expiry(pl.DataFrame({"date": [dt]}, schema={"date": pl.Date}))["has_expiry"][0])
138
+ return dt, code if code != int(EXPIRY.NONE) else int(EXPIRY.STANDARD)
139
+
140
+
141
+ # ---------------------------------------------------------------------------
142
+ # Incremental-cache wrapper
143
+ # ---------------------------------------------------------------------------
144
+
145
+
146
+ @version("0.1", dependencies=[ticker_expiries_day, MassiveClient])
147
+ def ticker_expiries(
148
+ ticker: str,
149
+ business_days: list[date],
150
+ *,
151
+ num_workers: int = -2,
152
+ threading: bool = False,
153
+ verbose: Context = Context.quiet,
154
+ ) -> pl.DataFrame:
155
+ """
156
+ For each date in ``business_days``, flag whether any option on ``ticker`` expires
157
+ (0-DTE check) and return the expiry type.
158
+
159
+ Results are stored in an incremental cache keyed by ``ticker`` so only the
160
+ missing dates are fetched on subsequent calls.
161
+
162
+ Parameters
163
+ ----------
164
+ ticker : str
165
+ business_days : list[date]
166
+ Sorted list of NYSE trading days to check.
167
+ num_workers : int
168
+ Parallel workers.
169
+ threading : bool
170
+ Use threads instead of processes.
171
+ verbose : Context
172
+
173
+ Returns
174
+ -------
175
+ pl.DataFrame
176
+ Columns: date (Date), has_expiry (Int8) — only rows where has_expiry is not null.
177
+ """
178
+ head_version = ticker_expiries.version.unique_id48
179
+ cache_key = f"expiries/{ticker}"
180
+
181
+ expiries: pl.DataFrame | None = (
182
+ _expiries_cache.read(cache_key, None, version=head_version)
183
+ if _expiries_cache.cache_mode.read
184
+ else None
185
+ )
186
+
187
+ known_dates: set[date] = set(expiries["date"].to_list()) if expiries is not None else set()
188
+ missing = sorted(set(business_days) - known_dates)
189
+ tmx = verbose.timer()
190
+
191
+ if missing:
192
+ with verbose.write_t(
193
+ lambda: f"Fetching {len(missing)} expiry dates for {ticker}..."
194
+ ) as tme:
195
+ jcpool = JCPool(num_workers, threading=threading)
196
+ found: dict[date, int | None] = {}
197
+
198
+ for dt_, code in jcpool.parallel(
199
+ jcpool.delayed(ticker_expiries_day)(ticker=ticker, dt=dt_) for dt_ in missing
200
+ ):
201
+ verbose.report(
202
+ 1,
203
+ lambda: f"\r {ticker}: {int((len(found) + 1) * 100 // len(missing))}%...",
204
+ end="",
205
+ )
206
+ found[dt_] = code
207
+
208
+ verbose.write(lambda: f"\rFetched {len(missing)} dates for {ticker}. Took {tme}.")
209
+
210
+ new_rows = pl.DataFrame(
211
+ {
212
+ "date": pl.Series(list(found.keys()), dtype=pl.Date),
213
+ "has_expiry": pl.Series(list(found.values()), dtype=pl.Int8),
214
+ }
215
+ )
216
+ expiries = pl.concat([expiries, new_rows]) if expiries is not None else new_rows
217
+ expiries = expiries.sort("date")
218
+
219
+ if _expiries_cache.cache_mode.write:
220
+ _expiries_cache.write(cache_key, expiries, version=head_version)
221
+
222
+ result = expiries.filter(
223
+ pl.col("date").is_in(business_days) & pl.col("has_expiry").is_not_null()
224
+ )
225
+
226
+ dupes = result.group_by("date").len().filter(pl.col("len") > 1)
227
+ if dupes.height > 0:
228
+ raise RuntimeError(f"Duplicate expiry dates for {ticker}: {dupes.head()}")
229
+
230
+ verbose.write(
231
+ lambda: (
232
+ f"Found {result.height} expiries for '{ticker}' between "
233
+ f"{fmt_date(business_days[0])} and {fmt_date(business_days[-1])}. Took {tmx}."
234
+ )
235
+ )
236
+ return result
237
+
238
+
239
+ if __name__ == "__main__":
240
+ from openqdata.cli import run_module
241
+
242
+ run_module(globals())
@@ -0,0 +1,5 @@
1
+ # openqdata.massive.options
2
+
3
+ Option contract lists and filters for Massive.
4
+
5
+ Documentation: [connectors/massive.md](https://github.com/hansbuehler/openqdata/blob/main/docs/connectors/massive.md#option-contracts)
@@ -0,0 +1,6 @@
1
+ """
2
+ Massive.com Options Data Module
3
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4
+
5
+ Option specific data pipeline element for `massive.com <https://massive.com/>`_ market data.
6
+ """