ptdata 0.1.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.
- ptdata/__init__.py +25 -0
- ptdata/_version.py +3 -0
- ptdata/client.py +432 -0
- ptdata/exceptions.py +62 -0
- ptdata/frames.py +157 -0
- ptdata/models.py +427 -0
- ptdata-0.1.0.dist-info/METADATA +192 -0
- ptdata-0.1.0.dist-info/RECORD +10 -0
- ptdata-0.1.0.dist-info/WHEEL +4 -0
- ptdata-0.1.0.dist-info/licenses/LICENSE +21 -0
ptdata/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Point-in-time client for the PtData API."""
|
|
2
|
+
|
|
3
|
+
from ptdata._version import __version__
|
|
4
|
+
from ptdata.client import PtDataClient
|
|
5
|
+
from ptdata.exceptions import (
|
|
6
|
+
PtDataAuthError,
|
|
7
|
+
PtDataError,
|
|
8
|
+
PtDataNotFound,
|
|
9
|
+
PtDataRateLimit,
|
|
10
|
+
PtDataValidationError,
|
|
11
|
+
)
|
|
12
|
+
from ptdata.frames import constituents_frame, fundamentals_frame, fundamentals_panel
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"PtDataAuthError",
|
|
16
|
+
"PtDataClient",
|
|
17
|
+
"PtDataError",
|
|
18
|
+
"PtDataNotFound",
|
|
19
|
+
"PtDataRateLimit",
|
|
20
|
+
"PtDataValidationError",
|
|
21
|
+
"__version__",
|
|
22
|
+
"constituents_frame",
|
|
23
|
+
"fundamentals_frame",
|
|
24
|
+
"fundamentals_panel",
|
|
25
|
+
]
|
ptdata/_version.py
ADDED
ptdata/client.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
"""HTTP client for the PtData API.
|
|
2
|
+
|
|
3
|
+
GET requests only. The disk cache is off unless ``cache_dir`` is set. The cache
|
|
4
|
+
key is the path plus the sorted query string, never the Authorization header.
|
|
5
|
+
The API key is removed from exception text when a response echoes it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
import time
|
|
15
|
+
import warnings
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from datetime import date, datetime
|
|
18
|
+
from email.utils import parsedate_to_datetime
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
import requests
|
|
23
|
+
|
|
24
|
+
from ptdata._version import __version__
|
|
25
|
+
from ptdata.exceptions import (
|
|
26
|
+
PtDataAuthError,
|
|
27
|
+
PtDataError,
|
|
28
|
+
PtDataNotFound,
|
|
29
|
+
PtDataRateLimit,
|
|
30
|
+
PtDataValidationError,
|
|
31
|
+
)
|
|
32
|
+
from ptdata.models import (
|
|
33
|
+
EarningsEventResponse,
|
|
34
|
+
FilingMetadataResponse,
|
|
35
|
+
FundamentalsResponse,
|
|
36
|
+
IndexConstituentsResponse,
|
|
37
|
+
parse_earnings_event,
|
|
38
|
+
parse_filings,
|
|
39
|
+
parse_fundamentals,
|
|
40
|
+
parse_index_constituents,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
logger = logging.getLogger(__name__)
|
|
44
|
+
|
|
45
|
+
DEFAULT_BASE_URL = "https://api.ptdata.io"
|
|
46
|
+
USER_AGENT = f"ptdata-python/{__version__}"
|
|
47
|
+
# A per-minute pause is short. A larger Retry-After is not slept: a daily limit
|
|
48
|
+
# mis-labelled as rate must not block the process for hours.
|
|
49
|
+
MAX_RATE_SLEEP_SECONDS = 180
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _redact(text: str, secret: str | None) -> str:
|
|
53
|
+
if secret and secret in text:
|
|
54
|
+
return text.replace(secret, "[redacted]")
|
|
55
|
+
return text
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _redact_obj(value: Any, secret: str | None) -> Any:
|
|
59
|
+
if not secret:
|
|
60
|
+
return value
|
|
61
|
+
if isinstance(value, str):
|
|
62
|
+
return value.replace(secret, "[redacted]")
|
|
63
|
+
if isinstance(value, list):
|
|
64
|
+
return [_redact_obj(item, secret) for item in value]
|
|
65
|
+
if isinstance(value, dict):
|
|
66
|
+
return {key: _redact_obj(item, secret) for key, item in value.items()}
|
|
67
|
+
return value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _stringify(value: Any) -> str:
|
|
71
|
+
if isinstance(value, datetime):
|
|
72
|
+
return value.date().isoformat()
|
|
73
|
+
if isinstance(value, date):
|
|
74
|
+
return value.isoformat()
|
|
75
|
+
return str(value)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _normalize_params(params: dict[str, Any] | list[tuple[str, Any]] | None) -> list[tuple[str, str]]:
|
|
79
|
+
"""Sort query parameters. A list value becomes repeated keys (``metrics``)."""
|
|
80
|
+
if not params:
|
|
81
|
+
return []
|
|
82
|
+
items: list[tuple[str, str]] = []
|
|
83
|
+
pairs = params.items() if isinstance(params, dict) else params
|
|
84
|
+
for key, value in pairs:
|
|
85
|
+
if value is None:
|
|
86
|
+
continue
|
|
87
|
+
if isinstance(value, list):
|
|
88
|
+
items.extend((str(key), _stringify(item)) for item in value)
|
|
89
|
+
else:
|
|
90
|
+
items.append((str(key), _stringify(value)))
|
|
91
|
+
return sorted(items)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _parse_retry_after(value: str | None) -> float | None:
|
|
95
|
+
"""Return seconds. Accepts a delta or an HTTP-date."""
|
|
96
|
+
if value is None or value == "":
|
|
97
|
+
return None
|
|
98
|
+
try:
|
|
99
|
+
return float(value)
|
|
100
|
+
except ValueError:
|
|
101
|
+
try:
|
|
102
|
+
moment = parsedate_to_datetime(value)
|
|
103
|
+
except (TypeError, ValueError, IndexError, OverflowError):
|
|
104
|
+
return None
|
|
105
|
+
return max(0.0, moment.timestamp() - time.time())
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _format_detail(detail: Any) -> str:
|
|
109
|
+
if detail is None:
|
|
110
|
+
return ""
|
|
111
|
+
if isinstance(detail, str):
|
|
112
|
+
return detail
|
|
113
|
+
if isinstance(detail, list):
|
|
114
|
+
parts: list[str] = []
|
|
115
|
+
for item in detail:
|
|
116
|
+
if isinstance(item, dict):
|
|
117
|
+
loc = item.get("loc", [])
|
|
118
|
+
loc_text = ".".join(str(part) for part in loc) if isinstance(loc, list) else str(loc)
|
|
119
|
+
msg = str(item.get("msg", ""))
|
|
120
|
+
parts.append(f"{loc_text}: {msg}" if loc_text else msg)
|
|
121
|
+
else:
|
|
122
|
+
parts.append(str(item))
|
|
123
|
+
return "; ".join(parts)
|
|
124
|
+
return str(detail)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class PtDataClient:
|
|
128
|
+
"""Client for ``https://api.ptdata.io``.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
base_url: API origin. Trailing slash is stripped.
|
|
132
|
+
api_key: Bearer token. ``None`` reads ``PTDATA_API_KEY``. An empty string,
|
|
133
|
+
or an unset variable, selects the free tier and sends no Authorization header.
|
|
134
|
+
cache_dir: Disk cache directory. ``None`` (the default) disables the disk cache.
|
|
135
|
+
Identical calls on one instance are still reused in memory.
|
|
136
|
+
session: ``requests.Session``, or any object with a ``request`` method. One session
|
|
137
|
+
is created and reused when this is omitted.
|
|
138
|
+
timeout: Per-request timeout in seconds.
|
|
139
|
+
max_retries: Attempts for transport errors, HTTP 5xx, and ``scope=rate`` 429s.
|
|
140
|
+
sleeper: Called with a number of seconds. Tests pass a recorder.
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
def __init__(
|
|
144
|
+
self,
|
|
145
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
146
|
+
api_key: str | None = None,
|
|
147
|
+
cache_dir: str | Path | None = None,
|
|
148
|
+
*,
|
|
149
|
+
session: Any | None = None,
|
|
150
|
+
timeout: float = 30,
|
|
151
|
+
max_retries: int = 4,
|
|
152
|
+
sleeper: Any | None = None,
|
|
153
|
+
) -> None:
|
|
154
|
+
if api_key is None:
|
|
155
|
+
api_key = os.environ.get("PTDATA_API_KEY") or None
|
|
156
|
+
elif api_key == "":
|
|
157
|
+
api_key = None
|
|
158
|
+
self._api_key = api_key
|
|
159
|
+
self.base_url = base_url.rstrip("/")
|
|
160
|
+
self.timeout = timeout
|
|
161
|
+
self.max_retries = max_retries
|
|
162
|
+
self._sleeper = sleeper or time.sleep
|
|
163
|
+
self._session = session or requests.Session()
|
|
164
|
+
self.cache_dir = Path(cache_dir) if cache_dir is not None else None
|
|
165
|
+
self.calls_made = 0
|
|
166
|
+
self._memory: dict[str, dict[str, Any]] = {}
|
|
167
|
+
|
|
168
|
+
def _headers(self) -> dict[str, str]:
|
|
169
|
+
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
|
|
170
|
+
if self._api_key:
|
|
171
|
+
headers["Authorization"] = f"Bearer {self._api_key}"
|
|
172
|
+
return headers
|
|
173
|
+
|
|
174
|
+
def fundamentals(
|
|
175
|
+
self,
|
|
176
|
+
ticker: str,
|
|
177
|
+
as_of_date: str | date,
|
|
178
|
+
metrics: Sequence[str],
|
|
179
|
+
fiscal_year: int | None = None,
|
|
180
|
+
fiscal_period: str | None = "FY",
|
|
181
|
+
) -> FundamentalsResponse:
|
|
182
|
+
"""Return point-in-time fundamentals for one ticker.
|
|
183
|
+
|
|
184
|
+
``metrics`` is required. Omitting it makes the API return an empty ``metrics``
|
|
185
|
+
object, so this method raises ``ValueError`` and does not send the request.
|
|
186
|
+
|
|
187
|
+
Without ``fiscal_year``, the API returns the latest ``fiscal_period`` known on
|
|
188
|
+
``as_of_date`` (default ``FY``), not the latest quarter.
|
|
189
|
+
|
|
190
|
+
Read ``unavailable``. An absent metric is not zero. ``code="financials_family"``
|
|
191
|
+
means the filer has no single revenue line; use ``available_alternatives`` and
|
|
192
|
+
do not invent a total. Values are the raw API numbers.
|
|
193
|
+
"""
|
|
194
|
+
if metrics is None or (isinstance(metrics, Sequence) and not isinstance(metrics, str) and len(metrics) == 0):
|
|
195
|
+
raise ValueError(
|
|
196
|
+
"metrics is required. Omitting metrics makes /v1/fundamentals return an empty metrics object."
|
|
197
|
+
)
|
|
198
|
+
if isinstance(metrics, str) or not isinstance(metrics, Sequence):
|
|
199
|
+
raise TypeError("metrics must be a sequence of metric names, not a string")
|
|
200
|
+
params: dict[str, Any] = {
|
|
201
|
+
"ticker": ticker,
|
|
202
|
+
"as_of_date": as_of_date,
|
|
203
|
+
"metrics": list(metrics),
|
|
204
|
+
}
|
|
205
|
+
if fiscal_year is not None:
|
|
206
|
+
params["fiscal_year"] = fiscal_year
|
|
207
|
+
if fiscal_period is not None:
|
|
208
|
+
params["fiscal_period"] = fiscal_period
|
|
209
|
+
return parse_fundamentals(self._get("/v1/fundamentals", params))
|
|
210
|
+
|
|
211
|
+
def index_constituents(self, index: str, as_of_date: str | date) -> IndexConstituentsResponse:
|
|
212
|
+
"""Return index members as understood on ``as_of_date``.
|
|
213
|
+
|
|
214
|
+
Documented ``index`` codes are ``SP500``, ``DJIA``, ``DJT``, ``DJU``, and ``NDX``.
|
|
215
|
+
Membership is survivorship-free at the API. This method does not filter it.
|
|
216
|
+
"""
|
|
217
|
+
return parse_index_constituents(
|
|
218
|
+
self._get("/v1/index-constituents", {"index": index, "as_of_date": as_of_date})
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
def filings(
|
|
222
|
+
self,
|
|
223
|
+
ticker: str,
|
|
224
|
+
as_of_date: str | date,
|
|
225
|
+
form_type: str | None = None,
|
|
226
|
+
) -> FilingMetadataResponse:
|
|
227
|
+
"""Return filings known on ``as_of_date``, newest first.
|
|
228
|
+
|
|
229
|
+
``form_type`` is optional and matches the API (exact strings such as ``10-K``,
|
|
230
|
+
``10-Q``, ``10-Q/A``, ``8-K``). Without it the list includes every form type
|
|
231
|
+
and can be very large. Pass a form type for research use. This method warns
|
|
232
|
+
when ``form_type`` is omitted.
|
|
233
|
+
"""
|
|
234
|
+
if form_type is None:
|
|
235
|
+
warnings.warn(
|
|
236
|
+
"filings() without form_type can return a very large list; pass form_type for research use.",
|
|
237
|
+
UserWarning,
|
|
238
|
+
stacklevel=2,
|
|
239
|
+
)
|
|
240
|
+
return parse_filings(
|
|
241
|
+
self._get(
|
|
242
|
+
"/v1/filings",
|
|
243
|
+
{"ticker": ticker, "as_of_date": as_of_date, "form_type": form_type},
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
def earnings_event(self, ticker: str, fiscal_year: int, fiscal_period: str) -> EarningsEventResponse:
|
|
248
|
+
"""Return one earnings 8-K event. There is no ``as_of_date``.
|
|
249
|
+
|
|
250
|
+
``fiscal_period`` is ``FY`` or ``Q1``–``Q3``. A fourth-quarter release is stored
|
|
251
|
+
as ``FY``. Use ``sec_acceptance_ts`` (SEC acceptance time) and ``as_reported``
|
|
252
|
+
revenue and ``eps_gaap``.
|
|
253
|
+
"""
|
|
254
|
+
return parse_earnings_event(
|
|
255
|
+
self._get(
|
|
256
|
+
"/v1/earnings-event",
|
|
257
|
+
{"ticker": ticker, "fiscal_year": fiscal_year, "fiscal_period": fiscal_period},
|
|
258
|
+
)
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def _get(self, path: str, params: dict[str, Any] | list[tuple[str, Any]] | None = None) -> dict[str, Any]:
|
|
262
|
+
normalized = _normalize_params(params)
|
|
263
|
+
key = self._cache_key(path, normalized)
|
|
264
|
+
cached = self._memory.get(key)
|
|
265
|
+
if cached is None and self.cache_dir is not None:
|
|
266
|
+
cached = self._read_disk(key)
|
|
267
|
+
if cached is not None:
|
|
268
|
+
self._memory[key] = cached
|
|
269
|
+
return cached
|
|
270
|
+
body = self._fetch(path, normalized)
|
|
271
|
+
self._memory[key] = body
|
|
272
|
+
if self.cache_dir is not None:
|
|
273
|
+
self._write_disk(key, body)
|
|
274
|
+
return body
|
|
275
|
+
|
|
276
|
+
def _cache_key(self, path: str, params: list[tuple[str, str]]) -> str:
|
|
277
|
+
payload = json.dumps({"path": path, "params": params}, separators=(",", ":"))
|
|
278
|
+
return hashlib.sha256(payload.encode()).hexdigest()
|
|
279
|
+
|
|
280
|
+
def _cache_path(self, key: str) -> Path:
|
|
281
|
+
if self.cache_dir is None:
|
|
282
|
+
raise PtDataError("Disk cache is disabled.")
|
|
283
|
+
return self.cache_dir / key[:2] / f"{key}.json"
|
|
284
|
+
|
|
285
|
+
def _read_disk(self, key: str) -> dict[str, Any] | None:
|
|
286
|
+
path = self._cache_path(key)
|
|
287
|
+
if not path.is_file():
|
|
288
|
+
return None
|
|
289
|
+
try:
|
|
290
|
+
with path.open(encoding="utf-8") as handle:
|
|
291
|
+
body = json.load(handle)
|
|
292
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
293
|
+
logger.warning("Ignoring unreadable PtData cache file (%s).", type(exc).__name__)
|
|
294
|
+
return None
|
|
295
|
+
if not isinstance(body, dict):
|
|
296
|
+
return None
|
|
297
|
+
return body
|
|
298
|
+
|
|
299
|
+
def _write_disk(self, key: str, body: dict[str, Any]) -> None:
|
|
300
|
+
path = self._cache_path(key)
|
|
301
|
+
try:
|
|
302
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
303
|
+
temporary = path.with_suffix(".json.tmp")
|
|
304
|
+
with temporary.open("w", encoding="utf-8") as handle:
|
|
305
|
+
json.dump(body, handle, separators=(",", ":"))
|
|
306
|
+
temporary.replace(path)
|
|
307
|
+
except OSError as exc:
|
|
308
|
+
logger.warning("Could not write the PtData cache (%s).", type(exc).__name__)
|
|
309
|
+
|
|
310
|
+
def _fetch(self, path: str, params: list[tuple[str, str]]) -> dict[str, Any]:
|
|
311
|
+
url = f"{self.base_url}{path}"
|
|
312
|
+
last_status: int | None = None
|
|
313
|
+
for attempt in range(self.max_retries):
|
|
314
|
+
self.calls_made += 1
|
|
315
|
+
try:
|
|
316
|
+
response = self._session.request(
|
|
317
|
+
"GET",
|
|
318
|
+
url,
|
|
319
|
+
params=params,
|
|
320
|
+
headers=self._headers(),
|
|
321
|
+
timeout=self.timeout,
|
|
322
|
+
)
|
|
323
|
+
except requests.RequestException as exc:
|
|
324
|
+
logger.warning(
|
|
325
|
+
"PtData request failed (%s), attempt %d of %d.",
|
|
326
|
+
type(exc).__name__,
|
|
327
|
+
attempt + 1,
|
|
328
|
+
self.max_retries,
|
|
329
|
+
)
|
|
330
|
+
if attempt + 1 == self.max_retries:
|
|
331
|
+
raise PtDataError(_redact(str(exc), self._api_key)) from None
|
|
332
|
+
self._sleeper(self._backoff(attempt))
|
|
333
|
+
continue
|
|
334
|
+
|
|
335
|
+
status = response.status_code
|
|
336
|
+
last_status = status
|
|
337
|
+
if status == 200:
|
|
338
|
+
return self._json_object(response)
|
|
339
|
+
if status == 401:
|
|
340
|
+
detail = self._detail(response)
|
|
341
|
+
message = "PtData rejected the credentials (HTTP 401)."
|
|
342
|
+
if detail:
|
|
343
|
+
message = f"{message} {detail}"
|
|
344
|
+
raise PtDataAuthError(message)
|
|
345
|
+
if status == 404:
|
|
346
|
+
raise PtDataNotFound(self._detail(response) or "not found")
|
|
347
|
+
if status == 422:
|
|
348
|
+
detail_raw = self._json_object(response, required=False).get("detail")
|
|
349
|
+
message = _redact(_format_detail(detail_raw), self._api_key) or "PtData rejected the query (HTTP 422)."
|
|
350
|
+
raise PtDataValidationError(message, detail=_redact_obj(detail_raw, self._api_key))
|
|
351
|
+
if status == 429:
|
|
352
|
+
self._handle_rate_limit(response, attempt)
|
|
353
|
+
continue
|
|
354
|
+
if 500 <= status < 600:
|
|
355
|
+
logger.warning("PtData returned HTTP %s, attempt %d of %d.", status, attempt + 1, self.max_retries)
|
|
356
|
+
if attempt + 1 == self.max_retries:
|
|
357
|
+
break
|
|
358
|
+
self._sleeper(self._backoff(attempt))
|
|
359
|
+
continue
|
|
360
|
+
raise PtDataError(self._detail(response) or f"HTTP {status}", status_code=status)
|
|
361
|
+
|
|
362
|
+
raise PtDataError(
|
|
363
|
+
f"PtData request failed after {self.max_retries} attempts (last HTTP {last_status}).",
|
|
364
|
+
status_code=last_status,
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
def _handle_rate_limit(self, response: Any, attempt: int) -> None:
|
|
368
|
+
body = self._json_object(response, required=False) or {}
|
|
369
|
+
retry_after = _parse_retry_after(response.headers.get("Retry-After"))
|
|
370
|
+
scope_raw = body.get("scope")
|
|
371
|
+
scope = str(scope_raw).strip().lower() if scope_raw else ""
|
|
372
|
+
tier_raw = body.get("tier")
|
|
373
|
+
tier = str(tier_raw) if tier_raw is not None else None
|
|
374
|
+
if scope == "daily":
|
|
375
|
+
# Do not sleep and do not retry. The free-tier counter resets at UTC midnight.
|
|
376
|
+
wait = f"{retry_after:g} seconds" if retry_after is not None else "the Retry-After time"
|
|
377
|
+
raise PtDataRateLimit(
|
|
378
|
+
"PtData daily request limit is exhausted "
|
|
379
|
+
f"(scope=daily, tier={tier or 'unknown'}). "
|
|
380
|
+
f"Retry-After asks for {wait}. "
|
|
381
|
+
"The free tier allows 200 requests per IP per UTC day. Stop.",
|
|
382
|
+
retry_after=retry_after,
|
|
383
|
+
scope="daily",
|
|
384
|
+
tier=tier,
|
|
385
|
+
)
|
|
386
|
+
effective = scope or "rate"
|
|
387
|
+
if retry_after is None:
|
|
388
|
+
retry_after = self._backoff(attempt)
|
|
389
|
+
if retry_after > MAX_RATE_SLEEP_SECONDS:
|
|
390
|
+
raise PtDataRateLimit(
|
|
391
|
+
f"PtData rate limit asked to wait {retry_after:g} seconds, "
|
|
392
|
+
f"which is above the {MAX_RATE_SLEEP_SECONDS}s client cap.",
|
|
393
|
+
retry_after=retry_after,
|
|
394
|
+
scope=effective,
|
|
395
|
+
tier=tier,
|
|
396
|
+
)
|
|
397
|
+
logger.warning("PtData rate limit (scope=%s). Waiting %s seconds.", effective, retry_after)
|
|
398
|
+
self._sleeper(retry_after)
|
|
399
|
+
if attempt + 1 == self.max_retries:
|
|
400
|
+
raise PtDataRateLimit(
|
|
401
|
+
"PtData rate limit persisted after retries.",
|
|
402
|
+
retry_after=retry_after,
|
|
403
|
+
scope=effective,
|
|
404
|
+
tier=tier,
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
def _json_object(self, response: Any, required: bool = True) -> dict[str, Any]:
|
|
408
|
+
try:
|
|
409
|
+
body = response.json()
|
|
410
|
+
except ValueError:
|
|
411
|
+
if not required:
|
|
412
|
+
return {}
|
|
413
|
+
raise PtDataError(
|
|
414
|
+
"PtData returned a response that is not JSON.",
|
|
415
|
+
status_code=response.status_code,
|
|
416
|
+
) from None
|
|
417
|
+
if not isinstance(body, dict):
|
|
418
|
+
if not required:
|
|
419
|
+
return {}
|
|
420
|
+
raise PtDataError(
|
|
421
|
+
"PtData returned a JSON value that is not an object.",
|
|
422
|
+
status_code=response.status_code,
|
|
423
|
+
)
|
|
424
|
+
return body
|
|
425
|
+
|
|
426
|
+
def _detail(self, response: Any) -> str:
|
|
427
|
+
body = self._json_object(response, required=False) or {}
|
|
428
|
+
return _redact(_format_detail(body.get("detail", "")), self._api_key)
|
|
429
|
+
|
|
430
|
+
@staticmethod
|
|
431
|
+
def _backoff(attempt: int) -> float:
|
|
432
|
+
return float(2**attempt)
|
ptdata/exceptions.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Errors raised by the PtData client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PtDataError(Exception):
|
|
9
|
+
"""Base error for the PtData client.
|
|
10
|
+
|
|
11
|
+
Attributes:
|
|
12
|
+
status_code: HTTP status when the failure came from a response.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, message: str, *, status_code: int | None = None) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.status_code = status_code
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PtDataNotFound(PtDataError):
|
|
21
|
+
"""HTTP 404. ``detail`` is the API's detail text."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, detail: str) -> None:
|
|
24
|
+
super().__init__(detail, status_code=404)
|
|
25
|
+
self.detail = detail
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PtDataAuthError(PtDataError):
|
|
29
|
+
"""HTTP 401. The bearer token was rejected."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, message: str) -> None:
|
|
32
|
+
super().__init__(message, status_code=401)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class PtDataValidationError(PtDataError):
|
|
36
|
+
"""HTTP 422. ``detail`` is the parsed validation payload when one was sent."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, message: str, *, detail: Any = None) -> None:
|
|
39
|
+
super().__init__(message, status_code=422)
|
|
40
|
+
self.detail = detail
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class PtDataRateLimit(PtDataError):
|
|
44
|
+
"""HTTP 429.
|
|
45
|
+
|
|
46
|
+
``scope`` is ``rate`` (per-minute) or ``daily``. A daily limit is not retried.
|
|
47
|
+
``retry_after`` is seconds from the ``Retry-After`` header when the server sent one.
|
|
48
|
+
``tier`` is the server's tier string (``free``, ``pro``, or ``scale``) when present.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
message: str,
|
|
54
|
+
*,
|
|
55
|
+
retry_after: float | None = None,
|
|
56
|
+
scope: str = "rate",
|
|
57
|
+
tier: str | None = None,
|
|
58
|
+
) -> None:
|
|
59
|
+
super().__init__(message, status_code=429)
|
|
60
|
+
self.retry_after = retry_after
|
|
61
|
+
self.scope = scope
|
|
62
|
+
self.tier = tier
|
ptdata/frames.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Pandas helpers. Missing metrics stay missing; they are not filled with zero."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from datetime import date
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from ptdata.models import FundamentalsResponse, IndexConstituentsResponse
|
|
12
|
+
|
|
13
|
+
_FUNDAMENTAL_COLUMNS = [
|
|
14
|
+
"ticker",
|
|
15
|
+
"as_of_date",
|
|
16
|
+
"metric",
|
|
17
|
+
"value",
|
|
18
|
+
"unit",
|
|
19
|
+
"fiscal_year",
|
|
20
|
+
"fiscal_period",
|
|
21
|
+
"source_accession",
|
|
22
|
+
"knowledge_from",
|
|
23
|
+
"provenance",
|
|
24
|
+
"extraction_confidence",
|
|
25
|
+
"derivation_method",
|
|
26
|
+
"unavailable_code",
|
|
27
|
+
"unavailable_reason",
|
|
28
|
+
"available_alternatives",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def fundamentals_frame(responses: FundamentalsResponse | Sequence[FundamentalsResponse]) -> pd.DataFrame:
|
|
33
|
+
"""One row per ticker, as-of date, and metric.
|
|
34
|
+
|
|
35
|
+
Rows cover both returned metrics and ``unavailable`` entries. Unavailable rows
|
|
36
|
+
have a null ``value`` (not zero) plus ``unavailable_code``, ``unavailable_reason``,
|
|
37
|
+
and ``available_alternatives``.
|
|
38
|
+
"""
|
|
39
|
+
if isinstance(responses, FundamentalsResponse):
|
|
40
|
+
items: Sequence[FundamentalsResponse] = [responses]
|
|
41
|
+
else:
|
|
42
|
+
items = responses
|
|
43
|
+
rows: list[dict[str, Any]] = []
|
|
44
|
+
for response in items:
|
|
45
|
+
for name, metric in response.metrics.items():
|
|
46
|
+
rows.append(
|
|
47
|
+
{
|
|
48
|
+
"ticker": response.ticker,
|
|
49
|
+
"as_of_date": response.as_of_date,
|
|
50
|
+
"metric": name,
|
|
51
|
+
"value": metric.value,
|
|
52
|
+
"unit": metric.unit,
|
|
53
|
+
"fiscal_year": metric.fiscal_year,
|
|
54
|
+
"fiscal_period": metric.fiscal_period,
|
|
55
|
+
"source_accession": metric.source_accession,
|
|
56
|
+
"knowledge_from": metric.knowledge_from,
|
|
57
|
+
"provenance": metric.provenance,
|
|
58
|
+
"extraction_confidence": metric.extraction_confidence,
|
|
59
|
+
"derivation_method": metric.derivation.method if metric.derivation else None,
|
|
60
|
+
"unavailable_code": None,
|
|
61
|
+
"unavailable_reason": None,
|
|
62
|
+
"available_alternatives": None,
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
for name, guidance in response.unavailable.items():
|
|
66
|
+
rows.append(
|
|
67
|
+
{
|
|
68
|
+
"ticker": response.ticker,
|
|
69
|
+
"as_of_date": response.as_of_date,
|
|
70
|
+
"metric": name,
|
|
71
|
+
"value": None,
|
|
72
|
+
"unit": None,
|
|
73
|
+
"fiscal_year": None,
|
|
74
|
+
"fiscal_period": None,
|
|
75
|
+
"source_accession": None,
|
|
76
|
+
"knowledge_from": None,
|
|
77
|
+
"provenance": None,
|
|
78
|
+
"extraction_confidence": None,
|
|
79
|
+
"derivation_method": None,
|
|
80
|
+
"unavailable_code": guidance.code,
|
|
81
|
+
"unavailable_reason": guidance.reason,
|
|
82
|
+
"available_alternatives": list(guidance.available_alternatives),
|
|
83
|
+
}
|
|
84
|
+
)
|
|
85
|
+
frame = pd.DataFrame(rows, columns=_FUNDAMENTAL_COLUMNS)
|
|
86
|
+
frame["as_of_date"] = pd.to_datetime(frame["as_of_date"])
|
|
87
|
+
frame["knowledge_from"] = pd.to_datetime(frame["knowledge_from"], utc=True)
|
|
88
|
+
frame["value"] = pd.to_numeric(frame["value"])
|
|
89
|
+
frame["fiscal_year"] = pd.to_numeric(frame["fiscal_year"], errors="coerce").astype("Int64")
|
|
90
|
+
return frame
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def fundamentals_panel(
|
|
94
|
+
client: Any,
|
|
95
|
+
tickers: Sequence[str],
|
|
96
|
+
as_of_dates: Sequence[str | date],
|
|
97
|
+
metrics: Sequence[str],
|
|
98
|
+
fiscal_year: int | None = None,
|
|
99
|
+
fiscal_period: str = "FY",
|
|
100
|
+
) -> pd.DataFrame:
|
|
101
|
+
"""Call ``fundamentals`` once per ticker and as-of date, then stack the frames.
|
|
102
|
+
|
|
103
|
+
Metrics for one call are sent together. The client sleeps on a per-minute
|
|
104
|
+
429 and raises ``PtDataRateLimit`` with ``scope="daily"`` without retrying.
|
|
105
|
+
This helper does not catch that error, so a daily limit stops the loop.
|
|
106
|
+
"""
|
|
107
|
+
if isinstance(metrics, str) or not isinstance(metrics, Sequence) or len(metrics) == 0:
|
|
108
|
+
raise ValueError("metrics is required.")
|
|
109
|
+
responses: list[FundamentalsResponse] = []
|
|
110
|
+
for ticker in tickers:
|
|
111
|
+
for as_of_date in as_of_dates:
|
|
112
|
+
responses.append(
|
|
113
|
+
client.fundamentals(
|
|
114
|
+
ticker,
|
|
115
|
+
as_of_date,
|
|
116
|
+
list(metrics),
|
|
117
|
+
fiscal_year=fiscal_year,
|
|
118
|
+
fiscal_period=fiscal_period,
|
|
119
|
+
)
|
|
120
|
+
)
|
|
121
|
+
return fundamentals_frame(responses)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def constituents_frame(response: IndexConstituentsResponse) -> pd.DataFrame:
|
|
125
|
+
"""One row per constituent, with ``index`` and ``as_of_date`` repeated.
|
|
126
|
+
|
|
127
|
+
Tickers present only in ``response.tickers`` are included with a null CIK and name.
|
|
128
|
+
"""
|
|
129
|
+
rows: list[dict[str, Any]] = []
|
|
130
|
+
seen: set[str] = set()
|
|
131
|
+
for item in response.constituents:
|
|
132
|
+
seen.add(item.ticker)
|
|
133
|
+
rows.append(
|
|
134
|
+
{
|
|
135
|
+
"index": response.index,
|
|
136
|
+
"as_of_date": response.as_of_date,
|
|
137
|
+
"ticker": item.ticker,
|
|
138
|
+
"cik": item.cik,
|
|
139
|
+
"name": item.name,
|
|
140
|
+
}
|
|
141
|
+
)
|
|
142
|
+
for ticker in response.tickers:
|
|
143
|
+
if ticker in seen:
|
|
144
|
+
continue
|
|
145
|
+
rows.append(
|
|
146
|
+
{
|
|
147
|
+
"index": response.index,
|
|
148
|
+
"as_of_date": response.as_of_date,
|
|
149
|
+
"ticker": ticker,
|
|
150
|
+
"cik": None,
|
|
151
|
+
"name": None,
|
|
152
|
+
}
|
|
153
|
+
)
|
|
154
|
+
frame = pd.DataFrame(rows, columns=["index", "as_of_date", "ticker", "cik", "name"])
|
|
155
|
+
frame["as_of_date"] = pd.to_datetime(frame["as_of_date"])
|
|
156
|
+
frame["cik"] = pd.to_numeric(frame["cik"], errors="coerce").astype("Int64")
|
|
157
|
+
return frame
|
ptdata/models.py
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
"""Dataclasses for the PtData HTTP API.
|
|
2
|
+
|
|
3
|
+
Shapes follow ``https://api.ptdata.io/openapi.json``. Unknown JSON fields are ignored.
|
|
4
|
+
``MetricValue.value`` is the number the API returned. It is not scaled.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import date, datetime
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from ptdata.exceptions import PtDataError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _require(body: dict[str, Any], key: str) -> Any:
|
|
17
|
+
if key not in body:
|
|
18
|
+
raise PtDataError(f"PtData response is missing {key}.")
|
|
19
|
+
return body[key]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _as_date(value: Any, field_name: str) -> date:
|
|
23
|
+
if not isinstance(value, str):
|
|
24
|
+
raise PtDataError(f"Could not parse {field_name} as a date.")
|
|
25
|
+
try:
|
|
26
|
+
return date.fromisoformat(value)
|
|
27
|
+
except ValueError as exc:
|
|
28
|
+
raise PtDataError(f"Could not parse {field_name} as a date.") from exc
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _as_date_opt(value: Any, field_name: str) -> date | None:
|
|
32
|
+
if value is None:
|
|
33
|
+
return None
|
|
34
|
+
return _as_date(value, field_name)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _as_datetime(value: Any, field_name: str) -> datetime:
|
|
38
|
+
if not isinstance(value, str):
|
|
39
|
+
raise PtDataError(f"Could not parse {field_name} as a datetime.")
|
|
40
|
+
text = value[:-1] + "+00:00" if value.endswith("Z") else value
|
|
41
|
+
try:
|
|
42
|
+
return datetime.fromisoformat(text)
|
|
43
|
+
except ValueError as exc:
|
|
44
|
+
raise PtDataError(f"Could not parse {field_name} as a datetime.") from exc
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _as_datetime_opt(value: Any, field_name: str) -> datetime | None:
|
|
48
|
+
if value is None:
|
|
49
|
+
return None
|
|
50
|
+
return _as_datetime(value, field_name)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _as_number(value: Any, field_name: str) -> int | float:
|
|
54
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
55
|
+
raise PtDataError(f"Field {field_name} is not a number.")
|
|
56
|
+
return value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _as_number_opt(value: Any, field_name: str) -> int | float | None:
|
|
60
|
+
if value is None:
|
|
61
|
+
return None
|
|
62
|
+
return _as_number(value, field_name)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _as_object(value: Any, field_name: str) -> dict[str, Any]:
|
|
66
|
+
if not isinstance(value, dict):
|
|
67
|
+
raise PtDataError(f"Field {field_name} is not an object.")
|
|
68
|
+
return value
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class DerivationInput:
|
|
73
|
+
"""One filed amount that went into a derived quarter."""
|
|
74
|
+
|
|
75
|
+
fiscal_period: str
|
|
76
|
+
accession: str
|
|
77
|
+
knowledge_from: datetime
|
|
78
|
+
value: int | float
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class Derivation:
|
|
83
|
+
"""How a quarter was produced. Present only when the service derived or copied it.
|
|
84
|
+
|
|
85
|
+
``method`` is one of ``fy_minus_q1_q3``, ``ytd_minus_prior_ytd``, ``direct_q4_fact``,
|
|
86
|
+
or ``fy_instant``. This client does not compute quarters itself.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
method: str
|
|
90
|
+
inputs: list[DerivationInput]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class MetricValue:
|
|
95
|
+
"""One fundamental.
|
|
96
|
+
|
|
97
|
+
``value`` is the raw API number (USD amounts are not converted from millions).
|
|
98
|
+
``knowledge_from`` is the API timestamp, often the filing date at 00:00Z, not the
|
|
99
|
+
SEC acceptance time. A missing metric is not a ``MetricValue``; see
|
|
100
|
+
``FundamentalsResponse.unavailable``.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
value: int | float
|
|
104
|
+
unit: str
|
|
105
|
+
fiscal_year: int
|
|
106
|
+
fiscal_period: str
|
|
107
|
+
source_accession: str
|
|
108
|
+
knowledge_from: datetime
|
|
109
|
+
methodology_version: str
|
|
110
|
+
provenance: str = "xbrl"
|
|
111
|
+
extraction_confidence: str | None = None
|
|
112
|
+
derivation: Derivation | None = None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass
|
|
116
|
+
class MetricGuidance:
|
|
117
|
+
"""Why a requested metric is absent.
|
|
118
|
+
|
|
119
|
+
``code`` is ``not_reported`` or ``financials_family``. ``available_alternatives``
|
|
120
|
+
may be empty. Do not treat the absence as zero and do not invent a total.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
reason: str
|
|
124
|
+
docs_url: str
|
|
125
|
+
code: str = "not_reported"
|
|
126
|
+
available_alternatives: list[str] = field(default_factory=list)
|
|
127
|
+
detail: str | None = None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass
|
|
131
|
+
class Lineage:
|
|
132
|
+
"""Provenance attached to a response."""
|
|
133
|
+
|
|
134
|
+
source: str
|
|
135
|
+
knowledge_from: datetime
|
|
136
|
+
methodology_version: str
|
|
137
|
+
ingestion_run_id: int | None = None
|
|
138
|
+
amends_chain: list[str] | None = None
|
|
139
|
+
derived_inputs: list[str] | None = None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass
|
|
143
|
+
class FundamentalsResponse:
|
|
144
|
+
"""``GET /v1/fundamentals``."""
|
|
145
|
+
|
|
146
|
+
ticker: str
|
|
147
|
+
as_of_date: date
|
|
148
|
+
metrics: dict[str, MetricValue]
|
|
149
|
+
lineage: Lineage
|
|
150
|
+
unavailable: dict[str, MetricGuidance] = field(default_factory=dict)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass
|
|
154
|
+
class Constituent:
|
|
155
|
+
"""One index member as understood on the queried date."""
|
|
156
|
+
|
|
157
|
+
ticker: str
|
|
158
|
+
cik: int | None = None
|
|
159
|
+
name: str | None = None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass
|
|
163
|
+
class IndexConstituentsResponse:
|
|
164
|
+
"""``GET /v1/index-constituents``."""
|
|
165
|
+
|
|
166
|
+
index: str
|
|
167
|
+
as_of_date: date
|
|
168
|
+
tickers: list[str]
|
|
169
|
+
constituents: list[Constituent]
|
|
170
|
+
lineage: Lineage
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@dataclass
|
|
174
|
+
class FilingMeta:
|
|
175
|
+
"""One filing row. ``acceptance_datetime`` is the SEC acceptance time."""
|
|
176
|
+
|
|
177
|
+
accession_number: str
|
|
178
|
+
form_type: str
|
|
179
|
+
filing_date: date
|
|
180
|
+
acceptance_datetime: datetime
|
|
181
|
+
period_of_report: date | None = None
|
|
182
|
+
amends_accession: str | None = None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@dataclass
|
|
186
|
+
class FilingMetadataResponse:
|
|
187
|
+
"""``GET /v1/filings``. ``filings`` is newest first, as the API sends it."""
|
|
188
|
+
|
|
189
|
+
ticker: str
|
|
190
|
+
as_of_date: date
|
|
191
|
+
filings: list[FilingMeta]
|
|
192
|
+
lineage: Lineage
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@dataclass
|
|
196
|
+
class FilingRef:
|
|
197
|
+
"""Filing pointer on an earnings event."""
|
|
198
|
+
|
|
199
|
+
accession_number: str
|
|
200
|
+
acceptance_datetime: datetime
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@dataclass
|
|
204
|
+
class AsReported:
|
|
205
|
+
"""Figures stated in the earnings filing. Absent fields are null, not zero."""
|
|
206
|
+
|
|
207
|
+
revenue: int | float | None = None
|
|
208
|
+
eps_gaap: int | float | None = None
|
|
209
|
+
eps_non_gaap: int | float | None = None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@dataclass
|
|
213
|
+
class ImpliedExpectationBlock:
|
|
214
|
+
"""Optional earnings block from the OpenAPI schema. Null when the API sends null."""
|
|
215
|
+
|
|
216
|
+
as_of_date: date
|
|
217
|
+
expected_move_pct: int | float
|
|
218
|
+
method: str
|
|
219
|
+
atm_iv: int | float | None = None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@dataclass
|
|
223
|
+
class EarningsEventResponse:
|
|
224
|
+
"""``GET /v1/earnings-event``. This route has no ``as_of_date``.
|
|
225
|
+
|
|
226
|
+
``fiscal_period`` is ``FY`` or ``Q1``–``Q3``. A fourth-quarter release is stored as ``FY``.
|
|
227
|
+
Use ``sec_acceptance_ts`` and ``as_reported`` revenue and ``eps_gaap``.
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
ticker: str
|
|
231
|
+
fiscal_year: int
|
|
232
|
+
fiscal_period: str
|
|
233
|
+
dissemination_confidence: str
|
|
234
|
+
filing_accession: str
|
|
235
|
+
filing: FilingRef
|
|
236
|
+
lineage: Lineage
|
|
237
|
+
sec_acceptance_ts: datetime | None = None
|
|
238
|
+
dissemination_ts: datetime | None = None
|
|
239
|
+
as_reported: AsReported | None = None
|
|
240
|
+
implied_expectation: ImpliedExpectationBlock | None = None
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _parse_derivation(body: Any) -> Derivation | None:
|
|
244
|
+
if body is None:
|
|
245
|
+
return None
|
|
246
|
+
raw = _as_object(body, "derivation")
|
|
247
|
+
inputs_raw = raw.get("inputs", [])
|
|
248
|
+
if not isinstance(inputs_raw, list):
|
|
249
|
+
raise PtDataError("Field derivation.inputs is not a list.")
|
|
250
|
+
inputs: list[DerivationInput] = []
|
|
251
|
+
for item in inputs_raw:
|
|
252
|
+
row = _as_object(item, "derivation.inputs")
|
|
253
|
+
inputs.append(
|
|
254
|
+
DerivationInput(
|
|
255
|
+
fiscal_period=str(_require(row, "fiscal_period")),
|
|
256
|
+
accession=str(_require(row, "accession")),
|
|
257
|
+
knowledge_from=_as_datetime(row.get("knowledge_from"), "derivation.knowledge_from"),
|
|
258
|
+
value=_as_number(row.get("value"), "derivation.value"),
|
|
259
|
+
)
|
|
260
|
+
)
|
|
261
|
+
return Derivation(method=str(_require(raw, "method")), inputs=inputs)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _parse_metric(body: Any) -> MetricValue:
|
|
265
|
+
raw = _as_object(body, "metric")
|
|
266
|
+
provenance = raw.get("provenance", "xbrl")
|
|
267
|
+
if provenance is None:
|
|
268
|
+
provenance = "xbrl"
|
|
269
|
+
return MetricValue(
|
|
270
|
+
value=_as_number(raw.get("value"), "value"),
|
|
271
|
+
unit=str(_require(raw, "unit")),
|
|
272
|
+
fiscal_year=int(_require(raw, "fiscal_year")),
|
|
273
|
+
fiscal_period=str(_require(raw, "fiscal_period")),
|
|
274
|
+
source_accession=str(_require(raw, "source_accession")),
|
|
275
|
+
knowledge_from=_as_datetime(raw.get("knowledge_from"), "knowledge_from"),
|
|
276
|
+
methodology_version=str(_require(raw, "methodology_version")),
|
|
277
|
+
provenance=str(provenance),
|
|
278
|
+
extraction_confidence=raw.get("extraction_confidence"),
|
|
279
|
+
derivation=_parse_derivation(raw.get("derivation")),
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _parse_guidance(body: Any) -> MetricGuidance:
|
|
284
|
+
raw = _as_object(body, "unavailable")
|
|
285
|
+
alternatives = raw.get("available_alternatives", [])
|
|
286
|
+
if not isinstance(alternatives, list):
|
|
287
|
+
raise PtDataError("Field available_alternatives is not a list.")
|
|
288
|
+
return MetricGuidance(
|
|
289
|
+
reason=str(_require(raw, "reason")),
|
|
290
|
+
docs_url=str(_require(raw, "docs_url")),
|
|
291
|
+
code=str(raw.get("code") or "not_reported"),
|
|
292
|
+
available_alternatives=[str(item) for item in alternatives],
|
|
293
|
+
detail=raw.get("detail"),
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _parse_lineage(body: Any) -> Lineage:
|
|
298
|
+
raw = _as_object(body, "lineage")
|
|
299
|
+
run_id = raw.get("ingestion_run_id")
|
|
300
|
+
if run_id is not None and (isinstance(run_id, bool) or not isinstance(run_id, int)):
|
|
301
|
+
raise PtDataError("Field ingestion_run_id is not an integer.")
|
|
302
|
+
amends = raw.get("amends_chain")
|
|
303
|
+
derived = raw.get("derived_inputs")
|
|
304
|
+
if amends is not None and not isinstance(amends, list):
|
|
305
|
+
raise PtDataError("Field amends_chain is not a list.")
|
|
306
|
+
if derived is not None and not isinstance(derived, list):
|
|
307
|
+
raise PtDataError("Field derived_inputs is not a list.")
|
|
308
|
+
return Lineage(
|
|
309
|
+
source=str(_require(raw, "source")),
|
|
310
|
+
knowledge_from=_as_datetime(raw.get("knowledge_from"), "lineage.knowledge_from"),
|
|
311
|
+
methodology_version=str(_require(raw, "methodology_version")),
|
|
312
|
+
ingestion_run_id=run_id,
|
|
313
|
+
amends_chain=[str(item) for item in amends] if amends is not None else None,
|
|
314
|
+
derived_inputs=[str(item) for item in derived] if derived is not None else None,
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _parse_map(raw: Any, field_name: str, parser: Any) -> dict[str, Any]:
|
|
319
|
+
if raw is None:
|
|
320
|
+
return {}
|
|
321
|
+
body = _as_object(raw, field_name)
|
|
322
|
+
return {str(key): parser(value) for key, value in body.items()}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def parse_fundamentals(body: dict[str, Any]) -> FundamentalsResponse:
|
|
326
|
+
"""Build a ``FundamentalsResponse``. ``unavailable`` defaults to an empty map."""
|
|
327
|
+
metrics_raw = body.get("metrics", {})
|
|
328
|
+
return FundamentalsResponse(
|
|
329
|
+
ticker=str(_require(body, "ticker")),
|
|
330
|
+
as_of_date=_as_date(body.get("as_of_date"), "as_of_date"),
|
|
331
|
+
metrics=_parse_map(metrics_raw, "metrics", _parse_metric),
|
|
332
|
+
unavailable=_parse_map(body.get("unavailable", {}), "unavailable", _parse_guidance),
|
|
333
|
+
lineage=_parse_lineage(body.get("lineage")),
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def parse_index_constituents(body: dict[str, Any]) -> IndexConstituentsResponse:
|
|
338
|
+
"""Build an ``IndexConstituentsResponse``."""
|
|
339
|
+
tickers = _require(body, "tickers")
|
|
340
|
+
rows = _require(body, "constituents")
|
|
341
|
+
if not isinstance(tickers, list) or not isinstance(rows, list):
|
|
342
|
+
raise PtDataError("Index constituents response is malformed.")
|
|
343
|
+
constituents: list[Constituent] = []
|
|
344
|
+
for item in rows:
|
|
345
|
+
raw = _as_object(item, "constituents")
|
|
346
|
+
cik = raw.get("cik")
|
|
347
|
+
if cik is not None and (isinstance(cik, bool) or not isinstance(cik, int)):
|
|
348
|
+
raise PtDataError("Field cik is not an integer.")
|
|
349
|
+
constituents.append(Constituent(ticker=str(_require(raw, "ticker")), cik=cik, name=raw.get("name")))
|
|
350
|
+
return IndexConstituentsResponse(
|
|
351
|
+
index=str(_require(body, "index")),
|
|
352
|
+
as_of_date=_as_date(body.get("as_of_date"), "as_of_date"),
|
|
353
|
+
tickers=[str(item) for item in tickers],
|
|
354
|
+
constituents=constituents,
|
|
355
|
+
lineage=_parse_lineage(body.get("lineage")),
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def parse_filings(body: dict[str, Any]) -> FilingMetadataResponse:
|
|
360
|
+
"""Build a ``FilingMetadataResponse``. Order is preserved."""
|
|
361
|
+
rows = _require(body, "filings")
|
|
362
|
+
if not isinstance(rows, list):
|
|
363
|
+
raise PtDataError("Field filings is not a list.")
|
|
364
|
+
filings: list[FilingMeta] = []
|
|
365
|
+
for item in rows:
|
|
366
|
+
raw = _as_object(item, "filings")
|
|
367
|
+
filings.append(
|
|
368
|
+
FilingMeta(
|
|
369
|
+
accession_number=str(_require(raw, "accession_number")),
|
|
370
|
+
form_type=str(_require(raw, "form_type")),
|
|
371
|
+
filing_date=_as_date(raw.get("filing_date"), "filing_date"),
|
|
372
|
+
acceptance_datetime=_as_datetime(raw.get("acceptance_datetime"), "acceptance_datetime"),
|
|
373
|
+
period_of_report=_as_date_opt(raw.get("period_of_report"), "period_of_report"),
|
|
374
|
+
amends_accession=raw.get("amends_accession"),
|
|
375
|
+
)
|
|
376
|
+
)
|
|
377
|
+
return FilingMetadataResponse(
|
|
378
|
+
ticker=str(_require(body, "ticker")),
|
|
379
|
+
as_of_date=_as_date(body.get("as_of_date"), "as_of_date"),
|
|
380
|
+
filings=filings,
|
|
381
|
+
lineage=_parse_lineage(body.get("lineage")),
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _parse_as_reported(body: Any) -> AsReported | None:
|
|
386
|
+
if body is None:
|
|
387
|
+
return None
|
|
388
|
+
raw = _as_object(body, "as_reported")
|
|
389
|
+
return AsReported(
|
|
390
|
+
revenue=_as_number_opt(raw.get("revenue"), "as_reported.revenue"),
|
|
391
|
+
eps_gaap=_as_number_opt(raw.get("eps_gaap"), "as_reported.eps_gaap"),
|
|
392
|
+
eps_non_gaap=_as_number_opt(raw.get("eps_non_gaap"), "as_reported.eps_non_gaap"),
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _parse_implied(body: Any) -> ImpliedExpectationBlock | None:
|
|
397
|
+
if body is None:
|
|
398
|
+
return None
|
|
399
|
+
raw = _as_object(body, "implied_expectation")
|
|
400
|
+
return ImpliedExpectationBlock(
|
|
401
|
+
as_of_date=_as_date(raw.get("as_of_date"), "implied_expectation.as_of_date"),
|
|
402
|
+
expected_move_pct=_as_number(raw.get("expected_move_pct"), "expected_move_pct"),
|
|
403
|
+
method=str(_require(raw, "method")),
|
|
404
|
+
atm_iv=_as_number_opt(raw.get("atm_iv"), "atm_iv"),
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def parse_earnings_event(body: dict[str, Any]) -> EarningsEventResponse:
|
|
409
|
+
"""Build an ``EarningsEventResponse``."""
|
|
410
|
+
filing_raw = _as_object(_require(body, "filing"), "filing")
|
|
411
|
+
filing = FilingRef(
|
|
412
|
+
accession_number=str(_require(filing_raw, "accession_number")),
|
|
413
|
+
acceptance_datetime=_as_datetime(filing_raw.get("acceptance_datetime"), "filing.acceptance_datetime"),
|
|
414
|
+
)
|
|
415
|
+
return EarningsEventResponse(
|
|
416
|
+
ticker=str(_require(body, "ticker")),
|
|
417
|
+
fiscal_year=int(_require(body, "fiscal_year")),
|
|
418
|
+
fiscal_period=str(_require(body, "fiscal_period")),
|
|
419
|
+
dissemination_confidence=str(_require(body, "dissemination_confidence")),
|
|
420
|
+
filing_accession=str(_require(body, "filing_accession")),
|
|
421
|
+
filing=filing,
|
|
422
|
+
lineage=_parse_lineage(body.get("lineage")),
|
|
423
|
+
sec_acceptance_ts=_as_datetime_opt(body.get("sec_acceptance_ts"), "sec_acceptance_ts"),
|
|
424
|
+
dissemination_ts=_as_datetime_opt(body.get("dissemination_ts"), "dissemination_ts"),
|
|
425
|
+
as_reported=_parse_as_reported(body.get("as_reported")),
|
|
426
|
+
implied_expectation=_parse_implied(body.get("implied_expectation")),
|
|
427
|
+
)
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ptdata
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Point-in-time client for the PtData fundamentals API.
|
|
5
|
+
Project-URL: Homepage, https://ptdata.io
|
|
6
|
+
Project-URL: Documentation, https://api.ptdata.io/docs
|
|
7
|
+
Project-URL: Source, https://github.com/ptdata-io/ptdata-python
|
|
8
|
+
Author-email: "PtData S.A." <info@ptdata.io>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: finance,fundamentals,point-in-time,ptdata
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Requires-Dist: pandas>=2.2
|
|
18
|
+
Requires-Dist: requests>=2.31
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: build>=1; extra == 'dev'
|
|
21
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# ptdata
|
|
25
|
+
|
|
26
|
+
Python client for the [PtData](https://ptdata.io) HTTP API at `https://api.ptdata.io`. It returns point-in-time fundamentals, SEC filings, index membership, and earnings 8-K metadata.
|
|
27
|
+
|
|
28
|
+
This package was written with AI assistance.
|
|
29
|
+
|
|
30
|
+
PtData has no prices. It does not serve consensus estimates or intraday data. This client does not fetch prices. Use a separate price source if you need them.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
The intended install, once the package is published, is:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install ptdata
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Not yet published; install from a local checkout:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
python -m venv .venv
|
|
44
|
+
source .venv/bin/activate
|
|
45
|
+
pip install -e ".[dev]"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Python 3.11 or newer. Runtime dependencies are `pandas` and `requests`.
|
|
49
|
+
|
|
50
|
+
## Access and limits
|
|
51
|
+
|
|
52
|
+
No API key is required on the free tier. Limits are 120 requests per minute and 200 requests per day per IP, reset at UTC midnight. The same data is served on every tier. Free access is for evaluation. Commercial use needs a paid plan: Pro is $49/month, Scale is $199/month. Create a bearer token at https://api.ptdata.io/account. On 2026-11-23 the pricing page also listed Pro at 1,200/minute and 15,000/day, and Scale at 5,000/minute and 100,000/day.
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from ptdata import PtDataClient
|
|
56
|
+
|
|
57
|
+
client = PtDataClient() # reads PTDATA_API_KEY if set, otherwise the free tier
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Pass `api_key=""` to force the free tier even when `PTDATA_API_KEY` is set. An empty string sends no `Authorization` header. The key is not written into logs, exception text, or the disk cache. The cache key is the path plus the sorted query.
|
|
61
|
+
|
|
62
|
+
`User-Agent` is `ptdata-python/<version>`.
|
|
63
|
+
|
|
64
|
+
HTTP 429 carries `Retry-After` (a number of seconds or an HTTP-date) and JSON fields `scope` (`rate` or `daily`) and `tier`. This client sleeps on `scope=rate`, capped at 180 seconds, and retries. `scope=daily` raises `PtDataRateLimit` and does not retry. Do not loop on a daily limit. Transient HTTP 5xx responses are retried. Only idempotent GETs are sent.
|
|
65
|
+
|
|
66
|
+
The disk cache is off unless `cache_dir` is set. One `PtDataClient` still reuses identical responses in memory. The example below turns the disk cache on.
|
|
67
|
+
|
|
68
|
+
## Usage
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from ptdata import PtDataClient
|
|
72
|
+
|
|
73
|
+
client = PtDataClient()
|
|
74
|
+
fund = client.fundamentals(
|
|
75
|
+
"GE",
|
|
76
|
+
as_of_date="2018-02-28",
|
|
77
|
+
metrics=["revenue", "net_income"],
|
|
78
|
+
fiscal_year=2017,
|
|
79
|
+
)
|
|
80
|
+
fund.metrics["revenue"].value # 122092000000.0
|
|
81
|
+
fund.metrics["revenue"].source_accession # 0000040545-18-000014
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Checked on the live API on 2026-11-23: GE FY2017 revenue as of 2018-02-28 is `122092000000.0` USD, accession `0000040545-18-000014`. Net income on that same response is `-5786000000.0`, same accession. Numbers are the raw API values, not millions.
|
|
85
|
+
|
|
86
|
+
`metrics` is required. If it is omitted, the API returns an empty `metrics` object; this method raises `ValueError` instead of sending that request. Without `fiscal_year`, the API returns the latest `fiscal_period` known on `as_of_date` (default `FY`), not the latest quarter.
|
|
87
|
+
|
|
88
|
+
Always read `fund.unavailable`. A missing metric is not zero. `code="financials_family"` means the filer has no single revenue line. Use `available_alternatives` when the API sends them, and do not invent a total.
|
|
89
|
+
|
|
90
|
+
`knowledge_from` on a metric is often the filing date at 00:00Z, not the SEC acceptance time. For acceptance time, use filings:
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
members = client.index_constituents("SP500", as_of_date="2020-12-21")
|
|
94
|
+
filings = client.filings("AAPL", as_of_date="2024-11-02", form_type="10-K")
|
|
95
|
+
event = client.earnings_event("AAPL", fiscal_year=2023, fiscal_period="FY")
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Documented index codes are `SP500`, `DJIA`, `DJT`, `DJU`, and `NDX`. Membership is whatever the API returns for that date.
|
|
99
|
+
|
|
100
|
+
`filings` without `form_type` matches the API and warns: the list can include every form type and be very large. Pass a form type such as `10-K` or `10-Q`.
|
|
101
|
+
|
|
102
|
+
`earnings_event` has no `as_of_date`. `fiscal_period` is `FY` or `Q1`–`Q3`. A fourth-quarter earnings release is stored as `FY`. Use `sec_acceptance_ts` and `as_reported.revenue` / `as_reported.eps_gaap`. Checked on 2026-11-23: AAPL FY2023 `as_reported.revenue` is `383285000000.0` and `eps_gaap` is `6.13`. Acceptance time on that response is `2023-11-02T20:30:32Z`.
|
|
103
|
+
|
|
104
|
+
This client does not derive quarters. A Q4 value is the API's value. When the service built it, `derivation.method` is set (live AAPL FY2024 Q4 revenue as of 2026-11-01 used `fy_minus_q1_q3`, provenance `derived`, accession `0000320193-24-000123`).
|
|
105
|
+
|
|
106
|
+
## Pandas
|
|
107
|
+
|
|
108
|
+
`fundamentals_frame` is one row per ticker, as-of date, and metric, including unavailable metrics. Columns include `value`, `unit`, `fiscal_year`, `fiscal_period`, `source_accession`, `knowledge_from`, `provenance`, and `unavailable_code` / `unavailable_reason` / `available_alternatives`. Unavailable `value` is null, not zero.
|
|
109
|
+
|
|
110
|
+
`fundamentals_panel(client, tickers, as_of_dates, metrics, ...)` loops those calls. A daily 429 stops the loop. `constituents_frame` is one row per member.
|
|
111
|
+
|
|
112
|
+
## Look-ahead example
|
|
113
|
+
|
|
114
|
+
`examples/look_ahead_fy2017.py` loads FY2017 `revenue`, `operating_income`, `net_income`, `operating_cash_flow`, and `total_assets` for GE, AMD, CRM, JPM, MSFT, and AAPL as of `2018-06-30` and as of `2026-11-01`. Metrics for one ticker and date go in one request, so a cold cache is 12 calls. The script sets `cache_dir` to `examples/.cache` (gitignored) and `api_key=""`.
|
|
115
|
+
|
|
116
|
+
Recorded on 2026-11-23. First run `http_calls=12`. Second run `http_calls=0`.
|
|
117
|
+
|
|
118
|
+
`pct_change = (latest - first) / abs(first) * 100`. A blank value is unavailable, not zero. `2018-06-30` is the comparison date used by the study below, not the filing morning of every company. CRM's FY2017 10-K was already public then (`knowledge_from` `2017-03-06`).
|
|
119
|
+
|
|
120
|
+
```
|
|
121
|
+
FY2017 as of 2018-06-30 vs 2026-11-01
|
|
122
|
+
http_calls=12
|
|
123
|
+
pct_change = (latest - first) / abs(first) * 100. Blank value means unavailable, not zero.
|
|
124
|
+
ticker metric first_value first_accession latest_value latest_accession pct_change first_unavailable latest_unavailable
|
|
125
|
+
GE revenue 122092000000 0000040545-18-000014 99279000000 0000040545-20-000009 -18.69
|
|
126
|
+
GE operating_income not_reported not_reported
|
|
127
|
+
GE net_income -5786000000 0000040545-18-000014 -8484000000 0000040545-19-000014 -46.63
|
|
128
|
+
GE operating_cash_flow 10426000000 0000040545-18-000014 6554000000 0000040545-20-000009 -37.14
|
|
129
|
+
GE total_assets 369245000000 0000040545-18-000032 369245000000 0000040545-18-000032 0.00
|
|
130
|
+
AMD revenue 5329000000 0000002488-18-000042 5329000000 0000002488-18-000042 0.00
|
|
131
|
+
AMD operating_income 204000000 0000002488-18-000042 127000000 0000002488-19-000011 -37.75
|
|
132
|
+
AMD net_income 43000000 0000002488-18-000042 -33000000 0000002488-19-000011 -176.74
|
|
133
|
+
AMD operating_cash_flow 68000000 0000002488-18-000042 12000000 0000002488-19-000011 -82.35
|
|
134
|
+
AMD total_assets 3552000000 0000002488-18-000068 3552000000 0000002488-18-000068 0.00
|
|
135
|
+
CRM revenue 8391984000 0001108524-17-000006 8391984000 0001108524-17-000006 0.00
|
|
136
|
+
CRM operating_income 64228000 0001108524-17-000006 218000000 0001108524-19-000009 239.42
|
|
137
|
+
CRM net_income 179632000 0001108524-17-000006 323000000 0001108524-19-000009 79.81
|
|
138
|
+
CRM operating_cash_flow 2162198000 0001108524-17-000006 2162000000 0001108524-19-000009 -0.01
|
|
139
|
+
CRM total_assets 17584923000 0001108524-17-000006 17584923000 0001108524-17-000006 0.00
|
|
140
|
+
JPM revenue 99624000000 0000019617-18-000057 100705000000 0000019617-19-000054 1.09
|
|
141
|
+
JPM operating_income not_reported not_reported
|
|
142
|
+
JPM net_income 24441000000 0000019617-18-000057 24441000000 0000019617-18-000057 0.00
|
|
143
|
+
JPM operating_cash_flow -2501000000 0000019617-18-000057 -10827000000 0000019617-19-000054 -332.91
|
|
144
|
+
JPM total_assets 2533600000000 0000019617-18-000057 2533600000000 0000019617-18-000057 0.00
|
|
145
|
+
MSFT revenue 89950000000 0001564590-17-014900 89950000000 0001564590-17-014900 0.00
|
|
146
|
+
MSFT operating_income 22326000000 0001564590-17-014900 29025000000 0001564590-18-019062 30.01
|
|
147
|
+
MSFT net_income 21204000000 0001564590-17-014900 25489000000 0001564590-18-019062 20.21
|
|
148
|
+
MSFT operating_cash_flow 39507000000 0001564590-17-014900 39507000000 0001564590-18-019062 0.00
|
|
149
|
+
MSFT total_assets 250312000000 0001564590-17-020171 250312000000 0001564590-17-020171 0.00
|
|
150
|
+
AAPL revenue 229234000000 0000320193-17-000070 229234000000 0000320193-17-000070 0.00
|
|
151
|
+
AAPL operating_income 61344000000 0000320193-17-000070 61344000000 0000320193-17-000070 0.00
|
|
152
|
+
AAPL net_income 48351000000 0000320193-17-000070 48351000000 0000320193-17-000070 0.00
|
|
153
|
+
AAPL operating_cash_flow 63598000000 0000320193-17-000070 64225000000 0000320193-18-000145 0.99
|
|
154
|
+
AAPL total_assets 375319000000 0000320193-17-000070 375319000000 0000320193-17-000070 0.00
|
|
155
|
+
operating_income / total_assets, rank 1 = highest. Names without operating_income are skipped.
|
|
156
|
+
skipped: GE, JPM
|
|
157
|
+
ticker first_oi_over_assets latest_oi_over_assets first_rank latest_rank
|
|
158
|
+
AMD 0.057432 0.035755 3 3
|
|
159
|
+
CRM 0.003652 0.012397 4 4
|
|
160
|
+
MSFT 0.089193 0.115955 2 2
|
|
161
|
+
AAPL 0.163445 0.163445 1 1
|
|
162
|
+
http_calls=12
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
GE and JPM have no `operating_income` at this coordinate (`not_reported`). They are left out of the ratio. In this six-name set the rank order of the other four names does not change. That is not a claim about a larger universe. An accession can change when the printed percent change is `0.00` (MSFT `operating_cash_flow`). Not investment advice.
|
|
166
|
+
|
|
167
|
+
The 86-name study was not re-run. Its README, read on 2026-11-23, says: 46 of 86 companies differ by at least 1% on at least one core line, and 21 by 5% or more; operating income changed for 29 of 68 companies, operating cash flow for 19 of 86, and total assets for 0 of 86; ranked on operating income / total assets, 4 of 68 changed quintile, so a broad rank mostly survived. https://github.com/ptdata-io/fy2017-restatements
|
|
168
|
+
|
|
169
|
+
## Coverage
|
|
170
|
+
|
|
171
|
+
Figures below are the public site and the methodology docs as read on 2026-11-23, not a new census of the database. The site says 8,300+ companies and about 6,300 with fundamentals. The methodology says XBRL statement facts start at FY2009, and FY2001–2008 values are a parsed tier (`provenance=parsed`, with `extraction_confidence`) for a growing subset of companies, not every filer. S&P 500 membership is reconstructed from 1996; older dates can under-include names that were not verified. Index codes also include DJIA, NDX, DJT, and DJU, with shallower history on some of them.
|
|
172
|
+
|
|
173
|
+
## Errors
|
|
174
|
+
|
|
175
|
+
| Situation | Exception |
|
|
176
|
+
| --- | --- |
|
|
177
|
+
| HTTP 404 | `PtDataNotFound` (`detail` is the API text) |
|
|
178
|
+
| HTTP 401 | `PtDataAuthError` |
|
|
179
|
+
| HTTP 422 | `PtDataValidationError` |
|
|
180
|
+
| HTTP 429 after the wait cap, or still limited after retries | `PtDataRateLimit` (`scope="rate"`, `retry_after`, `tier`) |
|
|
181
|
+
| HTTP 429 `scope=daily` | `PtDataRateLimit` with `scope="daily"`. Not retried. |
|
|
182
|
+
| Other HTTP failures, after 5xx retries | `PtDataError` |
|
|
183
|
+
|
|
184
|
+
## Tests
|
|
185
|
+
|
|
186
|
+
`pytest` does not call the network. The GE FY2017 check is marked `live` and skipped unless `PTDATA_LIVE=1`.
|
|
187
|
+
|
|
188
|
+
## Links
|
|
189
|
+
|
|
190
|
+
- https://ptdata.io
|
|
191
|
+
- https://api.ptdata.io/docs
|
|
192
|
+
- info@ptdata.io
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
ptdata/__init__.py,sha256=TG4uPfQ5UJKerfMtzbSpu0TykeHJBqTFBhFsL6Enuv8,600
|
|
2
|
+
ptdata/_version.py,sha256=sViYbbACjn2y6KahlVlU4fSETSgWTNniclaRlQv3zxk,89
|
|
3
|
+
ptdata/client.py,sha256=x-HOU03Ek1RYSOKbF_CQ0h7PPdkG5gbLhDZ4cJLs9dA,16938
|
|
4
|
+
ptdata/exceptions.py,sha256=OowLOW2cD1cok8t8yM16Eus6a3c3S58dePkppJg7eVg,1762
|
|
5
|
+
ptdata/frames.py,sha256=QMtgyrR8LY_qiewVT1ppBMKXLjhMj-U5Vmpz2cu5ayM,5759
|
|
6
|
+
ptdata/models.py,sha256=VilCFcPJ5Ok2XHHk4eQKmzJiYitDpJcd8Y92yovibLQ,14638
|
|
7
|
+
ptdata-0.1.0.dist-info/METADATA,sha256=B3ZrAesayVYPQaUROJqeTTh7Q96tViBDyPfRPIuwdc4,12669
|
|
8
|
+
ptdata-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
ptdata-0.1.0.dist-info/licenses/LICENSE,sha256=VTfskhFkFWat6Lapl3ZFNUBoHUj1DMlAsCVjC9Qf6QM,1068
|
|
10
|
+
ptdata-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PtData S.A.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|