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,370 @@
1
+ """
2
+ openqdata.tickers.ticker_calendar
3
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4
+
5
+ Build a calendar for a given ticker:
6
+
7
+ * Option Expiries (standard mechanical ones, i.e. monthly, quarterly, EOM)
8
+ * Dividends
9
+ * Stock splits
10
+ * Ticker changes (e.g. name changes, ticker changes, etc.)
11
+ * Earnings (from Yahoo Finance, as these are not easily available from other sources)
12
+
13
+
14
+
15
+ """
16
+
17
+ import os as os
18
+ import warnings as warnings
19
+ from datetime import date, timedelta
20
+ from enum import IntEnum
21
+
22
+ import numpy as np
23
+ import polars as pl
24
+ from cdxcore.pretty import PrettyObject
25
+ from cdxcore.util import fmt_date
26
+
27
+ from openqdata.biz_calendar import (
28
+ DateRange,
29
+ get_business_days,
30
+ next_business_day,
31
+ )
32
+ from openqdata.massive import MassiveClient
33
+ from openqdata.tickers import Context, SubDir, _locations_tickers, version
34
+ from openqdata.yahoo import YFClient
35
+
36
+
37
+ class EXPIRY(IntEnum):
38
+ """Expory codes"""
39
+
40
+ NONE = 0 # not an expiry
41
+ STANDARD = (
42
+ 1 # not one of the mechanical expiries below, but still an expiry (e.g. 0DTE or weeklies)
43
+ )
44
+ QUAD_WITCHING = 2 # third friday of March, June, September, December
45
+ MONTHLY = 3 # third friday of other months
46
+ QUARTERLY = 4 # quarterly expiry, i.e. third friday of March, June, September, December (same as quad witching, but we keep it separate for now in case we want to add more codes later)
47
+ EOM = 5 # end of month expiry (last business day of the month, if not quad witching or monthly)
48
+
49
+
50
+ def _date_code(d: date) -> int:
51
+ return d.year * 10000 + d.month * 100 + d.day
52
+
53
+
54
+ SCHEMA_TICKER_CALENDAR = {
55
+ "date": pl.Date,
56
+ "expiry_code": pl.Int8,
57
+ "is_ex_div": pl.Boolean,
58
+ "is_split": pl.Boolean,
59
+ "has_ticker_change": pl.Boolean,
60
+ "is_earnings": pl.Boolean,
61
+ "is_half_day": pl.Boolean,
62
+ }
63
+ """Schema of the :class:`polars.DataFrame` returned by :func:`build_ticker_calendar`."""
64
+
65
+ def _date_code( d : date ) -> int:
66
+ return d.year*10000 + d.month*100 + d.day
67
+
68
+ @version("0.1")
69
+ def get_standard_expiries(date_range: DateRange) -> pl.DataFrame:
70
+ """
71
+ Computes standard expiry codes for a list of dates.
72
+ Expiry codes computed by this function are mechanical:
73
+
74
+ * ``QUAD_WITCHING``: third friday of March, June, September, December
75
+ * ``MONTHLY``: third friday of other months
76
+ * ``EOM``: last business day of the month
77
+ * ``QUARTERLY``: quarterly expiry, i.e. last business day of the month of March, June, September, December
78
+
79
+ Parameters
80
+ ----------
81
+ date_range : DateRange
82
+ Date range for which to compute expiry codes.
83
+ The function will only return expiry codes for dates within this range.
84
+
85
+ Returns
86
+ -------
87
+ Expiries : :class:`polars.DataFrame`
88
+ DataFrame with columns:
89
+ * ``date``: date of the expiry
90
+ * ``expiry_code``: expiry code, one of the values of the :class:`EXPIRY` enum.
91
+ """
92
+
93
+ start_year = date_range.start.year
94
+ end_year = date_range.end.year
95
+ business_days = set(date_range.get_business_days())
96
+ dates = get_business_days(
97
+ date_range.start,
98
+ next_business_day(date_range.end, exclude_half_days=False, count_start=False),
99
+ exclude_half_days=False,
100
+ ) # (this is cached, in case its equal to businbess days)
101
+ datecodes = np.array([_date_code(d) for d in dates], dtype=np.int32)
102
+ assert np.min(np.diff(datecodes)) >= 1, (
103
+ f"Internal error: business days should be at least 1 day apart not {np.min(np.diff(datecodes))}"
104
+ )
105
+
106
+ expiries = []
107
+ codes = []
108
+
109
+ for year in range(start_year, end_year + 2):
110
+ for month in range(1, 13):
111
+ first_day = date(year, month, 1)
112
+
113
+ # get last business of previous month
114
+ last_prev_month = first_day - timedelta(days=1)
115
+ lpm_code = _date_code(last_prev_month)
116
+ ix = np.searchsorted(datecodes, lpm_code, side="right")
117
+ if ix > 0:
118
+ assert lpm_code >= datecodes[ix-1], f"Internal error: lpm_code {lpm_code} should be >= datecodes[{ix-1}]={datecodes[ix-1]}"
119
+ if dates[ix-1] in business_days:
120
+ assert not dates[ix-1] in expiries, f"Internal error: duplicate expiry date {dates[ix-1]}"
121
+ expiries.append( dates[ix-1] )
122
+ codes.append( int( EXPIRY.EOM if last_prev_month.month not in {3, 6, 9, 12} else EXPIRY.QUARTERLY ) )
123
+
124
+ # get third friday of this month
125
+ first_friday_offset = (4 - first_day.weekday()) % 7
126
+ third_friday = first_day + timedelta(days=first_friday_offset + 14)
127
+ tf_code = _date_code(third_friday)
128
+ ix = np.searchsorted(datecodes, tf_code, side="right")
129
+ if ix > 0:
130
+ assert tf_code >= datecodes[ix-1], f"Internal error: tf_code {tf_code} should be >= datecodes[{ix-1}]={datecodes[ix-1]}"
131
+ if dates[ix-1] in business_days:
132
+ assert not dates[ix-1] in expiries, f"Internal error: duplicate expiry date {dates[ix-1]}"
133
+ expiries.append( dates[ix-1] )
134
+ codes.append( int( EXPIRY.QUAD_WITCHING if month in {3, 6, 9, 12} else EXPIRY.MONTHLY ) )
135
+
136
+ if year==end_year+1:
137
+ # we only had to handle the first month of the next year
138
+ break
139
+
140
+ return pl.DataFrame(
141
+ {"date": pl.Series(expiries, dtype=pl.Date), "expiry_code": pl.Series(codes, dtype=pl.Int8)}
142
+ ).sort("date")
143
+
144
+
145
+ @version("0.1", dependencies=[MassiveClient.get_dividends])
146
+ def has_dividends(ticker: str, start: date, end: date) -> pl.DataFrame:
147
+ """
148
+ Retrieve dividends between two dates from [``/stocks/v1/dividends``](https://massive.com/docs/api/stocks/v1/dividends/).
149
+ """
150
+ client = MassiveClient()
151
+ df = client.get_dividends(ticker, start, end)
152
+ df = df.rename({"ex_dividend_date": "date"})
153
+ df = df.unique(subset=["date"]).sort("date").with_columns(pl.lit(True).alias("is_ex_div"))
154
+ df = df.select(["date", "is_ex_div"])
155
+ return df
156
+
157
+
158
+ @version("0.1", dependencies=[MassiveClient.get_splits])
159
+ def has_splits(ticker: str, start: date, end: date) -> pl.DataFrame:
160
+ """Retrieve stock splits between two dates from [``/stocks/v1/splits``](https://massive.com/docs/api/stocks/v1/splits/)."""
161
+ client = MassiveClient()
162
+ df = client.get_splits(ticker, start, end)
163
+ df = df.rename({"execution_date": "date"})
164
+ df = df.unique(subset=["date"]).sort("date").with_columns(pl.lit(True).alias("is_split"))
165
+ df = df.select(["date", "is_split"])
166
+ return df
167
+
168
+
169
+
170
+ @_locations_tickers(fmt=SubDir.POLARS_PARQUET).cache(
171
+ "0.3",
172
+ dependencies=[
173
+ MassiveClient.get_dividends,
174
+ MassiveClient.get_splits,
175
+ MassiveClient.has_ticker_changes,
176
+ YFClient.has_earnings,
177
+ DateRange,
178
+ ],
179
+ uid=lambda ticker, date_range: f"calendars/{ticker}/{date_range}",
180
+ exclude_args=["verbose"],
181
+ )
182
+ def build_ticker_calendar(
183
+ ticker: str,
184
+ date_range: DateRange, *,
185
+ verbose: Context = Context.all,
186
+ ) -> pl.DataFrame:
187
+ """
188
+ Build a per-day ticker-specific calendar for a given equity ticker.
189
+
190
+ Parameters
191
+ ----------
192
+ ticker : str
193
+ Equity ticker for which to build the calendar.
194
+ date_range : :class:`DateRange`
195
+ Date range for which to build the calendar.
196
+ verbose : :class:`cdxcore.verbose.Context`, default ``Context.all``
197
+ Verbose context for logging progress and timing. Default is ``Context.all``.
198
+
199
+ Returns
200
+ -------
201
+ Calendar : :class:`polars.DataFrame`
202
+ DataFrame with the schema :data:`SCHEMA_TICKER_CALENDAR` with columns:
203
+
204
+ * ``date``: date of the calendar entry
205
+ * ``expiry_code``: expiry code, one of the values of the :class:`EXPIRY` enum, indicating the type of expiry on that date (if any).
206
+ * ``is_ex_div``: boolean indicating whether this date is an ex-dividend date for the ticker.
207
+ * ``is_split``: boolean indicating whether this date is a stock split date for the ticker.
208
+ * ``has_ticker_change``: boolean indicating whether this date has a ticker change event for the ticker.
209
+ * ``is_earnings``: boolean indicating whether this date is an earnings date for the ticker.
210
+ * ``is_half_day``: boolean indicating whether this date is a half trading day (e.g. day before a holiday).
211
+ """
212
+ half_days = date_range.get_half_days()
213
+
214
+ dfs = PrettyObject()
215
+ start = date_range.start
216
+ end = date_range.end
217
+
218
+ with verbose.write_t(
219
+ lambda: f"Building calendar for {ticker} between {fmt_date(start)} and {fmt_date(end)}:"
220
+ ) as tmx:
221
+ verbose1 = verbose(1)
222
+ if not date_range.exclude_half_days:
223
+ with verbose1.write_t(
224
+ lambda: (
225
+ f"Retrieving half days for {ticker} between {fmt_date(start)} and {fmt_date(end)}:"
226
+ )
227
+ ) as tme:
228
+ half_days = date_range.get_half_days()
229
+ if not len(half_days) == 0:
230
+ dfs.half_days = pl.DataFrame(
231
+ {
232
+ "date": pl.Series(half_days, dtype=pl.Date),
233
+ "is_half_day": pl.Series([True] * len(half_days), dtype=pl.Boolean),
234
+ }
235
+ )
236
+
237
+ with verbose1.write_t(
238
+ lambda: (
239
+ f"Retrieving dividends for {ticker} between {fmt_date(start)} and {fmt_date(end)}... "
240
+ ),
241
+ end="",
242
+ ) as tme:
243
+ dfs.expiries = get_standard_expiries(date_range)
244
+ assert set(dfs.expiries.columns) == {"date", "expiry_code"}, (
245
+ f"Internal error retrieving expiries for {ticker} between {fmt_date(start)} and {fmt_date(end)}: expected columns {{'date', 'expiry_code'}} but got {set(dfs.expiries.columns)}."
246
+ )
247
+ verbose1.write(
248
+ lambda: f"done; {ticker} has {dfs.expiries.height} expiries. This took {tme}.",
249
+ head=False,
250
+ )
251
+
252
+ with verbose1.write_t(
253
+ lambda: (
254
+ f"Retrieving dividends for {ticker} between {fmt_date(start)} and {fmt_date(end)}... "
255
+ ),
256
+ end="",
257
+ ) as tme:
258
+ dfs.divs = has_dividends(ticker, start=start, end=end)
259
+ assert set(dfs.divs.columns) == {"date", "is_ex_div"}, (
260
+ f"Internal error retrieving dividends for {ticker} between {fmt_date(start)} and {fmt_date(end)}: expected columns {{'date', 'is_ex_div'}} but got {set(dfs.divs.columns)}."
261
+ )
262
+ verbose1.write(
263
+ lambda: f"done; {ticker} has {dfs.divs.height} dividends. This took {tme}.",
264
+ head=False,
265
+ )
266
+
267
+ with verbose1.write_t(
268
+ lambda: (
269
+ f"Retrieving splits for {ticker} between {fmt_date(start)} and {fmt_date(end)}... "
270
+ ),
271
+ end="",
272
+ ) as tme:
273
+ dfs.splits = has_splits(ticker, start=start, end=end)
274
+ assert set(dfs.splits.columns) == {"date", "is_split"}, (
275
+ f"Internal error retrieving splits for {ticker} between {fmt_date(start)} and {fmt_date(end)}: expected columns {{'date', 'is_split'}} but got {set(dfs.splits.columns)}."
276
+ )
277
+ verbose1.write(
278
+ lambda: f"done; {ticker} has {dfs.splits.height} splits. This took {tme}.",
279
+ head=False,
280
+ )
281
+
282
+ with verbose1.write_t(
283
+ lambda: (
284
+ f"Retrieving ticker changes for {ticker} between {fmt_date(start)} and {fmt_date(end)}... "
285
+ ),
286
+ end="",
287
+ ) as tme:
288
+ dfs.events = MassiveClient().has_ticker_changes(ticker, start=start, end=end)
289
+ assert set(dfs.events.columns) == {"date", "has_ticker_change"}, (
290
+ f"Internal error retrieving ticker changes for {ticker} between {fmt_date(start)} and {fmt_date(end)}: expected columns {{'date', 'has_ticker_change'}} but got {set(dfs.events.columns)}."
291
+ )
292
+ verbose1.write(
293
+ lambda: f"done; {ticker} has {dfs.events.height} ticker changes. This took {tme}.",
294
+ head=False,
295
+ )
296
+
297
+ with verbose1.write_t(
298
+ lambda: (
299
+ f"Retrieving earnings {ticker} between {fmt_date(start)} and {fmt_date(end)}... "
300
+ ),
301
+ end="",
302
+ ) as tme:
303
+ dfs.earnings = YFClient().has_earnings(ticker, start=start, end=end)
304
+ assert set(dfs.earnings.columns) == {"date", "is_earnings"}, (
305
+ f"Internal error retrieving earnings for {ticker} between {fmt_date(start)} and {fmt_date(end)}: expected columns {{'date', 'is_earnings'}} but got {set(dfs.earnings.columns)}."
306
+ )
307
+ verbose1.write(
308
+ lambda: f"done; {ticker} has {dfs.earnings.height} earnings. This took {tme}.",
309
+ head=False,
310
+ )
311
+
312
+ del verbose1
313
+
314
+ df = None
315
+ for fname, fdata in dfs.items():
316
+ if fdata is None:
317
+ continue
318
+
319
+ # Detect duplicate dates in this fdata BEFORE joining
320
+ if fdata.select(pl.col("date").is_duplicated().any()).item():
321
+ dupes = (
322
+ fdata.filter(pl.col("date").is_duplicated())
323
+ .select("date")
324
+ .unique()
325
+ .sort("date")
326
+ )
327
+ raise RuntimeError(
328
+ f"{fname} contains duplicate 'date' entries (showing up to 10): "
329
+ f"{dupes.head(10).to_dict(as_series=False)['date']}"
330
+ )
331
+
332
+ df = fdata if df is None else df.join(fdata, on="date", how="full", coalesce=True)
333
+
334
+ bool_cols = [col for col, dtype in SCHEMA_TICKER_CALENDAR.items() if dtype == pl.Boolean]
335
+ assert "date" in df.columns, f"Internal error: expected a 'date' column while building the calendar for {ticker}."
336
+ assert set(df.columns) <= set(SCHEMA_TICKER_CALENDAR), ("Internal error: unknonw columns", set(df.columns) - set(SCHEMA_TICKER_CALENDAR) )
337
+
338
+ for col in bool_cols:
339
+ if col not in df.columns:
340
+ df = df.with_columns(pl.lit(False).cast(pl.Boolean).alias(col))
341
+ else:
342
+ # fill bools with False to safe memory
343
+ df = df.with_columns(pl.col(col).fill_null(False).cast(pl.Boolean))
344
+
345
+ if "expiry_code" not in df.columns:
346
+ df = df.with_columns(pl.lit(int(EXPIRY.NONE), dtype=pl.Int8).alias("expiry_code"))
347
+ else:
348
+ # dates contributed only by other sources (dividends, splits, ...) are not expiries
349
+ df = df.with_columns(pl.col("expiry_code").fill_null(int(EXPIRY.NONE)).cast(pl.Int8))
350
+
351
+ # providers may return corporate actions outside the requested range
352
+ df = df.filter(pl.col("date").is_between(start, end, closed="both"))
353
+
354
+ # faster duplicate check than group_by len
355
+ if df.select(pl.col("date").is_duplicated().any()).item():
356
+ dupes = df.filter(pl.col("date").is_duplicated()).select("date").unique()
357
+ warnings.warn(str(dupes.head()))
358
+ raise RuntimeError("Date duplicates found!")
359
+
360
+ df = df.select([pl.col(col).cast(dtype) for col, dtype in SCHEMA_TICKER_CALENDAR.items()])
361
+
362
+ verbose.write(lambda: f"Built calendar for {ticker} between {fmt_date(start)} and {fmt_date(end)}. This took {tmx}.")
363
+
364
+ return df.sort("date")
365
+
366
+
367
+ if __name__ == "__main__":
368
+ from openqdata.cli import run_module
369
+
370
+ run_module(globals())
@@ -0,0 +1,3 @@
1
+ # openqdata.utils
2
+
3
+ pandas/Polars schema helpers and CVXPY patches.
@@ -0,0 +1,35 @@
1
+ """
2
+ Basic shared Utilities
3
+ ======================
4
+ """
5
+
6
+ from dataclasses import dataclass
7
+
8
+ from cdxcore.err import verify_inp
9
+
10
+
11
+ @dataclass
12
+ class Eps:
13
+ """
14
+ Detailed error tolerance for debugging.
15
+ """
16
+ prices : float = 1E-6 #: Tolerance for option price errors.
17
+ theta : float = 1E-6 #: Tolerance for theta errors during DLV computation.
18
+ gamma : float = 1E-6 #: Tolerance for gamma errors during DLV computation.
19
+ densities : float = 1E-6 #: Tolerance for density errors.
20
+ dlvsq : float = 1E-6 #: Tolerance for DLV squared errors being positive.
21
+
22
+ def __post_init__(self):
23
+ verify_inp( self.prices >= 0., f"Tolerance for prices must be non-negative, found {self.prices}" )
24
+ verify_inp( self.theta >= 0., f"Tolerance for theta must be non-negative, found {self.theta}" )
25
+ verify_inp( self.gamma >= 0., f"Tolerance for gamma must be non-negative, found {self.gamma}" )
26
+ verify_inp( self.densities >= 0., f"Tolerance for densities must be non-negative, found {self.densities}" )
27
+ verify_inp( self.dlvsq >= 0., f"Tolerance for dlvsq must be non-negative, found {self.dlvsq}" )
28
+
29
+
30
+ @staticmethod
31
+ def create( eps : float ) -> 'Eps':
32
+ """ Create an Eps object with all tolerances set to the same value. """
33
+ verify_inp( eps >= 0., f"Tolerance must be non-negative, found {eps}" )
34
+ return Eps( prices=eps, theta=eps, gamma=eps, densities=eps, dlvsq=eps )
35
+
@@ -0,0 +1,47 @@
1
+ """
2
+ CVXPY Utilities
3
+ ===============
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import numpy as np
9
+ from numpy.exceptions import AxisError
10
+
11
+ _PATCH_ATTR = "_openqdata_cvxpy_sum_shape_patch"
12
+
13
+
14
+ def patch_cvxpy_sum_shape_from_args() -> bool:
15
+ """
16
+ Patch CVXPY's Sum.shape_from_args() to avoid reducing uninitialized memory.
17
+
18
+ CVXPY 1.8.2 computes the output shape of cp.sum() by calling
19
+ ``np.sum(np.empty(shape))``. With NumPy 2.4 this can raise a spurious
20
+ ``RuntimeWarning: overflow encountered in reduce`` while the expression is
21
+ being validated. Replacing ``np.empty`` with ``np.zeros`` preserves the
22
+ shape inference while avoiding the warning.
23
+
24
+ Returns ``True`` when the patch is applied and ``False`` when it is already
25
+ active.
26
+ """
27
+ import cvxpy.atoms.affine.sum as cvxpy_sum
28
+
29
+ current = cvxpy_sum.Sum.shape_from_args
30
+ if getattr(current, _PATCH_ATTR, False):
31
+ return False
32
+
33
+ def safe_shape_from_args(self):
34
+ try:
35
+ return np.sum(
36
+ np.zeros(self.args[0].shape, dtype=np.float64),
37
+ axis=self.axis,
38
+ keepdims=self.keepdims,
39
+ ).shape
40
+ except (ValueError, AxisError, TypeError) as exc:
41
+ raise ValueError(f"Invalid arguments for cp.sum: {exc}") from exc
42
+
43
+ setattr(safe_shape_from_args, _PATCH_ATTR, True)
44
+ setattr(safe_shape_from_args, "_openqdata_original", current)
45
+ cvxpy_sum.Sum.shape_from_args = safe_shape_from_args
46
+ return True
47
+
openqdata/utils/pd.py ADDED
@@ -0,0 +1,125 @@
1
+ """
2
+ Panda Utilities
3
+ ===============
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Mapping
9
+ from typing import Any
10
+
11
+ import pandas as pd
12
+ from cdxcore.err import verify_inp
13
+ from cdxcore.util import fmt_list
14
+
15
+
16
+ def create_empty_df( schema ):
17
+ """
18
+ Creates an empty :class:`pandas.DataFrame` from a schema.
19
+
20
+ A schema is a dictionary of the form::
21
+
22
+ {
23
+ "col_a": np.dtype("float32"),
24
+ "col_b": np.dtype("int64"),
25
+ }
26
+ """
27
+ return pd.DataFrame({c: pd.Series(dtype=dtype) for c,dtype in schema.items()})
28
+
29
+ def _as_pandas_dtype(dtype: Any, *, col: str) -> Any:
30
+ try:
31
+ return pd.api.types.pandas_dtype(dtype)
32
+ except (TypeError, ValueError) as exc:
33
+ verify_inp(False, f"Invalid dtype for column {col!r}: {dtype!r}. Error: {exc}")
34
+
35
+ def verify_schema(
36
+ df: pd.DataFrame,
37
+ schema: Mapping[str, Any],
38
+ header : str|callable[[],str]| None = None,
39
+ *,
40
+ allow_extra_columns: bool = False,
41
+ ) -> pd.DataFrame:
42
+ """
43
+ Validate a :class:`pandas.DataFrame` against a schema of the form::
44
+
45
+ {
46
+ "col_a": np.dtype("float32"),
47
+ "col_b": np.dtype("int64"),
48
+ }
49
+
50
+ Checks:
51
+ - all schema columns exist
52
+ - no extra columns, unless allow_extra_columns=True
53
+ - exact dtype match
54
+
55
+ Returns df unchanged, so it can be used inline.
56
+ Raises :class:`ValueError` if validation fails. The error message will be preeded by ``header`` which can either
57
+ be a string or a callable returning a string (to avoid expensive message construction if validation passes).
58
+
59
+ Parameters
60
+ ----------
61
+ df : :class:`pandas.DataFrame`
62
+ Data frame to validate.
63
+ schema : Mapping[str, Any]
64
+ Mapping of column name to expected dtype.
65
+ header : str|callable[[],str]| None, optional
66
+ Header for error messages. Can be a string or a callable returning a string. Using a callable delays string composition to avoid unnecessary overhead when validation passes.
67
+ allow_extra_columns : bool, default False
68
+ Whether to allow columns in the DataFrame that are not in the schema.
69
+ """
70
+
71
+ def real_header():
72
+ if header is None:
73
+ return ""
74
+ elif isinstance(header, str):
75
+ return header + ": "
76
+ else:
77
+ return header() + ": "
78
+
79
+ assert isinstance(df, pd.DataFrame), f"{real_header()} must be a pandas DataFrame"
80
+ assert isinstance(schema, Mapping), f"{real_header()}schema must be a mapping of column name -> dtype"
81
+
82
+ expected_cols = set(schema.keys())
83
+ actual_cols = set(df.columns)
84
+
85
+ missing = sorted(expected_cols - actual_cols)
86
+ extra = sorted(actual_cols - expected_cols)
87
+
88
+ if len(missing) > 0:
89
+ if len(extra) > 0:
90
+ raise ValueError( f"{real_header()}is missing columns: {fmt_list(missing)} and has extra columns: {fmt_list(extra)}.")
91
+ raise ValueError( f"{real_header()}is missing columns {fmt_list(missing)}.")
92
+ if len(extra) > 0 and not allow_extra_columns:
93
+ raise ValueError( f"{real_header()}has extra columns {fmt_list(extra)}.")
94
+
95
+ dtype_errors: list[str] = []
96
+ for col, expected_dtype_raw in schema.items():
97
+ if col not in df.columns:
98
+ continue
99
+
100
+ expected_dtype = _as_pandas_dtype(expected_dtype_raw, col=col)
101
+ actual_dtype = _as_pandas_dtype(df[col].dtype, col=col)
102
+
103
+ if actual_dtype != expected_dtype:
104
+ dtype_errors.append(
105
+ f"{col!r}: expected {expected_dtype!r}, got {actual_dtype!r}"
106
+ )
107
+
108
+ if dtype_errors:
109
+ raise ValueError( f"{real_header()} has schema mismatches: {fmt_list(dtype_errors)}.")
110
+
111
+ return df
112
+
113
+ def restore_object_strings(df: pd.DataFrame, schema: Mapping[str, Any]) -> pd.DataFrame:
114
+ """Preserve declared object-string schemas across Pandas versions.
115
+
116
+ Only Pandas StringDtype columns declared as object are converted. Numeric
117
+ and date mismatches remain unchanged for verify_schema to reject.
118
+ Returns the original frame when no conversion is needed.
119
+ """
120
+ columns = {
121
+ column: object for column, dtype in schema.items()
122
+ if column in df.columns and pd.api.types.is_object_dtype(dtype)
123
+ and isinstance(df[column].dtype, pd.StringDtype)
124
+ }
125
+ return df.astype(columns) if columns else df