snoopsharp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,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,74 @@
1
+ # SnoopSharp
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ ## What it’s good for
8
+
9
+ - **Looking up companies** by ticker or CIK.
10
+ - **Pulling recent filings** (10-K, 10-Q, 8-K, etc.) from the SEC submissions endpoint.
11
+ - **Grabbing XBRL facts** (like revenue) without manually walking a giant JSON tree.
12
+ - **Playing nice with SEC rules** — it asks for a real `User-Agent` and throttles requests by default.
13
+
14
+ ## Install (local/dev)
15
+
16
+ ```bash
17
+ pip install -e .
18
+ ```
19
+
20
+ ## Quick start
21
+
22
+ ```python
23
+ from snoopsharp import EdgarClient
24
+
25
+ # The SEC asks for a descriptive User-Agent with contact info.
26
+ client = EdgarClient(user_agent="MyApp/1.0 (contact@example.com)")
27
+
28
+ company = client.company("AAPL")
29
+ print(company.name) # Apple Inc.
30
+ print(company.cik) # 0000320193
31
+
32
+ # Grab the latest 10-K filings
33
+ for filing in company.filings(form="10-K", limit=5):
34
+ print(filing.filed_at, filing.form, filing.accession_number)
35
+ print(filing.primary_document_url)
36
+
37
+ # Pull a specific XBRL fact
38
+ facts = company.facts("us-gaap", "Revenues")
39
+ latest = facts.latest(form="10-K", period="FY")
40
+
41
+ if latest:
42
+ print(latest.value, latest.unit, latest.end, latest.filed)
43
+ ```
44
+
45
+ ## Ticker or CIK, either is fine
46
+
47
+ ```python
48
+ client.get_company("MSFT")
49
+ client.get_company(320193)
50
+ client.get_company("CIK0000320193")
51
+ ```
52
+
53
+ ## If you want the raw SEC JSON
54
+
55
+ Sometimes you just want the source payload:
56
+
57
+ ```python
58
+ submissions = client.get_submissions("AAPL")
59
+ facts_json = client.get_company_facts("AAPL")
60
+ ```
61
+
62
+ ## A few honest notes
63
+
64
+ - **Use a real User-Agent.** The SEC may block generic or anonymous clients. Something like `AppName/Version (you@example.com)` is the right move.
65
+ - **Be polite.** The client throttles requests by default (about 10 requests/second). Leave that on.
66
+ - **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.
67
+ - This is an MVP. It covers the `submissions` and `companyfacts` endpoints. It doesn’t parse full XBRL documents or every corner of EDGAR.
68
+
69
+ ## Development
70
+
71
+ ```bash
72
+ pip install -e .[dev]
73
+ pytest
74
+ ```
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "snoopsharp"
7
+ version = "0.1.0"
8
+ description = "Python SDK for SEC EDGAR company filings and XBRL facts"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "REDX Contributors" }]
13
+ dependencies = []
14
+ keywords = ["sec", "edgar", "filings", "xbrl", "finance", "stocks"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: Office/Business :: Financial",
22
+ "Typing :: Typed",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest>=7.4"]
27
+
28
+ [tool.setuptools]
29
+ package-dir = {"" = "src"}
30
+ include-package-data = true
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+ include = ["snoopsharp*"]
35
+
36
+ [tool.setuptools.package-data]
37
+ snoopsharp = ["py.typed"]
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
41
+ pythonpath = ["src"]
42
+ addopts = "-ra"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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"
@@ -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)
@@ -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."""
@@ -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
+ }
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,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/snoopsharp/__init__.py
5
+ src/snoopsharp/client.py
6
+ src/snoopsharp/errors.py
7
+ src/snoopsharp/models.py
8
+ src/snoopsharp/py.typed
9
+ src/snoopsharp.egg-info/PKG-INFO
10
+ src/snoopsharp.egg-info/SOURCES.txt
11
+ src/snoopsharp.egg-info/dependency_links.txt
12
+ src/snoopsharp.egg-info/requires.txt
13
+ src/snoopsharp.egg-info/top_level.txt
14
+ tests/test_snoopsharp.py
@@ -0,0 +1,3 @@
1
+
2
+ [dev]
3
+ pytest>=7.4
@@ -0,0 +1 @@
1
+ snoopsharp
@@ -0,0 +1,306 @@
1
+ import json
2
+ from datetime import date
3
+
4
+ import pytest
5
+ import urllib.error
6
+
7
+ from snoopsharp import BadResponse, EdgarClient, InvalidUserAgent, NotFound
8
+
9
+
10
+ def make_client():
11
+ return EdgarClient(user_agent="TestApp/1.0 (test@example.com)", min_interval=0)
12
+
13
+
14
+ def test_requires_user_agent():
15
+ with pytest.raises(InvalidUserAgent):
16
+ EdgarClient(user_agent="no-contact-info")
17
+ with pytest.raises(InvalidUserAgent):
18
+ EdgarClient(user_agent="")
19
+
20
+
21
+ def test_get_company_by_ticker_uses_ticker_map(monkeypatch):
22
+ client = make_client()
23
+
24
+ def fake_get_json(url):
25
+ assert url.endswith("/files/company_tickers.json")
26
+ return {
27
+ "0": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."},
28
+ "1": {"cik_str": 789019, "ticker": "MSFT", "title": "MICROSOFT CORP"},
29
+ }
30
+
31
+ monkeypatch.setattr(client, "_get_json", fake_get_json)
32
+ company = client.get_company("aapl")
33
+ assert company.cik == "0000320193"
34
+ assert company.ticker == "AAPL"
35
+ assert company.name == "Apple Inc."
36
+
37
+
38
+ def test_get_company_not_found(monkeypatch):
39
+ client = make_client()
40
+ monkeypatch.setattr(client, "_get_json", lambda url: {"0": {"cik_str": 1, "ticker": "ZZZ", "title": "Z"}})
41
+ with pytest.raises(NotFound):
42
+ client.get_company("AAPL")
43
+
44
+
45
+ def test_get_filings_filters_and_limits(monkeypatch):
46
+ client = make_client()
47
+
48
+ def fake_get_json(url):
49
+ if "company_tickers.json" in url:
50
+ return {"0": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."}}
51
+ if "submissions/CIK0000320193.json" in url:
52
+ return {
53
+ "cik": "0000320193",
54
+ "name": "Apple Inc.",
55
+ "filings": {
56
+ "recent": {
57
+ "accessionNumber": ["0000320193-24-000001", "0000320193-24-000002", "0000320193-23-000003"],
58
+ "filingDate": ["2024-11-01", "2024-08-01", "2023-11-03"],
59
+ "reportDate": ["2024-09-28", "2024-06-29", "2023-09-30"],
60
+ "form": ["10-K", "10-Q", "10-K"],
61
+ "primaryDocument": ["a10k.htm", "a10q.htm", "old10k.htm"],
62
+ "primaryDocDescription": ["Annual report", "Quarterly report", "Annual report"],
63
+ }
64
+ },
65
+ }
66
+ raise AssertionError(url)
67
+
68
+ monkeypatch.setattr(client, "_get_json", fake_get_json)
69
+ filings = client.get_filings("AAPL", form="10-K", limit=1)
70
+
71
+ assert len(filings) == 1
72
+ f = filings[0]
73
+ assert f.form == "10-K"
74
+ assert f.accession_number == "0000320193-24-000001"
75
+ assert f.filed_at == date(2024, 11, 1)
76
+ assert f.company_name == "Apple Inc."
77
+ assert f.primary_document_url == (
78
+ "https://www.sec.gov/Archives/edgar/data/320193/000032019324000001/a10k.htm"
79
+ )
80
+
81
+
82
+ def test_company_filings_convenience(monkeypatch):
83
+ client = make_client()
84
+
85
+ def fake_get_json(url):
86
+ if "company_tickers.json" in url:
87
+ return {"0": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."}}
88
+ return {
89
+ "name": "Apple Inc.",
90
+ "filings": {"recent": {
91
+ "accessionNumber": ["1"],
92
+ "filingDate": ["2024-01-01"],
93
+ "reportDate": ["2023-12-31"],
94
+ "form": ["8-K"],
95
+ "primaryDocument": ["d1.htm"],
96
+ "primaryDocDescription": [""],
97
+ }},
98
+ }
99
+
100
+ monkeypatch.setattr(client, "_get_json", fake_get_json)
101
+ company = client.company("AAPL")
102
+ filings = company.filings(form=["8-K"])
103
+ assert len(filings) == 1
104
+ assert filings[0].form == "8-K"
105
+
106
+
107
+ def test_get_facts_and_latest(monkeypatch):
108
+ client = make_client()
109
+
110
+ def fake_get_json(url):
111
+ if "company_tickers.json" in url:
112
+ return {"0": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."}}
113
+ if "companyfacts/CIK0000320193.json" in url:
114
+ return {
115
+ "cik": 320193,
116
+ "entityName": "Apple Inc.",
117
+ "facts": {
118
+ "us-gaap": {
119
+ "Revenues": {
120
+ "label": "Revenues",
121
+ "units": {
122
+ "USD": [
123
+ {"end": "2023-09-30", "val": 383285000000, "fy": 2023, "fp": "FY", "form": "10-K", "filed": "2023-11-03", "accn": "old"},
124
+ {"end": "2024-09-28", "val": 391035000000, "fy": 2024, "fp": "FY", "form": "10-K", "filed": "2024-11-01", "accn": "new"},
125
+ {"end": "2024-06-29", "val": 85777000000, "fy": 2024, "fp": "Q3", "form": "10-Q", "filed": "2024-08-02", "accn": "q3"},
126
+ ]
127
+ }
128
+ }
129
+ }
130
+ },
131
+ }
132
+ raise AssertionError(url)
133
+
134
+ monkeypatch.setattr(client, "_get_json", fake_get_json)
135
+ facts = client.get_facts("AAPL", "us-gaap", "Revenues", unit="USD")
136
+ assert len(facts) == 3
137
+ # sorted newest filed first
138
+ assert facts[0].accession_number == "new"
139
+
140
+ latest_fy = facts.latest(form="10-K", period="FY")
141
+ assert latest_fy is not None
142
+ assert latest_fy.value == 391035000000
143
+ assert latest_fy.end == date(2024, 9, 28)
144
+
145
+ latest_q = facts.latest(period="Q3")
146
+ assert latest_q is not None
147
+ assert latest_q.fiscal_period == "Q3"
148
+
149
+
150
+ def test_document_url_without_cik():
151
+ from snoopsharp.models import Filing
152
+
153
+ f = Filing("1", "10-K", None, None, "a.htm", None, cik=None)
154
+ assert f.primary_document_url is None
155
+
156
+ def test_search_companies(monkeypatch):
157
+ client = make_client()
158
+
159
+ def fake_get_json(url):
160
+ assert "company_tickers.json" in url
161
+ return {
162
+ "0": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."},
163
+ "1": {"cik_str": 789019, "ticker": "MSFT", "title": "MICROSOFT CORP"},
164
+ "2": {"cik_str": 1045810, "ticker": "NVDA", "title": "NVIDIA CORP"},
165
+ }
166
+
167
+ monkeypatch.setattr(client, "_get_json", fake_get_json)
168
+ results = client.search_companies("micro")
169
+ assert len(results) == 1
170
+ assert results[0].ticker == "MSFT"
171
+
172
+ by_ticker = client.search_companies("NV")
173
+ assert by_ticker[0].ticker == "NVDA"
174
+
175
+
176
+ def test_latest_filing(monkeypatch):
177
+ client = make_client()
178
+
179
+ def fake_get_json(url):
180
+ if "company_tickers.json" in url:
181
+ return {"0": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."}}
182
+ return {
183
+ "name": "Apple Inc.",
184
+ "filings": {"recent": {
185
+ "accessionNumber": ["0000320193-24-000001", "0000320193-24-000002"],
186
+ "filingDate": ["2024-11-01", "2024-08-01"],
187
+ "reportDate": ["2024-09-28", "2024-06-29"],
188
+ "form": ["10-K", "10-Q"],
189
+ "primaryDocument": ["a10k.htm", "a10q.htm"],
190
+ "primaryDocDescription": ["Annual report", "Quarterly report"],
191
+ }},
192
+ }
193
+
194
+ monkeypatch.setattr(client, "_get_json", fake_get_json)
195
+ latest = client.latest_filing("AAPL", form="10-Q")
196
+ assert latest is not None
197
+ assert latest.form == "10-Q"
198
+ assert latest.accession_number == "0000320193-24-000002"
199
+
200
+
201
+ def test_download_filing_uses_primary_document(monkeypatch):
202
+ client = make_client()
203
+ calls = {}
204
+
205
+ def fake_get_bytes(url):
206
+ calls["url"] = url
207
+ return b"<html>filing</html>"
208
+
209
+ monkeypatch.setattr(client, "_get_bytes", fake_get_bytes)
210
+ from snoopsharp.models import Filing
211
+
212
+ filing = Filing(
213
+ accession_number="0000320193-24-000001",
214
+ form="10-K",
215
+ filed_at=None,
216
+ report_date=None,
217
+ primary_document="a10k.htm",
218
+ primary_doc_description=None,
219
+ company_name="Apple Inc.",
220
+ cik="0000320193",
221
+ )
222
+ content = client.download_filing(filing)
223
+ assert content == b"<html>filing</html>"
224
+ assert calls["url"].endswith("/320193/000032019324000001/a10k.htm")
225
+
226
+
227
+ def test_filings_date_filters(monkeypatch):
228
+ client = make_client()
229
+
230
+ def fake_get_json(url):
231
+ if "company_tickers.json" in url:
232
+ return {"0": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."}}
233
+ return {
234
+ "name": "Apple Inc.",
235
+ "filings": {"recent": {
236
+ "accessionNumber": ["a", "b", "c"],
237
+ "filingDate": ["2024-11-01", "2024-08-01", "2023-11-03"],
238
+ "reportDate": ["2024-09-28", "2024-06-29", "2023-09-30"],
239
+ "form": ["10-K", "10-Q", "10-K"],
240
+ "primaryDocument": ["a.htm", "b.htm", "c.htm"],
241
+ "primaryDocDescription": ["", "", ""],
242
+ }},
243
+ }
244
+
245
+ monkeypatch.setattr(client, "_get_json", fake_get_json)
246
+ filings = client.get_filings("AAPL", after="2024-01-01")
247
+ assert [f.accession_number for f in filings] == ["a", "b"]
248
+
249
+ filings = client.get_filings("AAPL", before="2024-09-01")
250
+ assert [f.accession_number for f in filings] == ["b", "c"]
251
+
252
+
253
+ def test_list_tickers_alias(monkeypatch):
254
+ client = make_client()
255
+ monkeypatch.setattr(client, "_get_json", lambda url: {"0": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."}})
256
+ assert client.list_tickers()[0].ticker == "AAPL"
257
+
258
+
259
+ def test_model_to_dict():
260
+ from snoopsharp.models import Company, Filing, Fact
261
+ company = Company(cik="0000320193", ticker="AAPL", name="Apple Inc.")
262
+ assert company.to_dict()["ticker"] == "AAPL"
263
+
264
+ filing = Filing("1-2", "10-K", date(2024, 1, 1), None, "a.htm", "Annual", "Apple", "0000320193")
265
+ d = filing.to_dict()
266
+ assert d["filed_at"] == "2024-01-01"
267
+ assert d["primary_document_url"].endswith("/a.htm")
268
+
269
+ fact = Fact("Revenues", "us-gaap", "USD", 100, None, date(2024, 9, 28), date(2024, 11, 1), "10-K", 2024, "FY", "accn")
270
+ fd = fact.to_dict()
271
+ assert fd["value"] == 100
272
+ assert fd["end"] == "2024-09-28"
273
+
274
+
275
+ def test_download_to(tmp_path, monkeypatch):
276
+ client = make_client()
277
+ monkeypatch.setattr(client, "_get_bytes", lambda url: b"hello")
278
+ out = client.download_to("https://example.com/a.htm", str(tmp_path / "a.htm"))
279
+ assert out.endswith("a.htm")
280
+ assert (tmp_path / "a.htm").read_bytes() == b"hello"
281
+
282
+
283
+ def test_request_retries_on_429(monkeypatch):
284
+ client = make_client()
285
+ calls = {"n": 0}
286
+
287
+ class FakeResp:
288
+ headers = {}
289
+ def read(self):
290
+ return b'{"ok": true}'
291
+ def __enter__(self):
292
+ return self
293
+ def __exit__(self, exc_type, exc, tb):
294
+ return False
295
+
296
+ def fake_urlopen(req, timeout=30.0):
297
+ calls["n"] += 1
298
+ if calls["n"] == 1:
299
+ raise urllib.error.HTTPError(req.full_url, 429, "rate limited", hdrs=None, fp=None)
300
+ return FakeResp()
301
+
302
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
303
+ monkeypatch.setattr("time.sleep", lambda s: None)
304
+ data = client._get_json("https://example.com/test.json")
305
+ assert data == {"ok": True}
306
+ assert calls["n"] == 2