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.
- openqdata/README.md +5 -0
- openqdata/__init__.py +15 -0
- openqdata/arbfree/README.md +5 -0
- openqdata/arbfree/__init__.py +9 -0
- openqdata/arbfree/arbfree.py +1494 -0
- openqdata/arbfree/sanos.py +316 -0
- openqdata/arbfree/sanos_tools.py +958 -0
- openqdata/arbfree/tridiag.py +85 -0
- openqdata/benchmark/README.md +5 -0
- openqdata/benchmark/__init__.py +4 -0
- openqdata/biz_calendar.py +506 -0
- openqdata/cli.py +91 -0
- openqdata/env.py +112 -0
- openqdata/fred/README.md +5 -0
- openqdata/fred/__init__.py +14 -0
- openqdata/fred/client.py +57 -0
- openqdata/fred/rates.py +162 -0
- openqdata/massive/README.md +5 -0
- openqdata/massive/__init__.py +15 -0
- openqdata/massive/client.py +1183 -0
- openqdata/massive/expiries.py +242 -0
- openqdata/massive/options/README.md +5 -0
- openqdata/massive/options/__init__.py +6 -0
- openqdata/massive/options/contracts.py +610 -0
- openqdata/massive/processing.py +447 -0
- openqdata/massive/testing/README.md +5 -0
- openqdata/massive/testing/__init__.py +8 -0
- openqdata/massive/testing/generate.py +61 -0
- openqdata/massive/testing/scope.py +8 -0
- openqdata/massive/tickers/README.md +5 -0
- openqdata/massive/tickers/__init__.py +5 -0
- openqdata/massive/tickers/basics.py +66 -0
- openqdata/massive/tickers/data.py +362 -0
- openqdata/massive/tickers/filtered_history.py +260 -0
- openqdata/massive/trade_conds.py +324 -0
- openqdata/models/README.md +5 -0
- openqdata/models/__init__.py +4 -0
- openqdata/pool.py +34 -0
- openqdata/tickers/README.md +5 -0
- openqdata/tickers/__init__.py +13 -0
- openqdata/tickers/ticker_calendar.py +370 -0
- openqdata/utils/README.md +3 -0
- openqdata/utils/__init__.py +35 -0
- openqdata/utils/cvxpy.py +47 -0
- openqdata/utils/pd.py +125 -0
- openqdata/utils/pl.py +114 -0
- openqdata/vixdata/README.md +5 -0
- openqdata/vixdata/__init__.py +6 -0
- openqdata/vixdata/cboe.py +119 -0
- openqdata/vixdata/client.py +44 -0
- openqdata/vixdata/formula.py +132 -0
- openqdata/widb/README.md +5 -0
- openqdata/widb/__init__.py +25 -0
- openqdata/widb/arbfree.py +581 -0
- openqdata/widb/bad.py +69 -0
- openqdata/widb/client.py +517 -0
- openqdata/widb/connection.py +72 -0
- openqdata/widb/day.py +1098 -0
- openqdata/widb/fitstats.py +328 -0
- openqdata/widb/options_filter.py +338 -0
- openqdata/widb/sanos.py +96 -0
- openqdata/widb/testing/README.md +5 -0
- openqdata/widb/testing/__init__.py +0 -0
- openqdata/widb/testing/generate.py +45 -0
- openqdata/widb/testing/scope.py +8 -0
- openqdata/widb/timeseries.py +434 -0
- openqdata/yahoo/README.md +5 -0
- openqdata/yahoo/__init__.py +8 -0
- openqdata/yahoo/client.py +229 -0
- openqdata-0.3.0.dist-info/METADATA +103 -0
- openqdata-0.3.0.dist-info/RECORD +75 -0
- openqdata-0.3.0.dist-info/WHEEL +5 -0
- openqdata-0.3.0.dist-info/licenses/LICENSE +131 -0
- openqdata-0.3.0.dist-info/licenses/NOTICE +1 -0
- openqdata-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""
|
|
2
|
+
openqdata.massive.tickers.data
|
|
3
|
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
4
|
+
|
|
5
|
+
Build underlying tick-level data from Massive: unadjusted trades, weighted mid-price
|
|
6
|
+
tape, and 1-second trade bars.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import math
|
|
12
|
+
from datetime import date, datetime, timedelta
|
|
13
|
+
|
|
14
|
+
import polars as pl
|
|
15
|
+
from cdxcore.err import verify
|
|
16
|
+
from cdxcore.util import fmt_date
|
|
17
|
+
from cdxcore.version import version
|
|
18
|
+
|
|
19
|
+
from openqdata.biz_calendar import TZ_NY, full_second_grid_ns, session_open_close
|
|
20
|
+
from openqdata.massive import MassiveClient
|
|
21
|
+
from openqdata.massive.processing import valid_quote_mask
|
|
22
|
+
from openqdata.tickers import SubDir, _locations_tickers
|
|
23
|
+
|
|
24
|
+
_data_cache = _locations_tickers
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# ---------------------------------------------------------------------------
|
|
28
|
+
# Helpers
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@version("0.1")
|
|
33
|
+
def _second_bin_ix_expr(dt_ns_expr: pl.Expr, open_dt: datetime) -> pl.Expr:
|
|
34
|
+
base = pl.lit(open_dt).cast(pl.Datetime("ns", TZ_NY))
|
|
35
|
+
return ((dt_ns_expr - base).dt.total_seconds()).cast(pl.Int32).alias("second_bin_ix")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@version("0.1")
|
|
39
|
+
def _bin_type_series(n: int) -> pl.Series:
|
|
40
|
+
# bin_type: 1 = opening bin, 0 = middle bin, 2 = closing bin
|
|
41
|
+
if n <= 0:
|
|
42
|
+
return pl.Series("bin_type", [], dtype=pl.Int8)
|
|
43
|
+
if n == 1:
|
|
44
|
+
return pl.Series("bin_type", [1], dtype=pl.Int8)
|
|
45
|
+
return pl.Series("bin_type", [1] + [0] * (n - 2) + [2], dtype=pl.Int8)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@version("0.1")
|
|
49
|
+
def _map_close_inclusive_to_last_bin(ts_col: str, close_dt: datetime) -> pl.Expr:
|
|
50
|
+
"""
|
|
51
|
+
Map any timestamp exactly at ``close_dt`` to the last bin key ``close_dt - 1s``,
|
|
52
|
+
implementing the semantics:
|
|
53
|
+
|
|
54
|
+
* all bins except last: ``[t, t+1s)``
|
|
55
|
+
* last bin: ``[close_dt-1s, close_dt]``
|
|
56
|
+
"""
|
|
57
|
+
last_bin_dt = close_dt - timedelta(seconds=1)
|
|
58
|
+
return (
|
|
59
|
+
pl.when(pl.col(ts_col) == pl.lit(close_dt))
|
|
60
|
+
.then(pl.lit(last_bin_dt))
|
|
61
|
+
.otherwise(pl.col(ts_col))
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ---------------------------------------------------------------------------
|
|
66
|
+
# Unadjusted trades
|
|
67
|
+
# ---------------------------------------------------------------------------
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@_data_cache(fmt=SubDir.POLARS_PARQUET).cache(
|
|
71
|
+
"0.1",
|
|
72
|
+
uid=lambda underlying, d: f"unadjusted_trades/{underlying}/{fmt_date(d)}",
|
|
73
|
+
exclude_args=["client"],
|
|
74
|
+
dependencies=[MassiveClient.fetch_trades, session_open_close],
|
|
75
|
+
)
|
|
76
|
+
def build_unadjusted_trades(
|
|
77
|
+
underlying: str,
|
|
78
|
+
d: date,
|
|
79
|
+
*,
|
|
80
|
+
client: MassiveClient | None = None,
|
|
81
|
+
) -> pl.DataFrame:
|
|
82
|
+
"""
|
|
83
|
+
Unadjusted trades for ``underlying`` on ``d``, filtered to RTH session ``[open, close]``.
|
|
84
|
+
|
|
85
|
+
Applies a timestamp filter only. Closing prints and official/corrected closes
|
|
86
|
+
are retained; ``NORMAL_TRADE_EXCLUDE_FLAGS`` is not applied. For a trade stream
|
|
87
|
+
that excludes those conditions, use ``filter_valid_trades()`` instead.
|
|
88
|
+
|
|
89
|
+
Returns
|
|
90
|
+
-------
|
|
91
|
+
pl.DataFrame
|
|
92
|
+
Columns: ts_ns (Datetime[ns, NY]), price (Float32), size (Float32), trade_code (UInt32)
|
|
93
|
+
"""
|
|
94
|
+
client = MassiveClient() if client is None else client
|
|
95
|
+
open_dt, close_dt, _hd = session_open_close(d)
|
|
96
|
+
trades = client.fetch_trades(underlying, d)
|
|
97
|
+
|
|
98
|
+
assert set(trades.columns) >= {"ts_ns", "price", "size"}, trades.columns
|
|
99
|
+
verify(not trades.is_empty(), f"No trades for {underlying} on {d}")
|
|
100
|
+
|
|
101
|
+
trades = trades.filter(
|
|
102
|
+
(pl.col("ts_ns") >= pl.lit(open_dt)) & (pl.col("ts_ns") <= pl.lit(close_dt))
|
|
103
|
+
)
|
|
104
|
+
return trades
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ---------------------------------------------------------------------------
|
|
108
|
+
# Underlying spot (weighted mid-price)
|
|
109
|
+
# ---------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _build_unadjusted_spot_wmid(
|
|
113
|
+
underlying: str,
|
|
114
|
+
d: date,
|
|
115
|
+
trades: pl.DataFrame | None,
|
|
116
|
+
client: MassiveClient | None,
|
|
117
|
+
) -> pl.DataFrame:
|
|
118
|
+
client = MassiveClient() if client is None else client
|
|
119
|
+
open_dt, close_dt, _hd = session_open_close(d)
|
|
120
|
+
|
|
121
|
+
oc = client.fetch_day_summary(underlying, d, adjusted=False)
|
|
122
|
+
open_px = float(oc["open"])
|
|
123
|
+
close_px = float(oc["close"])
|
|
124
|
+
assert math.isfinite(open_px) and open_px > 0.0, f"Bad open price {underlying} {d}: {open_px}"
|
|
125
|
+
assert math.isfinite(close_px) and close_px > 0.0, (
|
|
126
|
+
f"Bad close price {underlying} {d}: {close_px}"
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
schema = {
|
|
130
|
+
"u_ts_ns": pl.Datetime("ns", TZ_NY),
|
|
131
|
+
"spot": pl.Float32,
|
|
132
|
+
"is_trade": pl.Boolean,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
init = pl.DataFrame(
|
|
136
|
+
{"u_ts_ns": [open_dt, close_dt], "spot": [open_px, close_px], "is_trade": [False, False]},
|
|
137
|
+
schema=schema,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
q = client.fetch_quotes(underlying, d)
|
|
141
|
+
if not q.is_empty():
|
|
142
|
+
q = (
|
|
143
|
+
q.filter((pl.col("ts_ns") >= pl.lit(open_dt)) & (pl.col("ts_ns") <= pl.lit(close_dt)) & valid_quote_mask())
|
|
144
|
+
.with_columns(
|
|
145
|
+
(
|
|
146
|
+
(pl.col("bid_price") * pl.col("ask_size") + pl.col("ask_price") * pl.col("bid_size"))
|
|
147
|
+
/ (pl.col("bid_size") + pl.col("ask_size"))
|
|
148
|
+
)
|
|
149
|
+
.cast(pl.Float32)
|
|
150
|
+
.alias("spot")
|
|
151
|
+
)
|
|
152
|
+
.select(pl.col("ts_ns").alias("u_ts_ns"), "spot")
|
|
153
|
+
.with_columns(pl.lit(False).cast(pl.Boolean).alias("is_trade"))
|
|
154
|
+
.cast(schema)
|
|
155
|
+
.sort("u_ts_ns")
|
|
156
|
+
)
|
|
157
|
+
else:
|
|
158
|
+
q = pl.DataFrame(schema=schema)
|
|
159
|
+
|
|
160
|
+
trades = build_unadjusted_trades(underlying, d, client=client) if trades is None else trades
|
|
161
|
+
t = (
|
|
162
|
+
trades.filter((pl.col("ts_ns") >= pl.lit(open_dt)) & (pl.col("ts_ns") <= pl.lit(close_dt)))
|
|
163
|
+
.select(pl.col("ts_ns").alias("u_ts_ns"), pl.col("price").cast(pl.Float32).alias("spot"))
|
|
164
|
+
.with_columns(pl.lit(True).cast(pl.Boolean).alias("is_trade"))
|
|
165
|
+
.cast(schema)
|
|
166
|
+
.sort("u_ts_ns")
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
out = (
|
|
170
|
+
pl.concat([init, q, t], how="vertical")
|
|
171
|
+
.sort(["u_ts_ns", "is_trade"], descending=[False, True])
|
|
172
|
+
.unique(subset=["u_ts_ns"], keep="first")
|
|
173
|
+
.sort("u_ts_ns")
|
|
174
|
+
)
|
|
175
|
+
verify(out.height >= 1, lambda: f"Spot wmid tape empty for {underlying} on {d}")
|
|
176
|
+
return out
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@_data_cache(fmt=SubDir.POLARS_PARQUET).cache(
|
|
181
|
+
"0.2",
|
|
182
|
+
uid=lambda underlying, d: f"spot_wmid/{underlying}/{fmt_date(d)}",
|
|
183
|
+
exclude_args=["client"],
|
|
184
|
+
dependencies=[
|
|
185
|
+
MassiveClient.fetch_quotes,
|
|
186
|
+
MassiveClient.fetch_day_summary,
|
|
187
|
+
build_unadjusted_trades,
|
|
188
|
+
valid_quote_mask,
|
|
189
|
+
],
|
|
190
|
+
)
|
|
191
|
+
def _build_unadjusted_spot_wmid_cached(underlying: str, d: date, *, client: MassiveClient | None = None) -> pl.DataFrame:
|
|
192
|
+
return _build_unadjusted_spot_wmid(underlying, d, None, client)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def build_unadjusted_spot_wmid(
|
|
196
|
+
underlying: str,
|
|
197
|
+
d: date,
|
|
198
|
+
*,
|
|
199
|
+
trades: pl.DataFrame | None = None,
|
|
200
|
+
client: MassiveClient | None = None,
|
|
201
|
+
) -> pl.DataFrame:
|
|
202
|
+
"""
|
|
203
|
+
Weighted mid-price tape for ``underlying`` on ``d``, suitable for asof-joins.
|
|
204
|
+
|
|
205
|
+
The tape is initialised at session open and close with the unadjusted open/close
|
|
206
|
+
from ``/v1/open-close`` so a spot price is always available. Quote wmid and
|
|
207
|
+
trade prices are interleaved; trades win on identical timestamps.
|
|
208
|
+
|
|
209
|
+
Returns
|
|
210
|
+
-------
|
|
211
|
+
pl.DataFrame
|
|
212
|
+
Columns: u_ts_ns (Datetime[ns, NY]), spot (Float32), is_trade (Boolean)
|
|
213
|
+
"""
|
|
214
|
+
# Only the default trade stream is cached; caller-supplied trades bypass the cache so that
|
|
215
|
+
# differently filtered inputs never share a cache entry.
|
|
216
|
+
if trades is not None:
|
|
217
|
+
return _build_unadjusted_spot_wmid(underlying, d, trades, client)
|
|
218
|
+
return _build_unadjusted_spot_wmid_cached(underlying, d, client=client)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# ---------------------------------------------------------------------------
|
|
222
|
+
# 1-second trade bars
|
|
223
|
+
# ---------------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _build_1s_trade_bars(
|
|
227
|
+
underlying: str,
|
|
228
|
+
d: date,
|
|
229
|
+
trades: pl.DataFrame | None,
|
|
230
|
+
client: MassiveClient | None,
|
|
231
|
+
) -> pl.DataFrame:
|
|
232
|
+
client = MassiveClient() if client is None else client
|
|
233
|
+
open_dt, close_dt, is_half_day = session_open_close(d)
|
|
234
|
+
|
|
235
|
+
grid = full_second_grid_ns(open_dt, close_dt)
|
|
236
|
+
verify(
|
|
237
|
+
grid.to_list()[-1] == close_dt - timedelta(seconds=1),
|
|
238
|
+
lambda: f"Grid does not end at close_dt-1s: {grid.to_list()[-1]} vs {close_dt}",
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
u = pl.DataFrame({"dt_ns": grid}).with_columns(
|
|
242
|
+
_second_bin_ix_expr(pl.col("dt_ns"), open_dt),
|
|
243
|
+
_bin_type_series(len(grid)),
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
trades = build_unadjusted_trades(underlying, d, client=client) if trades is None else trades
|
|
247
|
+
|
|
248
|
+
trades = (
|
|
249
|
+
trades.with_columns(
|
|
250
|
+
pl.col("ts_ns").dt.truncate("1s").alias("sec_ns_raw"),
|
|
251
|
+
(pl.col("price") * pl.col("size")).alias("cash"),
|
|
252
|
+
)
|
|
253
|
+
.with_columns(_map_close_inclusive_to_last_bin("sec_ns_raw", close_dt).alias("sec_ns"))
|
|
254
|
+
.drop("sec_ns_raw")
|
|
255
|
+
.sort("ts_ns")
|
|
256
|
+
.with_columns(
|
|
257
|
+
pl.col("ts_ns").cast(pl.Datetime("ns", TZ_NY)),
|
|
258
|
+
pl.col("price").cast(pl.Float32),
|
|
259
|
+
pl.col("size").cast(pl.Float32),
|
|
260
|
+
pl.col("cash").cast(pl.Float32),
|
|
261
|
+
pl.col("sec_ns").cast(pl.Datetime("ns", TZ_NY)),
|
|
262
|
+
)
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
agg = (
|
|
266
|
+
trades.group_by("sec_ns")
|
|
267
|
+
.agg(
|
|
268
|
+
pl.col("price").first().alias("open"),
|
|
269
|
+
pl.col("price").last().alias("close"),
|
|
270
|
+
pl.col("price").max().alias("high"),
|
|
271
|
+
pl.col("price").min().alias("low"),
|
|
272
|
+
pl.col("size").sum().fill_null(0.0).alias("volume"),
|
|
273
|
+
pl.col("cash").sum().fill_null(0.0).alias("cash_volume"),
|
|
274
|
+
pl.len().cast(pl.Int64).alias("num_trades"),
|
|
275
|
+
)
|
|
276
|
+
.sort("sec_ns")
|
|
277
|
+
.with_columns(
|
|
278
|
+
pl.when(pl.col("volume") > 0)
|
|
279
|
+
.then(pl.col("cash_volume") / pl.col("volume"))
|
|
280
|
+
.otherwise(None)
|
|
281
|
+
.alias("vwap"),
|
|
282
|
+
(pl.col("volume") + 1.0).log10().alias("log_volume"),
|
|
283
|
+
(pl.col("cash_volume") + 1.0).log10().alias("log_cash_volume"),
|
|
284
|
+
)
|
|
285
|
+
.drop(["volume", "cash_volume"])
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
u = (
|
|
289
|
+
u.join(agg.rename({"sec_ns": "dt_ns"}), on="dt_ns", how="left")
|
|
290
|
+
.with_columns(
|
|
291
|
+
pl.col("close").forward_fill().cast(pl.Float32).alias("last_trade"),
|
|
292
|
+
pl.col("open").cast(pl.Float32),
|
|
293
|
+
pl.col("close").cast(pl.Float32),
|
|
294
|
+
pl.col("high").cast(pl.Float32),
|
|
295
|
+
pl.col("low").cast(pl.Float32),
|
|
296
|
+
pl.col("vwap").cast(pl.Float32),
|
|
297
|
+
pl.col("num_trades").fill_null(0).cast(pl.Int64),
|
|
298
|
+
pl.col("log_cash_volume").fill_null(0).cast(pl.Float32),
|
|
299
|
+
pl.col("log_volume").fill_null(0).cast(pl.Float32),
|
|
300
|
+
)
|
|
301
|
+
.with_columns(
|
|
302
|
+
pl.lit(underlying).alias("underlying"),
|
|
303
|
+
pl.lit(d).alias("date").cast(pl.Date),
|
|
304
|
+
pl.lit(is_half_day).alias("is_half_day").cast(pl.Boolean),
|
|
305
|
+
)
|
|
306
|
+
)
|
|
307
|
+
return u
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
if __name__ == "__main__":
|
|
311
|
+
from openqdata.cli import run_module
|
|
312
|
+
|
|
313
|
+
run_module(globals())
|
|
314
|
+
|
|
315
|
+
@_data_cache(fmt=SubDir.POLARS_PARQUET).cache(
|
|
316
|
+
"0.1",
|
|
317
|
+
uid=lambda underlying, d: f"u1s_bars/{underlying}/{fmt_date(d)}",
|
|
318
|
+
exclude_args=["client"],
|
|
319
|
+
dependencies=[
|
|
320
|
+
MassiveClient.fetch_trades,
|
|
321
|
+
session_open_close,
|
|
322
|
+
full_second_grid_ns,
|
|
323
|
+
build_unadjusted_trades,
|
|
324
|
+
],
|
|
325
|
+
)
|
|
326
|
+
def _build_1s_trade_bars_cached(underlying: str, d: date, *, client: MassiveClient | None = None) -> pl.DataFrame:
|
|
327
|
+
return _build_1s_trade_bars(underlying, d, None, client)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def build_1s_trade_bars(
|
|
331
|
+
underlying: str,
|
|
332
|
+
d: date,
|
|
333
|
+
*,
|
|
334
|
+
trades: pl.DataFrame | None = None,
|
|
335
|
+
client: MassiveClient | None = None,
|
|
336
|
+
) -> pl.DataFrame:
|
|
337
|
+
"""
|
|
338
|
+
Per-second OHLCV trade bars for ``underlying`` on ``d``.
|
|
339
|
+
|
|
340
|
+
By default, trades come from ``build_unadjusted_trades()``: this restricts
|
|
341
|
+
timestamps to the session but retains closing prints and official/corrected
|
|
342
|
+
closes. To exclude these conditions, pass
|
|
343
|
+
``trades=filter_valid_trades(underlying, d)`` explicitly.
|
|
344
|
+
|
|
345
|
+
Bin semantics:
|
|
346
|
+
|
|
347
|
+
* all bins except last: ``[t, t+1s)``
|
|
348
|
+
* last bin: ``[close_dt-1s, close_dt]`` (inclusive close)
|
|
349
|
+
|
|
350
|
+
Returns
|
|
351
|
+
-------
|
|
352
|
+
pl.DataFrame
|
|
353
|
+
Columns: dt_ns, second_bin_ix, bin_type, open, close, high, low, last_trade,
|
|
354
|
+
num_trades, vwap, log_cash_volume, log_volume, date, underlying, is_half_day
|
|
355
|
+
"""
|
|
356
|
+
# Only the default trade stream is cached; caller-supplied trades bypass the cache so that
|
|
357
|
+
# differently filtered inputs never share a cache entry.
|
|
358
|
+
if trades is not None:
|
|
359
|
+
return _build_1s_trade_bars(underlying, d, trades, client)
|
|
360
|
+
return _build_1s_trade_bars_cached(underlying, d, client=client)
|
|
361
|
+
|
|
362
|
+
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""
|
|
2
|
+
openqdata.massive.tickers.filtered_history
|
|
3
|
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
4
|
+
|
|
5
|
+
Adjusted daily bars for a ticker over a date range, handling ticker-change events
|
|
6
|
+
and filtering by minimum liquidity thresholds.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from datetime import date, timedelta
|
|
12
|
+
from typing import Optional
|
|
13
|
+
|
|
14
|
+
import polars as pl
|
|
15
|
+
from cdxcore.err import verify, verify_inp
|
|
16
|
+
from cdxcore.jcpool import JCPool
|
|
17
|
+
from cdxcore.util import fmt_date, fmt_digits
|
|
18
|
+
from cdxcore.verbose import Context
|
|
19
|
+
|
|
20
|
+
from openqdata.biz_calendar import prev_business_day
|
|
21
|
+
from openqdata.massive import MassiveClient
|
|
22
|
+
from openqdata.massive.tickers.basics import get_listing_date
|
|
23
|
+
from openqdata.tickers import SubDir, _locations_tickers
|
|
24
|
+
|
|
25
|
+
MIN_CASH_VOLUME_M = 10
|
|
26
|
+
MIN_NUM_TRADES = 1000
|
|
27
|
+
|
|
28
|
+
_history_cache = _locations_tickers
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@_history_cache(fmt=SubDir.POLARS_PARQUET).cache(
|
|
32
|
+
"0.2",
|
|
33
|
+
uid=lambda ticker, start, end, min_cash_volume_m, min_num_trades: (
|
|
34
|
+
f"filtered_history/m{min_cash_volume_m}_{min_num_trades}/{fmt_date(start)}_{fmt_date(end)}/{ticker}"
|
|
35
|
+
),
|
|
36
|
+
exclude_args=["verbose", "num_workers", "client"],
|
|
37
|
+
dependencies=[get_listing_date, MassiveClient],
|
|
38
|
+
)
|
|
39
|
+
def ticker_filtered_history(
|
|
40
|
+
ticker: str,
|
|
41
|
+
start: date,
|
|
42
|
+
end: date,
|
|
43
|
+
*,
|
|
44
|
+
min_cash_volume_m: float = MIN_CASH_VOLUME_M,
|
|
45
|
+
min_num_trades: int = MIN_NUM_TRADES,
|
|
46
|
+
num_workers: int = -2,
|
|
47
|
+
client: Optional[MassiveClient] = None,
|
|
48
|
+
verbose: Context = Context.quiet,
|
|
49
|
+
) -> pl.DataFrame:
|
|
50
|
+
"""
|
|
51
|
+
Adjusted daily bars for ``ticker`` between ``start`` and ``end``, handling ticker
|
|
52
|
+
changes and filtering by minimum liquidity.
|
|
53
|
+
|
|
54
|
+
Steps:
|
|
55
|
+
|
|
56
|
+
1. Resolve the listing date and verify the ticker is active.
|
|
57
|
+
2. Fetch ticker-change events to determine the correct symbol for each sub-period.
|
|
58
|
+
3. Download adjusted daily bars per sub-period via :meth:`MassiveClient.fetch_bars`.
|
|
59
|
+
4. Filter by ``min_cash_volume_m`` (USD millions) and ``min_num_trades``.
|
|
60
|
+
5. Compute log returns.
|
|
61
|
+
|
|
62
|
+
Parameters
|
|
63
|
+
----------
|
|
64
|
+
ticker : str
|
|
65
|
+
Current ticker symbol (used for events lookup).
|
|
66
|
+
start, end : date
|
|
67
|
+
Inclusive date range.
|
|
68
|
+
min_cash_volume_m : float
|
|
69
|
+
Minimum cash volume in millions of USD per day.
|
|
70
|
+
min_num_trades : int
|
|
71
|
+
Minimum number of trades per day.
|
|
72
|
+
num_workers : int
|
|
73
|
+
Parallel workers for bar downloads.
|
|
74
|
+
client : MassiveClient | None
|
|
75
|
+
Optional pre-constructed client.
|
|
76
|
+
verbose : Context
|
|
77
|
+
|
|
78
|
+
Returns
|
|
79
|
+
-------
|
|
80
|
+
pl.DataFrame
|
|
81
|
+
Columns: date, ticker, cash_vol, n_trades, return_open_prev_close, return_close_open
|
|
82
|
+
"""
|
|
83
|
+
client = MassiveClient() if client is None else client
|
|
84
|
+
verify_inp(start <= end, lambda: f"start {fmt_date(start)} must be <= end {fmt_date(end)}")
|
|
85
|
+
|
|
86
|
+
with verbose.write_t(lambda: f"Fetching listing date for {ticker}... ", end="") as tme:
|
|
87
|
+
list_date = get_listing_date(ticker, client=client)
|
|
88
|
+
verbose.write(f"done (list_date: {fmt_date(list_date)}); took {tme}.", head=False)
|
|
89
|
+
|
|
90
|
+
with verbose.write_t(lambda: f"Fetching ticker events for {ticker}... ", end="") as tme:
|
|
91
|
+
url = f"{MassiveClient.BASE_URL}/vX/reference/tickers/{ticker}/events"
|
|
92
|
+
response = client(url)
|
|
93
|
+
events_data = response.get("results", {}).get("events", [])
|
|
94
|
+
|
|
95
|
+
ticker_events = []
|
|
96
|
+
for event in events_data:
|
|
97
|
+
if event.get("type") == "ticker_change":
|
|
98
|
+
tc = event.get("ticker_change", {})
|
|
99
|
+
ev_ticker = tc.get("ticker")
|
|
100
|
+
ev_date_str = event.get("date")
|
|
101
|
+
verify(
|
|
102
|
+
ev_ticker is not None, lambda: f"Missing ticker in change event for {ticker}"
|
|
103
|
+
)
|
|
104
|
+
verify(
|
|
105
|
+
ev_date_str is not None, lambda: f"Missing date in change event for {ticker}"
|
|
106
|
+
)
|
|
107
|
+
ticker_events.append({"date": date.fromisoformat(ev_date_str), "ticker": ev_ticker})
|
|
108
|
+
|
|
109
|
+
if len(ticker_events) > 1:
|
|
110
|
+
ticker_events.sort(key=lambda x: x["date"])
|
|
111
|
+
min_test = max(start, list_date)
|
|
112
|
+
verify(
|
|
113
|
+
ticker_events[0]["date"] <= min_test,
|
|
114
|
+
lambda: (
|
|
115
|
+
f"Cannot identify historic ticker for {ticker} from {fmt_date(min_test)}: "
|
|
116
|
+
f"first change event is {ticker_events[0]['date']} → {ticker_events[0]['ticker']}"
|
|
117
|
+
),
|
|
118
|
+
)
|
|
119
|
+
else:
|
|
120
|
+
verify(
|
|
121
|
+
len(ticker_events) == 0 or ticker_events[0]["ticker"] == ticker,
|
|
122
|
+
lambda: f"Unexpected single change event for {ticker}: {ticker_events}",
|
|
123
|
+
)
|
|
124
|
+
ticker_events = [{"date": list_date, "ticker": ticker}]
|
|
125
|
+
|
|
126
|
+
verbose.write(f"done ({len(ticker_events)} events); took {tme}.", head=False)
|
|
127
|
+
|
|
128
|
+
effective_start = max(start, list_date)
|
|
129
|
+
verify_inp(
|
|
130
|
+
effective_start <= end,
|
|
131
|
+
lambda: (
|
|
132
|
+
f"Ticker {ticker}: effective start {fmt_date(effective_start)} is after end {fmt_date(end)}"
|
|
133
|
+
),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
ticker_events.append({"date": end + timedelta(days=1), "ticker": ticker})
|
|
137
|
+
# Fetch from the previous business day so the first day in range has an overnight return.
|
|
138
|
+
fetch_start = max(list_date, ticker_events[0]["date"], prev_business_day(start))
|
|
139
|
+
assert fetch_start >= ticker_events[0]["date"], (
|
|
140
|
+
f"Internal: fetch_start {fetch_start} < first event {ticker_events[0]['date']}"
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
ticker_ranges = []
|
|
144
|
+
current_start = fetch_start
|
|
145
|
+
while len(ticker_events) > 1:
|
|
146
|
+
while current_start >= ticker_events[0]["date"]:
|
|
147
|
+
current_ticker = ticker_events.pop(0)["ticker"]
|
|
148
|
+
ticker_ranges.append(
|
|
149
|
+
(current_ticker, current_start, ticker_events[0]["date"] - timedelta(days=1))
|
|
150
|
+
)
|
|
151
|
+
current_start = ticker_events[0]["date"]
|
|
152
|
+
|
|
153
|
+
all_bars = []
|
|
154
|
+
|
|
155
|
+
def _period_bars(ticker_for_range: str, range_start: date, range_end: date):
|
|
156
|
+
df = client.fetch_bars(
|
|
157
|
+
ticker_for_range, range_start, range_end, adjusted=True, timespan="day"
|
|
158
|
+
)
|
|
159
|
+
verify(
|
|
160
|
+
not df.is_empty(),
|
|
161
|
+
lambda: (
|
|
162
|
+
f"No bars for {ticker_for_range} from {fmt_date(range_start)} to {fmt_date(range_end)}"
|
|
163
|
+
),
|
|
164
|
+
)
|
|
165
|
+
df = df.with_columns(
|
|
166
|
+
pl.col("ts_ms").dt.date().alias("date"),
|
|
167
|
+
pl.col("open").cast(pl.Float32),
|
|
168
|
+
pl.col("close").cast(pl.Float32),
|
|
169
|
+
pl.col("num_trades").alias("n"),
|
|
170
|
+
pl.col("volume").cast(pl.Int64),
|
|
171
|
+
pl.col("vwap").cast(pl.Float32),
|
|
172
|
+
pl.lit(ticker_for_range).alias("ticker"),
|
|
173
|
+
).drop_nulls()
|
|
174
|
+
return ticker_for_range, range_start, range_end, df
|
|
175
|
+
|
|
176
|
+
with verbose.write_t(lambda: f"Downloading daily bars for {ticker}... ", end="") as tme:
|
|
177
|
+
jcpool = JCPool(num_workers, threading=True)
|
|
178
|
+
for t_, rs, re, df in jcpool.parallel(
|
|
179
|
+
jcpool.delayed(_period_bars)(t_, rs, re) for t_, rs, re in ticker_ranges
|
|
180
|
+
):
|
|
181
|
+
verbose.write(lambda: f"\r {t_} {fmt_date(rs)}–{fmt_date(re)}", end="")
|
|
182
|
+
all_bars.append(df)
|
|
183
|
+
|
|
184
|
+
with verbose.write_t(lambda: f"\rComputing metrics... ", end="") as tme:
|
|
185
|
+
df = pl.concat(all_bars).sort("date")
|
|
186
|
+
|
|
187
|
+
df = df.with_columns(
|
|
188
|
+
pl.when(pl.col("vwap").is_not_null() & pl.col("volume").is_not_null())
|
|
189
|
+
.then(pl.col("vwap") * pl.col("volume"))
|
|
190
|
+
.otherwise(pl.lit(0.0))
|
|
191
|
+
.alias("cash_volume")
|
|
192
|
+
)
|
|
193
|
+
df = df.filter(
|
|
194
|
+
pl.col("open").is_not_null()
|
|
195
|
+
& pl.col("close").is_not_null()
|
|
196
|
+
& (pl.col("cash_volume") >= min_cash_volume_m * 1_000_000)
|
|
197
|
+
& (pl.col("n").fill_null(0) >= min_num_trades)
|
|
198
|
+
)
|
|
199
|
+
verify(
|
|
200
|
+
not df.is_empty(),
|
|
201
|
+
lambda: (
|
|
202
|
+
f"No valid bars for {ticker} after filtering at "
|
|
203
|
+
f"{fmt_digits(min_cash_volume_m)}m$ cash vol / {fmt_digits(min_num_trades)} trades"
|
|
204
|
+
),
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
df = df.sort("date").with_columns(pl.col("close").shift(1).alias("prev_close"))
|
|
208
|
+
|
|
209
|
+
df = df.with_columns(
|
|
210
|
+
pl.when(
|
|
211
|
+
pl.col("open").is_not_null()
|
|
212
|
+
& pl.col("prev_close").is_not_null()
|
|
213
|
+
& (pl.col("open") > 0)
|
|
214
|
+
& (pl.col("prev_close") > 0)
|
|
215
|
+
)
|
|
216
|
+
.then((pl.col("open") / pl.col("prev_close")).log())
|
|
217
|
+
.otherwise(0.0)
|
|
218
|
+
.cast(pl.Float32)
|
|
219
|
+
.alias("return_open_prev_close"),
|
|
220
|
+
pl.when(
|
|
221
|
+
pl.col("close").is_not_null()
|
|
222
|
+
& pl.col("open").is_not_null()
|
|
223
|
+
& (pl.col("close") > 0)
|
|
224
|
+
& (pl.col("open") > 0)
|
|
225
|
+
)
|
|
226
|
+
.then((pl.col("close") / pl.col("open")).log())
|
|
227
|
+
.otherwise(0.0)
|
|
228
|
+
.cast(pl.Float32)
|
|
229
|
+
.alias("return_close_open"),
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
df = df.with_columns(
|
|
233
|
+
(pl.col("cash_volume") + 1.0).log10().cast(pl.Float32).alias("cash_vol")
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
df = df.filter(pl.col("date") >= start)
|
|
237
|
+
|
|
238
|
+
df = df.select(
|
|
239
|
+
"date",
|
|
240
|
+
"ticker",
|
|
241
|
+
"cash_vol",
|
|
242
|
+
pl.col("n").cast(pl.Int32).alias("n_trades"),
|
|
243
|
+
"return_open_prev_close",
|
|
244
|
+
"return_close_open",
|
|
245
|
+
)
|
|
246
|
+
verify(
|
|
247
|
+
df.height > 0,
|
|
248
|
+
lambda: (
|
|
249
|
+
f"No valid rows remain for {ticker} from {fmt_date(effective_start)} to {fmt_date(end)}"
|
|
250
|
+
),
|
|
251
|
+
)
|
|
252
|
+
verbose.write(f"done ({df.height} rows); took {tme}.", head=False)
|
|
253
|
+
|
|
254
|
+
return df
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
if __name__ == "__main__":
|
|
258
|
+
from openqdata.cli import run_module
|
|
259
|
+
|
|
260
|
+
run_module(globals())
|