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,1183 @@
1
+ """
2
+ openqdata.massive.client
3
+ ^^^^^^^^^^^^^^^^^^^^^^^^
4
+
5
+ A simple client wrapper for the `www.massive.com <https://www.massive.com>`_ API.
6
+
7
+ Access
8
+ ======
9
+
10
+ You will require a `massive.com token <https://www.massive.com/docs/rest/authentication>`_ to access the data.
11
+ Set the token in the ``MASSIVE_TOKEN`` environment variable, e.g. by adding the following line to your ``~/.bashrc`` or ``~/.zshrc`` file:
12
+
13
+ .. code-block:: bash
14
+
15
+ export MASSIVE_TOKEN="your_token"
16
+
17
+ Once installed, use is straightforward, e.g. to fetch trades and quotes for Apple 150 call expiring on 2023-06-16::
18
+
19
+ from openqdata.massive import MassiveClient
20
+ client = MassiveClient()
21
+
22
+ trades = client.fetch_trades("AAPL230616C00150000", date(2023,6,16))
23
+ quotes = client.fetch_quotes("AAPL230616C00150000", date(2023,6,16))
24
+ ...
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import os as os
30
+ import time as pytime
31
+ import warnings as warnings
32
+ from collections.abc import Mapping
33
+ from datetime import date
34
+ from urllib.parse import urlsplit
35
+
36
+ import polars as pl
37
+ import requests as requests
38
+ from cdxcore.err import verify
39
+ from cdxcore.subdir import SubDir, version
40
+ from cdxcore.uniquehash import label_unique_filename48_8, named_unique_filename48_8
41
+ from cdxcore.util import fmt_date, fmt_list, is_filename, verify_inp
42
+ from massive import RESTClient
43
+ from requests.adapters import HTTPAdapter
44
+ from urllib3.util.retry import Retry
45
+
46
+ from openqdata import env
47
+ from openqdata.biz_calendar import TZ_NY, add_business_days
48
+ from openqdata.massive.trade_conds import pack_conditions
49
+
50
+ _massive_locations = env.locations(
51
+ "massive",
52
+ fmt_raw=SubDir.PICKLE,
53
+ fmt_processed=SubDir.PANDAS_PARQUET,
54
+
55
+ )
56
+ _cache = _massive_locations.raw
57
+
58
+ # --------------------------------------------------------------------
59
+ # Low-level HTTP helpers
60
+ # --------------------------------------------------------------------
61
+
62
+ @version("0.1")
63
+ class MassiveClient(object):
64
+ """
65
+ Wrapper around massive.com connectivity.
66
+
67
+ Standard usage::
68
+
69
+ from openqdata.massive import MassiveClient
70
+ client = MassiveClient()
71
+
72
+ trades = client.fetch_trades("AAPL230616C00150000", date(2023,6,16))
73
+ quotes = client.fetch_quotes("AAPL230616C00150000", date(2023,6,16))
74
+
75
+ **Temporary Caching**
76
+
77
+ This client supports in-session caching. Unlike the overall caching framework for :mod:`openqdata`, this caching
78
+ scheme is temporary and is not guaranteed to persist between machine reboots (e.g. in Linux the root temporary directory is ``/tmp/massive``).
79
+ This can be useful for speeding up repeated requests during an active session
80
+ but should not be relied upon for long-term storage of data.
81
+
82
+ To enable temporary caching in a, say, ``"work"`` context::
83
+
84
+ handle = MassiveClient("work")
85
+ """
86
+
87
+ locations = _massive_locations
88
+ """ :class:`openqdata.Locations` for massive data. """
89
+
90
+ _MASSIVE_TOKEN = None
91
+ _HTTP_SESSION = None
92
+
93
+ BASE_URL = "https://api.massive.com" #: Base URL for requests.
94
+ MAX_RETRIES = 5 #: Retries of transient request failures in :meth:`get`, with increasing timeouts.
95
+ RETRY_STATUS = frozenset({408, 429, 500, 502, 503, 504}) #: Transient HTTP statuses which are retried.
96
+ RETRY_EXCEPTIONS = (
97
+ requests.exceptions.RetryError,
98
+ requests.exceptions.Timeout,
99
+ requests.exceptions.JSONDecodeError,
100
+ requests.exceptions.ChunkedEncodingError,
101
+ requests.exceptions.ConnectionError,
102
+ ) #: Transient transport errors which are retried.
103
+ START_DATE = date(
104
+ 2022, 3, 7
105
+ )
106
+ """ Start date for quote and trade requests for options. `See massive.com <https://massive.com/docs/rest/options/trades-quotes/quotes>`_ """
107
+
108
+ TIME_SPANS = {
109
+ "second",
110
+ "minute",
111
+ "hour",
112
+ "day",
113
+ "week",
114
+ "month",
115
+ "quarter",
116
+ "year",
117
+ }
118
+ """ Standard `massive time spans <https://massive.com/docs/rest/stocks/aggregates/custom-bars>`_ """
119
+
120
+ _PREV_CLOSE_CACHE = {}
121
+
122
+ """
123
+ Static members
124
+ """
125
+
126
+ @staticmethod
127
+ def get_token():
128
+ """Reads massive token from the ``MASSIVE_TOKEN`` environment variable"""
129
+ env.require_live("Massive")
130
+ if MassiveClient._MASSIVE_TOKEN is None:
131
+ verify( not env.test_mode, "Attempted to connect to massive.com in test mode. Set OQ_DATA_TEST_MODE=0 to enable connections." )
132
+ MassiveClient._MASSIVE_TOKEN = os.environ.get("MASSIVE_TOKEN", None)
133
+ verify(
134
+ not MassiveClient._MASSIVE_TOKEN is None,
135
+ "Must specify environment variable 'MASSIVE_TOKEN' to access `massive.com <https://www.massive.com>`_ data",
136
+ exception=RuntimeError,
137
+ )
138
+ return MassiveClient._MASSIVE_TOKEN
139
+
140
+ @staticmethod
141
+ def get_rest_client():
142
+ """
143
+ Returns a :class:`massive.RESTClient` instance with the current token, defined by the ``MASSIVE_TOKEN`` environment variable.
144
+ """
145
+ return RESTClient(MassiveClient.get_token())
146
+
147
+ @staticmethod
148
+ def get_session():
149
+ """
150
+ Return an HTTP session per process.
151
+ """
152
+ if MassiveClient._HTTP_SESSION is None:
153
+ MassiveClient._HTTP_SESSION = requests.Session()
154
+ MassiveClient._HTTP_SESSION.mount(
155
+ "https://",
156
+ HTTPAdapter(
157
+ pool_connections=50,
158
+ pool_maxsize=50,
159
+ max_retries=Retry(
160
+ total=5, backoff_factor=0.2, status_forcelist=[429, 500, 502, 503, 504]
161
+ ),
162
+ ),
163
+ )
164
+ MassiveClient._HTTP_SESSION.mount(
165
+ "http://",
166
+ HTTPAdapter(
167
+ pool_connections=50,
168
+ pool_maxsize=50,
169
+ max_retries=Retry(
170
+ total=5, backoff_factor=0.2, status_forcelist=[429, 500, 502, 503, 504]
171
+ ),
172
+ ),
173
+ )
174
+ return MassiveClient._HTTP_SESSION
175
+
176
+ """
177
+ Object
178
+ """
179
+
180
+ def __init__(self, temp_caching_topic: str | None = None, fmt: SubDir.Format = SubDir.PICKLE):
181
+ """Create client with temporary caching topic"""
182
+ self._session = None
183
+ self._temp_dir = (
184
+ MassiveClient.locations.processed("session_cache/massive_api")(temp_caching_topic, fmt=fmt)
185
+ if not temp_caching_topic is None
186
+ else None
187
+ )
188
+ self.get = (
189
+ self._temp_dir.cache(label="massive_get", exclude_args=["self"])(self._get)
190
+ if not self._temp_dir is None
191
+ else self._get
192
+ )
193
+
194
+ @version("0.2")
195
+ def _get(self, url: str, params: dict | None = None) -> dict:
196
+ """
197
+ GET wrapper restricted to the API origin; redirects are rejected.
198
+ Do not call this function, call ``self.get`` which is optionally
199
+ cached in a temporary directory for speed
200
+ """
201
+ target, origin = urlsplit(url), urlsplit(self.BASE_URL)
202
+ # Never attach credentials to a response-supplied external URL.
203
+ if (target.scheme, target.netloc) != (origin.scheme, origin.netloc):
204
+ raise ValueError("Massive request URL must use the configured API origin")
205
+ # The key travels in the Authorization header, never in the URL, so that it cannot
206
+ # appear in exception messages, warnings or logs that quote the request URL.
207
+ headers = {"Authorization": f"Bearer {MassiveClient.get_token()}"}
208
+ cnt = 1
209
+ while True:
210
+ try:
211
+ r = self.session.get(url, params=params, headers=headers, timeout=60 * cnt, allow_redirects=False)
212
+ if 300 <= r.status_code < 400:
213
+ raise ValueError("Massive API redirects are not allowed")
214
+ r.raise_for_status()
215
+ return r.json()
216
+ except requests.exceptions.HTTPError as e:
217
+ status = e.response.status_code if e.response is not None else None
218
+ # Only transient statuses are retried; anything else (4xx, 501, 505, ...) raises immediately.
219
+ if status not in self.RETRY_STATUS or cnt > self.MAX_RETRIES:
220
+ raise
221
+ e_ = e
222
+ except self.RETRY_EXCEPTIONS as e:
223
+ if cnt > self.MAX_RETRIES:
224
+ raise
225
+ e_ = e
226
+ warnings.warn(f"**** Massive error: {e_} ...retry {cnt}/{self.MAX_RETRIES} after sleeping for {cnt} seconds ***")
227
+ pytime.sleep(cnt)
228
+ cnt += 1
229
+
230
+ @version("0.1", dependencies=[_get])
231
+ def __call__(self, url: str, params: dict | None = None) -> dict:
232
+ """Short-cut for ``self.get``"""
233
+ return self.get(url=url, params=params)
234
+
235
+ @version("0.1", dependencies=[_get])
236
+ def paginate(self, initial_url: str, params: dict | None = None) -> list[dict]:
237
+ """
238
+ Handle `v3-style pagination <https://massive.com/blog/api-pagination-patterns>`_ (quotes, trades, contracts), c.f.
239
+ """
240
+ results: list[dict] = []
241
+ data = self.get(initial_url, params or {})
242
+ results.extend(data.get("results", []) or [])
243
+ next_url = data.get("next_url")
244
+
245
+ while next_url:
246
+ if next_url and next_url.startswith("/"):
247
+ next_url = self.BASE_URL + next_url
248
+ data = self.get(next_url, None)
249
+ results.extend(data.get("results", []) or [])
250
+ next_url = data.get("next_url")
251
+ pytime.sleep(0.02) # be gentle
252
+
253
+ return results
254
+
255
+ @property
256
+ def session(self):
257
+ """Return the HTTP session for this MassiveClient. Note that a session is shared within a process"""
258
+ if self._session is None:
259
+ self._session = MassiveClient.get_session()
260
+ return self._session
261
+
262
+ def clear_temp(self):
263
+ """Clear the temporary directory for this MassiveClient."""
264
+ if self._temp_dir is not None:
265
+ self._temp_dir.delete_all_content(delete_self=True)
266
+
267
+ # =============================================================================
268
+ # Polygon fetch: v3 trades / quotes (SIP). Keep ts_ns in ns.
269
+ # =============================================================================
270
+
271
+ @_cache(fmt=SubDir.PICKLE).cache(
272
+ "0.1",
273
+ label=lambda ticker, d: f"has_any_quotes_or_trades/{ticker}/{fmt_date(d)}",
274
+ exclude_args=["self"],
275
+ )
276
+ def has_any_quotes_or_trades(self, ticker: str, d: date) -> tuple[bool, bool]:
277
+ """Whether ``ticker`` has any quotes or trades on date ``d``. Returns tuple (has_quotes, has_trades)."""
278
+ url = f"{MassiveClient.BASE_URL}/v3/quotes/{ticker}"
279
+ response = self.get(
280
+ url,
281
+ params={
282
+ "timestamp": d.strftime("%Y-%m-%d"), # YYYY-MM-DD
283
+ "limit": 1,
284
+ "order": "asc",
285
+ "sort": "timestamp",
286
+ },
287
+ )
288
+ has_quotes = len(response["results"]) > 0
289
+
290
+ url = f"{MassiveClient.BASE_URL}/v3/trades/{ticker}"
291
+ response = self.get(
292
+ url,
293
+ params={
294
+ "timestamp": d.strftime("%Y-%m-%d"), # YYYY-MM-DD
295
+ "limit": 1,
296
+ "order": "asc",
297
+ "sort": "timestamp",
298
+ },
299
+ )
300
+
301
+ has_trades = len(response["results"]) > 0
302
+ return has_quotes, has_trades
303
+
304
+ def has_any_quotes(self, ticker: str, d: date) -> bool:
305
+ """Whether ``ticker`` has any quotes on date ``d``."""
306
+ return self.has_any_quotes_or_trades(ticker, d)[0]
307
+
308
+ def has_any_trades(self, ticker: str, d: date) -> bool:
309
+ """Whether ``ticker`` has any trades on date ``d``."""
310
+ return self.has_any_quotes_or_trades(ticker, d)[1]
311
+
312
+ SCHEMA_TRADES = {
313
+ "ts_ns": pl.Datetime("ns", TZ_NY),
314
+ "price": pl.Float64,
315
+ "size": pl.Float64,
316
+ "trade_code": pl.UInt32,
317
+ "sequence_number": pl.UInt64,
318
+ }
319
+ """ Schema of the :class:`polars.DataFrame` returned by :meth:`fetch_trades`. """
320
+
321
+ @_cache(fmt=SubDir.POLARS_PARQUET).cache(
322
+ "0.11", label=lambda ticker, d: f"trades/{ticker}/{fmt_date(d)}", exclude_args=["self"]
323
+ )
324
+ def fetch_trades(self, ticker: str, d: date) -> pl.DataFrame:
325
+ """
326
+ Gets trades from /v3/trades/{ticker} sorted by sip_timestamp asc.
327
+ Used both for options and underlyings. This is raw trade access: it
328
+ encodes condition flags but does not apply ``NORMAL_TRADE_EXCLUDE_FLAGS``.
329
+ Closing prints and official/corrected closes are retained. Use
330
+ ``filter_valid_trades()`` for the default condition-filtered trade stream.
331
+
332
+ The returned :class:`polars.DataFrame` has the following columns:
333
+
334
+ * ts_ns: Datetime[ns, tz]: time zone information with nanonsecond resolutuin.
335
+ * price: Float64
336
+ * size: Float64
337
+ * trade_code: UInt32. Compressed & Packed trade conditions, see :func:`openqdata.massive.trade_conds.pack_conditions`.
338
+ It is recommended to remove trades with uncommon conditions, see :attr:`openqdata.massive.trade_conds.NORMAL_TRADE_EXCLUDE_FLAGS`.
339
+ * sequence_number: UInt64. Sequence number of the trade for a given timestamp, useful for ordering trades with the same timestamp.
340
+
341
+ Parameters
342
+ ----------
343
+ ticker : str
344
+ Ticker symbol, e.g. "AAPL230616C00150000" for Apple 150 call expiring on 2023-06-16.
345
+ d : date
346
+ Date for which to fetch trades.
347
+
348
+ Returns
349
+ -------
350
+ Result : :class:`polars.DataFrame`
351
+ Returns a data frame with schema :attr:`MassiveClient.SCHEMA_TRADES`.
352
+ The dataframe can have length zero (but it will have the correct data schema).
353
+
354
+ * ts_ns: Datetime[ns, tz]
355
+ * price: Float64
356
+ * size: Float64
357
+ * trade_code: UInt32. Compressed & Packed trade conditions, see :func:`openqdata.massive.trade_conds.pack_conditions`.
358
+ * sequence_number: UInt64. Sequence number of the trade for a given timestamp. Trades will be sorted by (ts_ns, sequence_number) asc.
359
+ """
360
+ url = f"{self.BASE_URL}/v3/trades/{ticker}"
361
+ params = {
362
+ "timestamp": d.strftime("%Y-%m-%d"),
363
+ "order": "asc",
364
+ "limit": 50000,
365
+ "sort": "sip_timestamp",
366
+ }
367
+ rows = self.paginate(url, params)
368
+ rows = [
369
+ dict(
370
+ price=float(r["price"]),
371
+ size=float(r["size"]),
372
+ sip_timestamp=r["sip_timestamp"],
373
+ trade_code=pack_conditions(r.get("conditions", [])),
374
+ sequence_number=int(r["sequence_number"]),
375
+ )
376
+ for r in rows
377
+ ]
378
+
379
+ if not rows:
380
+ return pl.DataFrame(schema=MassiveClient.SCHEMA_TRADES)
381
+
382
+ df = pl.DataFrame(rows, schema={
383
+ 'price': pl.Float64,
384
+ 'size': pl.Float64,
385
+ 'sip_timestamp': pl.Int64,
386
+ 'trade_code': pl.UInt32,
387
+ 'sequence_number': pl.UInt64,
388
+ }, infer_schema_length=None)
389
+ out = df.select(
390
+ pl.from_epoch(pl.col("sip_timestamp").cast(pl.Int64), time_unit="ns")
391
+ .dt.convert_time_zone(TZ_NY.key)
392
+ .alias("ts_ns"),
393
+ pl.col("price").cast(pl.Float64),
394
+ pl.col("size").cast(pl.Float64),
395
+ pl.col("trade_code").cast(pl.UInt32),
396
+ pl.col("sequence_number").cast(pl.UInt64)
397
+ ).sort("ts_ns", "sequence_number")
398
+ assert set(out.columns) == set(MassiveClient.SCHEMA_TRADES), (
399
+ f"Internal error: expected columns {set(MassiveClient.SCHEMA_TRADES)} but got {set(out.columns)}. Sanity check the request and contact the authors if you need help."
400
+ )
401
+ return out
402
+
403
+ SCHEMA_QUOTES = {
404
+ "ts_ns": pl.Datetime("ns", TZ_NY),
405
+ "bid_price": pl.Float64,
406
+ "bid_size": pl.Float64,
407
+ "ask_price": pl.Float64,
408
+ "ask_size": pl.Float64,
409
+ "sequence_number": pl.UInt64,
410
+ }
411
+ """ Schema of the :class:`polars.DataFrame` returned by :meth:`fetch_quotes`. """
412
+
413
+ @_cache(fmt=SubDir.POLARS_PARQUET).cache(
414
+ "0.11", label=lambda ticker, d: f"quotes/{ticker}/{fmt_date(d)}", exclude_args=["self"]
415
+ )
416
+ def fetch_quotes(self, ticker: str, d: date) -> pl.DataFrame:
417
+ """
418
+ Fetches quotes from "/v3/quotes/{ticker}" sorted by sip_timestamp (and sequence_number) asc.
419
+ Used both for options and underlyings.
420
+
421
+ Parameters
422
+ ----------
423
+ ticker : str
424
+ Ticker symbol, e.g. "AAPL230616C00150000" for Apple 150 call expiring on 2023-06-16.
425
+ d : date
426
+ Date for which to fetch quotes.
427
+
428
+ Returns
429
+ -------
430
+ Result : :class:`polars.DataFrame`
431
+ Returns a data frame with schema :attr:`MassiveClient.SCHEMA_QUOTES`.
432
+ The dataframe can have length zero (but it will have the correct data schema).
433
+
434
+ * ts_ns: Datetime[ns, tz]
435
+ * bid_price: Float64
436
+ * bid_size: Float64
437
+ * ask_price: Float64
438
+ * ask_size: Float64
439
+ * sequence_number: UInt64. Sequence number of the quote for a given timestamp. Quotes will be sorted by (ts_ns, sequence_number) asc.
440
+ """
441
+ url = f"{self.BASE_URL}/v3/quotes/{ticker}"
442
+ params = {
443
+ "timestamp": d.strftime("%Y-%m-%d"),
444
+ "order": "asc",
445
+ "limit": 50000,
446
+ "sort": "sip_timestamp",
447
+ }
448
+ rows = self.paginate(url, params)
449
+ if not rows:
450
+ return pl.DataFrame(schema=MassiveClient.SCHEMA_QUOTES)
451
+
452
+ df = pl.DataFrame(rows, schema={
453
+ # https://massive.com/docs/rest/options/trades-quotes/quotes#
454
+ "bid_price": pl.Float64,
455
+ "bid_size": pl.Float64,
456
+ "ask_price": pl.Float64,
457
+ "ask_size": pl.Float64,
458
+ "sip_timestamp": pl.Int64,
459
+ "sequence_number": pl.UInt64
460
+ }, infer_schema_length=None)
461
+ out = df.select(
462
+ pl.from_epoch(pl.col("sip_timestamp").cast(pl.Int64), time_unit="ns")
463
+ .dt.convert_time_zone(TZ_NY.key)
464
+ .alias("ts_ns"),
465
+ pl.col("bid_price").cast(pl.Float64),
466
+ pl.col("bid_size").cast(pl.Float64),
467
+ pl.col("ask_price").cast(pl.Float64),
468
+ pl.col("ask_size").cast(pl.Float64),#
469
+ pl.col("sequence_number").cast(pl.UInt64)
470
+ ).sort("ts_ns", "sequence_number")
471
+ assert set(out.columns) == set(MassiveClient.SCHEMA_QUOTES), (
472
+ f"Internal error: expected columns {set(MassiveClient.SCHEMA_QUOTES)} but got {set(out.columns)}. Sanity check the request and contact the authors if you need help."
473
+ )
474
+ return out
475
+
476
+ SCHEMA_BARS = {
477
+ "ts_ms": pl.Datetime("ms", TZ_NY),
478
+ "close": pl.Float64,
479
+ "open": pl.Float64,
480
+ "high": pl.Float64,
481
+ "low": pl.Float64,
482
+ "volume": pl.Float64,
483
+ "vwap": pl.Float64,
484
+ "num_trades": pl.Int64,
485
+ }
486
+ """ Schema of the :class:`polars.DataFrame` returned by :meth:`fetch_bars`. """
487
+
488
+ @_cache(fmt=SubDir.POLARS_PARQUET).cache(
489
+ "0.2",
490
+ uid=lambda ticker, start, end, adjusted, timespan: (
491
+ f"bars/{timespan}/{'adj' if adjusted else 'raw'}/{ticker if is_filename(ticker) else label_unique_filename48_8(ticker)}/{fmt_date(start)}_{fmt_date(end)}_{timespan}"
492
+ ),
493
+ exclude_args=["self"],
494
+ ) # 'self' is excluded fromm the arguments as it does not affect the output.
495
+ def fetch_bars(
496
+ self, ticker: str, start: date, end: date, adjusted: bool, timespan: str
497
+ ) -> pl.DataFrame:
498
+ """
499
+ Download daily bars for a ticker accross a number of dates; convert timestamp to datetime in NY/ns.
500
+ See `custom bars documentation<https://massive.com/docs/rest/stocks/aggregates/custom-bars>`_
501
+
502
+ Parameters
503
+ ----------
504
+ ticker : str
505
+ Ticker symbol, e.g. "AAPL" for Apple.
506
+ start : :class:`datetime.date`
507
+ Start date for bars.
508
+ end : :class:`datetime.date`
509
+ End date for bars.
510
+ adjusted : bool
511
+ Whether to fetch adjusted bars.
512
+ timespan : str
513
+ Timespan for the bars, e.g. "day", "week", "month".
514
+ Must be one of 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'.
515
+
516
+ Returns
517
+ -------
518
+ Result : :class:`polars.DataFrame`
519
+ Data frame wiwh schema :attr:`MassiveClient.SCHEMA_BARS`. The dataframe can have length zero (but it will have the correct data schema).
520
+
521
+ - ts_ms: Datetime[ms, tz]: time zone information with millisecond precision
522
+ - close: Float64
523
+ - open: Float64
524
+ - high: Float64
525
+ - low: Float64
526
+ - volume: Float64
527
+ - vwap: Float64
528
+ - num_trades: Int64
529
+ """
530
+ if timespan not in self.TIME_SPANS:
531
+ raise ValueError(
532
+ f"Cannot retrieve bars for {ticker} between {start} and {end}: invalid timespan '{timespan}'. Must be one of {sorted(self.TIME_SPANS)}"
533
+ )
534
+ if start > end:
535
+ raise ValueError(
536
+ f"Cannot retrieve bars for {ticker} between {start} and {end}: start date must be before end date."
537
+ )
538
+
539
+ url = f"{self.BASE_URL}/v2/aggs/ticker/{ticker}/range/1/{timespan}/{start:%Y-%m-%d}/{end:%Y-%m-%d}"
540
+ rows = self.paginate(
541
+ url,
542
+ params={"adjusted": "false" if not adjusted else "true", "limit": 50000, "sort": "asc"},
543
+ )
544
+
545
+ if not rows:
546
+ return pl.DataFrame(schema=MassiveClient.SCHEMA_BARS)
547
+
548
+ df = pl.DataFrame(rows, infer_schema_length=None, schema={
549
+ # https://massive.com/docs/rest/stocks/aggregates/custom-bars
550
+ 'c': pl.Float64,
551
+ 'h': pl.Float64,
552
+ 'l': pl.Float64,
553
+ 'n': pl.Int64,
554
+ 'o': pl.Float64,
555
+ 't': pl.Int64,
556
+ 'v': pl.Float64,
557
+ 'vw': pl.Float64,
558
+ })
559
+ out = df.select(
560
+ pl.from_epoch(pl.col("t").cast(pl.Int64), time_unit="ms")
561
+ .dt.replace_time_zone("UTC")
562
+ .dt.convert_time_zone(TZ_NY.key)
563
+ .dt.cast_time_unit("ms")
564
+ .alias("ts_ms"),
565
+ pl.col("c").cast(pl.Float64).alias("close"),
566
+ pl.col("o").cast(pl.Float64).alias("open"),
567
+ pl.col("h").cast(pl.Float64).alias("high"),
568
+ pl.col("l").cast(pl.Float64).alias("low"),
569
+ pl.col("v").cast(pl.Float64).alias("volume"),
570
+ pl.col("vw").cast(pl.Float64).alias("vwap"),
571
+ pl.col("n").cast(pl.Int64).alias("num_trades"),
572
+ ).sort("ts_ms")
573
+ assert set(out.columns) == set(MassiveClient.SCHEMA_BARS), (
574
+ f"Internal error: expected columns {set(MassiveClient.SCHEMA_BARS)} but got {set(out.columns)}. Sanity check the request and contact the authors if you need help."
575
+ )
576
+ return out
577
+
578
+ @_cache(fmt=SubDir.PICKLE).cache(
579
+ "0.1",
580
+ label=lambda ticker, d, adjusted, can_be_none: (
581
+ f"open-close/{ticker}/{fmt_date(d)} {'a1' if adjusted else 'a0'} {'c0' if can_be_none else 'c1'}"
582
+ ),
583
+ exclude_args=["self"],
584
+ )
585
+ def fetch_day_summary(
586
+ self, ticker: str, d: date, *, adjusted: bool, can_be_none: bool = False
587
+ ) -> dict | None:
588
+ """
589
+ Fetch open/close/volume/high/low for ``ticker`` on date ``d``.
590
+ Returns dict with keys: open, close, low, high, volume, adjusted and optionally afterHours and preMarket if available.
591
+
592
+ See `daily ticker summary documentation <https://massive.com/docs/rest/options/aggregates/daily-ticker-summary>`_.
593
+
594
+ If no trade was recorded raise an exception except of ``can_be_none`` is True,
595
+ in which case return ``None``.
596
+
597
+ Parameters
598
+ ----------
599
+ ticker : str
600
+ Ticker symbol, e.g. "AAPL230616C00150000" for Apple 150 call expiring on 2023-06-16.
601
+ d : date
602
+ Date for which to fetch open/close/volume.
603
+ adjusted : bool
604
+ Whether to fetch adjusted or unadjusted open/close/volume.
605
+ can_be_none : bool, default False
606
+ If True, return None if no trade was recorded for the day. If False, raise an exception if no trade was recorded for the day.
607
+
608
+ Returns
609
+ -------
610
+ Result : dict
611
+ Dict with keys:
612
+
613
+ * ``open [float]``
614
+ * ``close [float]``
615
+ * ``low [float]``
616
+ * ``high [float]``
617
+ * ``volume [float]``
618
+ * ``adjusted [bool]``
619
+ * ``afterHours [float|None]`` (optional)
620
+ * ``preMarket [float|None]`` (optional)
621
+ """
622
+ url = f"{self.BASE_URL}/v1/open-close/{ticker}/{d:%Y-%m-%d}"
623
+ try:
624
+ data = self.get(url, {"adjusted": "false" if not adjusted else "true"})
625
+ except requests.exceptions.HTTPError as e:
626
+ if e.response.status_code == 404 and can_be_none:
627
+ return None
628
+ raise requests.exceptions.HTTPError(
629
+ f"No open/close/volume for {ticker} on {d} url {url}: {e.response.text}",
630
+ response=e.response,
631
+ request=e.request,
632
+ ) from e
633
+
634
+ # Polygon open-close has "open","close","volume" (and more)
635
+ assert not "next_url" in data, (
636
+ f"Internal error: pagination not expected for open-close endpoint, url '{url}' response '{data}'. Sanity check request & contact the authors."
637
+ )
638
+ open = data.get("open")
639
+ close = data.get("close")
640
+ volume = data.get("volume")
641
+ high = data.get("high")
642
+ low = data.get("low")
643
+ has_data = (
644
+ open is not None
645
+ and close is not None
646
+ and volume is not None
647
+ and high is not None
648
+ and low is not None
649
+ )
650
+ if not has_data:
651
+ if can_be_none:
652
+ return None
653
+ raise RuntimeError(
654
+ f"Cannot get {'adjusted' if adjusted else 'unadjusted'} open/close/volume/high/low for {ticker} on {d}. Massive URL used: '{url}'."
655
+ )
656
+
657
+ def get_optional(item, type=float):
658
+ x = data.get(item, None)
659
+ return x if x is None else type(x)
660
+
661
+ return {
662
+ "open": float(open),
663
+ "close": float(close),
664
+ "volume": float(volume),
665
+ "high": float(high),
666
+ "low": float(low),
667
+ "afterHours": get_optional("afterHours"),
668
+ "preMarket": get_optional("preMarket"),
669
+ "adjusted": adjusted,
670
+ }
671
+
672
+ @_cache(fmt=SubDir.PICKLE).cache(
673
+ "0.1",
674
+ label=lambda underlying, d, max_dte: (
675
+ f"all_contracts/max_dte={max_dte if not max_dte is None else 'all'}/{underlying}/{fmt_date(d)}"
676
+ ),
677
+ exclude_args=["self"],
678
+ ) # 'self' is excluded fromm the arguments as it does not affect the output.
679
+ def list_all_contracts_expiring_after_day(
680
+ self, underlying: str, d: date, max_dte: int = None
681
+ ) -> list[dict]:
682
+ """
683
+ Download ALL option contracts with expiration_date at or past ``d``, with an optional upper bound.
684
+
685
+ Parameters
686
+ ----------
687
+ underlying : str
688
+ Underlying ticker symbol, e.g. "AAPL" for Apple.
689
+ d : date
690
+ Date for which to fetch contracts. Only contracts with expiration_date >= d are returned.
691
+ max_dte : int | None, default ``None``
692
+ If not None, only return contracts with ``expiration_date <= d + max_dte`` in business days.
693
+ This is computed using :func:`openqdata.biz_calendar.add_business_days` with the NYSE calendar *including half days*.
694
+
695
+ Returns:
696
+ -------
697
+ Result : dict
698
+ See `v3/reference/options/contracts documentation <https://massive.com/docs/rest/options/contracts>`_.
699
+ """
700
+ url = f"{self.BASE_URL}/v3/reference/options/contracts"
701
+ params = {
702
+ "underlying_ticker": underlying,
703
+ "as_of": d.strftime("%Y-%m-%d"),
704
+ "expiration_date.gte": d.strftime("%Y-%m-%d"), # at or after today
705
+ "limit": 1000,
706
+ "order": "asc",
707
+ "sort": "expiration_date",
708
+ }
709
+ if not max_dte is None:
710
+ max_expiry = add_business_days(d, max_dte, exclude_half_days=False)
711
+ verify_inp(
712
+ max_expiry >= d,
713
+ f"'max_dte' {max_dte} leads to max_expiry {max_expiry} before date {d}",
714
+ )
715
+ params["expiration_date.lte"] = max_expiry.strftime("%Y-%m-%d")
716
+ return self.paginate(url, params)
717
+
718
+ @_cache(fmt=SubDir.PICKLE).cache(
719
+ "0.1",
720
+ uid=lambda opt_ticker, as_of: f"opt_ref_date/{named_unique_filename48_8(str(opt_ticker) if as_of is None else f'{opt_ticker} {as_of}')}",
721
+ )
722
+ def option_contract_overview( self, opt_ticker: str, as_of : date | None = None ) -> dict:
723
+ """
724
+ Download option `contract overview data <https://massive.com/docs/rest/options/contracts/contract-overview>`_
725
+ for a given options ticker.
726
+
727
+ Parameters
728
+ ----------
729
+ opt_ticker : str
730
+ Option ticker symbol, e.g. "AAPL230616C00150000" for Apple 150 call expiring on 2023-06-16.
731
+ as_of : :class:`datetime.date` | None, default None
732
+ If not None, fetch the contract overview as of this date. Otherwise, fetch the latest.
733
+
734
+ Returns
735
+ -------
736
+ Result : dict
737
+ See `v3/reference/options/contract overview documentation <https://massive.com/docs/rest/options/contracts/contract-overview>`_.
738
+ """
739
+ url = f"{self.BASE_URL}/v3/reference/options/contracts/{opt_ticker}{'' if as_of is None else f'?as_of={as_of.isoformat()}'}"
740
+ r = self.get(url)
741
+ return r['results']
742
+
743
+ @_cache(fmt=SubDir.PICKLE).cache(
744
+ "0.1",
745
+ uid=lambda underlying, d, expiry: f"expiry_contracts/{underlying}/{fmt_date(d)}/{expiry}"
746
+ )
747
+ def list_all_contracts_for_expiry(
748
+ self, underlying: str, d: date, expiry: date
749
+ ) -> list[dict]:
750
+ """
751
+ Download ALL option contracts with expiration_date at or past ``d``, with an optional upper bound.
752
+
753
+ Parameters
754
+ ----------
755
+ underlying : str
756
+ Underlying ticker symbol, e.g. "AAPL" for Apple.
757
+ d : date
758
+ Date for which to fetch contracts. Only contracts with expiration_date >= d are returned.
759
+ expiry : date
760
+ Expiration date for which to fetch contracts. Only contracts with expiration_date equal to expiry are returned.
761
+
762
+ Returns:
763
+ -------
764
+ Result : dict
765
+ See `v3/reference/options/contracts documentation <https://massive.com/docs/rest/options/contracts>`_.
766
+ """
767
+ url = f"{self.BASE_URL}/v3/reference/options/contracts"
768
+ params = {
769
+ "underlying_ticker": underlying,
770
+ "as_of": d.strftime("%Y-%m-%d"),
771
+ "expiration_date.gte": expiry.strftime("%Y-%m-%d"),
772
+ "expiration_date.lte": expiry.strftime("%Y-%m-%d"),
773
+ "limit": 1000,
774
+ "order": "asc",
775
+ "sort": "expiration_date",
776
+ }
777
+ return self.paginate(url, params)
778
+
779
+ @_cache(fmt=SubDir.POLARS_PARQUET).cache(
780
+ "0.1",
781
+ uid=lambda ticker, start, end: f"adjfactors/{ticker}/{fmt_date(start)}_{fmt_date(end)}",
782
+ exclude_args=["self"],
783
+ ) # 'self' is excluded fromm the arguments as it does not affect the output.
784
+ def adjustment_factors(self, ticker: str, start: date, end: date) -> pl.DataFrame:
785
+ """
786
+ Downloads daily adjusted and unadjusted close, and computes the adjustment factor as ``adj_close / unadj_close``.
787
+
788
+ See `custom bars documentation <https://massive.com/docs/rest/stocks/aggregates/custom-bars>`_
789
+
790
+ Returns a Polars frame with:
791
+
792
+ * date
793
+ * close_unadj
794
+ * close_adj
795
+ * factor_close = close_adj / close_unadj
796
+
797
+ Notes:
798
+
799
+ * Uses NY timezone to derive the trading date from 't'.
800
+ * Uses only 'close' as requested.
801
+ * If you later want volume/cash-vol invariance checks, also download 'v' and compute factors similarly.
802
+ """
803
+ verify_inp(
804
+ start <= end,
805
+ lambda: (
806
+ f"Cannot find adjustment factors for {ticker}: dates must be in order; found start {fmt_date(start)} vs end {fmt_date(end)}"
807
+ ),
808
+ )
809
+
810
+ unadjusted = self.fetch_bars(ticker, start, end, adjusted=False, timespan="day")
811
+ adjusted = self.fetch_bars(ticker, start, end, adjusted=True, timespan="day")
812
+
813
+ if len(unadjusted) == 0 or len(adjusted) == 0:
814
+ raise RuntimeError(
815
+ f"Cannot find adjustment factors for {ticker} between {fmt_date(start)} and {fmt_date(end)}: no bars found for {'adjusted' if len(adjusted) == 0 else 'unadjusted'} data. Please check that the ticker is correct and that there were trades for this ticker between {fmt_date(start)} and {fmt_date(end)}. If you need help, please contact the authors."
816
+ )
817
+
818
+ unadjusted = (
819
+ unadjusted.with_columns(pl.col("ts_ms").dt.date().alias("date"))
820
+ .rename({"close": "unadj_close"})
821
+ .select(["date", "unadj_close"])
822
+ )
823
+ adjusted = (
824
+ adjusted.with_columns(pl.col("ts_ms").dt.date().alias("date"))
825
+ .rename({"close": "adj_close"})
826
+ .select(["date", "adj_close"])
827
+ )
828
+
829
+ # Join + factor
830
+ out = (
831
+ unadjusted.join(adjusted, on="date", how="full", coalesce=True)
832
+ .sort("date")
833
+ .with_columns(
834
+ (pl.col("adj_close") / pl.col("unadj_close")).cast(pl.Float32).alias("adjfactor")
835
+ )
836
+ )
837
+ err = out.filter(pl.col("adjfactor").is_infinite() | pl.col("adjfactor").is_nan())
838
+ if err.height > 0:
839
+ raise RuntimeError(
840
+ f"Unexpected data error: found infinite/NaN adjustment factor for ticker {ticker} between {fmt_date(start)} and {fmt_date(end)} on {fmt_list(err['date'].head(5).to_list())}. This likely indicates a data error in the underlying bars, e.g. a missing unadjusted close price. Please check the underlying bars and contact the authors if you need help."
841
+ )
842
+
843
+ out = out.select(["date", "adjfactor"])
844
+ return out
845
+
846
+ @_cache(fmt=SubDir.PICKLE).cache(
847
+ "0.1", uid=lambda ticker: f"reference/{ticker}", exclude_args=["self"]
848
+ ) # 'self' is excluded fromm the arguments as it does not affect the output.
849
+ def ticker_reference_data(self, ticker: str) -> dict:
850
+ """
851
+ Return reference data for a given ticker.
852
+
853
+ See `ticker overview documentation <https://massive.com/docs/rest/stocks/tickers/ticker-overview>`_ for details.
854
+ This function converts boolean, integer, floats and dates.
855
+
856
+ Parameters
857
+ ----------
858
+ ticker : str
859
+ Ticker symbol, e.g. "AAPL230616C00150000" for Apple 150 call expiring on 2023-06-16.
860
+
861
+ Returns
862
+ -------
863
+ Result : dict
864
+ Dict with reference data for the ticker. See `ticker overview documentation <https://massive.com/docs/rest/stocks/tickers/ticker-overview>`_ for details.
865
+ The following conversions will be performed:
866
+
867
+ * active [bool|None]
868
+ * list_date [date|None]
869
+ * delisted_utc [date|None]
870
+ * market_cap [float|None]
871
+ * round_lot [int|None]
872
+ * total_employees [int|None]
873
+ * weighted_shares_outstanding [int|None]
874
+ * share_class_shares_outstanding [int|None]
875
+
876
+ Raises
877
+ ------
878
+ Ticker not found: :class:`FileNotFoundError`
879
+ If the request for reference data from massive did not yield any results.
880
+ """
881
+
882
+ url = f"{self.BASE_URL}/v3/reference/tickers/{ticker}"
883
+ response = self.get(url)
884
+ results = response.get("results", {})
885
+
886
+ if len(results) == 0:
887
+ raise FileNotFoundError(
888
+ f"No reference data found for ticker {ticker} on massive.com. URL {url}."
889
+ )
890
+
891
+ bool_fields = ["active"]
892
+ date_fields = ["list_date", "delisted_utc"]
893
+ float_fields = ["market_cap"]
894
+ int_fields = [
895
+ "round_lot",
896
+ "total_employees",
897
+ "weighted_shares_outstanding",
898
+ "share_class_shares_outstanding",
899
+ "sic_code",
900
+ ]
901
+
902
+ for f in bool_fields:
903
+ if f in results:
904
+ results[f] = bool(results[f])
905
+
906
+ for f in date_fields:
907
+ if f in results and results[f] is not None:
908
+ results[f] = date.fromisoformat(results[f])
909
+
910
+ for f in float_fields:
911
+ if f in results and results[f] is not None:
912
+ results[f] = float(results[f])
913
+
914
+ for f in int_fields:
915
+ if f in results and results[f] is not None:
916
+ results[f] = int(results[f])
917
+
918
+ return results
919
+
920
+ # ----------------------------
921
+ # corporate events etc
922
+ # ----------------------------
923
+
924
+ def _process_massive(
925
+ self,
926
+ what,
927
+ rows: list[dict],
928
+ schema: dict[str, pl.DataType],
929
+ massive_schema : dict[str, pl.DataType], # massive data schema; not necessarily the same as output schema
930
+ sort_by: list[str] | str,
931
+ drop_ticker: bool,
932
+ ) -> pl.DataFrame:
933
+ """
934
+ Helper function to process corporate events data (dividends, splits) and convert to Polars DataFrame with correct schema.
935
+ """
936
+ if not rows:
937
+ return pl.DataFrame(schema=schema)
938
+
939
+ df = pl.DataFrame(rows, massive_schema, infer_schema_length=None)
940
+ if drop_ticker:
941
+ df = df.drop("ticker")
942
+
943
+ for k, t in schema.items():
944
+ if k not in df.columns:
945
+ df = df.with_columns(pl.lit(None).cast(t).alias(k))
946
+ elif t == pl.Date:
947
+ df = df.with_columns(pl.col(k).str.strptime(pl.Date, "%Y-%m-%d").alias(k))
948
+ else:
949
+ df = df.with_columns(pl.col(k).cast(t).alias(k))
950
+
951
+ df = df.sort(sort_by)
952
+ assert set(df.columns) == set(schema), (
953
+ f"Internal error {what()}: expected columns {set(schema)} but got {set(df.columns)}. Sanity check the request and contact the authors if you need help."
954
+ )
955
+ return df
956
+
957
+ SCHEMA_DIVIDENDS = {
958
+ "cash_amount": pl.Float64,
959
+ "currency": pl.String,
960
+ "declaration_date": pl.Date,
961
+ "distribution_type": pl.String,
962
+ "ex_dividend_date": pl.Date,
963
+ "frequency": pl.Int16,
964
+ "historical_adjustment_factor": pl.Float64,
965
+ "id": pl.String,
966
+ "pay_date": pl.Date,
967
+ "record_date": pl.Date,
968
+ "split_adjusted_cash_amount": pl.Float64,
969
+ }
970
+ """ Schema of the :class:`polars.DataFrame` returned by :meth:`get_dividends`. """
971
+
972
+ @_cache(fmt=SubDir.POLARS_PARQUET).cache(
973
+ "0.1",
974
+ uid=lambda ticker, start, end: f"dividends/{ticker}/{fmt_date(start)}_{fmt_date(end)}",
975
+ exclude_args=["self"],
976
+ ) # 'self' is excluded fromm the arguments as it does not affect the output.
977
+ def get_dividends(self, ticker: str, start: date, end: date) -> pl.DataFrame:
978
+ """
979
+ Retrieve dividends which go ex div between two dates from `/stocks/v1/dividends < https://massive.com/docs/rest/stocks/corporate-actions/dividends>`_.
980
+
981
+ Parameters
982
+ ----------
983
+ ticker : str
984
+ Ticker symbol, e.g. "AAPL" for Apple.
985
+ start : :class:`datetime.date`
986
+ Start date for dividends.
987
+ end : :class:`datetime.date`
988
+ End date for dividends.
989
+
990
+ Returns
991
+ -------
992
+ :class:`polars.DataFrame`
993
+ DataFrame with dividend information using schema :class:`MassiveClient.SCHEMA_DIVIDENDS`.
994
+ The dataframe can have length zero (but it will have the correct data schema).
995
+ """
996
+
997
+ verify_inp(
998
+ start <= end,
999
+ lambda: (
1000
+ f"Cannot find adjustment factors for {ticker}: dates must be in order; found start {fmt_date(start)} vs end {fmt_date(end)}"
1001
+ ),
1002
+ )
1003
+
1004
+ url = f"{self.BASE_URL}/stocks/v1/dividends"
1005
+ params = {
1006
+ "ticker": ticker,
1007
+ "ex_dividend_date.gte": start.strftime("%Y-%m-%d"),
1008
+ "ex_dividend_date.lte": end.strftime("%Y-%m-%d"),
1009
+ "limit": 1000,
1010
+ "order": "asc",
1011
+ "sort": "ex_dividend_date",
1012
+ }
1013
+ rows = self.paginate(url, params)
1014
+ return self._process_massive(
1015
+ what=lambda: f"dividends for {ticker} between {fmt_date(start)} and {fmt_date(end)}",
1016
+ rows=rows,
1017
+ schema=MassiveClient.SCHEMA_DIVIDENDS,
1018
+ massive_schema={
1019
+ # https://massive.com/docs/rest/stocks/corporate-actions/dividends
1020
+ 'cash_amount': pl.Float64,
1021
+ 'currency': pl.String,
1022
+ 'declaration_date': pl.String,
1023
+ 'distribution_type': pl.String,
1024
+ 'ex_dividend_date': pl.String,
1025
+ 'frequency': pl.Int16,
1026
+ 'historical_adjustment_factor': pl.Float64,
1027
+ 'id': pl.String,
1028
+ 'pay_date': pl.String,
1029
+ 'record_date': pl.String,
1030
+ 'split_adjusted_cash_amount': pl.Float64,
1031
+ 'ticker': pl.String,
1032
+ },
1033
+ sort_by="ex_dividend_date",
1034
+ drop_ticker=True,
1035
+ )
1036
+
1037
+ SCHEMA_SPLITS = {
1038
+ "adjustment_type": pl.String,
1039
+ "execution_date": pl.Date,
1040
+ "historical_adjustment_factor": pl.Float64,
1041
+ "id": pl.String,
1042
+ "split_from": pl.Int32,
1043
+ "split_to": pl.Int32,
1044
+ }
1045
+ """ Schema of the :class:`polars.DataFrame` returned by :meth:`get_splits`. """
1046
+
1047
+ @_cache(fmt=SubDir.POLARS_PARQUET).cache(
1048
+ "0.1",
1049
+ uid=lambda ticker, start, end: f"splits/{ticker}/{fmt_date(start)}_{fmt_date(end)}",
1050
+ exclude_args=["self"],
1051
+ ) # 'self' is excluded fromm the arguments as it does not affect the output.
1052
+ def get_splits(self, ticker: str, start: date, end: date) -> pl.DataFrame:
1053
+ """Retrieve stock splits between two dates from `/stocks/v1/splits <https://massive.com/docs/rest/stocks/corporate-actions/splits>`_."""
1054
+ url = f"{self.BASE_URL}/stocks/v1/splits"
1055
+ params = {
1056
+ "ticker": ticker,
1057
+ "execution_date.gte": start.strftime("%Y-%m-%d"),
1058
+ "execution_date.lte": end.strftime("%Y-%m-%d"),
1059
+ "limit": 1000,
1060
+ "order": "asc",
1061
+ "sort": "execution_date",
1062
+ }
1063
+ rows = self.paginate(url, params)
1064
+ return self._process_massive(
1065
+ what=lambda: f"splits for {ticker} between {fmt_date(start)} and {fmt_date(end)}",
1066
+ rows=rows,
1067
+ schema=MassiveClient.SCHEMA_SPLITS,
1068
+ massive_schema={
1069
+ # https://massive.com/docs/rest/stocks/corporate-actions/splits
1070
+ 'adjustment_type': pl.String,
1071
+ 'execution_date': pl.String,
1072
+ 'historical_adjustment_factor': pl.Float64,
1073
+ 'id': pl.String,
1074
+ 'split_from': pl.Int32,
1075
+ 'split_to': pl.Int32,
1076
+ 'ticker': pl.String,
1077
+ },
1078
+ sort_by="execution_date",
1079
+ drop_ticker=True,
1080
+ )
1081
+
1082
+ SCHEMA_HAS_TICKER_CHANGES = {
1083
+ "date": pl.Date,
1084
+ "has_ticker_change": pl.Boolean,
1085
+ }
1086
+ """ Schema of the :class:`polars.DataFrame` returned by :meth:`has_ticker_changes`. """
1087
+
1088
+ @_cache(fmt=SubDir.POLARS_PARQUET).cache(
1089
+ "0.2",
1090
+ uid=lambda ticker, start, end: f"ticker_changes/{ticker}/{fmt_date(start)}_{fmt_date(end)}",
1091
+ exclude_args=["self"],
1092
+ ) # 'self' is excluded fromm the arguments as it does not affect the output.
1093
+ def has_ticker_changes(self, ticker: str, start: date, end: date) -> pl.DataFrame:
1094
+ """
1095
+ Find dates at which an underlying had ticker changes.
1096
+
1097
+ If the endpoint is not available return an empty frame.
1098
+ At the moment ticker changes are `the only events massive.com supports <https://massive.com/docs/rest/stocks/corporate-actions/ticker-events>`_.
1099
+ """
1100
+
1101
+ client = self.get_rest_client()
1102
+ events = client.get_ticker_events(ticker)
1103
+ events = events.events or []
1104
+ if len(events) == 0:
1105
+ return pl.DataFrame(schema=MassiveClient.SCHEMA_HAS_TICKER_CHANGES)
1106
+ # SDK events expose `type`; name the normalized field explicitly.
1107
+ df = pl.DataFrame(
1108
+ [{"date": event["date"], "event_type": event["type"]}
1109
+ if isinstance(event, Mapping) else
1110
+ {"date": event.date, "event_type": event.type}
1111
+ for event in events],
1112
+ schema={"date": pl.String, "event_type": pl.String},
1113
+ )
1114
+ event_types = set(df.select(pl.col("event_type").unique()).get_column("event_type").to_list())
1115
+ assert event_types == {"ticker_change"}, (
1116
+ f"Internal error retrieving ticker changes for {ticker} between {fmt_date(start)} and {fmt_date(end)}: expected event type 'ticker_change' but got {sorted(event_types)}. Please update code. Ref: https://massive.com/docs/rest/stocks/corporate-actions/ticker-events"
1117
+ )
1118
+
1119
+ df = df.select(
1120
+ pl.col("date").str.slice(0, 10).str.strptime(pl.Date, "%Y-%m-%d").alias("date")
1121
+ )
1122
+
1123
+ # filter by requested window
1124
+ df = df.filter((pl.col("date") >= start) & (pl.col("date") <= end))
1125
+ if df.is_empty():
1126
+ return pl.DataFrame(schema=MassiveClient.SCHEMA_HAS_TICKER_CHANGES)
1127
+
1128
+ df = (
1129
+ df.unique(subset=["date"])
1130
+ .sort("date")
1131
+ .with_columns(pl.lit(True).alias("has_ticker_change"))
1132
+ )
1133
+ df = df.sort("date")
1134
+ assert df.height > 0
1135
+ assert set(df.columns) == set(MassiveClient.SCHEMA_HAS_TICKER_CHANGES), (
1136
+ f"Internal error retrieving ticker changes for {ticker} between {fmt_date(start)} and {fmt_date(end)}: expected columns {set(MassiveClient.SCHEMA_HAS_TICKER_CHANGES)} but got {set(df.columns)}. Please update code. Ref: https://massive.com/docs/rest/stocks/corporate-actions/ticker-events"
1137
+ )
1138
+ return df
1139
+
1140
+ @version("0.1")
1141
+ def consistent_prev_close( self, ticker : str, d : date, *, prev_d : date|None = None, exclude_half_days: bool = True ) -> float:
1142
+ r"""
1143
+ Computes the previous day close consistent with today's unadjusted prices.
1144
+
1145
+ It computes
1146
+ $$
1147
+ S_{\mathrm{t-1}} := S^{\mathrm{adjusted}}_{\mathrm{t-1}} \cdot \frac{S^{\mathrm{unadjusted}}_{\mathrm{t}}}{S^{\mathrm{adjusted}}_{\mathrm{t}}}
1148
+ $$
1149
+
1150
+ Parameters
1151
+ ----------
1152
+ ticker : str
1153
+ Ticker symbol, e.g. "AAPL".
1154
+ d : :class:`datetime.date`
1155
+ Date for which to compute the previous close.
1156
+ prev_d : :class:`datetime.date` | None, default None
1157
+ If not None, use this date as the previous day instead of computing it as the previous business day.
1158
+ exclude_half_days : bool, default ``True``
1159
+ Whether to exclude half days when computing the previous business day.
1160
+ This is used if ``prev_d`` is ``None``.
1161
+
1162
+ Returns
1163
+ -------
1164
+ Close : ``float``
1165
+ The previous day's close, consistent with today's unadjusted prices.
1166
+ """
1167
+ prev_d = prev_d if not prev_d is None else 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)
1168
+ r = self._PREV_CLOSE_CACHE.get((ticker, d, prev_d), None)
1169
+ if r is not None:
1170
+ return r
1171
+
1172
+ close_adj_prev = self.fetch_day_summary( ticker, prev_d, adjusted=True, can_be_none=False )["close"]
1173
+ close_unadj = self.fetch_day_summary( ticker, d, adjusted=False, can_be_none=False )["close"]
1174
+ close_adj = self.fetch_day_summary(ticker, d, adjusted=True, can_be_none=False)[ "close" ]
1175
+ prev_adj_close = close_adj_prev / close_adj * close_unadj
1176
+ self._PREV_CLOSE_CACHE[(ticker, d, prev_d)] = prev_adj_close
1177
+ return prev_adj_close
1178
+
1179
+
1180
+ if __name__ == "__main__":
1181
+ from openqdata.cli import run_module
1182
+
1183
+ run_module(globals())