snoopsharp 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.
- snoopsharp/__init__.py +19 -0
- snoopsharp/client.py +428 -0
- snoopsharp/errors.py +21 -0
- snoopsharp/models.py +98 -0
- snoopsharp/py.typed +0 -0
- snoopsharp-0.1.0.dist-info/METADATA +95 -0
- snoopsharp-0.1.0.dist-info/RECORD +10 -0
- snoopsharp-0.1.0.dist-info/WHEEL +5 -0
- snoopsharp-0.1.0.dist-info/licenses/LICENSE +21 -0
- snoopsharp-0.1.0.dist-info/top_level.txt +1 -0
snoopsharp/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from .client import CompanyClient, EdgarClient, FactSet
|
|
2
|
+
from .errors import BadResponse, EdgarError, InvalidUserAgent, NotFound, RateLimited
|
|
3
|
+
from .models import Company, Fact, Filing
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"EdgarClient",
|
|
7
|
+
"CompanyClient",
|
|
8
|
+
"FactSet",
|
|
9
|
+
"Company",
|
|
10
|
+
"Filing",
|
|
11
|
+
"Fact",
|
|
12
|
+
"EdgarError",
|
|
13
|
+
"NotFound",
|
|
14
|
+
"RateLimited",
|
|
15
|
+
"InvalidUserAgent",
|
|
16
|
+
"BadResponse",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
snoopsharp/client.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.request
|
|
7
|
+
from datetime import date
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .errors import BadResponse, InvalidUserAgent, NotFound, RateLimited
|
|
11
|
+
from .models import Company, Fact, Filing
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _parse_date(value: Any) -> date | None:
|
|
15
|
+
if not isinstance(value, str) or not value:
|
|
16
|
+
return None
|
|
17
|
+
try:
|
|
18
|
+
return date.fromisoformat(value)
|
|
19
|
+
except ValueError:
|
|
20
|
+
return None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _normalize_cik(value: str | int) -> str:
|
|
24
|
+
s = str(value).strip()
|
|
25
|
+
if s.upper().startswith("CIK"):
|
|
26
|
+
s = s[3:].strip()
|
|
27
|
+
if not s.isdigit():
|
|
28
|
+
raise ValueError(f"CIK must be numeric, got {value!r}")
|
|
29
|
+
return s.zfill(10)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class FactSet(list[Fact]):
|
|
33
|
+
"""List of facts with convenience filters."""
|
|
34
|
+
|
|
35
|
+
def latest(
|
|
36
|
+
self,
|
|
37
|
+
*,
|
|
38
|
+
unit: str | None = None,
|
|
39
|
+
form: str | list[str] | tuple[str, ...] | None = None,
|
|
40
|
+
period: str | None = None,
|
|
41
|
+
) -> Fact | None:
|
|
42
|
+
allowed_forms = None
|
|
43
|
+
if form is not None:
|
|
44
|
+
allowed_forms = {form.upper()} if isinstance(form, str) else {f.upper() for f in form}
|
|
45
|
+
for fact in self:
|
|
46
|
+
if unit is not None and fact.unit != unit:
|
|
47
|
+
continue
|
|
48
|
+
if allowed_forms is not None and (fact.form or "").upper() not in allowed_forms:
|
|
49
|
+
continue
|
|
50
|
+
if period is not None and (fact.fiscal_period or "").upper() != period.upper():
|
|
51
|
+
continue
|
|
52
|
+
return fact
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class EdgarClient:
|
|
57
|
+
"""Minimal SEC EDGAR client.
|
|
58
|
+
|
|
59
|
+
SEC requires a descriptive User-Agent with contact information.
|
|
60
|
+
Example: "MyApp/1.0 (contact@example.com)"
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
user_agent: str,
|
|
66
|
+
*,
|
|
67
|
+
min_interval: float = 0.11,
|
|
68
|
+
timeout: float = 30.0,
|
|
69
|
+
data_base_url: str = "https://data.sec.gov",
|
|
70
|
+
www_base_url: str = "https://www.sec.gov",
|
|
71
|
+
):
|
|
72
|
+
ua = (user_agent or "").strip()
|
|
73
|
+
if not ua or "@" not in ua:
|
|
74
|
+
raise InvalidUserAgent(
|
|
75
|
+
"A descriptive User-Agent with contact info is required, e.g. 'MyApp/1.0 (you@example.com)'"
|
|
76
|
+
)
|
|
77
|
+
self.user_agent = ua
|
|
78
|
+
self.min_interval = float(min_interval)
|
|
79
|
+
self.timeout = float(timeout)
|
|
80
|
+
self.data_base_url = data_base_url.rstrip("/")
|
|
81
|
+
self.www_base_url = www_base_url.rstrip("/")
|
|
82
|
+
self._last_request_at = 0.0
|
|
83
|
+
self._ticker_cache: dict[str, Company] | None = None
|
|
84
|
+
self._ticker_rows: list[Company] | None = None
|
|
85
|
+
|
|
86
|
+
def _throttle(self) -> None:
|
|
87
|
+
if self.min_interval <= 0:
|
|
88
|
+
return
|
|
89
|
+
now = time.monotonic()
|
|
90
|
+
wait = self.min_interval - (now - self._last_request_at)
|
|
91
|
+
if wait > 0:
|
|
92
|
+
time.sleep(wait)
|
|
93
|
+
self._last_request_at = time.monotonic()
|
|
94
|
+
|
|
95
|
+
def _request(self, url: str, *, accept: str) -> bytes:
|
|
96
|
+
attempts = 3
|
|
97
|
+
last_error: Exception | None = None
|
|
98
|
+
for attempt in range(attempts):
|
|
99
|
+
self._throttle()
|
|
100
|
+
req = urllib.request.Request(
|
|
101
|
+
url,
|
|
102
|
+
headers={
|
|
103
|
+
"User-Agent": self.user_agent,
|
|
104
|
+
"Accept-Encoding": "gzip, deflate",
|
|
105
|
+
"Accept": accept,
|
|
106
|
+
},
|
|
107
|
+
)
|
|
108
|
+
try:
|
|
109
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
110
|
+
raw = resp.read()
|
|
111
|
+
content_encoding = (resp.headers.get("Content-Encoding") or "").lower()
|
|
112
|
+
last_error = None
|
|
113
|
+
break
|
|
114
|
+
except urllib.error.HTTPError as e:
|
|
115
|
+
if e.code == 404:
|
|
116
|
+
raise NotFound(f"SEC resource not found: {url}") from e
|
|
117
|
+
if e.code == 429:
|
|
118
|
+
last_error = RateLimited(f"SEC rate limit hit for {url}")
|
|
119
|
+
elif e.code == 403:
|
|
120
|
+
raise BadResponse(
|
|
121
|
+
f"SEC rejected request ({e.code}). Ensure User-Agent is descriptive: {url}"
|
|
122
|
+
) from e
|
|
123
|
+
elif 500 <= e.code < 600:
|
|
124
|
+
last_error = BadResponse(f"SEC HTTP error {e.code} for {url}")
|
|
125
|
+
else:
|
|
126
|
+
raise BadResponse(f"SEC HTTP error {e.code} for {url}") from e
|
|
127
|
+
except urllib.error.URLError as e:
|
|
128
|
+
last_error = BadResponse(f"Network error fetching {url}: {e}")
|
|
129
|
+
|
|
130
|
+
if attempt < attempts - 1:
|
|
131
|
+
time.sleep(min(1.5 * (attempt + 1), 5.0))
|
|
132
|
+
continue
|
|
133
|
+
if last_error is not None:
|
|
134
|
+
raise last_error
|
|
135
|
+
|
|
136
|
+
if "gzip" in content_encoding:
|
|
137
|
+
import gzip
|
|
138
|
+
|
|
139
|
+
raw = gzip.decompress(raw)
|
|
140
|
+
elif "deflate" in content_encoding:
|
|
141
|
+
import zlib
|
|
142
|
+
|
|
143
|
+
raw = zlib.decompress(raw)
|
|
144
|
+
return raw
|
|
145
|
+
|
|
146
|
+
def _get_json(self, url: str) -> Any:
|
|
147
|
+
raw = self._request(url, accept="application/json,text/plain,*/*")
|
|
148
|
+
try:
|
|
149
|
+
return json.loads(raw.decode("utf-8"))
|
|
150
|
+
except Exception as e:
|
|
151
|
+
raise BadResponse(f"Invalid JSON from {url}") from e
|
|
152
|
+
|
|
153
|
+
def _get_bytes(self, url: str) -> bytes:
|
|
154
|
+
return self._request(url, accept="*/*")
|
|
155
|
+
|
|
156
|
+
def _load_ticker_map(self) -> dict[str, Company]:
|
|
157
|
+
if self._ticker_cache is not None:
|
|
158
|
+
return self._ticker_cache
|
|
159
|
+
url = f"{self.www_base_url}/files/company_tickers.json"
|
|
160
|
+
data = self._get_json(url)
|
|
161
|
+
if not isinstance(data, dict):
|
|
162
|
+
raise BadResponse("Unexpected company_tickers.json shape")
|
|
163
|
+
mapping: dict[str, Company] = {}
|
|
164
|
+
rows: list[Company] = []
|
|
165
|
+
for _, row in data.items():
|
|
166
|
+
if not isinstance(row, dict):
|
|
167
|
+
continue
|
|
168
|
+
cik = _normalize_cik(row.get("cik_str", ""))
|
|
169
|
+
ticker = str(row.get("ticker") or "").upper() or None
|
|
170
|
+
name = str(row.get("title") or "").strip()
|
|
171
|
+
company = Company(cik=cik, ticker=ticker, name=name)
|
|
172
|
+
rows.append(company)
|
|
173
|
+
mapping[cik] = company
|
|
174
|
+
if ticker:
|
|
175
|
+
mapping[ticker.upper()] = company
|
|
176
|
+
self._ticker_cache = mapping
|
|
177
|
+
self._ticker_rows = rows
|
|
178
|
+
return mapping
|
|
179
|
+
|
|
180
|
+
def get_tickers(self) -> list[Company]:
|
|
181
|
+
"""Return all companies from the SEC ticker map."""
|
|
182
|
+
self._load_ticker_map()
|
|
183
|
+
return list(self._ticker_rows or [])
|
|
184
|
+
|
|
185
|
+
def list_tickers(self) -> list[Company]:
|
|
186
|
+
"""Alias for :meth:get_tickers."""
|
|
187
|
+
return self.get_tickers()
|
|
188
|
+
|
|
189
|
+
def search_companies(self, query: str, *, limit: int = 10) -> list[Company]:
|
|
190
|
+
"""Simple local search over ticker/name from the SEC ticker map."""
|
|
191
|
+
q = (query or "").strip().lower()
|
|
192
|
+
if not q:
|
|
193
|
+
return []
|
|
194
|
+
self._load_ticker_map()
|
|
195
|
+
scored: list[tuple[int, Company]] = []
|
|
196
|
+
for company in self._ticker_rows or []:
|
|
197
|
+
ticker = (company.ticker or "").lower()
|
|
198
|
+
name = company.name.lower()
|
|
199
|
+
hay = f"{ticker} {name}"
|
|
200
|
+
if q not in hay:
|
|
201
|
+
continue
|
|
202
|
+
if ticker == q:
|
|
203
|
+
score = 0
|
|
204
|
+
elif ticker.startswith(q):
|
|
205
|
+
score = 1
|
|
206
|
+
elif name.startswith(q):
|
|
207
|
+
score = 2
|
|
208
|
+
elif q in ticker:
|
|
209
|
+
score = 3
|
|
210
|
+
else:
|
|
211
|
+
score = 4
|
|
212
|
+
scored.append((score, company))
|
|
213
|
+
scored.sort(key=lambda item: (item[0], item[1].ticker or "", item[1].name))
|
|
214
|
+
return [company for _, company in scored[:limit]]
|
|
215
|
+
|
|
216
|
+
def get_company(self, ticker_or_cik: str | int) -> Company:
|
|
217
|
+
"""Resolve a ticker or CIK to a Company."""
|
|
218
|
+
key = str(ticker_or_cik).strip()
|
|
219
|
+
if key.isdigit() or key.upper().startswith("CIK"):
|
|
220
|
+
cik = _normalize_cik(key)
|
|
221
|
+
try:
|
|
222
|
+
mapping = self._load_ticker_map()
|
|
223
|
+
if cik in mapping:
|
|
224
|
+
return mapping[cik]
|
|
225
|
+
except Exception:
|
|
226
|
+
pass
|
|
227
|
+
return Company(cik=cik, ticker=None, name="")
|
|
228
|
+
mapping = self._load_ticker_map()
|
|
229
|
+
company = mapping.get(key.upper())
|
|
230
|
+
if not company:
|
|
231
|
+
raise NotFound(f"Company not found for ticker/CIK: {ticker_or_cik!r}")
|
|
232
|
+
return company
|
|
233
|
+
|
|
234
|
+
def company(self, ticker_or_cik: str | int) -> "CompanyClient":
|
|
235
|
+
return CompanyClient(self, self.get_company(ticker_or_cik))
|
|
236
|
+
|
|
237
|
+
def get_submissions(self, ticker_or_cik: str | int) -> dict[str, Any]:
|
|
238
|
+
company = self.get_company(ticker_or_cik)
|
|
239
|
+
url = f"{self.data_base_url}/submissions/CIK{company.cik_padded}.json"
|
|
240
|
+
data = self._get_json(url)
|
|
241
|
+
if not isinstance(data, dict):
|
|
242
|
+
raise BadResponse("Unexpected submissions response shape")
|
|
243
|
+
return data
|
|
244
|
+
|
|
245
|
+
def get_filings(
|
|
246
|
+
self,
|
|
247
|
+
ticker_or_cik: str | int,
|
|
248
|
+
*,
|
|
249
|
+
form: str | list[str] | tuple[str, ...] | None = None,
|
|
250
|
+
limit: int | None = None,
|
|
251
|
+
before: str | date | None = None,
|
|
252
|
+
after: str | date | None = None,
|
|
253
|
+
) -> list[Filing]:
|
|
254
|
+
company = self.get_company(ticker_or_cik)
|
|
255
|
+
data = self.get_submissions(company.cik)
|
|
256
|
+
recent = ((data.get("filings") or {}).get("recent") or {})
|
|
257
|
+
if not isinstance(recent, dict):
|
|
258
|
+
return []
|
|
259
|
+
|
|
260
|
+
forms = recent.get("form") or []
|
|
261
|
+
accessions = recent.get("accessionNumber") or []
|
|
262
|
+
filing_dates = recent.get("filingDate") or []
|
|
263
|
+
report_dates = recent.get("reportDate") or []
|
|
264
|
+
primary_docs = recent.get("primaryDocument") or []
|
|
265
|
+
descriptions = recent.get("primaryDocDescription") or []
|
|
266
|
+
n = min(len(forms), len(accessions), len(filing_dates), len(report_dates), len(primary_docs))
|
|
267
|
+
|
|
268
|
+
allowed = None
|
|
269
|
+
if form is not None:
|
|
270
|
+
allowed = {form.upper()} if isinstance(form, str) else {f.upper() for f in form}
|
|
271
|
+
before_d = _parse_date(before) if not isinstance(before, date) else before
|
|
272
|
+
after_d = _parse_date(after) if not isinstance(after, date) else after
|
|
273
|
+
|
|
274
|
+
out: list[Filing] = []
|
|
275
|
+
for i in range(n):
|
|
276
|
+
ftype = str(forms[i])
|
|
277
|
+
if allowed is not None and ftype.upper() not in allowed:
|
|
278
|
+
continue
|
|
279
|
+
filed_at = _parse_date(filing_dates[i])
|
|
280
|
+
if before_d is not None and (filed_at is None or filed_at > before_d):
|
|
281
|
+
continue
|
|
282
|
+
if after_d is not None and (filed_at is None or filed_at < after_d):
|
|
283
|
+
continue
|
|
284
|
+
out.append(
|
|
285
|
+
Filing(
|
|
286
|
+
accession_number=str(accessions[i]),
|
|
287
|
+
form=ftype,
|
|
288
|
+
filed_at=filed_at,
|
|
289
|
+
report_date=_parse_date(report_dates[i]),
|
|
290
|
+
primary_document=str(primary_docs[i]) if primary_docs[i] else None,
|
|
291
|
+
primary_doc_description=str(descriptions[i]) if i < len(descriptions) and descriptions[i] else None,
|
|
292
|
+
company_name=data.get("name") or company.name,
|
|
293
|
+
cik=company.cik,
|
|
294
|
+
)
|
|
295
|
+
)
|
|
296
|
+
if limit is not None and len(out) >= limit:
|
|
297
|
+
break
|
|
298
|
+
return out
|
|
299
|
+
|
|
300
|
+
def latest_filing(self, ticker_or_cik: str | int, *, form: str | list[str] | tuple[str, ...] | None = None, before: str | date | None = None, after: str | date | None = None) -> Filing | None:
|
|
301
|
+
filings = self.get_filings(ticker_or_cik, form=form, limit=1, before=before, after=after)
|
|
302
|
+
return filings[0] if filings else None
|
|
303
|
+
|
|
304
|
+
def download(self, url: str) -> bytes:
|
|
305
|
+
"""Download a raw SEC resource (uses the same User-Agent and throttling)."""
|
|
306
|
+
return self._get_bytes(url)
|
|
307
|
+
|
|
308
|
+
def download_filing(self, filing: Filing) -> bytes:
|
|
309
|
+
url = filing.primary_document_url
|
|
310
|
+
if not url:
|
|
311
|
+
raise ValueError("Filing has no primary document URL")
|
|
312
|
+
return self.download(url)
|
|
313
|
+
|
|
314
|
+
def download_to(self, url: str, path: str) -> str:
|
|
315
|
+
"""Download a URL to a local file and return the path."""
|
|
316
|
+
content = self.download(url)
|
|
317
|
+
from pathlib import Path
|
|
318
|
+
p = Path(path)
|
|
319
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
320
|
+
p.write_bytes(content)
|
|
321
|
+
return str(p)
|
|
322
|
+
|
|
323
|
+
def download_filing_to(self, filing: Filing, path: str) -> str:
|
|
324
|
+
url = filing.primary_document_url
|
|
325
|
+
if not url:
|
|
326
|
+
raise ValueError("Filing has no primary document URL")
|
|
327
|
+
return self.download_to(url, path)
|
|
328
|
+
|
|
329
|
+
def get_company_facts(self, ticker_or_cik: str | int) -> dict[str, Any]:
|
|
330
|
+
company = self.get_company(ticker_or_cik)
|
|
331
|
+
url = f"{self.data_base_url}/api/xbrl/companyfacts/CIK{company.cik_padded}.json"
|
|
332
|
+
data = self._get_json(url)
|
|
333
|
+
if not isinstance(data, dict):
|
|
334
|
+
raise BadResponse("Unexpected companyfacts response shape")
|
|
335
|
+
return data
|
|
336
|
+
|
|
337
|
+
def get_facts(
|
|
338
|
+
self,
|
|
339
|
+
ticker_or_cik: str | int,
|
|
340
|
+
taxonomy: str,
|
|
341
|
+
concept: str,
|
|
342
|
+
*,
|
|
343
|
+
unit: str | None = None,
|
|
344
|
+
) -> FactSet:
|
|
345
|
+
data = self.get_company_facts(ticker_or_cik)
|
|
346
|
+
facts_root = data.get("facts") or {}
|
|
347
|
+
taxonomy_obj = facts_root.get(taxonomy) or {}
|
|
348
|
+
concept_obj = taxonomy_obj.get(concept) or {}
|
|
349
|
+
units = concept_obj.get("units") or {}
|
|
350
|
+
if not isinstance(units, dict):
|
|
351
|
+
return FactSet()
|
|
352
|
+
|
|
353
|
+
out = FactSet()
|
|
354
|
+
unit_items = units.items() if unit is None else [(unit, units.get(unit, []))]
|
|
355
|
+
for unit_name, items in unit_items:
|
|
356
|
+
if not isinstance(items, list):
|
|
357
|
+
continue
|
|
358
|
+
for item in items:
|
|
359
|
+
if not isinstance(item, dict):
|
|
360
|
+
continue
|
|
361
|
+
out.append(
|
|
362
|
+
Fact(
|
|
363
|
+
concept=concept,
|
|
364
|
+
taxonomy=taxonomy,
|
|
365
|
+
unit=str(unit_name),
|
|
366
|
+
value=item.get("val"),
|
|
367
|
+
start=_parse_date(item.get("start")),
|
|
368
|
+
end=_parse_date(item.get("end")),
|
|
369
|
+
filed=_parse_date(item.get("filed")),
|
|
370
|
+
form=item.get("form"),
|
|
371
|
+
fiscal_year=item.get("fy"),
|
|
372
|
+
fiscal_period=item.get("fp"),
|
|
373
|
+
accession_number=item.get("accn"),
|
|
374
|
+
frame=item.get("frame"),
|
|
375
|
+
)
|
|
376
|
+
)
|
|
377
|
+
out.sort(key=lambda f: (f.filed or date.min, f.end or date.min), reverse=True)
|
|
378
|
+
return out
|
|
379
|
+
|
|
380
|
+
def latest_fact(
|
|
381
|
+
self,
|
|
382
|
+
ticker_or_cik: str | int,
|
|
383
|
+
taxonomy: str,
|
|
384
|
+
concept: str,
|
|
385
|
+
**kwargs: Any,
|
|
386
|
+
) -> Fact | None:
|
|
387
|
+
return self.get_facts(ticker_or_cik, taxonomy, concept, unit=kwargs.get("unit")).latest(
|
|
388
|
+
form=kwargs.get("form"),
|
|
389
|
+
period=kwargs.get("period"),
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
class CompanyClient:
|
|
394
|
+
"""Convenience wrapper bound to a single company."""
|
|
395
|
+
|
|
396
|
+
def __init__(self, client: EdgarClient, company: Company):
|
|
397
|
+
self._client = client
|
|
398
|
+
self.company_info = company
|
|
399
|
+
self.cik = company.cik
|
|
400
|
+
self.ticker = company.ticker
|
|
401
|
+
self.name = company.name
|
|
402
|
+
|
|
403
|
+
def submissions(self) -> dict[str, Any]:
|
|
404
|
+
return self._client.get_submissions(self.cik)
|
|
405
|
+
|
|
406
|
+
def filings(self, *, form: str | list[str] | tuple[str, ...] | None = None, limit: int | None = None, before: str | date | None = None, after: str | date | None = None) -> list[Filing]:
|
|
407
|
+
return self._client.get_filings(self.cik, form=form, limit=limit, before=before, after=after)
|
|
408
|
+
|
|
409
|
+
def latest_filing(self, *, form: str | list[str] | tuple[str, ...] | None = None, before: str | date | None = None, after: str | date | None = None) -> Filing | None:
|
|
410
|
+
return self._client.latest_filing(self.cik, form=form, before=before, after=after)
|
|
411
|
+
|
|
412
|
+
def download(self, url: str) -> bytes:
|
|
413
|
+
return self._client.download(url)
|
|
414
|
+
|
|
415
|
+
def download_filing(self, filing: Filing) -> bytes:
|
|
416
|
+
return self._client.download_filing(filing)
|
|
417
|
+
|
|
418
|
+
def download_to(self, url: str, path: str) -> str:
|
|
419
|
+
return self._client.download_to(url, path)
|
|
420
|
+
|
|
421
|
+
def download_filing_to(self, filing: Filing, path: str) -> str:
|
|
422
|
+
return self._client.download_filing_to(filing, path)
|
|
423
|
+
|
|
424
|
+
def facts(self, taxonomy: str, concept: str, *, unit: str | None = None) -> FactSet:
|
|
425
|
+
return self._client.get_facts(self.cik, taxonomy, concept, unit=unit)
|
|
426
|
+
|
|
427
|
+
def latest_fact(self, taxonomy: str, concept: str, **kwargs: Any) -> Fact | None:
|
|
428
|
+
return self._client.latest_fact(self.cik, taxonomy, concept, **kwargs)
|
snoopsharp/errors.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Errors for the SnoopSharp."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class EdgarError(Exception):
|
|
5
|
+
"""Base error for the EDGAR SDK."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class NotFound(EdgarError):
|
|
9
|
+
"""Raised when a requested resource was not found."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class RateLimited(EdgarError):
|
|
13
|
+
"""Raised when the SEC rate limit is hit."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class InvalidUserAgent(EdgarError):
|
|
17
|
+
"""Raised when the User-Agent is missing or clearly invalid."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class BadResponse(EdgarError):
|
|
21
|
+
"""Raised when the SEC returns an unexpected response."""
|
snoopsharp/models.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import date
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class Company:
|
|
10
|
+
cik: str
|
|
11
|
+
ticker: str | None
|
|
12
|
+
name: str
|
|
13
|
+
|
|
14
|
+
@property
|
|
15
|
+
def cik_padded(self) -> str:
|
|
16
|
+
return self.cik.zfill(10)
|
|
17
|
+
|
|
18
|
+
def to_dict(self) -> dict[str, Any]:
|
|
19
|
+
return {"cik": self.cik, "ticker": self.ticker, "name": self.name}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Filing:
|
|
24
|
+
accession_number: str
|
|
25
|
+
form: str
|
|
26
|
+
filed_at: date | None
|
|
27
|
+
report_date: date | None
|
|
28
|
+
primary_document: str | None
|
|
29
|
+
primary_doc_description: str | None
|
|
30
|
+
company_name: str | None = None
|
|
31
|
+
cik: str | None = None
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def accession_nodashes(self) -> str:
|
|
35
|
+
return self.accession_number.replace("-", "")
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def primary_document_url(self) -> str | None:
|
|
39
|
+
if not self.cik or not self.primary_document:
|
|
40
|
+
return None
|
|
41
|
+
cik_num = str(int(self.cik))
|
|
42
|
+
return f"https://www.sec.gov/Archives/edgar/data/{cik_num}/{self.accession_nodashes}/{self.primary_document}"
|
|
43
|
+
|
|
44
|
+
def document_url(self) -> str | None:
|
|
45
|
+
return self.primary_document_url
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def index_url(self) -> str | None:
|
|
49
|
+
if not self.cik:
|
|
50
|
+
return None
|
|
51
|
+
cik_num = str(int(self.cik))
|
|
52
|
+
return f"https://www.sec.gov/Archives/edgar/data/{cik_num}/{self.accession_nodashes}/{self.accession_number}-index.htm"
|
|
53
|
+
|
|
54
|
+
def to_dict(self) -> dict[str, Any]:
|
|
55
|
+
return {
|
|
56
|
+
"accession_number": self.accession_number,
|
|
57
|
+
"form": self.form,
|
|
58
|
+
"filed_at": self.filed_at.isoformat() if self.filed_at else None,
|
|
59
|
+
"report_date": self.report_date.isoformat() if self.report_date else None,
|
|
60
|
+
"primary_document": self.primary_document,
|
|
61
|
+
"primary_doc_description": self.primary_doc_description,
|
|
62
|
+
"company_name": self.company_name,
|
|
63
|
+
"cik": self.cik,
|
|
64
|
+
"primary_document_url": self.primary_document_url,
|
|
65
|
+
"index_url": self.index_url,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True)
|
|
70
|
+
class Fact:
|
|
71
|
+
concept: str
|
|
72
|
+
taxonomy: str
|
|
73
|
+
unit: str
|
|
74
|
+
value: Any
|
|
75
|
+
start: date | None
|
|
76
|
+
end: date | None
|
|
77
|
+
filed: date | None
|
|
78
|
+
form: str | None
|
|
79
|
+
fiscal_year: int | None
|
|
80
|
+
fiscal_period: str | None
|
|
81
|
+
accession_number: str | None
|
|
82
|
+
frame: str | None = None
|
|
83
|
+
|
|
84
|
+
def to_dict(self) -> dict[str, Any]:
|
|
85
|
+
return {
|
|
86
|
+
"concept": self.concept,
|
|
87
|
+
"taxonomy": self.taxonomy,
|
|
88
|
+
"unit": self.unit,
|
|
89
|
+
"value": self.value,
|
|
90
|
+
"start": self.start.isoformat() if self.start else None,
|
|
91
|
+
"end": self.end.isoformat() if self.end else None,
|
|
92
|
+
"filed": self.filed.isoformat() if self.filed else None,
|
|
93
|
+
"form": self.form,
|
|
94
|
+
"fiscal_year": self.fiscal_year,
|
|
95
|
+
"fiscal_period": self.fiscal_period,
|
|
96
|
+
"accession_number": self.accession_number,
|
|
97
|
+
"frame": self.frame,
|
|
98
|
+
}
|
snoopsharp/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: snoopsharp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for SEC EDGAR company filings and XBRL facts
|
|
5
|
+
Author: REDX Contributors
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: sec,edgar,filings,xbrl,finance,stocks
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest>=7.4; extra == "dev"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# SnoopSharp
|
|
23
|
+
|
|
24
|
+
SEC EDGAR has a ton of useful public data, but getting it out is fiddlier than it should be. The endpoints are spread out, the JSON is bulky, XBRL facts take some digging, and the SEC expects you to identify yourself and not hammer their servers.
|
|
25
|
+
|
|
26
|
+
SnoopSharp wraps the common EDGAR stuff in a plain Python API, so you can go from “I want Apple’s last 10-Ks” to working code without wrestling the raw endpoints.
|
|
27
|
+
|
|
28
|
+
## What it’s good for
|
|
29
|
+
|
|
30
|
+
- **Looking up companies** by ticker or CIK.
|
|
31
|
+
- **Pulling recent filings** (10-K, 10-Q, 8-K, etc.) from the SEC submissions endpoint.
|
|
32
|
+
- **Grabbing XBRL facts** (like revenue) without manually walking a giant JSON tree.
|
|
33
|
+
- **Playing nice with SEC rules** — it asks for a real `User-Agent` and throttles requests by default.
|
|
34
|
+
|
|
35
|
+
## Install (local/dev)
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install -e .
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from snoopsharp import EdgarClient
|
|
45
|
+
|
|
46
|
+
# The SEC asks for a descriptive User-Agent with contact info.
|
|
47
|
+
client = EdgarClient(user_agent="MyApp/1.0 (contact@example.com)")
|
|
48
|
+
|
|
49
|
+
company = client.company("AAPL")
|
|
50
|
+
print(company.name) # Apple Inc.
|
|
51
|
+
print(company.cik) # 0000320193
|
|
52
|
+
|
|
53
|
+
# Grab the latest 10-K filings
|
|
54
|
+
for filing in company.filings(form="10-K", limit=5):
|
|
55
|
+
print(filing.filed_at, filing.form, filing.accession_number)
|
|
56
|
+
print(filing.primary_document_url)
|
|
57
|
+
|
|
58
|
+
# Pull a specific XBRL fact
|
|
59
|
+
facts = company.facts("us-gaap", "Revenues")
|
|
60
|
+
latest = facts.latest(form="10-K", period="FY")
|
|
61
|
+
|
|
62
|
+
if latest:
|
|
63
|
+
print(latest.value, latest.unit, latest.end, latest.filed)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Ticker or CIK, either is fine
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
client.get_company("MSFT")
|
|
70
|
+
client.get_company(320193)
|
|
71
|
+
client.get_company("CIK0000320193")
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## If you want the raw SEC JSON
|
|
75
|
+
|
|
76
|
+
Sometimes you just want the source payload:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
submissions = client.get_submissions("AAPL")
|
|
80
|
+
facts_json = client.get_company_facts("AAPL")
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## A few honest notes
|
|
84
|
+
|
|
85
|
+
- **Use a real User-Agent.** The SEC may block generic or anonymous clients. Something like `AppName/Version (you@example.com)` is the right move.
|
|
86
|
+
- **Be polite.** The client throttles requests by default (about 10 requests/second). Leave that on.
|
|
87
|
+
- **Public data still needs context.** EDGAR is the source, but companies report things differently. If a number really matters, trace it back to the actual filing.
|
|
88
|
+
- This is an MVP. It covers the `submissions` and `companyfacts` endpoints. It doesn’t parse full XBRL documents or every corner of EDGAR.
|
|
89
|
+
|
|
90
|
+
## Development
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
pip install -e .[dev]
|
|
94
|
+
pytest
|
|
95
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
snoopsharp/__init__.py,sha256=_CfoIrIar5TxTRhbQSNNRRW6j5Sq_k6EpWOtjZavuuY,435
|
|
2
|
+
snoopsharp/client.py,sha256=Verao2JbubLLJbw04nWHxnfnOPPQ_vXH5tMot5WjvGQ,16984
|
|
3
|
+
snoopsharp/errors.py,sha256=9lnmB8CjuQPZboXQ9YGEQz58E8kdgWRKGNGzW0lRiuY,475
|
|
4
|
+
snoopsharp/models.py,sha256=CHnDZnWqf3qN-P6rsOeKlttwEfHxEGMxJNx29FG44uU,3095
|
|
5
|
+
snoopsharp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
snoopsharp-0.1.0.dist-info/licenses/LICENSE,sha256=xqlhK2dYD4XQ0q8RVsRpcpTyqR5AMUzga2Ta0PJpTrU,1078
|
|
7
|
+
snoopsharp-0.1.0.dist-info/METADATA,sha256=QijKpl1tqX0qc2n48xq196eBibvCUPoT49aDBQpXwrA,3271
|
|
8
|
+
snoopsharp-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
snoopsharp-0.1.0.dist-info/top_level.txt,sha256=-YIH6VUbo-8JdWwGoXldG1NRVfoY4tdEO3ZBkXCzm00,11
|
|
10
|
+
snoopsharp-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 REDX Contributors
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
snoopsharp
|