Metadata-Version: 2.5
Name: secblast
Version: 3.1.0
Summary: Python SDK for the SEC Blast v3 API: SEC EDGAR filings, documents, full-text search, and XBRL financial data
Project-URL: Homepage, https://www.secblast.com/docs/sdks
Project-URL: Documentation, https://www.secblast.com/docs/sdks
Author-email: SEC Blast <support@secblast.com>
License-Expression: MIT
License-File: LICENSE
Keywords: api,edgar,filings,financial,sdk,sec,xbrl
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx>=0.25.0
Requires-Dist: typing-extensions>=4.7.0
Provides-Extra: dev
Requires-Dist: build>=1.0.0; extra == 'dev'
Requires-Dist: mypy>=1.8.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Description-Content-Type: text/markdown

# SEC Blast Python SDK

The Python client for the SEC Blast v3 API: SEC EDGAR filings, documents, full-text search, XBRL financial data, ownership data, and the filing stream.

Version 1.0 targets the v3 API (`https://api.secblast.com/v3`). Versions 0.x targeted the v2 API.

## Install

```bash
pip install secblast
```

It needs Python 3.9 or later. It depends on `httpx` and `typing_extensions`.

## Quickstart

```python
from secblast import SecBlastClient

client = SecBlastClient()  # reads SECBLAST_API_KEY
page = client.list_filings(ticker="AAPL", form="10-K", limit=5)
for filing in page["data"]:
    print(filing["accession"], filing["filing_date"])
```

## The client

```python
client = SecBlastClient(
    api_key="sb_...",          # an API key or an OAuth access token; default: SECBLAST_API_KEY
    base_url="https://api.secblast.com/v3",  # default: SECBLAST_BASE_URL, then this URL
    timeout=60.0,              # seconds
    max_retries=3,             # retries of 429 and 503 responses
    max_retry_wait=60.0,       # the longest Retry-After to wait for, in seconds
)
```

- The credential is sent as `Authorization: Bearer <credential>`.
- Use the client as a context manager (`with SecBlastClient() as client:`), or call `client.close()`.
- `AsyncSecBlastClient` takes the same arguments. Its methods are coroutines, and its `iter_*` methods and `stream()` are async iterators.

## Methods

There is one method for each v3 operation, such as `list_filings`, `get_filing`, `get_entity`, `search`, `get_income_statement`, `list_insider_transactions`, and `create_endpoint`. Path parameters are positional. Query parameters are keyword arguments with the API's names. `from` is spelled `from_`, and camelCase names such as `dateRange` are snake_case (`date_range`). `extra_params={...}` sends parameters as given.

```python
entity = client.get_entity("AAPL")           # a CIK or a ticker
filing = client.get_filing("0000320193-26-000026")
hits = client.search(q='"going concern"', forms="10-K", filed_from="2024-01-01", limit=10)
income = client.get_income_statement("MSFT", period="annual", limit=5)
```

- List parameters take a list or a comma-separated string: `ticker=["AAPL", "MSFT"]` and `ticker="AAPL,MSFT"` are the same. `True` and `False` are sent as `true` and `false`. Dates take a string or a `datetime.date`.
- Responses are plain dicts. `secblast.models` has a TypedDict for every schema in the OpenAPI document, so editors and type checkers know the keys.

## Paging

List methods return one page: `data`, `has_more`, and `next_cursor`. Each paged method has an `iter_*` twin that follows `next_cursor` until `has_more` is false. It makes requests as you iterate.

```python
for row in client.iter_insider_transactions(issuer_ticker="TSLA", filed_from="2025-01-01"):
    print(row)

page = client.list_filings(cik=320193, limit=100)
next_page = client.list_filings(cik=320193, limit=100, cursor=page["next_cursor"])
```

## Documents

```python
docs = client.list_documents("0000320193-26-000026")["data"]
raw = client.get_document("0000320193-26-000026", "1")         # bytes, as filed
text = client.get_document_text("0000320193-26-000026", "1")   # str, the extracted text
pdf = client.get_document_pdf("0000320193-26-000026", "1")     # bytes, a PDF of one document
whole = client.get_filing_pdf("0000320193-26-000026")          # bytes, a PDF of the filing

with open("10-K.pdf", "wb") as f:
    f.write(whole)
```

A document is named by its sequence number or its file name.

## Errors

Every error response raises an `APIError` subclass built from the RFC 9457 problem body. It has `status`, `code`, `detail`, `request_id`, `parameter`, and the whole body in `problem`. `code` is stable.

| Status | Exception |
|---|---|
| 400, 422 | `ValidationError` (also `BadRequestError`) |
| 401 | `AuthenticationError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 409 | `ConflictError` |
| 410 | `GoneError` |
| 429 | `RateLimitError`, with `retry_after` in seconds |
| 503 | `ServiceUnavailableError` |
| other 5xx | `ServerError` |

No HTTP response (DNS, connection, or timeout) raises `APIConnectionError`. All of them are `SecBlastError`.

```python
from secblast import SecBlastClient, ValidationError

try:
    client.list_filings(ticker="NOPE")
except ValidationError as e:
    print(e.status, e.code, e.detail, e.request_id)   # 400 unknown_ticker ...
```

Retries: a 429 or 503 response is retried up to `max_retries` times. The client waits for `Retry-After` when the header is present and at most `max_retry_wait` seconds; a longer `Retry-After` raises the error at once. Without the header, it waits about 0.5, 1, 2, and 4 seconds. A GET that gets no response is retried the same way.

## Stream

`stream()` long-polls `GET /v3/stream` and yields events as they arrive. It takes the `get_stream` filters (`forms`, `tickers`, `ciks`, `items`, `types`, and so on).

```python
stream = client.stream(after=saved_cursor, forms=["8-K"], items=["2.02"])
for event in stream:
    handle(event)              # event["id"], event["type"], event["data"]["filing"]
    save(stream.cursor)        # where to resume
```

- `after` is a `next_cursor` from an earlier run, or `"now"`. Left out, the stream starts at the newest event.
- `stream.cursor` moves to a page's `next_cursor` after the last event of that page. Resuming from it in the middle of a page delivers the rest of that page again. Each event has an `id`.
- The iterator runs until you stop it. With `stop_when_caught_up=True`, it stops when a page has `has_more` false; add `wait=0` to return at once.

## Webhooks

`verify_webhook` checks the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers of a delivery (Standard Webhooks v1) against the endpoint's signing secret and returns the parsed JSON body.

```python
from secblast import verify_webhook, WebhookVerificationError

try:
    event = verify_webhook(raw_body, request_headers, "whsec_...")
except WebhookVerificationError:
    ...  # answer 400
```

- `raw_body` is the request body as bytes, exactly as received; the signature covers `<webhook-id>.<webhook-timestamp>.<body>`. A body parsed and serialized again (`request.json()`, `json.dumps`) is not the signed byte sequence and does not verify; Flask `request.get_data()` and Starlette `await request.body()` return the bytes.
- Signature check: base64(HMAC-SHA256) with the secret's bytes (the base64 after `whsec_`), compared in constant time. The header holds one or more space-separated `v1,<signature>` entries; two entries are sent while a rotated secret's previous value still signs, and the delivery verifies when any entry matches. `secret` can also be a list of `whsec_` values.
- Tolerance: the `webhook-timestamp` must be within 5 minutes of the clock (`tolerance_s=300`; `now=` sets the reference time, in Unix seconds). A non-finite or negative `tolerance_s`, or a non-finite `now`, raises `WebhookVerificationError`. SEC Blast stamps every attempt with its own time.
- Deduplication: the `webhook-id` is the same on every attempt of a delivery, and is the `id` in the body.
- Raises `WebhookVerificationError` for a missing header, a timestamp outside the tolerance, no matching `v1` signature, a secret that is not a `whsec_` value, or a body that is not a JSON object.

## License

MIT
