quantpad-data 0.8.5__tar.gz → 0.10.0__tar.gz

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 (25) hide show
  1. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/PKG-INFO +63 -16
  2. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/README.md +62 -15
  3. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/pyproject.toml +1 -1
  4. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/quantpad_data/__init__.py +9 -2
  5. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/quantpad_data/client.py +114 -1
  6. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/quantpad_data/errors.py +14 -0
  7. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/quantpad_data/v2.py +6 -3
  8. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/test_client.py +60 -0
  9. quantpad_data-0.10.0/tests/test_in_app_only.py +62 -0
  10. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/.gitignore +0 -0
  11. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/quantpad_data/cache.py +0 -0
  12. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/quantpad_data/lean.py +0 -0
  13. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/quantpad_data/memory.py +0 -0
  14. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/quantpad_data/py.typed +0 -0
  15. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/quantpad_data/rth.py +0 -0
  16. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/conftest.py +0 -0
  17. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/test_lean.py +0 -0
  18. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/test_message_encoding.py +0 -0
  19. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/test_packaging.py +0 -0
  20. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/test_refusal_hint.py +0 -0
  21. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/test_rth.py +0 -0
  22. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/test_v2.py +0 -0
  23. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/test_v2_cache.py +0 -0
  24. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/test_v2_gate.py +0 -0
  25. {quantpad_data-0.8.5 → quantpad_data-0.10.0}/tests/test_version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: quantpad-data
3
- Version: 0.8.5
3
+ Version: 0.10.0
4
4
  Summary: Official Python client for the QuantPad market-data API
5
5
  Project-URL: Documentation, https://api.quantpad.ai/external/docs
6
6
  Author: QuantPad
@@ -49,7 +49,7 @@ import time
49
49
  import quantpad_data as qpd
50
50
 
51
51
  end = int(time.time() * 1000)
52
- bars = qpd.get_bars("ES.FUT", "1m", end - 86_400_000, end)
52
+ bars = qpd.get_bars("SPY", "1m", end - 86_400_000, end)
53
53
 
54
54
  for chunk in qpd.get_ticks(
55
55
  "AAPL", "trades", end - 3_600_000, end, columns=["t", "price", "size"]
@@ -59,7 +59,7 @@ for chunk in qpd.get_ticks(
59
59
  # 10-level L2 market-by-price order-book depth. This streams chunks;
60
60
  # project columns to avoid materializing all 60+ book fields when unnecessary.
61
61
  for chunk in qpd.get_mbp10(
62
- "ES.FUT",
62
+ "AAPL",
63
63
  end - 3_600_000,
64
64
  end,
65
65
  columns=["t", "bid_px_00", "ask_px_00", "bid_sz_00", "ask_sz_00"],
@@ -80,16 +80,63 @@ connect timeouts are still retried, because failing to reach the service
80
80
  costs the service nothing.
81
81
  QuantPad notebooks remain compatible through `QUANTPAD_NOTEBOOK_DATA_TOKEN`.
82
82
 
83
+ ### CME futures data
84
+
85
+ CME futures data (dataset `GLBX.MDP3`: ES, NQ, CL and every other CME future
86
+ and option on futures) is available inside QuantPad only. With an API key the
87
+ SDK raises `InAppOnlyError` (a `PermissionDeniedError`) for it, with a message
88
+ saying so; `get_universe()` and `get_coverage()` still answer for CME
89
+ symbols. To work with CME data, create a new project at https://quantpad.ai
90
+ and run your code there: inside a project the same calls return it, and no
91
+ API key is needed.
92
+
93
+ ```python
94
+ try:
95
+ qpd.get_bars("ES.v.0", "1m", end - 86_400_000, end)
96
+ except qpd.InAppOnlyError as exc:
97
+ print(exc) # available inside QuantPad only; create a project to use it
98
+ ```
99
+
83
100
  Bars preserve the notebook helper's OHLCV aliases and smart futures
84
101
  back-adjustment default. Tick timestamps are epoch nanoseconds.
85
102
 
86
103
  `mbp-10` is true L2 depth with bid/ask price, size, and order-count fields at
87
- levels 0-9. It is available for supported CME futures, individual CME
88
- options-on-futures contracts, and US equities, subject to `get_coverage()` and
89
- the plan lookback window (currently 30 days).
104
+ levels 0-9. With an API key it is available for US equities, subject to
105
+ `get_coverage()` and the plan lookback window (currently 30 days).
106
+
107
+ This SDK intentionally exposes only bars, ticks, universe, coverage,
108
+ symbology, and SEC insider transactions. It does not proxy FRED or SEC EDGAR.
109
+
110
+ ## SEC insider transactions
111
+
112
+ `get_insider_transactions` returns QuantPad's cleaned copy of the SEC's public
113
+ Form 3/4/5 filings: every transaction line since 2006, refreshed nightly. The
114
+ filings themselves are public domain; what the service adds is the cleaning:
115
+
116
+ - amendments (4/A) applied, so a corrected trade replaces the original;
117
+ - a trade filed separately by several members of a group (a fund, its general
118
+ partner, its principals) counted once;
119
+ - weighted-average price ranges and Rule 10b5-1 plans read from the footnotes;
120
+ - price typos flagged or corrected (a total value or a share count typed as
121
+ the price), checked within each security class (ADS vs ordinary shares);
122
+ - tickers that follow a company through renames.
123
+
124
+ ```python
125
+ # open-market buys and sells at one company
126
+ df = qpd.get_insider_transactions("NVDA", start="2020-01-01", signal=True)
127
+
128
+ # everything one insider filed, at every company
129
+ df = qpd.get_insider_transactions(owner_cik=1214156)
130
+
131
+ # market-wide open-market purchases (fetched a year at a time)
132
+ buys = qpd.get_insider_transactions(start="2025-01-01", end="2025-04-01",
133
+ codes="P", signal=True)
134
+ ```
90
135
 
91
- This SDK intentionally exposes only bars, ticks, universe, coverage, and
92
- symbology. It does not proxy FRED or SEC EDGAR.
136
+ `signal=True` keeps open-market purchases (`P`) and sales (`S`) that are
137
+ current, counted once, and sanely priced. For a backtest, use `accepted_at`
138
+ (UTC), or the end of `filed_date` where it is null, as the event time; never
139
+ `trans_date`, because insiders have two business days to file.
93
140
 
94
141
  ## Explicit addressing: `qpd.v2`
95
142
 
@@ -103,7 +150,7 @@ symbology. It does not proxy FRED or SEC EDGAR.
103
150
 
104
151
  The helpers above infer which dataset a symbol lives in and what kind of
105
152
  symbol it is. That is convenient until it is wrong, and when it is wrong it
106
- fails quietly — asking for a specific futures contract returns an empty frame
153
+ fails quietly: a symbol looked up on the wrong venue returns an empty frame
107
154
  that looks exactly like a coverage gap.
108
155
 
109
156
  `qpd.v2.Historical` removes the inference. Every call names its dataset and
@@ -115,18 +162,18 @@ import quantpad_data as qpd
115
162
  client = qpd.v2.Historical()
116
163
 
117
164
  bars = client.timeseries.get_range(
118
- dataset="GLBX.MDP3", # required — never guessed
119
- symbols="ESZ6", # a specific contract month
165
+ dataset="XNAS.ITCH", # required, never guessed
166
+ symbols="AAPL",
120
167
  stype_in="raw_symbol", # raw_symbol | instrument_id | parent | continuous
121
168
  schema="ohlcv-1m",
122
169
  start="2026-01-05",
123
170
  end="2026-01-06",
124
171
  )
125
172
 
126
- # What actually answered, so you can confirm it was the contract you meant.
173
+ # What actually answered, so you can confirm it was the instrument you meant.
127
174
  print(bars.attrs["quantpad"])
128
- # {'dataset': 'GLBX.MDP3', 'stype_in': 'raw_symbol',
129
- # 'resolved': 'ESZ6=651968', 'clamped': False, ...}
175
+ # {'dataset': 'XNAS.ITCH', 'stype_in': 'raw_symbol',
176
+ # 'resolved': 'AAPL=<instrument_id>', 'clamped': False, ...}
130
177
  ```
131
178
 
132
179
  Every response reports the address it used, and a window that had to be
@@ -154,7 +201,7 @@ delivery path with `mode="interactive"` or `mode="bulk"`, or stream day by day:
154
201
 
155
202
  ```python
156
203
  for day in client.timeseries.iter_range(
157
- dataset="GLBX.MDP3", symbols="ESZ6", schema="mbp-10",
204
+ dataset="XNAS.ITCH", symbols="AAPL", schema="trades",
158
205
  start="2026-01-05", end="2026-02-05",
159
206
  ):
160
207
  process(day)
@@ -170,7 +217,7 @@ the cache so ordinary `get_range` calls serve it from storage:
170
217
 
171
218
  ```python
172
219
  job = client.batch.submit(
173
- dataset="GLBX.MDP3", symbols="ESZ6", schema="mbp-10",
220
+ dataset="XNAS.ITCH", symbols="AAPL", schema="trades",
174
221
  start="2026-01-05", end="2026-02-05", hydrate=True,
175
222
  )
176
223
  client.batch.hydrate(job["job_id"])
@@ -27,7 +27,7 @@ import time
27
27
  import quantpad_data as qpd
28
28
 
29
29
  end = int(time.time() * 1000)
30
- bars = qpd.get_bars("ES.FUT", "1m", end - 86_400_000, end)
30
+ bars = qpd.get_bars("SPY", "1m", end - 86_400_000, end)
31
31
 
32
32
  for chunk in qpd.get_ticks(
33
33
  "AAPL", "trades", end - 3_600_000, end, columns=["t", "price", "size"]
@@ -37,7 +37,7 @@ for chunk in qpd.get_ticks(
37
37
  # 10-level L2 market-by-price order-book depth. This streams chunks;
38
38
  # project columns to avoid materializing all 60+ book fields when unnecessary.
39
39
  for chunk in qpd.get_mbp10(
40
- "ES.FUT",
40
+ "AAPL",
41
41
  end - 3_600_000,
42
42
  end,
43
43
  columns=["t", "bid_px_00", "ask_px_00", "bid_sz_00", "ask_sz_00"],
@@ -58,16 +58,63 @@ connect timeouts are still retried, because failing to reach the service
58
58
  costs the service nothing.
59
59
  QuantPad notebooks remain compatible through `QUANTPAD_NOTEBOOK_DATA_TOKEN`.
60
60
 
61
+ ### CME futures data
62
+
63
+ CME futures data (dataset `GLBX.MDP3`: ES, NQ, CL and every other CME future
64
+ and option on futures) is available inside QuantPad only. With an API key the
65
+ SDK raises `InAppOnlyError` (a `PermissionDeniedError`) for it, with a message
66
+ saying so; `get_universe()` and `get_coverage()` still answer for CME
67
+ symbols. To work with CME data, create a new project at https://quantpad.ai
68
+ and run your code there: inside a project the same calls return it, and no
69
+ API key is needed.
70
+
71
+ ```python
72
+ try:
73
+ qpd.get_bars("ES.v.0", "1m", end - 86_400_000, end)
74
+ except qpd.InAppOnlyError as exc:
75
+ print(exc) # available inside QuantPad only; create a project to use it
76
+ ```
77
+
61
78
  Bars preserve the notebook helper's OHLCV aliases and smart futures
62
79
  back-adjustment default. Tick timestamps are epoch nanoseconds.
63
80
 
64
81
  `mbp-10` is true L2 depth with bid/ask price, size, and order-count fields at
65
- levels 0-9. It is available for supported CME futures, individual CME
66
- options-on-futures contracts, and US equities, subject to `get_coverage()` and
67
- the plan lookback window (currently 30 days).
82
+ levels 0-9. With an API key it is available for US equities, subject to
83
+ `get_coverage()` and the plan lookback window (currently 30 days).
84
+
85
+ This SDK intentionally exposes only bars, ticks, universe, coverage,
86
+ symbology, and SEC insider transactions. It does not proxy FRED or SEC EDGAR.
87
+
88
+ ## SEC insider transactions
89
+
90
+ `get_insider_transactions` returns QuantPad's cleaned copy of the SEC's public
91
+ Form 3/4/5 filings: every transaction line since 2006, refreshed nightly. The
92
+ filings themselves are public domain; what the service adds is the cleaning:
93
+
94
+ - amendments (4/A) applied, so a corrected trade replaces the original;
95
+ - a trade filed separately by several members of a group (a fund, its general
96
+ partner, its principals) counted once;
97
+ - weighted-average price ranges and Rule 10b5-1 plans read from the footnotes;
98
+ - price typos flagged or corrected (a total value or a share count typed as
99
+ the price), checked within each security class (ADS vs ordinary shares);
100
+ - tickers that follow a company through renames.
101
+
102
+ ```python
103
+ # open-market buys and sells at one company
104
+ df = qpd.get_insider_transactions("NVDA", start="2020-01-01", signal=True)
105
+
106
+ # everything one insider filed, at every company
107
+ df = qpd.get_insider_transactions(owner_cik=1214156)
108
+
109
+ # market-wide open-market purchases (fetched a year at a time)
110
+ buys = qpd.get_insider_transactions(start="2025-01-01", end="2025-04-01",
111
+ codes="P", signal=True)
112
+ ```
68
113
 
69
- This SDK intentionally exposes only bars, ticks, universe, coverage, and
70
- symbology. It does not proxy FRED or SEC EDGAR.
114
+ `signal=True` keeps open-market purchases (`P`) and sales (`S`) that are
115
+ current, counted once, and sanely priced. For a backtest, use `accepted_at`
116
+ (UTC), or the end of `filed_date` where it is null, as the event time; never
117
+ `trans_date`, because insiders have two business days to file.
71
118
 
72
119
  ## Explicit addressing: `qpd.v2`
73
120
 
@@ -81,7 +128,7 @@ symbology. It does not proxy FRED or SEC EDGAR.
81
128
 
82
129
  The helpers above infer which dataset a symbol lives in and what kind of
83
130
  symbol it is. That is convenient until it is wrong, and when it is wrong it
84
- fails quietly — asking for a specific futures contract returns an empty frame
131
+ fails quietly: a symbol looked up on the wrong venue returns an empty frame
85
132
  that looks exactly like a coverage gap.
86
133
 
87
134
  `qpd.v2.Historical` removes the inference. Every call names its dataset and
@@ -93,18 +140,18 @@ import quantpad_data as qpd
93
140
  client = qpd.v2.Historical()
94
141
 
95
142
  bars = client.timeseries.get_range(
96
- dataset="GLBX.MDP3", # required — never guessed
97
- symbols="ESZ6", # a specific contract month
143
+ dataset="XNAS.ITCH", # required, never guessed
144
+ symbols="AAPL",
98
145
  stype_in="raw_symbol", # raw_symbol | instrument_id | parent | continuous
99
146
  schema="ohlcv-1m",
100
147
  start="2026-01-05",
101
148
  end="2026-01-06",
102
149
  )
103
150
 
104
- # What actually answered, so you can confirm it was the contract you meant.
151
+ # What actually answered, so you can confirm it was the instrument you meant.
105
152
  print(bars.attrs["quantpad"])
106
- # {'dataset': 'GLBX.MDP3', 'stype_in': 'raw_symbol',
107
- # 'resolved': 'ESZ6=651968', 'clamped': False, ...}
153
+ # {'dataset': 'XNAS.ITCH', 'stype_in': 'raw_symbol',
154
+ # 'resolved': 'AAPL=<instrument_id>', 'clamped': False, ...}
108
155
  ```
109
156
 
110
157
  Every response reports the address it used, and a window that had to be
@@ -132,7 +179,7 @@ delivery path with `mode="interactive"` or `mode="bulk"`, or stream day by day:
132
179
 
133
180
  ```python
134
181
  for day in client.timeseries.iter_range(
135
- dataset="GLBX.MDP3", symbols="ESZ6", schema="mbp-10",
182
+ dataset="XNAS.ITCH", symbols="AAPL", schema="trades",
136
183
  start="2026-01-05", end="2026-02-05",
137
184
  ):
138
185
  process(day)
@@ -148,7 +195,7 @@ the cache so ordinary `get_range` calls serve it from storage:
148
195
 
149
196
  ```python
150
197
  job = client.batch.submit(
151
- dataset="GLBX.MDP3", symbols="ESZ6", schema="mbp-10",
198
+ dataset="XNAS.ITCH", symbols="AAPL", schema="trades",
152
199
  start="2026-01-05", end="2026-02-05", hydrate=True,
153
200
  )
154
201
  client.batch.hydrate(job["job_id"])
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "quantpad-data"
7
- version = "0.8.5"
7
+ version = "0.10.0"
8
8
  description = "Official Python client for the QuantPad market-data API"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -11,6 +11,7 @@ import pyarrow as pa
11
11
  from .client import Client, ROLL_ADJUST_MODES, TICK_SCHEMAS, USER_AGENT, VERSION
12
12
  from .errors import (
13
13
  AuthenticationError,
14
+ InAppOnlyError,
14
15
  IncompleteResponseError,
15
16
  NotFoundError,
16
17
  PermissionDeniedError,
@@ -89,6 +90,12 @@ def get_coverage(symbol: str):
89
90
  return _client().get_coverage(symbol)
90
91
 
91
92
 
93
+ def get_insider_transactions(ticker=None, **kwargs):
94
+ """SEC insider transactions (Forms 3/4/5); see
95
+ :meth:`Client.get_insider_transactions`."""
96
+ return _client().get_insider_transactions(ticker, **kwargs)
97
+
98
+
92
99
  def _iter_rth_windows_ms(start_ms: int, end_ms: int):
93
100
  try:
94
101
  import exchange_calendars as ec
@@ -212,13 +219,13 @@ TruncatedChainWarning = v2.TruncatedChainWarning
212
219
 
213
220
  __all__ = [
214
221
  "Client", "QuantPadClient", "QuantPadDataError", "QuantPadDataNotReady", "AuthenticationError",
215
- "PermissionDeniedError", "RateLimitError", "QuotaExceededError",
222
+ "PermissionDeniedError", "InAppOnlyError", "RateLimitError", "QuotaExceededError",
216
223
  "NotFoundError", "V2NotAvailableError", "ValidationError", "UpstreamError",
217
224
  "IncompleteResponseError", "ResponseTooLargeError", "TruncatedChainWarning", "TICK_SCHEMAS",
218
225
  "ROLL_ADJUST_MODES", "get_bars", "get_bars_with_retry", "get_ticks",
219
226
  "get_trades", "get_mbp1", "get_mbp10", "get_trades_rth", "get_mbp1_rth",
220
227
  "get_mbp10_rth", "get_spread_1m_rth", "symbology_resolve", "get_universe",
221
- "get_coverage", "iter_trades", "iter_mbp1", "iter_l1_df_chunks",
228
+ "get_coverage", "get_insider_transactions", "iter_trades", "iter_mbp1", "iter_l1_df_chunks",
222
229
  "iter_l1_trades_df_chunks", "iter_l1_mbp1_df_chunks", "cache", "lean",
223
230
  "v2", "Historical", "np", "pd", "pa",
224
231
  ]
@@ -19,6 +19,7 @@ from .errors import (
19
19
  AuthenticationError,
20
20
  IncompleteResponseError,
21
21
  NotFoundError,
22
+ InAppOnlyError,
22
23
  PermissionDeniedError,
23
24
  QuantPadDataError,
24
25
  QuotaExceededError,
@@ -87,7 +88,7 @@ V2_NOT_AVAILABLE = (
87
88
  "QuantPad support about /v2 access."
88
89
  )
89
90
 
90
- VERSION = "0.8.5"
91
+ VERSION = "0.10.0"
91
92
  USER_AGENT = f"quantpad-data-python/{VERSION}"
92
93
  TICK_SCHEMAS = (
93
94
  "trades", "mbp-1", "mbp-10", "cmbp-1", "tcbbo", "cbbo-1s",
@@ -209,6 +210,30 @@ def _prose_with_hint(error: dict) -> str:
209
210
  return str(message)
210
211
 
211
212
 
213
+ _INSIDER_DATE_COLS = (
214
+ "filed_date", "trans_date", "deemed_execution_date", "exercise_date", "expiration_date",
215
+ )
216
+ _INSIDER_NUMERIC_COLS = (
217
+ "shares", "price", "price_clean", "price_low", "price_high", "value",
218
+ "shares_owned_after", "conv_exercise_price", "underlying_shares",
219
+ )
220
+
221
+
222
+ def _insider_frame(rows: list[dict]) -> pd.DataFrame:
223
+ df = pd.DataFrame(rows)
224
+ if df.empty:
225
+ return df
226
+ for c in _INSIDER_DATE_COLS:
227
+ if c in df:
228
+ df[c] = pd.to_datetime(df[c], errors="coerce")
229
+ if "accepted_at" in df:
230
+ df["accepted_at"] = pd.to_datetime(df["accepted_at"], utc=True, errors="coerce")
231
+ for c in _INSIDER_NUMERIC_COLS:
232
+ if c in df:
233
+ df[c] = pd.to_numeric(df[c], errors="coerce")
234
+ return df
235
+
236
+
212
237
  class Client:
213
238
  def __init__(
214
239
  self,
@@ -304,6 +329,8 @@ class Client:
304
329
  if status == 401:
305
330
  raise AuthenticationError(message, status)
306
331
  if status == 403:
332
+ if isinstance(detail, dict) and detail.get("code") == InAppOnlyError.CODE:
333
+ raise InAppOnlyError(message, status, detail)
307
334
  raise PermissionDeniedError(message, status)
308
335
  if status == 404:
309
336
  raise NotFoundError(message)
@@ -541,3 +568,89 @@ class Client:
541
568
 
542
569
  def get_coverage(self, symbol: str) -> dict:
543
570
  return self._request("GET", "/v1/coverage", params={"symbol": symbol}).json()
571
+
572
+ def get_insider_transactions(
573
+ self,
574
+ ticker: str | None = None,
575
+ *,
576
+ issuer_cik: int | None = None,
577
+ owner_cik: int | None = None,
578
+ start: str | None = None,
579
+ end: str | None = None,
580
+ date_field: str = "filed",
581
+ codes: str | None = None,
582
+ kinds: str | None = None,
583
+ signal: bool = False,
584
+ include_superseded: bool = False,
585
+ include_duplicates: bool = False,
586
+ max_rows: int = 1_000_000,
587
+ ) -> pd.DataFrame:
588
+ """SEC insider transactions (Forms 3/4/5), one row per transaction line.
589
+
590
+ QuantPad's cleaned copy of the SEC's public filings, every line since
591
+ 2006, refreshed nightly: amendments applied, a trade filed by several
592
+ members of a group counted once, weighted-average price ranges and
593
+ 10b5-1 plans read from the footnotes, and price typos flagged.
594
+
595
+ Examples::
596
+
597
+ client.get_insider_transactions("NVDA", start="2020-01-01", signal=True)
598
+ client.get_insider_transactions(owner_cik=1214156)
599
+ client.get_insider_transactions(start="2025-01-01", end="2025-04-01",
600
+ codes="P", signal=True)
601
+
602
+ ``ticker`` follows the company through renames (by CIK). ``start``
603
+ is inclusive and ``end`` exclusive, on ``date_field`` ("filed", the
604
+ default, or "trans"). ``signal=True`` keeps open-market purchases
605
+ (P) and sales (S) that are current, counted once and sanely priced.
606
+ A market-wide pull (no ticker or CIK) needs ``start`` and ``end``
607
+ and is fetched a year at a time. Pages of up to 20,000 rows are
608
+ followed for you.
609
+
610
+ For a backtest, the event time is ``accepted_at`` (UTC), or the end
611
+ of ``filed_date`` where it is null. Never ``trans_date``: insiders
612
+ have two business days to file.
613
+ """
614
+ windows: list[tuple[str | None, str | None]] = [(start, end)]
615
+ if ticker is None and issuer_cik is None and owner_cik is None:
616
+ if not (start and end):
617
+ raise ValueError("a market-wide pull needs start and end")
618
+ s, e = pd.Timestamp(start), pd.Timestamp(end)
619
+ windows = []
620
+ while s < e:
621
+ n = min(s + pd.DateOffset(years=1), e)
622
+ windows.append((s.strftime("%Y-%m-%d"), n.strftime("%Y-%m-%d")))
623
+ s = n
624
+ rows: list[dict] = []
625
+ for ws, we in windows:
626
+ after = None
627
+ while len(rows) < max_rows:
628
+ params = {
629
+ "ticker": ticker, "issuer_cik": issuer_cik, "owner_cik": owner_cik,
630
+ "start": ws, "end": we, "date_field": date_field,
631
+ "codes": codes, "kinds": kinds,
632
+ "signal": str(bool(signal)).lower(),
633
+ "include_superseded": str(bool(include_superseded)).lower(),
634
+ "include_duplicates": str(bool(include_duplicates)).lower(),
635
+ "limit": min(20_000, max_rows - len(rows)),
636
+ "after": after,
637
+ }
638
+ page = self._request(
639
+ "GET", "/v1/insiders/transactions",
640
+ params={k: v for k, v in params.items() if v is not None},
641
+ ).json()
642
+ notes = page.get("footnotes") or {}
643
+ for r in page.get("rows") or []:
644
+ texts = notes.get(r.get("accession")) or {}
645
+ ids = r.pop("footnote_ids", None) or {}
646
+ r["footnotes"] = {
647
+ field: [texts[i] for i in fids if i in texts]
648
+ for field, fids in ids.items()
649
+ } or None
650
+ rows.append(r)
651
+ after = page.get("next_cursor")
652
+ if not after:
653
+ break
654
+ if len(rows) >= max_rows:
655
+ break
656
+ return _insider_frame(rows)
@@ -42,6 +42,20 @@ class PermissionDeniedError(QuantPadDataError):
42
42
  pass
43
43
 
44
44
 
45
+ class InAppOnlyError(PermissionDeniedError):
46
+ """The data asked for is available inside QuantPad only.
47
+
48
+ CME futures data (``GLBX.MDP3``) is licensed for use inside the
49
+ QuantPad app, so the API refuses it to API keys with a 403 whose body
50
+ carries ``code: "cme_in_app_only"``. The message says where to work
51
+ with it instead. A subclass of :class:`PermissionDeniedError`, so an
52
+ existing ``except PermissionDeniedError`` still catches it.
53
+ """
54
+
55
+ #: The refusal code the service sends for this case.
56
+ CODE = "cme_in_app_only"
57
+
58
+
45
59
  class RateLimitError(QuantPadDataError):
46
60
  def __init__(
47
61
  self,
@@ -3,8 +3,8 @@
3
3
  The v1 helpers take QuantPad's own arguments and infer the rest: which
4
4
  dataset a symbol lives in, what kind of symbol it is, how far back to
5
5
  look. That inference is convenient right up until it is wrong, and when
6
- it is wrong it fails quietly — a specific futures contract returns an
7
- empty frame that looks exactly like a coverage gap.
6
+ it is wrong it fails quietly: a symbol looked up on the wrong venue
7
+ returns an empty frame that looks exactly like a coverage gap.
8
8
 
9
9
  This module removes the inference. Every call names its dataset and its
10
10
  symbology type, and every response reports the address it actually used:
@@ -12,10 +12,13 @@ symbology type, and every response reports the address it actually used:
12
12
  import quantpad_data as qpd
13
13
  client = qpd.v2.Historical()
14
14
  df = client.timeseries.get_range(
15
- dataset="GLBX.MDP3", symbols="ESZ6", schema="ohlcv-1m",
15
+ dataset="XNAS.ITCH", symbols="AAPL", schema="ohlcv-1m",
16
16
  start="2026-01-05", end="2026-01-06",
17
17
  )
18
18
 
19
+ CME futures (``GLBX.MDP3``) are served inside QuantPad only: with an API
20
+ key they raise :class:`~quantpad_data.errors.InAppOnlyError`.
21
+
19
22
  A DataFrame comes back directly, and there is no cost or billing surface,
20
23
  because data is included in the QuantPad plan rather than metered per
21
24
  request.
@@ -332,3 +332,63 @@ def test_get_mbp10_exposes_l2_schema_and_column_projection(monkeypatch):
332
332
  )
333
333
  assert captured["args"][:2] == ("ES.FUT", "mbp-10")
334
334
  assert captured["kwargs"] == {"columns": columns, "chunksize": 50_000}
335
+
336
+
337
+ def test_get_insider_transactions_pages_and_attaches_footnotes():
338
+ import json
339
+
340
+ page1 = {
341
+ "rows": [{"txn_key": "a:N:1", "accession": "a", "filed_date": "2026-11-16",
342
+ "accepted_at": "2026-11-16T21:05:00+00:00", "shares": "2700.0",
343
+ "price_clean": "63.917", "footnote_ids": {"price": ["F1"]}}],
344
+ "next_cursor": "2026-11-16|a:N:1",
345
+ "footnotes": {"a": {"F1": "weighted average, $63.50 to $64.20"}},
346
+ }
347
+ page2 = {"rows": [{"txn_key": "b:N:1", "accession": "b", "filed_date": "2026-11-17"}],
348
+ "next_cursor": None, "footnotes": {}}
349
+ session = FakeSession([response(body=json.dumps(page1).encode()),
350
+ response(body=json.dumps(page2).encode())])
351
+ client = Client(api_key="secret", session=session)
352
+ df = client.get_insider_transactions("pam", start="2026-11-01", signal=True)
353
+
354
+ assert list(df["txn_key"]) == ["a:N:1", "b:N:1"]
355
+ assert df.loc[0, "footnotes"] == {"price": ["weighted average, $63.50 to $64.20"]}
356
+ assert df.loc[0, "shares"] == 2700.0 and str(df["accepted_at"].dt.tz) == "UTC"
357
+ method, url, kwargs = session.calls[0]
358
+ assert method == "GET" and url.endswith("/v1/insiders/transactions")
359
+ assert kwargs["params"]["ticker"] == "pam" and kwargs["params"]["signal"] == "true"
360
+ assert "end" not in kwargs["params"] and "after" not in kwargs["params"]
361
+ assert session.calls[1][2]["params"]["after"] == "2026-11-16|a:N:1"
362
+ assert kwargs["headers"]["X-API-Key"] == "secret"
363
+
364
+
365
+ def test_get_insider_transactions_market_wide_needs_a_window_and_splits_by_year():
366
+ import json
367
+
368
+ client = Client(api_key="secret", session=FakeSession([]))
369
+ with pytest.raises(ValueError):
370
+ client.get_insider_transactions(codes="P")
371
+ empty = json.dumps({"rows": [], "next_cursor": None}).encode()
372
+ session = FakeSession([response(body=empty), response(body=empty)])
373
+ client = Client(api_key="secret", session=session)
374
+ df = client.get_insider_transactions(start="2024-01-01", end="2025-06-01", codes="P")
375
+ assert df.empty
376
+ windows = [(c[2]["params"]["start"], c[2]["params"]["end"]) for c in session.calls]
377
+ assert windows == [("2024-01-01", "2025-01-01"), ("2025-01-01", "2025-06-01")]
378
+
379
+
380
+ def test_module_level_insider_alias(monkeypatch):
381
+ captured = {}
382
+
383
+ class Stub:
384
+ def get_insider_transactions(self, ticker, **kwargs):
385
+ captured.update(ticker=ticker, kwargs=kwargs)
386
+ return "df"
387
+
388
+ monkeypatch.setattr(quantpad_data, "_client", lambda **kwargs: Stub())
389
+ assert quantpad_data.get_insider_transactions("NVDA", signal=True) == "df"
390
+ assert captured == {"ticker": "NVDA", "kwargs": {"signal": True}}
391
+
392
+
393
+ def test_insider_helper_is_public():
394
+ assert "get_insider_transactions" in quantpad_data.__all__
@@ -0,0 +1,62 @@
1
+ """CME data refused to an API key raises InAppOnlyError with the full text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ import pytest
8
+ import requests
9
+
10
+ import quantpad_data
11
+ from quantpad_data.client import Client
12
+ from quantpad_data.errors import InAppOnlyError, PermissionDeniedError
13
+
14
+ BODY = {
15
+ "code": "cme_in_app_only",
16
+ "message": (
17
+ "CME futures data (GLBX.MDP3) is available inside QuantPad only, so it "
18
+ "can’t be downloaded through the API, Python SDK or MCP."
19
+ ),
20
+ "hint": "To work with it, create a new project at https://quantpad.ai.",
21
+ "dataset": "GLBX.MDP3",
22
+ }
23
+
24
+
25
+ def _response(body: dict, status: int = 403) -> requests.Response:
26
+ response = requests.Response()
27
+ response.status_code = status
28
+ response.url = "https://example.test/v1/bars"
29
+ response._content = json.dumps({"error": body}).encode()
30
+ response.headers["Content-Type"] = "application/json"
31
+ return response
32
+
33
+
34
+ def _raise(body, path="/v1/bars"):
35
+ Client(api_key="k", base_url="https://example.test")._raise_for_status(
36
+ _response(body), path
37
+ )
38
+
39
+
40
+ @pytest.mark.parametrize("path", ["/v1/bars", "/v2/timeseries/get_range"])
41
+ def test_the_cme_refusal_is_its_own_error_with_message_and_hint(path):
42
+ with pytest.raises(InAppOnlyError) as caught:
43
+ _raise(BODY, path)
44
+ assert str(caught.value) == f"{BODY['message']} {BODY['hint']}"
45
+ assert caught.value.status_code == 403
46
+ assert caught.value.detail["dataset"] == "GLBX.MDP3"
47
+
48
+
49
+ def test_existing_permission_handlers_still_catch_it():
50
+ with pytest.raises(PermissionDeniedError):
51
+ _raise(BODY)
52
+
53
+
54
+ def test_other_403s_are_unchanged():
55
+ with pytest.raises(PermissionDeniedError) as caught:
56
+ _raise({"message": "API key is inactive"})
57
+ assert not isinstance(caught.value, InAppOnlyError)
58
+
59
+
60
+ def test_it_is_exported():
61
+ assert quantpad_data.InAppOnlyError is InAppOnlyError
62
+ assert "InAppOnlyError" in quantpad_data.__all__
File without changes