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,85 @@
1
+ """
2
+ Grid Sanos tridiagonal solver for SANOS-type transition operators, c.f. http://arxiv.org/abs/2211.13227
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import numpy as np
8
+
9
+
10
+ def solve_sanos_tridiagonal(*, w_minus: np.ndarray, w_plus: np.ndarray, rhs: np.ndarray) -> np.ndarray:
11
+ """Solve SANOS tridiagonal system with boundary structure from w_minus/w_plus.
12
+
13
+ The system size is ``N = (N-2) + 2`` where:
14
+ - ``w_minus`` and ``w_plus`` have shape ``(..., N-2)``
15
+ - ``rhs`` has shape ``(..., N)``
16
+
17
+ This avoids materializing full tridiagonal bands and is more memory efficient
18
+ for the SANOS parameterization.
19
+ """
20
+ assert w_minus.shape == w_plus.shape, f"w_minus and w_plus must have the same shape, got {w_minus.shape} and {w_plus.shape}"
21
+
22
+ n_inner = w_minus.shape[-1]
23
+ n = n_inner + 2
24
+ lead = w_minus.shape[:-1]
25
+
26
+ assert rhs.shape == lead + (n,), f"rhs must have shape {lead + (n,)}, got {tuple(rhs.shape)}"
27
+
28
+ # classic form
29
+ # https://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm
30
+ #
31
+ # b_0 c_0 x_0 rhs_0
32
+ # a_1 b_1 c_1 x_1 rhs_1
33
+ # a_2 b_2 c_2 x_2 = rhs_2
34
+ # ... ... ...
35
+ # a_{N-1} b_{N-1} x_{N-1} rhs_{N-1}
36
+ #
37
+
38
+ # Row 0:
39
+ # b_0 = 1
40
+ # c_0 = -w_minus[0]
41
+ #
42
+ # 1 * x0 - w_minus[0] * x1 = rhs0
43
+ cp_terms = [-w_minus[..., 0]] # = c_0/b_0
44
+ y_terms = [rhs[..., 0]] # = rhs_0/b_0
45
+
46
+ # Rows 1..N-2
47
+ # a_i = - w_plus[i-1] (if i > 1 else 0)
48
+ # b_i = 1 + w_minus[i] + w_plus[i]
49
+ # c_i = - w_minus[i+1] (if i < N-2 else 0)
50
+ #
51
+ # =>
52
+ #
53
+ # cp_i = c_i / (b_i - a_i * cp_{i-1})
54
+ # y_i = (rhs_i - a_i * y_{i-1}) / (b_i - a_i * cp_{i-1})
55
+
56
+ for i in range(1, n - 1):
57
+ a_i = -w_plus[..., i - 2] if i > 1 else 0.
58
+ b_i = 1.0 + w_minus[..., i - 1] + w_plus[..., i - 1]
59
+ c_i = -w_minus[..., i] if i < (n - 2) else 0.
60
+
61
+ denom = b_i - a_i * cp_terms[i - 1]
62
+ cp_terms.append(c_i / denom)
63
+ y_terms.append((rhs[..., i] - a_i * y_terms[i - 1]) / denom)
64
+
65
+ # Last row:
66
+ # a_{N-1} = -w_plus[N-3]
67
+ # b_{N-1} = 1
68
+ #
69
+ # -w_plus[N-3] * x[N-2] + 1 * x[N-1] = rhs[N-1]
70
+ a_last = -w_plus[..., -1]
71
+ b_last = 1.
72
+ denom = b_last - a_last * cp_terms[-1]
73
+ y_terms.append((rhs[..., -1] - a_last * y_terms[-1]) / denom)
74
+
75
+ # forward pass
76
+ x_terms = [None] * n
77
+ x_terms[-1] = y_terms[-1]
78
+ for i in range(n - 2, -1, -1):
79
+ x_terms[i] = y_terms[i] - cp_terms[i] * x_terms[i + 1]
80
+ return np.stack(x_terms, axis=-1).astype(rhs.dtype, copy=False)
81
+
82
+ if __name__ == "__main__":
83
+ from openqdata.cli import run_module
84
+
85
+ run_module(globals())
@@ -0,0 +1,5 @@
1
+ # openqdata.benchmark
2
+
3
+ Namespace for separately installed benchmark packages. Nothing is included here.
4
+
5
+ Documentation: [extensions.md](https://github.com/hansbuehler/openqdata/blob/main/docs/extensions.md)
@@ -0,0 +1,4 @@
1
+ """Shared namespace for separately installed openqdata benchmark packages."""
2
+ from pkgutil import extend_path
3
+
4
+ __path__ = extend_path(__path__, __name__)
@@ -0,0 +1,506 @@
1
+ """
2
+ Business day calendar utilities.
3
+
4
+ Uses pandas_market_calendars to get NYSE trading days and identify
5
+ early-close (half) days.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import datetime as dt
11
+ import math as math
12
+ import warnings
13
+ from dataclasses import dataclass
14
+ from zoneinfo import ZoneInfo
15
+
16
+ import numpy as np
17
+ import pandas_market_calendars as mcal
18
+ import polars as pl
19
+ from cdxcore.err import verify_inp
20
+ from cdxcore.version import version
21
+
22
+ import openqdata as openqdata # NOQA
23
+
24
+ TZ_NY = ZoneInfo("America/New_York")
25
+ """ New York time zone. """
26
+
27
+ DAYS_PER_YEAR = 252
28
+ """ Standardized business days per year. """
29
+
30
+ ONE_MINUTE = 1.0 / (60.0 * 6.5 * DAYS_PER_YEAR)
31
+ """ One minute in year fraction, assuming 6.5 trading hours per day and ``DAYS_PER_YEAR`` trading days per year. """
32
+
33
+ AM_EXIRY_SUBTRACT = 0.8
34
+ """ How much to subtract from an expiry (in days) to account for AM settlement. """
35
+
36
+ NYSE_CALENDAR = mcal.get_calendar("NYSE")
37
+ """ NYSE calendar provided by `pandas market calendars <https://pandas-market-calendars.readthedocs.io/en/latest/usage.html>`_. """
38
+
39
+ _BUSINESS_DAYS_CACHE = {}
40
+ _EARLY_DAYS_CACHE = {}
41
+
42
+ @dataclass(frozen=True)
43
+ class NormalizedStrikes:
44
+ r"""
45
+ NMS generates relative strikes by:
46
+ $$
47
+ \mathrm{NMS}(z,t) := \exp\left( z \cdot \sqrt{\frac{\sigma_\epsilon^2\epsilon+\sigma^2 t}{\epsilon+1}} \right)
48
+ $$
49
+ where:
50
+
51
+ * $\epsilon$ is :attr:`EPS`, and $t$ is time to expiry in years.
52
+ * $\sigma$ is the volatility scale, which defaults to :attr:`SCALE`.
53
+ * $\sigma_\epsilon$ is the volatility scale for epsilon.
54
+ """
55
+
56
+ EPS : float = 1.0 / DAYS_PER_YEAR / 8.0 #: Small epsilon for NMS computation ~ 1 hour
57
+ SCALE : float = math.log(1.1) #: 10% vol
58
+
59
+ def __post_init__(self):
60
+ verify_inp( self.EPS > 0., "EPS must be positive" )
61
+ verify_inp( self.SCALE > 0., "SCALE must be positive" )
62
+
63
+ def from_nms(self, z: float|np.ndarray, t: float|np.ndarray, *, vol : float|np.ndarray|None = None, eps_vol : float|np.ndarray|None = None) -> float|np.ndarray:
64
+ """
65
+ Converts an NMS strike to a relative strike
66
+
67
+ Parameters
68
+ ----------
69
+ z : float | :class:`numpy.ndarray`
70
+ NMS strike level.
71
+ t : float | :class:`numpy.ndarray`
72
+ Time to expiry in years.
73
+ vol : float | :class:`numpy.ndarray` | None, default ``None``
74
+ Volatility in year fraction. If None, :attr:`SCALE` is used.
75
+ eps_vol : float | :class:`numpy.ndarray`| None, default ``None``
76
+ Volatility scale for epsilon. If None, :attr:`SCALE` is used.
77
+
78
+ Returns
79
+ -------
80
+ Strikes: float or :class:`numpy.ndarray`
81
+ Relative strikes corresponding to the given NMS strikes, time to expiry and volatility.
82
+ """
83
+ assert np.min(t) >= 0., "Time must be non-negative"
84
+ if not vol is None:
85
+ assert np.min(vol) > 0., "Volatility must be positive"
86
+ else:
87
+ vol = self.SCALE
88
+ if eps_vol is None:
89
+ eps_vol = self.SCALE
90
+ else:
91
+ assert np.min(eps_vol) > 0., "Eps_vol must be positive"
92
+ return np.exp(z * np.sqrt((eps_vol * eps_vol * self.EPS + vol * vol * t) / (self.EPS + 1.0)))
93
+
94
+ def to_nms(self, k: float|np.ndarray, t: float|np.ndarray, *, vol: float|np.ndarray|None = None, eps_vol : float|np.ndarray|None = None) -> float|np.ndarray:
95
+ """
96
+ Converts a relative strike to an NMS strike.
97
+
98
+ Parameters
99
+ ----------
100
+ k : float | :class:`numpy.ndarray`
101
+ Relative strike level.
102
+ t : float | :class:`numpy.ndarray`
103
+ Time to expiry in years.
104
+ vol : float | :class:`numpy.ndarray` | None, default ``None``
105
+ Volatility in year fraction. If None, :attr:`SCALE` is used.
106
+ eps_vol : float | :class:`numpy.ndarray`| None, default ``None``
107
+ Volatility scale for epsilon. If None, :attr:`SCALE` is used.
108
+
109
+ Returns
110
+ -------
111
+ NMS Strikes: float or :class:`numpy.ndarray`
112
+ Relative strikes corresponding to the given NMS strikes, time to expiry and volatility.
113
+ """
114
+ vol = self.SCALE if vol is None else vol
115
+ assert np.min(k) > 0., "Strike must be positive"
116
+ assert np.min(t) >= 0., "Time must be non-negative"
117
+ if not vol is None:
118
+ assert np.min(vol) > 0., "Volatility must be positive"
119
+ else:
120
+ vol = self.SCALE
121
+ if eps_vol is None:
122
+ eps_vol = self.SCALE
123
+ else:
124
+ assert np.min(eps_vol) > 0., "Eps_vol must be positive"
125
+ return (np.log(k) ) * np.sqrt((self.EPS + 1.0) / (eps_vol * eps_vol * self.EPS + vol * vol * t))
126
+
127
+ NMS = NormalizedStrikes(EPS = 1.0 / DAYS_PER_YEAR / 8.0, SCALE = math.log(1.1))
128
+ NMS5 = NormalizedStrikes(EPS = 5.0 / DAYS_PER_YEAR, SCALE=math.log(1.1))
129
+
130
+ def to_date(d: str | dt.datetime | dt.date | np.datetime64 | None) -> dt.date | None:
131
+ """
132
+ Convert ``d`` to a :class:`datetime.date`, or ``None`` if ``d`` is ``None``.
133
+ This function converts:
134
+
135
+ * ``np.datetime64``
136
+ * :class:`datetime.datetime`
137
+ * :class:`datetime.date`
138
+ * ``str`` assuming it is in iso format e.g. "2024-01-31"
139
+ """
140
+ if d is None:
141
+ return d
142
+ if isinstance(d, np.datetime64):
143
+ d = d.astype("datetime64[D]").astype(dt.date)
144
+ if isinstance(d, dt.datetime):
145
+ return d.date()
146
+ if isinstance(d, dt.date):
147
+ return d
148
+ if isinstance(d, str):
149
+ return dt.date.fromisoformat(d)
150
+ raise ValueError(f"Unsupported type for date conversion: {type(d)}")
151
+
152
+
153
+ @version("0.1")
154
+ def get_business_days(
155
+ start: str | dt.date, end: str | dt.date, exclude_half_days: bool = False
156
+ ) -> list[dt.date]:
157
+ """
158
+ Return NYSE trading days within start and end.
159
+
160
+ This function returns business days inclusive of ``start`` and ``end``. That means that if ``start`` equals ``end``, and if that is a trading day,
161
+ then this function returns that day.
162
+
163
+ Parameters
164
+ ----------
165
+ start : str | :class:`datetime.date`
166
+ Start date (inclusive).
167
+ end : str | :class:`datetime.date`
168
+ End date (inclusive).
169
+ exclude_half_days : bool, default ``False``
170
+ If True, remove early-close trading sessions from the calendar.
171
+
172
+ Returns
173
+ -------
174
+ list[:class:`datetime.date`]
175
+ Sorted trading dates (timezone-naive, date-only precision).
176
+ """
177
+ global _BUSINESS_DAYS_CACHE
178
+ start = to_date(start)
179
+ end = to_date(end)
180
+ exclude_half_days = bool(exclude_half_days)
181
+
182
+ if start > end:
183
+ raise ValueError(f"start ({start}) must be <= end ({end})")
184
+
185
+ key = (start, end, exclude_half_days)
186
+ schedule = _BUSINESS_DAYS_CACHE.get(key, None)
187
+ if schedule is not None:
188
+ return schedule
189
+
190
+ schedule = NYSE_CALENDAR.schedule(start_date=str(start), end_date=str(end))
191
+
192
+ if exclude_half_days and len(schedule) > 0:
193
+ early = NYSE_CALENDAR.early_closes(schedule)
194
+ schedule = schedule.drop(early.index, errors="ignore")
195
+
196
+ schedule = schedule.index.normalize().tz_localize(
197
+ None
198
+ ) # index is a DatetimeIndex of trading days in the range
199
+ schedule = [dt.date(d.year, d.month, d.day) for d in schedule]
200
+ assert len(schedule) == 0 or schedule[0] <= schedule[-1], f"Internal error: schedule is not sorted: {schedule}"
201
+
202
+ _BUSINESS_DAYS_CACHE[key] = schedule
203
+ return schedule
204
+
205
+
206
+ @version("0.1", dependencies=[get_business_days])
207
+ def count_business_days_between(
208
+ start: dt.date | np.ndarray,
209
+ end: dt.date | np.ndarray,
210
+ exclude_half_days: bool = False,
211
+ ) -> int | np.ndarray:
212
+ """
213
+ Count the number of trading days in ``(start, end]``, i.e. from ``start`` (exclusive) to ``end`` (inclusive).
214
+ If ``end < start``, then count the number of trading days in ``[end, start)`` and return the negative of that count.
215
+
216
+ The count *includes* ``end`` if it is a trading day, but *excludes* ``start``, assuming, essentially, an end-of-day convention.
217
+ Half days are counted as full trading days unless ``exclude_half_days`` is ``True``.
218
+
219
+ If ``start == end``, and if that day is a business day, then this function returns 0.
220
+ If ``start`` and ``end`` are non-business days bracketing no business days, this function raises a :class:`ValueError`.
221
+
222
+ Parameters
223
+ ----------
224
+ start : ``datetime.date`` | :class:`numpy.ndarray` of dates
225
+ Start date(s) (exclusive).
226
+ end : ``datetime.date`` | :class:`numpy.ndarray` of dates
227
+ End date(s) (inclusive).
228
+ exclude_half_days : bool, default ``False``
229
+ If True, remove early-close trading sessions from the calendar before counting.
230
+
231
+ Returns
232
+ -------
233
+ Count: ``int`` or :class:`numpy.ndarray`
234
+ Number of trading days.
235
+ """
236
+ start = to_date(start) if not isinstance(start, np.ndarray) else start
237
+ end = to_date(end) if not isinstance(end, np.ndarray) else end
238
+ is_vec = isinstance(start, np.ndarray) or isinstance(end, np.ndarray)
239
+ start = np.asarray(start, dtype="datetime64[D]")
240
+ end = np.asarray(end, dtype="datetime64[D]")
241
+
242
+ mstart = min(np.min(start), np.min(end))
243
+ mend = max(np.max(start), np.max(end))
244
+ trading_days = get_business_days(mstart, mend, exclude_half_days=exclude_half_days)
245
+
246
+ if len(trading_days) == 0:
247
+ raise ValueError(f"No trading days between {mstart} and {mend} with half days {'excluded' if exclude_half_days else 'included'}")
248
+
249
+ if not is_vec:
250
+ # Scalar case: count how many trading days are in (start, end]
251
+ if start <= end:
252
+ count = np.sum((trading_days > start) & (trading_days <= end))
253
+ else:
254
+ count = -np.sum((trading_days >= end) & (trading_days < start))
255
+
256
+ return int(count)
257
+
258
+ # Vectorised case, matching the scalar convention:
259
+ # count trading days in (start, end] if start <= end, and minus those in [end, start) otherwise.
260
+ td_array = np.asarray(trading_days, dtype="datetime64[D]")
261
+ forward = np.searchsorted(td_array, end, side="right") - np.searchsorted(td_array, start, side="right")
262
+ backward = np.searchsorted(td_array, end, side="left") - np.searchsorted(td_array, start, side="left")
263
+ return np.where(start <= end, forward, backward).astype(np.int32)
264
+
265
+
266
+ @version("0.2", dependencies=[get_business_days])
267
+ def add_business_days(
268
+ start: dt.date, num_days: int, exclude_half_days: bool = False, *, count_start: bool = False
269
+ ) -> dt.date:
270
+ """
271
+ Add a number of business days to a date.
272
+
273
+ Counting starts from the first business day after (or, if ``num_days < 0``, before) ``start``.
274
+ If ``start`` is a business day and ``count_start`` is ``True``, then ``start`` itself is counted
275
+ as the first day in either direction, i.e. ``num_days=1`` and ``num_days=-1`` both return ``start``.
276
+
277
+ If ``start`` is not a business day, the first business day after (before) ``start`` is
278
+ counted as the first day; ``count_start`` has no effect. For example, if ``start`` is a Saturday
279
+ then ``num_days=1`` returns the following Monday and ``num_days=-1`` the preceding Friday,
280
+ assuming both are business days.
281
+
282
+ ``num_days=0`` returns ``start`` if it is a business day, and otherwise the next business day.
283
+
284
+ Parameters
285
+ ----------
286
+ start : ``datetime.date`` | :class:`numpy.ndarray` of dates
287
+ Start date(s). Does not need to be a business day.
288
+ num_days : int | :class:`numpy.ndarray` of ints
289
+ Number of business days to add. Can be negative to subtract business days.
290
+ exclude_half_days : bool, default ``False``
291
+ If ``True``, remove early-close trading sessions from the calendar before counting.
292
+ count_start : bool, default ``False``
293
+ Whether to count ``start`` as the first day if it is a business day.
294
+ This flag has no effect if ``start`` is not a business day.
295
+
296
+ Returns
297
+ -------
298
+ ``datetime.date`` | :class:`numpy.ndarray` of dates
299
+ Resulting date(s) after adding the specified number of business days.
300
+ Array inputs return ``datetime64[D]`` arrays with element-wise identical results to the scalar version.
301
+ """
302
+ kwargs = dict(exclude_half_days=exclude_half_days, count_start=count_start)
303
+ if isinstance(start, np.ndarray) or isinstance(num_days, np.ndarray):
304
+ starts, nums = np.broadcast_arrays(np.asarray(start, dtype="datetime64[D]"), np.asarray(num_days))
305
+ verify_inp(np.issubdtype(nums.dtype, np.integer),
306
+ lambda: f"num_days must be integer, found dtype {nums.dtype}")
307
+ out = [add_business_days(s.astype(dt.date), int(n), **kwargs) for s, n in zip(starts.ravel(), nums.ravel(), strict=True)]
308
+ return np.asarray(out, dtype="datetime64[D]").reshape(starts.shape)
309
+
310
+ # scalar version
311
+ start = to_date(start)
312
+ num_days = int(num_days)
313
+ forward = num_days >= 0
314
+ steps = abs(num_days)
315
+
316
+ # Calendar window large enough for ``steps`` business days; widened on long market closures.
317
+ window = steps * 7 // 5 + 10
318
+ while True:
319
+ if forward:
320
+ schedule = get_business_days(start, start + dt.timedelta(days=window), exclude_half_days=exclude_half_days)
321
+ else:
322
+ schedule = list(reversed(get_business_days(start - dt.timedelta(days=window), start, exclude_half_days=exclude_half_days)))
323
+ # schedule[0] is ``start`` if it is a business day, otherwise the first business day beyond it.
324
+ start_is_business_day = len(schedule) > 0 and schedule[0] == start
325
+ if start_is_business_day and not count_start:
326
+ index = steps
327
+ else:
328
+ index = max(steps - 1, 0)
329
+ if index < len(schedule):
330
+ return schedule[index]
331
+ window *= 2
332
+
333
+
334
+ @version("0.2", dependencies=[add_business_days])
335
+ def prev_business_day(
336
+ date: dt.date, exclude_half_days: bool = False, *, count_start: bool = False
337
+ ) -> dt.date:
338
+ """
339
+ Get the previous business day before the given date.
340
+
341
+ Parameters
342
+ ----------
343
+ date : ``datetime.date``
344
+ Reference date. This date does not have to be a business day.
345
+ exclude_half_days : bool, default ``False``
346
+ If True, remove early-close trading sessions from the calendar before counting.
347
+ count_start : bool, default ``False``
348
+ Whether to count ``date`` if it is a business day. If ``False``, then the counts starts from the first business day before date.
349
+ That means even if ``date`` is a business day, the function will return the previous business day before it.
350
+ If ``True``, then if ``date`` is a business day, the function will return that date.
351
+
352
+ This flag has no effect if ``date`` is not a business day.
353
+
354
+ Returns
355
+ -------
356
+ ``datetime.date``
357
+ Previous business day before the given date.
358
+ """
359
+ return add_business_days(date, -1, exclude_half_days=exclude_half_days, count_start=count_start)
360
+
361
+
362
+ @version("0.2", dependencies=[add_business_days])
363
+ def next_business_day(
364
+ date: dt.date, exclude_half_days: bool = False, *, count_start: bool = False
365
+ ) -> dt.date:
366
+ """
367
+ Get the next business day after the given date.
368
+
369
+ Parameters
370
+ ----------
371
+ date : ``datetime.date``
372
+ Reference date. This date does not have to be a business day.
373
+ exclude_half_days : bool, default ``False``
374
+ If True, remove early-close trading sessions from the calendar before counting.
375
+ count_start : bool, default ``False``
376
+ Whether to count ``date`` if it is a business day. If ``False``, then the counts starts from the first business day after date.
377
+ That means even if ``date`` is a business day, the function will return the next business day after it.
378
+ If ``True``, then if ``date`` is a business day, the function will return that date.
379
+ This flag has no effect if ``date`` is not a business day.
380
+
381
+ Returns
382
+ -------
383
+ ``datetime.date``
384
+ Next business day after the given date.
385
+ """
386
+ return add_business_days(date, 1, exclude_half_days=exclude_half_days, count_start=count_start)
387
+
388
+
389
+ @version("0.1")
390
+ def get_half_days(start: dt.date, end: dt.date) -> list[dt.date]:
391
+ """
392
+ Return a list of half days (early closes) between start and end, inclusive.
393
+ """
394
+ global _EARLY_DAYS_CACHE
395
+
396
+ start = to_date(start)
397
+ end = to_date(end)
398
+ if start > end:
399
+ raise ValueError(f"start ({start}) must be <= end ({end})")
400
+
401
+ key = (start, end)
402
+ schedule = _EARLY_DAYS_CACHE.get(key, None)
403
+ if schedule is not None:
404
+ return schedule
405
+
406
+ schedule = NYSE_CALENDAR.schedule(start_date=str(start), end_date=str(end))
407
+ schedule = NYSE_CALENDAR.early_closes(schedule=schedule)
408
+ schedule = schedule.index.normalize().tz_localize(
409
+ None
410
+ ) # index is a DatetimeIndex of trading days in the range
411
+ schedule = [dt.date(d.year, d.month, d.day) for d in schedule]
412
+ _EARLY_DAYS_CACHE[key] = schedule
413
+ return schedule
414
+
415
+
416
+ @version("0.1", dependencies=[get_business_days, get_half_days])
417
+ @dataclass
418
+ class DateRange:
419
+ """A simple date range class."""
420
+
421
+ start: dt.date | str #: Start date (inclusive).
422
+ end: dt.date | str #: End date (inclusive).
423
+ exclude_half_days: bool = True #: Whether to exclude half days (early closes) from the business day count. Default is True.
424
+
425
+ def __post_init__(self):
426
+ if isinstance(self.start, str):
427
+ self.start = dt.date.fromisoformat(self.start)
428
+ if isinstance(self.end, str):
429
+ self.end = dt.date.fromisoformat(self.end)
430
+ verify_inp(
431
+ isinstance(self.start, dt.date),
432
+ f"'start' must be a datetime.date, but found {type(self.start)}",
433
+ )
434
+ verify_inp(
435
+ isinstance(self.end, dt.date),
436
+ f"'end' must be a datetime.date, but found {type(self.end)}",
437
+ )
438
+
439
+ if self.start > self.end:
440
+ raise ValueError(f"'start' ({self.start}) must be at or before 'end' ({self.end})")
441
+
442
+ bdays = self.get_business_days()
443
+ if len(bdays) == 0:
444
+ raise ValueError(
445
+ f"No business days in the range {self.start} to {self.end} with half days {'excluded' if self.exclude_half_days else 'included'}"
446
+ )
447
+
448
+ def __str__(self):
449
+ return f"{self.start}_{self.end}{'x' if self.exclude_half_days else 'i'}"
450
+
451
+ def __hash__(self):
452
+ return hash((self.start, self.end, self.exclude_half_days))
453
+
454
+ def get_business_days(self) -> list[dt.date]:
455
+ """Get business days in this date range."""
456
+ return get_business_days(self.start, self.end, exclude_half_days=self.exclude_half_days)
457
+
458
+ def get_half_days(self) -> list[dt.date]:
459
+ """Get half days (early closes) in this date range."""
460
+ return get_half_days(self.start, self.end) if not self.exclude_half_days else []
461
+
462
+ @version("0.1")
463
+ def session_open_close( date: dt.date ) -> tuple[dt.datetime, dt.datetime, bool]:
464
+ """
465
+ Returns the session open and close for a given ``date`` as :class:`datetime.datetime` objects in New York time zone,
466
+ and a boolean indicating whether it is a half day (early close) or not.
467
+
468
+ This function will return ``(None, None, False)`` if the given date is not a trading day.
469
+ """
470
+
471
+ date = to_date(date)
472
+ schedule = NYSE_CALENDAR.schedule(start_date=date, end_date=date)
473
+
474
+ if len(schedule) == 0:
475
+ return None, None, False
476
+
477
+ early = NYSE_CALENDAR.early_closes(schedule)
478
+
479
+ with warnings.catch_warnings(action="ignore"):
480
+ schedule['market_open'] = schedule['market_open'].apply(lambda ts: ts.to_pydatetime())
481
+ schedule['market_close'] = schedule['market_close'].apply(lambda ts: ts.to_pydatetime())
482
+ schedule['market_open'] = schedule['market_open'].dt.tz_convert('America/New_York')
483
+ schedule['market_close'] = schedule['market_close'].dt.tz_convert('America/New_York')
484
+
485
+ assert len(schedule['market_open']) <= 1, "Internal error"
486
+ assert len(schedule['market_close']) <= 1, "Internal error"
487
+
488
+ return schedule['market_open'].iloc[0], schedule['market_close'].iloc[0], len(early)>0
489
+
490
+ @version("0.1")
491
+ def full_second_grid_ns(open_dt: dt.datetime, close_dt: dt.datetime) -> pl.Series:
492
+ """
493
+ Per-second Polars Series for RTH bins: ``[open_dt, open_dt+1s, ..., close_dt-1s]``.
494
+
495
+ The grid is end-exclusive so the last bin key is ``close_dt - 1s`` and represents
496
+ ``[close_dt-1s, close_dt]`` (inclusive close handled by timestamp mapping in the caller).
497
+ """
498
+ s = pl.datetime_range(
499
+ open_dt,
500
+ close_dt,
501
+ interval="1s",
502
+ time_zone=TZ_NY.key,
503
+ eager=True,
504
+ closed="left",
505
+ )
506
+ return s.dt.cast_time_unit("ns").rename("dt_ns")
openqdata/cli.py ADDED
@@ -0,0 +1,91 @@
1
+ """Shared command line adapter for public data-processing functions."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import inspect
6
+ import json
7
+ from datetime import date, datetime
8
+ from pathlib import Path
9
+ from typing import Any, get_type_hints
10
+
11
+
12
+ def run_module(namespace: dict[str, Any]) -> None:
13
+ """Expose locally defined public functions using JSON keyword arguments.
14
+
15
+ Run ``python -m openqdata.<source>.<module> --help`` to list functions.
16
+ Output defaults to stdout; use --output with an external data-root path.
17
+ """
18
+ functions = {
19
+ name: value for name, value in namespace.items()
20
+ if not name.startswith("_") and inspect.isfunction(value)
21
+ and value.__module__ == namespace.get("__name__")
22
+ }
23
+ clients = {
24
+ name: value for name, value in namespace.items()
25
+ if inspect.isclass(value) and name.endswith("Client")
26
+ and value.__module__ == namespace.get("__name__")
27
+ }
28
+ methods = {
29
+ f"{name}.{method}": (client, method)
30
+ for name, client in clients.items()
31
+ for method, value in inspect.getmembers(client)
32
+ if callable(value) and not method.startswith("_")
33
+ and method not in {"get_token", "api_key", "credentials", "connect", "get_rest_client", "get_session"}
34
+ }
35
+ parser = argparse.ArgumentParser(description=namespace.get("__doc__"))
36
+ parser.add_argument("function", choices=sorted(set(functions) | set(methods)))
37
+ parser.add_argument("--params", default="{}", help="JSON object of keyword arguments; dates use YYYY-MM-DD")
38
+ parser.add_argument("--init-params", default="{}", help="JSON constructor arguments for Client.method commands")
39
+ parser.add_argument("--output", type=Path, help="Output path outside the source checkout (.parquet, .csv or .json)")
40
+ args = parser.parse_args()
41
+ try:
42
+ if args.function in methods:
43
+ client, method = methods[args.function]
44
+ constructor = json.loads(args.init_params)
45
+ if not isinstance(constructor, dict):
46
+ raise ValueError("--init-params must contain a JSON object")
47
+ function = getattr(client(**constructor), method)
48
+ else:
49
+ function = functions[args.function]
50
+ params = json.loads(args.params)
51
+ if not isinstance(params, dict):
52
+ raise ValueError("--params must contain a JSON object")
53
+ signature = inspect.signature(function)
54
+ try:
55
+ hints = get_type_hints(function)
56
+ except (NameError, TypeError):
57
+ # Some APIs use descriptive, non-runtime annotations.
58
+ hints = {}
59
+ for key, value in params.items():
60
+ annotation = hints.get(key)
61
+ if annotation is date and isinstance(value, str):
62
+ params[key] = date.fromisoformat(value)
63
+ elif annotation is datetime and isinstance(value, str):
64
+ params[key] = datetime.fromisoformat(value)
65
+ signature.bind(**params)
66
+ if args.output:
67
+ output = args.output.expanduser().resolve()
68
+ repository = Path(__file__).resolve().parents[2]
69
+ if output.is_relative_to(repository):
70
+ raise ValueError("Store generated output outside the Git checkout")
71
+ if output.suffix not in {".parquet", ".csv", ".json"}:
72
+ raise ValueError("Output must end in .parquet, .csv or .json")
73
+ result = function(**params)
74
+ if not args.output:
75
+ print(result)
76
+ return
77
+ output.parent.mkdir(parents=True, exist_ok=True)
78
+ if output.suffix == ".parquet":
79
+ writer = getattr(result, "write_parquet", None) or getattr(result, "to_parquet", None)
80
+ if writer is None:
81
+ raise ValueError("This result does not support Parquet output")
82
+ writer(output)
83
+ elif output.suffix == ".csv":
84
+ writer = getattr(result, "write_csv", None) or getattr(result, "to_csv", None)
85
+ if writer is None:
86
+ raise ValueError("This result does not support CSV output")
87
+ writer(output)
88
+ else:
89
+ output.write_text(json.dumps(result, default=str, indent=2) + "\n")
90
+ except (ValueError, TypeError) as error:
91
+ parser.error(str(error))