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,447 @@
|
|
|
1
|
+
"""
|
|
2
|
+
openqdata.massive.processing
|
|
3
|
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
4
|
+
|
|
5
|
+
Some simple tools to make life easier when working with Massive data.
|
|
6
|
+
These are not meant to be comprehensive utilities, but rather simple examples of how to filter and align trades and quotes.
|
|
7
|
+
|
|
8
|
+
Function in this file:
|
|
9
|
+
|
|
10
|
+
* :func:`filter_valid_trades` removes trades with invalid timestamps, prices, sizes, or trade codes.
|
|
11
|
+
* :func:`filter_valid_quotes` removes quotes with invalid timestamps, prices, sizes, or crossed/locked markets.
|
|
12
|
+
* :func:`align_quotes_to_trades` matches each trade to a nearby valid quote based on price and timestamp criteria.
|
|
13
|
+
* :func:`align_trades_to_quotes` matches each quote to a nearby valid trade based on price and timestamp criteria.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from datetime import date
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import polars as pl
|
|
21
|
+
from cdxcore.err import verify, verify_inp
|
|
22
|
+
|
|
23
|
+
import openqdata
|
|
24
|
+
from openqdata import version
|
|
25
|
+
from openqdata.biz_calendar import session_open_close
|
|
26
|
+
from openqdata.massive.client import MassiveClient
|
|
27
|
+
from openqdata.massive.trade_conds import NORMAL_TRADE_EXCLUDE_FLAGS
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@version("0.1", dependencies=[openqdata.biz_calendar.session_open_close, openqdata.massive.client.MassiveClient.fetch_trades])
|
|
31
|
+
def filter_valid_trades(
|
|
32
|
+
ticker: str,
|
|
33
|
+
d: date,
|
|
34
|
+
within_session: bool = True,
|
|
35
|
+
) -> pl.DataFrame:
|
|
36
|
+
"""
|
|
37
|
+
Returns trades for a given underlying and date within session hours (optionally).
|
|
38
|
+
Always applies ``NORMAL_TRADE_EXCLUDE_FLAGS``: closing prints (condition IDs
|
|
39
|
+
8 and 19), official closes (15), corrected consolidated closes (38), opening
|
|
40
|
+
prints/official opens, crosses, contingent trades and data-quality exclusions
|
|
41
|
+
are removed. This condition filter also applies with ``within_session=False``;
|
|
42
|
+
that argument changes only the session-hours restriction. Odd lots are retained.
|
|
43
|
+
Trades with nonpositive prices or sizes are removed. Trades sharing a SIP
|
|
44
|
+
timestamp are aggregated using total size and volume-weighted price.
|
|
45
|
+
|
|
46
|
+
Use ``MassiveClient.fetch_trades()`` to retain closing-condition records.
|
|
47
|
+
|
|
48
|
+
Returns a polars data frame with :attr:`MassiveClient.SCHEMA_TRADES` schema with the following columns:
|
|
49
|
+
ts_ns Datetime[ns,tz]
|
|
50
|
+
price Float64
|
|
51
|
+
size Float64
|
|
52
|
+
trade_code UInt32 (semantic mask)
|
|
53
|
+
sequence_number UInt64. Sequence number of the trade for a given timestamp, useful for ordering trades with the same timestamp.
|
|
54
|
+
"""
|
|
55
|
+
client = MassiveClient()
|
|
56
|
+
trades = client.fetch_trades(ticker, d)
|
|
57
|
+
assert set(trades.columns) >= {"ts_ns", "price", "size", "trade_code", "sequence_number"}, (
|
|
58
|
+
"trades must have ts_ns, price, size, trade_code, sequence_number",
|
|
59
|
+
trades.columns,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
if not within_session:
|
|
63
|
+
trades = trades.filter(
|
|
64
|
+
pl.col("ts_ns").is_not_null()
|
|
65
|
+
& pl.col("price").is_not_null()
|
|
66
|
+
& pl.col("size").is_not_null()
|
|
67
|
+
& pl.col("price").is_finite()
|
|
68
|
+
& pl.col("size").is_finite()
|
|
69
|
+
& ((pl.col("trade_code") & int(NORMAL_TRADE_EXCLUDE_FLAGS)) == 0)
|
|
70
|
+
& (pl.col("price") > 0)
|
|
71
|
+
& (pl.col("size") > 0)
|
|
72
|
+
)
|
|
73
|
+
else:
|
|
74
|
+
open_dt, close_dt, _ = session_open_close(d)
|
|
75
|
+
trades = trades.filter(
|
|
76
|
+
(pl.col("ts_ns") >= pl.lit(open_dt))
|
|
77
|
+
& (pl.col("ts_ns") <= pl.lit(close_dt))
|
|
78
|
+
& pl.col("price").is_not_null()
|
|
79
|
+
& pl.col("size").is_not_null()
|
|
80
|
+
& pl.col("price").is_finite()
|
|
81
|
+
& pl.col("size").is_finite()
|
|
82
|
+
& ((pl.col("trade_code") & int(NORMAL_TRADE_EXCLUDE_FLAGS)) == 0)
|
|
83
|
+
& (pl.col("price") > 0)
|
|
84
|
+
& (pl.col("size") > 0)
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
# Aggregate trades at same ts_ns: sum sizes and compute weighted average price
|
|
88
|
+
trades = trades.group_by("ts_ns", maintain_order=True).agg(
|
|
89
|
+
price=pl.when(pl.col("size").sum() > 0)
|
|
90
|
+
.then((pl.col("price") * pl.col("size")).sum() / pl.col("size").sum())
|
|
91
|
+
.otherwise(pl.col("price").first()),
|
|
92
|
+
size=pl.col("size").sum(),
|
|
93
|
+
trade_code=pl.col("trade_code").last(),
|
|
94
|
+
sequence_number=pl.col("sequence_number").last(),
|
|
95
|
+
).sort("ts_ns")
|
|
96
|
+
|
|
97
|
+
return trades
|
|
98
|
+
|
|
99
|
+
@version("0.1")
|
|
100
|
+
def valid_quote_mask() -> pl.Expr:
|
|
101
|
+
"""
|
|
102
|
+
Polars mask of usable quotes: timestamp present, finite positive bid and ask with ``bid < ask``
|
|
103
|
+
(crossed and locked markets are rejected), finite non-negative sizes that are not both zero.
|
|
104
|
+
"""
|
|
105
|
+
return (
|
|
106
|
+
pl.col("ts_ns").is_not_null()
|
|
107
|
+
& pl.col("bid_price").is_not_null()
|
|
108
|
+
& pl.col("ask_price").is_not_null()
|
|
109
|
+
& pl.col("bid_price").is_finite()
|
|
110
|
+
& pl.col("ask_price").is_finite()
|
|
111
|
+
& (pl.col("bid_price") > 0.0)
|
|
112
|
+
& (pl.col("ask_price") > 0.0)
|
|
113
|
+
& (pl.col("ask_price") > pl.col("bid_price"))
|
|
114
|
+
& pl.col("bid_size").is_not_null()
|
|
115
|
+
& pl.col("ask_size").is_not_null()
|
|
116
|
+
& pl.col("bid_size").is_finite()
|
|
117
|
+
& pl.col("ask_size").is_finite()
|
|
118
|
+
& (pl.col("bid_size") >= 0.0)
|
|
119
|
+
& (pl.col("ask_size") >= 0.0)
|
|
120
|
+
& ((pl.col("bid_size") + pl.col("ask_size")) > 0.0)
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
@version("0.1", dependencies=[openqdata.biz_calendar.session_open_close, openqdata.massive.client.MassiveClient.fetch_quotes, valid_quote_mask])
|
|
124
|
+
def filter_valid_quotes(
|
|
125
|
+
ticker: str,
|
|
126
|
+
d: date,
|
|
127
|
+
within_session: bool = True,
|
|
128
|
+
) -> pl.DataFrame:
|
|
129
|
+
"""
|
|
130
|
+
Returns quotes for a given underlying and date within session hours (optionally).
|
|
131
|
+
Removes quotes with invalid timestamps, prices, sizes, or crossed/locked markets.
|
|
132
|
+
|
|
133
|
+
Returns a polars data frame with :attr:`MassiveClient.SCHEMA_QUOTES` schema with the following columns:
|
|
134
|
+
ts_ns Datetime[ns,tz]
|
|
135
|
+
bid_price Float64
|
|
136
|
+
bid_size Float64
|
|
137
|
+
ask_price Float64
|
|
138
|
+
ask_size Float64
|
|
139
|
+
"""
|
|
140
|
+
client = MassiveClient()
|
|
141
|
+
quotes = client.fetch_quotes(ticker, d)
|
|
142
|
+
assert set(quotes.columns) >= {"ts_ns", "bid_price", "bid_size", "ask_price", "ask_size"}, (
|
|
143
|
+
"quotes must have ts_ns, bid_price, bid_size, ask_price, ask_size",
|
|
144
|
+
quotes.columns,
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
valid_quotes = valid_quote_mask()
|
|
148
|
+
|
|
149
|
+
if within_session:
|
|
150
|
+
open_dt, close_dt, _ = session_open_close(d)
|
|
151
|
+
valid_quotes = (
|
|
152
|
+
(pl.col("ts_ns") >= pl.lit(open_dt))
|
|
153
|
+
& (pl.col("ts_ns") <= pl.lit(close_dt))
|
|
154
|
+
& valid_quotes
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
# Aggregate quotes at same ts_ns: keep only the last one by sequence_number
|
|
158
|
+
quotes = (
|
|
159
|
+
quotes.filter(valid_quotes)
|
|
160
|
+
.group_by("ts_ns", maintain_order=True)
|
|
161
|
+
.last()
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
return quotes
|
|
165
|
+
|
|
166
|
+
@version("0.1")
|
|
167
|
+
@dataclass(frozen=True)
|
|
168
|
+
class TradeQuoteAlignmentConfig:
|
|
169
|
+
"""
|
|
170
|
+
Configuration for matching trades to nearby valid quotes.
|
|
171
|
+
Times are in milliseconds. These settings control matching windows only;
|
|
172
|
+
alignment always uses ``filter_valid_trades()``, excluding closing prints
|
|
173
|
+
and official/corrected closes through ``NORMAL_TRADE_EXCLUDE_FLAGS``.
|
|
174
|
+
"""
|
|
175
|
+
lookback_ms: int = 250 # how many milliseconds to look back
|
|
176
|
+
lookfwd_ms: int = 250 # how many milliseconds to look forward
|
|
177
|
+
|
|
178
|
+
def __post_init__(self):
|
|
179
|
+
verify_inp(self.lookback_ms >= 0, f"lookback_ms must be non-negative, found {self.lookback_ms}")
|
|
180
|
+
verify_inp(self.lookfwd_ms >= 0, f"lookfwd_ms must be non-negative, found {self.lookfwd_ms}")
|
|
181
|
+
|
|
182
|
+
def __str__(self):
|
|
183
|
+
return f"bck={self.lookback_ms},fwd={self.lookfwd_ms})"
|
|
184
|
+
|
|
185
|
+
def _ts_ns(df: pl.DataFrame) -> np.ndarray:
|
|
186
|
+
return df.select(pl.col("ts_ns").cast(pl.Int64)).to_series().to_numpy()
|
|
187
|
+
|
|
188
|
+
def _find_quote(
|
|
189
|
+
bid_price: np.ndarray,
|
|
190
|
+
ask_price: np.ndarray,
|
|
191
|
+
price: float,
|
|
192
|
+
left: int,
|
|
193
|
+
right: int,
|
|
194
|
+
prefer_last: bool,
|
|
195
|
+
) -> int:
|
|
196
|
+
if left == right:
|
|
197
|
+
return -1
|
|
198
|
+
valid = np.flatnonzero((bid_price[left:right] <= price) & (price <= ask_price[left:right]))
|
|
199
|
+
if len(valid) == 0:
|
|
200
|
+
return -1
|
|
201
|
+
return left + (valid[-1] if prefer_last else valid[0])
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _find_trade(
|
|
205
|
+
trade_price: np.ndarray,
|
|
206
|
+
bid: float,
|
|
207
|
+
ask: float,
|
|
208
|
+
left: int,
|
|
209
|
+
right: int,
|
|
210
|
+
prefer_last: bool,
|
|
211
|
+
) -> int:
|
|
212
|
+
if left == right:
|
|
213
|
+
return -1
|
|
214
|
+
valid = np.flatnonzero((bid <= trade_price[left:right]) & (trade_price[left:right] <= ask))
|
|
215
|
+
if len(valid) == 0:
|
|
216
|
+
return -1
|
|
217
|
+
return left + (valid[-1] if prefer_last else valid[0])
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
SCHEMA_ALIGN_QUOTES_TO_TRADES = {
|
|
221
|
+
"ts_ns": np.dtype("datetime64[ns]"),
|
|
222
|
+
"price": np.float64,
|
|
223
|
+
"size": np.float64,
|
|
224
|
+
"trade_code": np.uint32,
|
|
225
|
+
"quote_ts_ns": np.dtype("datetime64[ns]"),
|
|
226
|
+
"bid_price": np.float64,
|
|
227
|
+
"bid_size": np.float64,
|
|
228
|
+
"ask_price": np.float64,
|
|
229
|
+
"ask_size": np.float64,
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
@version("0.1", dependencies=[filter_valid_quotes, filter_valid_trades, TradeQuoteAlignmentConfig])
|
|
233
|
+
def align_quotes_to_trades(
|
|
234
|
+
ticker: str,
|
|
235
|
+
d: date,
|
|
236
|
+
drop_unmatched: bool,
|
|
237
|
+
config: TradeQuoteAlignmentConfig = TradeQuoteAlignmentConfig(), *,
|
|
238
|
+
within_session: bool = True,
|
|
239
|
+
) -> pl.DataFrame:
|
|
240
|
+
"""
|
|
241
|
+
Fetch valid trades and quotes for ``ticker`` on ``d`` and align them on a common timeline.
|
|
242
|
+
|
|
243
|
+
Trade selection uses ``filter_valid_trades()`` and always excludes closing
|
|
244
|
+
prints and official/corrected closes, along with the other
|
|
245
|
+
``NORMAL_TRADE_EXCLUDE_FLAGS``. Setting ``within_session=False`` does not
|
|
246
|
+
restore these trades. Odd lots are retained.
|
|
247
|
+
|
|
248
|
+
For each trade, this first finds the latest quote between ``config.lookback_ms``
|
|
249
|
+
and the trade timestamp where ``bid_price <= price <= ask_price``. If no such
|
|
250
|
+
quote exists, it finds the first matching quote up to ``config.lookfwd_ms`` after
|
|
251
|
+
the trade.
|
|
252
|
+
|
|
253
|
+
The output keeps all trade columns and adds the matched quote columns. If
|
|
254
|
+
``drop_unmatched`` is False, unmatched trades have null quote fields.
|
|
255
|
+
|
|
256
|
+
Parameters
|
|
257
|
+
----------
|
|
258
|
+
ticker : str
|
|
259
|
+
The underlying ticker to fetch trades and quotes for.
|
|
260
|
+
d : :class:`datetime.date`
|
|
261
|
+
The date to fetch trades and quotes for.
|
|
262
|
+
drop_unmatched : bool
|
|
263
|
+
If True, only keep trades with a matched quote. If False, keep all trades and have null quote fields for unmatched trades.
|
|
264
|
+
config : :class:`TradeQuoteAlignmentConfig`, default ``TradeQuoteAlignmentConfig()``
|
|
265
|
+
Configuration for matching trades to nearby valid quotes.
|
|
266
|
+
within_session : bool, default True
|
|
267
|
+
Whether to only consider trades and quotes within session hours when aligning.
|
|
268
|
+
"""
|
|
269
|
+
trades = filter_valid_trades(ticker, d, within_session=within_session).sort("ts_ns").drop("sequence_number")
|
|
270
|
+
quotes = filter_valid_quotes(ticker, d, within_session=within_session).sort("ts_ns").drop("sequence_number")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
trade_ts = _ts_ns(trades)
|
|
274
|
+
quote_ts = _ts_ns(quotes)
|
|
275
|
+
trade_price = trades["price"].to_numpy() if "price" in trades.columns else np.array([], dtype=float)
|
|
276
|
+
bid_price = quotes["bid_price"].to_numpy() if "bid_price" in quotes.columns else np.array([], dtype=float)
|
|
277
|
+
ask_price = quotes["ask_price"].to_numpy() if "ask_price" in quotes.columns else np.array([], dtype=float)
|
|
278
|
+
|
|
279
|
+
matched_rows = np.full(len(trades), -1, dtype=np.int64)
|
|
280
|
+
lookback_ns = int(config.lookback_ms) * 1_000_000
|
|
281
|
+
lookfwd_ns = int(config.lookfwd_ms) * 1_000_000
|
|
282
|
+
|
|
283
|
+
for i, (ts, price) in enumerate(zip(trade_ts, trade_price, strict=True)):
|
|
284
|
+
quote_row = _find_quote(
|
|
285
|
+
bid_price=bid_price,
|
|
286
|
+
ask_price=ask_price,
|
|
287
|
+
price=price,
|
|
288
|
+
left=np.searchsorted(quote_ts, ts - lookback_ns, side="left"),
|
|
289
|
+
right=np.searchsorted(quote_ts, ts, side="right"),
|
|
290
|
+
prefer_last=True,
|
|
291
|
+
)
|
|
292
|
+
if quote_row < 0:
|
|
293
|
+
quote_row = _find_quote(
|
|
294
|
+
bid_price=bid_price,
|
|
295
|
+
ask_price=ask_price,
|
|
296
|
+
price=price,
|
|
297
|
+
left=np.searchsorted(quote_ts, ts, side="left"),
|
|
298
|
+
right=np.searchsorted(quote_ts, ts + lookfwd_ns, side="right"),
|
|
299
|
+
prefer_last=False,
|
|
300
|
+
)
|
|
301
|
+
if quote_row < 0:
|
|
302
|
+
continue
|
|
303
|
+
matched_rows[i] = quote_row
|
|
304
|
+
|
|
305
|
+
out = (
|
|
306
|
+
trades.with_row_index("_trade_row")
|
|
307
|
+
.with_columns(
|
|
308
|
+
pl.Series("_quote_row", matched_rows),
|
|
309
|
+
)
|
|
310
|
+
.join(
|
|
311
|
+
quotes.with_row_index("_quote_row")
|
|
312
|
+
.with_columns(pl.col("_quote_row").cast(pl.Int64))
|
|
313
|
+
.rename({"ts_ns": "quote_ts_ns"}),
|
|
314
|
+
on="_quote_row",
|
|
315
|
+
how="left",
|
|
316
|
+
)
|
|
317
|
+
.sort("_trade_row")
|
|
318
|
+
.drop("_trade_row", "_quote_row")
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
assert out["ts_ns"].is_not_null().all(), "Found null values in 'ts_ns' after filtering unmatched quotes."
|
|
322
|
+
assert out["price"].is_not_null().all(), "Found null values in 'price' after filtering unmatched quotes."
|
|
323
|
+
assert out["size"].is_not_null().all(), "Found null values in 'size' after filtering unmatched quotes."
|
|
324
|
+
assert out["trade_code"].is_not_null().all(), "Found null values in 'trade_code' after filtering unmatched quotes."
|
|
325
|
+
|
|
326
|
+
if drop_unmatched:
|
|
327
|
+
out = out.filter(pl.col("quote_ts_ns").is_not_null())
|
|
328
|
+
assert out["quote_ts_ns"].is_not_null().all(), "Found null values in 'ts_ns' after filtering unmatched quotes."
|
|
329
|
+
assert out["bid_price"].is_not_null().all(), "Found null values in 'bid_price' after filtering unmatched quotes."
|
|
330
|
+
assert out["ask_price"].is_not_null().all(), "Found null values in 'ask_price' after filtering unmatched quotes."
|
|
331
|
+
assert out["bid_size"].is_not_null().all(), "Found null values in 'bid_size' after filtering unmatched quotes."
|
|
332
|
+
assert out["ask_size"].is_not_null().all(), "Found null values in 'ask_size' after filtering unmatched quotes."
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
verify(set(out.columns) == set(SCHEMA_ALIGN_QUOTES_TO_TRADES), f"Output is missing expected columns: {sorted(set(SCHEMA_ALIGN_QUOTES_TO_TRADES) - set(out.columns))} and has superfluous columns: {sorted(set(out.columns) - set(SCHEMA_ALIGN_QUOTES_TO_TRADES))}")
|
|
336
|
+
return out
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
SCHEMA_ALIGN_TRADES_TO_QUOTES = {
|
|
340
|
+
"ts_ns": np.dtype("datetime64[ns]"),
|
|
341
|
+
"bid_price": np.float64,
|
|
342
|
+
"bid_size": np.float64,
|
|
343
|
+
"ask_price": np.float64,
|
|
344
|
+
"ask_size": np.float64,
|
|
345
|
+
"trade_ts_ns": np.dtype("datetime64[ns]"),
|
|
346
|
+
"price": np.float64,
|
|
347
|
+
"size": np.float64,
|
|
348
|
+
"trade_code": np.uint32,
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
@version("0.1", dependencies=[filter_valid_quotes, filter_valid_trades])
|
|
352
|
+
def align_trades_to_quotes(
|
|
353
|
+
ticker: str,
|
|
354
|
+
d: date,
|
|
355
|
+
drop_unmatched: bool,
|
|
356
|
+
config: TradeQuoteAlignmentConfig = TradeQuoteAlignmentConfig(),
|
|
357
|
+
*,
|
|
358
|
+
within_session: bool = True
|
|
359
|
+
) -> pl.DataFrame:
|
|
360
|
+
"""
|
|
361
|
+
Fetch valid trades and quotes for ``ticker`` on ``d`` and align trades onto quotes.
|
|
362
|
+
|
|
363
|
+
Trade selection uses ``filter_valid_trades()`` and always excludes closing
|
|
364
|
+
prints and official/corrected closes, along with the other
|
|
365
|
+
``NORMAL_TRADE_EXCLUDE_FLAGS``. Setting ``within_session=False`` does not
|
|
366
|
+
restore these trades. Odd lots are retained.
|
|
367
|
+
|
|
368
|
+
For each quote, this first finds the latest trade between ``config.lookback_ms``
|
|
369
|
+
and the quote timestamp where ``bid_price <= price <= ask_price``. If no such
|
|
370
|
+
trade exists, it finds the first matching trade up to ``config.lookfwd_ms`` after
|
|
371
|
+
the quote. The output keeps all quote columns and adds matched trade columns. If
|
|
372
|
+
``drop_unmatched`` is False, unmatched quotes have null trade fields.
|
|
373
|
+
|
|
374
|
+
Parameters
|
|
375
|
+
----------
|
|
376
|
+
ticker : str
|
|
377
|
+
The underlying ticker to fetch trades and quotes for.
|
|
378
|
+
d : :class:`datetime.date`
|
|
379
|
+
The date to fetch trades and quotes for.
|
|
380
|
+
drop_unmatched : bool
|
|
381
|
+
If True, only keep quotes with a matched trade. If False, keep all quotes and have null trade fields for unmatched quotes.
|
|
382
|
+
config : :class:`TradeQuoteAlignmentConfig`, default ``TradeQuoteAlignmentConfig()``
|
|
383
|
+
Configuration for matching trades to nearby valid quotes.
|
|
384
|
+
within_session : bool, default True
|
|
385
|
+
Whether to only consider trades and quotes within session hours when aligning.
|
|
386
|
+
"""
|
|
387
|
+
trades = filter_valid_trades(ticker, d, within_session=within_session).sort("ts_ns").drop("sequence_number")
|
|
388
|
+
quotes = filter_valid_quotes(ticker, d, within_session=within_session).sort("ts_ns").drop("sequence_number")
|
|
389
|
+
|
|
390
|
+
trade_ts = _ts_ns(trades)
|
|
391
|
+
quote_ts = _ts_ns(quotes)
|
|
392
|
+
trade_price = trades["price"].to_numpy() if "price" in trades.columns else np.array([], dtype=float)
|
|
393
|
+
bid_price = quotes["bid_price"].to_numpy() if "bid_price" in quotes.columns else np.array([], dtype=float)
|
|
394
|
+
ask_price = quotes["ask_price"].to_numpy() if "ask_price" in quotes.columns else np.array([], dtype=float)
|
|
395
|
+
|
|
396
|
+
matched_rows = np.full(len(quotes), -1, dtype=np.int64)
|
|
397
|
+
lookback_ns = int(config.lookback_ms) * 1_000_000
|
|
398
|
+
lookfwd_ns = int(config.lookfwd_ms) * 1_000_000
|
|
399
|
+
|
|
400
|
+
for i, (ts, bid, ask) in enumerate(zip(quote_ts, bid_price, ask_price, strict=True)):
|
|
401
|
+
trade_row = _find_trade(
|
|
402
|
+
trade_price=trade_price,
|
|
403
|
+
bid=bid,
|
|
404
|
+
ask=ask,
|
|
405
|
+
left=np.searchsorted(trade_ts, ts - lookback_ns, side="left"),
|
|
406
|
+
right=np.searchsorted(trade_ts, ts, side="right"),
|
|
407
|
+
prefer_last=True,
|
|
408
|
+
)
|
|
409
|
+
if trade_row < 0:
|
|
410
|
+
trade_row = _find_trade(
|
|
411
|
+
trade_price=trade_price,
|
|
412
|
+
bid=bid,
|
|
413
|
+
ask=ask,
|
|
414
|
+
left=np.searchsorted(trade_ts, ts, side="left"),
|
|
415
|
+
right=np.searchsorted(trade_ts, ts + lookfwd_ns, side="right"),
|
|
416
|
+
prefer_last=False,
|
|
417
|
+
)
|
|
418
|
+
if trade_row < 0:
|
|
419
|
+
continue
|
|
420
|
+
matched_rows[i] = trade_row
|
|
421
|
+
|
|
422
|
+
out = (
|
|
423
|
+
quotes.with_row_index("_quote_row")
|
|
424
|
+
.with_columns(
|
|
425
|
+
pl.Series("_trade_row", matched_rows),
|
|
426
|
+
)
|
|
427
|
+
.join(
|
|
428
|
+
trades.with_row_index("_trade_row")
|
|
429
|
+
.with_columns(pl.col("_trade_row").cast(pl.Int64))
|
|
430
|
+
.rename({"ts_ns": "trade_ts_ns"}),
|
|
431
|
+
on="_trade_row",
|
|
432
|
+
how="left",
|
|
433
|
+
)
|
|
434
|
+
.sort("_quote_row")
|
|
435
|
+
.drop("_quote_row", "_trade_row")
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
if drop_unmatched:
|
|
439
|
+
out = out.filter(pl.col("trade_ts_ns").is_not_null())
|
|
440
|
+
verify(set(out.columns) == set(SCHEMA_ALIGN_TRADES_TO_QUOTES), f"Output is missing expected columns: {sorted(set(SCHEMA_ALIGN_TRADES_TO_QUOTES) - set(out.columns))} and has superfluous columns: {sorted(set(out.columns) - set(SCHEMA_ALIGN_TRADES_TO_QUOTES))}")
|
|
441
|
+
return out
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
if __name__ == "__main__":
|
|
445
|
+
from openqdata.cli import run_module
|
|
446
|
+
|
|
447
|
+
run_module(globals())
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Generate massive test data
|
|
3
|
+
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
4
|
+
|
|
5
|
+
python -m generate
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
from openqdata import env # triggers construction of caches.
|
|
11
|
+
from openqdata.massive.testing.scope import DATES, TICKERS
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def generate_day(ticker, d):
|
|
15
|
+
from openqdata.massive.client import MassiveClient
|
|
16
|
+
from openqdata.massive.processing import (
|
|
17
|
+
align_quotes_to_trades,
|
|
18
|
+
align_trades_to_quotes,
|
|
19
|
+
filter_valid_quotes,
|
|
20
|
+
filter_valid_trades,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
client = MassiveClient()
|
|
24
|
+
ocv = client.fetch_day_summary(ticker, d, adjusted=True)
|
|
25
|
+
print(ocv)
|
|
26
|
+
ocv = client.fetch_day_summary(ticker, d, adjusted=False)
|
|
27
|
+
print(ocv)
|
|
28
|
+
trades = client.fetch_trades(ticker, d) # raw trades retain condition flags; filtering below applies NORMAL_TRADE_EXCLUDE_FLAGS
|
|
29
|
+
print(trades)
|
|
30
|
+
quotes = client.fetch_quotes(ticker, d)
|
|
31
|
+
print(quotes)
|
|
32
|
+
v = filter_valid_trades(ticker, d, True)
|
|
33
|
+
print(v)
|
|
34
|
+
v = filter_valid_quotes(ticker, d, False)
|
|
35
|
+
print(v)
|
|
36
|
+
v = align_quotes_to_trades(ticker, d, drop_unmatched = True)
|
|
37
|
+
print(v)
|
|
38
|
+
v = align_quotes_to_trades(ticker, d, drop_unmatched = False)
|
|
39
|
+
print(v)
|
|
40
|
+
v = align_trades_to_quotes(ticker, d, drop_unmatched = True)
|
|
41
|
+
print(v)
|
|
42
|
+
v = align_trades_to_quotes(ticker, d, drop_unmatched = False)
|
|
43
|
+
print(v)
|
|
44
|
+
v = align_quotes_to_trades(ticker, d, drop_unmatched = True, within_session = False)
|
|
45
|
+
print(v)
|
|
46
|
+
v = align_quotes_to_trades(ticker, d, drop_unmatched = False, within_session = False)
|
|
47
|
+
print(v)
|
|
48
|
+
v = align_trades_to_quotes(ticker, d, drop_unmatched = True, within_session = False)
|
|
49
|
+
print(v)
|
|
50
|
+
v = align_trades_to_quotes(ticker, d, drop_unmatched = False, within_session = False)
|
|
51
|
+
print(v)
|
|
52
|
+
|
|
53
|
+
def main():
|
|
54
|
+
env.require_live("fixture generation")
|
|
55
|
+
for ticker in TICKERS:
|
|
56
|
+
for d in DATES:
|
|
57
|
+
print(f"Generating data for {ticker} {d}")
|
|
58
|
+
generate_day(ticker, d)
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
main()
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""
|
|
2
|
+
WIDB Testing scope for locally stored sample testing data
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from openqdata.biz_calendar import next_business_day
|
|
6
|
+
|
|
7
|
+
TICKERS = ["FICO", "TDG"]
|
|
8
|
+
DATES = [next_business_day(d) for d in ["2025-11-18", "2024-03-04", "2025-01-02", "2024-12-24", "2023-07-05", "2021-07-06"]]
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""
|
|
2
|
+
openqdata.massive.tickers.basics
|
|
3
|
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
4
|
+
|
|
5
|
+
Listing date and basic reference data for tickers via MassiveClient.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from datetime import date
|
|
11
|
+
|
|
12
|
+
from cdxcore.err import verify
|
|
13
|
+
from cdxcore.version import version
|
|
14
|
+
|
|
15
|
+
from openqdata.massive import MassiveClient
|
|
16
|
+
|
|
17
|
+
MANUAL_LISTING_DATES: dict[str, date] = {
|
|
18
|
+
"VXX": date(2019, 5, 1),
|
|
19
|
+
}
|
|
20
|
+
"""
|
|
21
|
+
Overrides for tickers whose Massive-reported list_date is too late to be used as the
|
|
22
|
+
data start date (e.g. a re-listed product).
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@version("0.1", dependencies=[MassiveClient.ticker_reference_data])
|
|
27
|
+
def get_listing_date(ticker: str, client: MassiveClient | None = None) -> date:
|
|
28
|
+
"""
|
|
29
|
+
Return the listing date for ``ticker``.
|
|
30
|
+
|
|
31
|
+
Applies :attr:`MANUAL_LISTING_DATES` overrides and raises if the ticker is not active.
|
|
32
|
+
|
|
33
|
+
Parameters
|
|
34
|
+
----------
|
|
35
|
+
ticker : str
|
|
36
|
+
Ticker symbol, e.g. "AAPL".
|
|
37
|
+
client : MassiveClient | None
|
|
38
|
+
Optional pre-constructed client; a new one is created if ``None``.
|
|
39
|
+
|
|
40
|
+
Returns
|
|
41
|
+
-------
|
|
42
|
+
date
|
|
43
|
+
The earlier of the Massive-reported list_date and any manual override (which corrects listing dates Massive reports too late).
|
|
44
|
+
"""
|
|
45
|
+
client = MassiveClient() if client is None else client
|
|
46
|
+
data = client.ticker_reference_data(ticker)
|
|
47
|
+
|
|
48
|
+
verify(
|
|
49
|
+
data.get("active", False),
|
|
50
|
+
lambda: f"Ticker {ticker} is not currently active on Massive",
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
list_date = data.get("list_date")
|
|
54
|
+
verify(
|
|
55
|
+
list_date is not None,
|
|
56
|
+
lambda: f"No list_date found for ticker {ticker} on Massive",
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
manual = MANUAL_LISTING_DATES.get(ticker, list_date)
|
|
60
|
+
return min(list_date, manual)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
if __name__ == "__main__":
|
|
64
|
+
from openqdata.cli import run_module
|
|
65
|
+
|
|
66
|
+
run_module(globals())
|