quantset 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,48 @@
1
+ name: Publish Python package
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: '3.12'
18
+ - run: python -m pip install build twine pytest
19
+ - name: Check release tag
20
+ run: |
21
+ python - <<'PY'
22
+ import os
23
+ import tomllib
24
+ from pathlib import Path
25
+ version = tomllib.loads(Path("pyproject.toml").read_text())["project"]["version"]
26
+ if os.environ["GITHUB_REF_NAME"] != f"v{version}":
27
+ raise SystemExit(f"Expected release tag v{version}")
28
+ PY
29
+ - run: python -m build
30
+ - run: python -m twine check dist/*
31
+ - run: python -m pip install dist/*.whl && python -c 'import quantset'
32
+ - run: python -m pytest -q tests
33
+ - uses: actions/upload-artifact@v4
34
+ with:
35
+ name: distributions
36
+ path: dist/
37
+ publish:
38
+ needs: build
39
+ runs-on: ubuntu-latest
40
+ environment: pypi
41
+ permissions:
42
+ id-token: write
43
+ steps:
44
+ - uses: actions/download-artifact@v4
45
+ with:
46
+ name: distributions
47
+ path: dist/
48
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,4 @@
1
+ __pycache__/
2
+ .venv/
3
+ dist/
4
+ .pytest_cache/
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.5
2
+ Name: quantset
3
+ Version: 0.1.0
4
+ Summary: 52,000+ global stocks (67 countries, 64yr US history), 734 crypto pairs, live quotes, 40-factor stock screener, consensus estimates, ETF look-through, correlations, macro curves & SEC financials in one Python SDK.
5
+ Project-URL: Homepage, https://quantset.dev
6
+ Project-URL: Documentation, https://quantset.dev/docs/quickstart
7
+ Project-URL: Live API Playground, https://quantset.dev/docs/api
8
+ Project-URL: Switch from yfinance, https://quantset.dev/docs/switch/yfinance
9
+ Project-URL: Switch from FMP, https://quantset.dev/docs/switch/fmp
10
+ Project-URL: MCP for Claude & Cursor, https://quantset.dev/docs/agents
11
+ Project-URL: Repository, https://github.com/quantset/quantset-python
12
+ Project-URL: Issues, https://github.com/quantset/quantset-python/issues
13
+ Author-email: QuantSet <hello@quantset.dev>
14
+ License: MIT
15
+ Keywords: analyst-estimates,backtesting,crypto-api,earnings-calendar,etf-holdings,fmp-alternative,forex-api,market-data,mcp,pandas,polars,quantitative-finance,stock-market-api,stock-screener,treasury-yields,yfinance-alternative
16
+ Classifier: Development Status :: 4 - Beta
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Intended Audience :: Financial and Insurance Industry
19
+ Classifier: Intended Audience :: Science/Research
20
+ Classifier: License :: OSI Approved :: MIT License
21
+ Classifier: Operating System :: OS Independent
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Topic :: Office/Business :: Financial :: Investment
28
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
29
+ Classifier: Typing :: Typed
30
+ Requires-Python: >=3.10
31
+ Requires-Dist: httpx<1,>=0.27
32
+ Provides-Extra: pandas
33
+ Requires-Dist: pandas>=2; extra == 'pandas'
34
+ Provides-Extra: polars
35
+ Requires-Dist: polars>=1; extra == 'polars'
36
+ Provides-Extra: test
37
+ Requires-Dist: pytest>=8; extra == 'test'
38
+ Description-Content-Type: text/markdown
39
+
40
+ # QuantSet — The Institutional Python SDK for Global Stocks, SEC EDGAR XBRL, 4,899 ETFs, Estimates & Macro
41
+
42
+ **Stop stitching together broken `yfinance` scrapers, `429 Too Many Requests` IP bans, YTD 10-Q cash-flow traps, and overpriced legacy data feeds.**
43
+
44
+ **[QuantSet](https://quantset.dev)** gives Python quants, backtests, and AI agents **90,000+ global listings across 67 countries** (US daily OHLCV back to **1962**, S&P 500 back to **1927**), **127M+ reconciled SEC EDGAR XBRL facts (`10-K`, discrete quarterly `10-Q`, `Form 13F`, `Form 4` w/ Rule 10b5-1 flags, segments & debt walls)**, **4,899 ETF look-through holdings (`175k+` N-PORT rows)**, **Wall Street consensus estimates**, a **40+ factor point-in-time stock screener**, **734 crypto pairs**, **42 ECB FX currencies**, **hourly & 5-minute intraday bars**, **multi-asset correlation & drawdown analytics**, and **live U.S. Treasury/TIPS/FRED macroeconomic curves**—all behind one fast, typed Python client with `.to_df()` Pandas/Polars support and built-in credit-budget controls.
45
+
46
+ Zero signup required to try: every install works **immediately out of the box** on benchmark US, London, Tokyo, India, ETF, index, macro, and crypto symbols (`mw_demo`).
47
+
48
+ **[Live Playground](https://quantset.dev/docs/api)** · **[60-Second Quickstart](https://quantset.dev/docs/quickstart)** · **[vs. yfinance](https://quantset.dev/docs/switch/yfinance)** · **[1-Line FMP Migration](https://quantset.dev/docs/switch/fmp)** · **[Claude & Cursor MCP](https://quantset.dev/docs/agents)**
49
+
50
+ ---
51
+
52
+ ## Credit estimates and receipts
53
+
54
+ ```python
55
+ from quantset import Client
56
+
57
+ with Client(max_credits_per_request=10, workflow_id="daily-research") as client:
58
+ planned = {"ticker": "NVDA", "limit": 251}
59
+ quote = client.estimate_credit_cost("GET", "/prices", params=planned)
60
+ read = client.get_with_receipt("prices", max_credits=quote["maximum_credits"], **planned)
61
+ print(read.receipt.credit_cost, read.receipt.credits_remaining)
62
+ history = client.price_history("NVDA", limit=250, max_pages=5, credit_budget=5)
63
+ ```
64
+
65
+ `rate_card()` and `estimate_credit_cost()` are free. The price ceiling is enforced on the server. A budgeted paginated read sends the remaining budget on each call and leaves `next_cursor` when stopped early. Use `page_receipts` to reconcile combined history pages and `QuantsetError.receipt` to inspect a refused request.
66
+
67
+
68
+ ## Install & Run in 15 Seconds (No API Key Needed to Start)
69
+
70
+ ```sh
71
+ pip install "quantset[pandas]" # or: pip install "quantset[polars]" / pip install quantset
72
+ ```
73
+
74
+ ```python
75
+ import quantset as qs
76
+
77
+ # Five daily bars in one price request
78
+ df = qs.prices("NVDA", limit=5).to_df()
79
+
80
+ # Batch live/daily quotes across US stocks, London, Tokyo & crypto in 1 request
81
+ quotes = qs.quotes(["NVDA", "AAPL", "global:SHEL.L", "global:1301.T", "crypto:BTCUSDT"]).to_df()
82
+
83
+ # Wall Street forward EPS/revenue consensus + quarterly revenue/cash-flow fundamentals
84
+ est = qs.estimates("NVDA", metric="eps").to_df()
85
+ inc = qs.income(["AAPL"], period="quarterly", limit_per_instrument=8).to_df()
86
+ ```
87
+
88
+ Ready for the full **52,000+ symbol** universe and market-wide stock screening? Set `QUANTSET_API_KEY` (choose a prepaid pack or a monthly credit pool; consult the published rate card for batch and history costs). **[Get a full key →](https://quantset.dev/pricing)**
89
+
90
+ ---
91
+
92
+ ## Why Quants & Builders Move Off `yfinance` & Fragmented APIs
93
+
94
+ - **Zero `429 Too Many Requests` or cookie/crumb bans on AWS & GitHub Actions:** Clean REST contract with explicit `X-RateLimit-Remaining` and `Retry-After` headers.
95
+ - **Built-in quant primitives (not just raw bars):** Total-return series (dividends reinvested), peak-to-trough drawdowns, multi-asset USD correlation matrices, point-in-time historical P/E, and S&P 500 benchmark alpha out of the box.
96
+ - **40+ factor institutional screener:** Filter 14,000+ US listings by `ROIC`, `EV/EBITDA`, `EV/FCF`, `FFO` (for REITs), `SMA-50/200`, dividend-increase streaks, and net buyback share-count shrinkage.
97
+ - **Reverse ETF look-through (`4,899` funds):** See every stock inside an ETF *or* reverse-query which ETFs hold a stock and at what weight (`etf-exposures`).
98
+ - **Evidence-checked `adj_close` & zero fake zeros:** Splits and dividends are cross-checked against actual price gaps. Unverified or missing values return `None` (`null`)—never silently coerced to `0`.
99
+ - **1-line drop-in FMP compatibility:** Migrating an existing Financial Modeling Prep codebase? Swap the base URL and keep your `/stable/` or `/v3/` paths unchanged.
100
+
101
+ ---
102
+
103
+ ## Everything Under One Client
104
+
105
+ Pass a catalog ticker such as `NVDA` or `7203.T`. Use canonical IDs such as `global:SHEL.L`, `crypto:BTCUSDT` or `index:SPX` to select an exact listing. Ambiguous tickers return canonical candidates.
106
+
107
+ | What you're building | Built-in methods (`qs.*` & `client.*`) |
108
+ | --- | --- |
109
+ | **Prices, Intraday & Live Sessions** | `instruments`, `quotes`, `prices`, `intraday`, `snapshot`, `get("market-session", ticker="NVDA")` |
110
+ | **40-Factor Stock Screener & Peers** | `screener`, `fundamentals`, `get("peers", ticker="NVDA")` |
111
+ | **Quant Returns, Alpha & Correlations** | `get("total-return", ticker="NVDA")`, `get("drawdowns", ticker="NVDA")`, `get("analytics/correlations", ...)` |
112
+ | **Wall Street Estimates & Calendars** | `estimates`, `earnings`, `get("analyst-ratings", ticker="NVDA")`, `get("calendar/earnings")` |
113
+ | **ETFs, Splits, Dividends & Buybacks** | `etf_holdings`, `get("etf-exposures", ticker="NVDA")`, `corporate_actions` |
114
+ | **Macro, Yield Curves (TIPS/2s10s) & FX** | `treasury_yields`, `macro_series`, `macro`, `fx` |
115
+ | **Deep Financials, Segments & Insiders** | `income`, `balance_sheet`, `cash_flow`, `sec_facts`, `get("segments", ticker="NVDA")`, `get("insider-activity", ticker="NVDA")` |
116
+
117
+ ```python
118
+ with qs.Client() as client:
119
+ # Multi-asset USD correlation & volatility matrix
120
+ corr = client.get("analytics/correlations", tickers=["NVDA", "AAPL", "crypto:BTCUSDT"])
121
+
122
+ # U.S. Treasury curve (1M–30Y + 2s10s spread + TIPS real yields) & 42 ECB FX rates
123
+ curve = client.treasury_yields(limit=5)
124
+ fx = client.fx("EUR,GBP,JPY", latest_only=True)
125
+
126
+ # Snapshot-pinned factor screen: high-ROIC net share-cannibals (full key)
127
+ for page in client.paginate("screener", max_pages=3, min_roic=20, max_share_count_change_1y=-2, limit=100):
128
+ print(page.snapshot_id, len(page.data))
129
+ ```
130
+
131
+ ## Pagination and errors
132
+
133
+ `prices()` reads one page. To assemble ascending history within a request budget, call
134
+ `price_history("NVDA", start="2024-01-01", limit=500, max_pages=4)`.
135
+ If the budget ends before the data, the result retains `next_cursor` and `snapshot_id`.
136
+
137
+ - Multi-page reads stay pinned to `snapshot_id` so nightly pipeline updates never corrupt a cross-sectional scan mid-loop.
138
+ - HTTP errors raise `qs.QuantsetError` (subclass of `httpx.HTTPStatusError`) with `exc.code`, `exc.detail`, `exc.field`, `exc.candidates` and `exc.retry_after`. For `snapshot_changed`, discard the partial result and restart at page one.
139
+
140
+ ## Links
141
+
142
+ - **Website & Pricing:** [quantset.dev](https://quantset.dev)
143
+ - **Interactive API Reference:** [quantset.dev/docs/api](https://quantset.dev/docs/api)
144
+ - **Guides & Migration Playbooks:** [quantset.dev/docs/guides](https://quantset.dev/docs/guides)
145
+ - **Full LLM contract:** [api.quantset.dev/llms-full.txt](https://api.quantset.dev/llms-full.txt)
@@ -0,0 +1,106 @@
1
+ # QuantSet — The Institutional Python SDK for Global Stocks, SEC EDGAR XBRL, 4,899 ETFs, Estimates & Macro
2
+
3
+ **Stop stitching together broken `yfinance` scrapers, `429 Too Many Requests` IP bans, YTD 10-Q cash-flow traps, and overpriced legacy data feeds.**
4
+
5
+ **[QuantSet](https://quantset.dev)** gives Python quants, backtests, and AI agents **90,000+ global listings across 67 countries** (US daily OHLCV back to **1962**, S&P 500 back to **1927**), **127M+ reconciled SEC EDGAR XBRL facts (`10-K`, discrete quarterly `10-Q`, `Form 13F`, `Form 4` w/ Rule 10b5-1 flags, segments & debt walls)**, **4,899 ETF look-through holdings (`175k+` N-PORT rows)**, **Wall Street consensus estimates**, a **40+ factor point-in-time stock screener**, **734 crypto pairs**, **42 ECB FX currencies**, **hourly & 5-minute intraday bars**, **multi-asset correlation & drawdown analytics**, and **live U.S. Treasury/TIPS/FRED macroeconomic curves**—all behind one fast, typed Python client with `.to_df()` Pandas/Polars support and built-in credit-budget controls.
6
+
7
+ Zero signup required to try: every install works **immediately out of the box** on benchmark US, London, Tokyo, India, ETF, index, macro, and crypto symbols (`mw_demo`).
8
+
9
+ **[Live Playground](https://quantset.dev/docs/api)** · **[60-Second Quickstart](https://quantset.dev/docs/quickstart)** · **[vs. yfinance](https://quantset.dev/docs/switch/yfinance)** · **[1-Line FMP Migration](https://quantset.dev/docs/switch/fmp)** · **[Claude & Cursor MCP](https://quantset.dev/docs/agents)**
10
+
11
+ ---
12
+
13
+ ## Credit estimates and receipts
14
+
15
+ ```python
16
+ from quantset import Client
17
+
18
+ with Client(max_credits_per_request=10, workflow_id="daily-research") as client:
19
+ planned = {"ticker": "NVDA", "limit": 251}
20
+ quote = client.estimate_credit_cost("GET", "/prices", params=planned)
21
+ read = client.get_with_receipt("prices", max_credits=quote["maximum_credits"], **planned)
22
+ print(read.receipt.credit_cost, read.receipt.credits_remaining)
23
+ history = client.price_history("NVDA", limit=250, max_pages=5, credit_budget=5)
24
+ ```
25
+
26
+ `rate_card()` and `estimate_credit_cost()` are free. The price ceiling is enforced on the server. A budgeted paginated read sends the remaining budget on each call and leaves `next_cursor` when stopped early. Use `page_receipts` to reconcile combined history pages and `QuantsetError.receipt` to inspect a refused request.
27
+
28
+
29
+ ## Install & Run in 15 Seconds (No API Key Needed to Start)
30
+
31
+ ```sh
32
+ pip install "quantset[pandas]" # or: pip install "quantset[polars]" / pip install quantset
33
+ ```
34
+
35
+ ```python
36
+ import quantset as qs
37
+
38
+ # Five daily bars in one price request
39
+ df = qs.prices("NVDA", limit=5).to_df()
40
+
41
+ # Batch live/daily quotes across US stocks, London, Tokyo & crypto in 1 request
42
+ quotes = qs.quotes(["NVDA", "AAPL", "global:SHEL.L", "global:1301.T", "crypto:BTCUSDT"]).to_df()
43
+
44
+ # Wall Street forward EPS/revenue consensus + quarterly revenue/cash-flow fundamentals
45
+ est = qs.estimates("NVDA", metric="eps").to_df()
46
+ inc = qs.income(["AAPL"], period="quarterly", limit_per_instrument=8).to_df()
47
+ ```
48
+
49
+ Ready for the full **52,000+ symbol** universe and market-wide stock screening? Set `QUANTSET_API_KEY` (choose a prepaid pack or a monthly credit pool; consult the published rate card for batch and history costs). **[Get a full key →](https://quantset.dev/pricing)**
50
+
51
+ ---
52
+
53
+ ## Why Quants & Builders Move Off `yfinance` & Fragmented APIs
54
+
55
+ - **Zero `429 Too Many Requests` or cookie/crumb bans on AWS & GitHub Actions:** Clean REST contract with explicit `X-RateLimit-Remaining` and `Retry-After` headers.
56
+ - **Built-in quant primitives (not just raw bars):** Total-return series (dividends reinvested), peak-to-trough drawdowns, multi-asset USD correlation matrices, point-in-time historical P/E, and S&P 500 benchmark alpha out of the box.
57
+ - **40+ factor institutional screener:** Filter 14,000+ US listings by `ROIC`, `EV/EBITDA`, `EV/FCF`, `FFO` (for REITs), `SMA-50/200`, dividend-increase streaks, and net buyback share-count shrinkage.
58
+ - **Reverse ETF look-through (`4,899` funds):** See every stock inside an ETF *or* reverse-query which ETFs hold a stock and at what weight (`etf-exposures`).
59
+ - **Evidence-checked `adj_close` & zero fake zeros:** Splits and dividends are cross-checked against actual price gaps. Unverified or missing values return `None` (`null`)—never silently coerced to `0`.
60
+ - **1-line drop-in FMP compatibility:** Migrating an existing Financial Modeling Prep codebase? Swap the base URL and keep your `/stable/` or `/v3/` paths unchanged.
61
+
62
+ ---
63
+
64
+ ## Everything Under One Client
65
+
66
+ Pass a catalog ticker such as `NVDA` or `7203.T`. Use canonical IDs such as `global:SHEL.L`, `crypto:BTCUSDT` or `index:SPX` to select an exact listing. Ambiguous tickers return canonical candidates.
67
+
68
+ | What you're building | Built-in methods (`qs.*` & `client.*`) |
69
+ | --- | --- |
70
+ | **Prices, Intraday & Live Sessions** | `instruments`, `quotes`, `prices`, `intraday`, `snapshot`, `get("market-session", ticker="NVDA")` |
71
+ | **40-Factor Stock Screener & Peers** | `screener`, `fundamentals`, `get("peers", ticker="NVDA")` |
72
+ | **Quant Returns, Alpha & Correlations** | `get("total-return", ticker="NVDA")`, `get("drawdowns", ticker="NVDA")`, `get("analytics/correlations", ...)` |
73
+ | **Wall Street Estimates & Calendars** | `estimates`, `earnings`, `get("analyst-ratings", ticker="NVDA")`, `get("calendar/earnings")` |
74
+ | **ETFs, Splits, Dividends & Buybacks** | `etf_holdings`, `get("etf-exposures", ticker="NVDA")`, `corporate_actions` |
75
+ | **Macro, Yield Curves (TIPS/2s10s) & FX** | `treasury_yields`, `macro_series`, `macro`, `fx` |
76
+ | **Deep Financials, Segments & Insiders** | `income`, `balance_sheet`, `cash_flow`, `sec_facts`, `get("segments", ticker="NVDA")`, `get("insider-activity", ticker="NVDA")` |
77
+
78
+ ```python
79
+ with qs.Client() as client:
80
+ # Multi-asset USD correlation & volatility matrix
81
+ corr = client.get("analytics/correlations", tickers=["NVDA", "AAPL", "crypto:BTCUSDT"])
82
+
83
+ # U.S. Treasury curve (1M–30Y + 2s10s spread + TIPS real yields) & 42 ECB FX rates
84
+ curve = client.treasury_yields(limit=5)
85
+ fx = client.fx("EUR,GBP,JPY", latest_only=True)
86
+
87
+ # Snapshot-pinned factor screen: high-ROIC net share-cannibals (full key)
88
+ for page in client.paginate("screener", max_pages=3, min_roic=20, max_share_count_change_1y=-2, limit=100):
89
+ print(page.snapshot_id, len(page.data))
90
+ ```
91
+
92
+ ## Pagination and errors
93
+
94
+ `prices()` reads one page. To assemble ascending history within a request budget, call
95
+ `price_history("NVDA", start="2024-01-01", limit=500, max_pages=4)`.
96
+ If the budget ends before the data, the result retains `next_cursor` and `snapshot_id`.
97
+
98
+ - Multi-page reads stay pinned to `snapshot_id` so nightly pipeline updates never corrupt a cross-sectional scan mid-loop.
99
+ - HTTP errors raise `qs.QuantsetError` (subclass of `httpx.HTTPStatusError`) with `exc.code`, `exc.detail`, `exc.field`, `exc.candidates` and `exc.retry_after`. For `snapshot_changed`, discard the partial result and restart at page one.
100
+
101
+ ## Links
102
+
103
+ - **Website & Pricing:** [quantset.dev](https://quantset.dev)
104
+ - **Interactive API Reference:** [quantset.dev/docs/api](https://quantset.dev/docs/api)
105
+ - **Guides & Migration Playbooks:** [quantset.dev/docs/guides](https://quantset.dev/docs/guides)
106
+ - **Full LLM contract:** [api.quantset.dev/llms-full.txt](https://api.quantset.dev/llms-full.txt)
@@ -0,0 +1,62 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "quantset"
7
+ version = "0.1.0"
8
+ description = "52,000+ global stocks (67 countries, 64yr US history), 734 crypto pairs, live quotes, 40-factor stock screener, consensus estimates, ETF look-through, correlations, macro curves & SEC financials in one Python SDK."
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.10"
12
+ authors = [{name = "QuantSet", email = "hello@quantset.dev"}]
13
+ keywords = [
14
+ "stock-market-api",
15
+ "market-data",
16
+ "quantitative-finance",
17
+ "backtesting",
18
+ "yfinance-alternative",
19
+ "fmp-alternative",
20
+ "stock-screener",
21
+ "crypto-api",
22
+ "forex-api",
23
+ "etf-holdings",
24
+ "analyst-estimates",
25
+ "earnings-calendar",
26
+ "treasury-yields",
27
+ "pandas",
28
+ "polars",
29
+ "mcp",
30
+ ]
31
+ classifiers = [
32
+ "Development Status :: 4 - Beta",
33
+ "Intended Audience :: Developers",
34
+ "Intended Audience :: Financial and Insurance Industry",
35
+ "Intended Audience :: Science/Research",
36
+ "License :: OSI Approved :: MIT License",
37
+ "Operating System :: OS Independent",
38
+ "Programming Language :: Python :: 3",
39
+ "Programming Language :: Python :: 3.10",
40
+ "Programming Language :: Python :: 3.11",
41
+ "Programming Language :: Python :: 3.12",
42
+ "Programming Language :: Python :: 3.13",
43
+ "Topic :: Office/Business :: Financial :: Investment",
44
+ "Topic :: Scientific/Engineering :: Information Analysis",
45
+ "Typing :: Typed",
46
+ ]
47
+ dependencies = ["httpx>=0.27,<1"]
48
+
49
+ [project.optional-dependencies]
50
+ pandas = ["pandas>=2"]
51
+ polars = ["polars>=1"]
52
+ test = ["pytest>=8"]
53
+
54
+ [project.urls]
55
+ Homepage = "https://quantset.dev"
56
+ Documentation = "https://quantset.dev/docs/quickstart"
57
+ "Live API Playground" = "https://quantset.dev/docs/api"
58
+ "Switch from yfinance" = "https://quantset.dev/docs/switch/yfinance"
59
+ "Switch from FMP" = "https://quantset.dev/docs/switch/fmp"
60
+ "MCP for Claude & Cursor" = "https://quantset.dev/docs/agents"
61
+ Repository = "https://github.com/quantset/quantset-python"
62
+ Issues = "https://github.com/quantset/quantset-python/issues"
@@ -0,0 +1,444 @@
1
+ """Read market data from Quantset."""
2
+
3
+ import json
4
+ import os
5
+ from collections.abc import Callable, Iterator, Sequence
6
+ from dataclasses import dataclass
7
+ from typing import Any, Concatenate, Literal, ParamSpec, TypedDict, TypeVar
8
+ from urllib.parse import quote, unquote, urlsplit
9
+
10
+ import httpx
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class CreditReceipt:
15
+ credit_cost: int | None
16
+ credits_remaining: int | None
17
+ rate_card_version: str | None
18
+ request_id: str | None
19
+
20
+ @classmethod
21
+ def from_response(cls, response):
22
+ def number(header):
23
+ value = response.headers.get(header)
24
+ return int(value) if value is not None and value.isdecimal() else None
25
+
26
+ return cls(number("X-Credit-Cost"), number("X-Credits-Remaining"),
27
+ response.headers.get("X-Rate-Card-Version"), response.headers.get("X-Request-Id"))
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class BilledResponse:
32
+ data: Any
33
+ receipt: CreditReceipt
34
+
35
+
36
+ def _credit_limit(value):
37
+ if value is not None and (type(value) is not int or not 0 <= value < 10**12):
38
+ raise ValueError("Credit limits must be integers between 0 and 999999999999")
39
+ return value
40
+
41
+
42
+ @dataclass
43
+ class Result:
44
+ data: list[dict[str, Any]]
45
+ snapshot_id: str | None
46
+ provenance: dict[str, Any]
47
+ next_cursor: str | None
48
+ total_count: int | None
49
+ schema_version: str
50
+ receipt: CreditReceipt | None = None
51
+ page_receipts: tuple[CreditReceipt, ...] = ()
52
+
53
+ def to_df(self):
54
+ """Return a pandas DataFrame with nested statement values as dotted columns."""
55
+ import pandas as pd
56
+
57
+ return pd.json_normalize(self.data)
58
+
59
+ def to_polars(self):
60
+ """Return a Polars DataFrame. Nested statement values are Struct columns."""
61
+ import polars as pl
62
+
63
+ return pl.from_dicts(self.data, infer_schema_length=None) if self.data else pl.DataFrame()
64
+
65
+
66
+ def _ticker_list(tickers: Sequence[str]) -> list[str]:
67
+ if isinstance(tickers, str):
68
+ raise TypeError("Pass tickers as a sequence of listing selectors")
69
+ return list(tickers)
70
+
71
+
72
+ def _query_params(params):
73
+ return {
74
+ key: ",".join(value) if isinstance(value, (list, tuple)) else value
75
+ for key, value in params.items()
76
+ if value is not None
77
+ }
78
+
79
+
80
+ class QuantsetError(httpx.HTTPStatusError):
81
+ """API status error with the server detail and original response."""
82
+
83
+ def __init__(self, response: httpx.Response):
84
+ try:
85
+ payload = response.json()
86
+ except ValueError:
87
+ payload = None
88
+ self.error = payload if isinstance(payload, dict) else {}
89
+ self.code = self.error.get("code")
90
+ self.detail = self.error.get("detail") or response.text or response.reason_phrase
91
+ self.field = self.error.get("field")
92
+ self.hint = self.error.get("hint")
93
+ self.docs_url = self.error.get("docs_url")
94
+ self.candidates = self.error.get("candidates")
95
+ self.snapshot_id = self.error.get("snapshot_id")
96
+ self.receipt = CreditReceipt.from_response(response)
97
+ self.retry_after = response.headers.get("Retry-After")
98
+ detail = self.detail if isinstance(self.detail, str) else json.dumps(self.detail)
99
+ message = f"Quantset HTTP {response.status_code}: {detail}"
100
+ if self.retry_after is not None:
101
+ message += f" (Retry-After: {self.retry_after})"
102
+ super().__init__(message, request=response.request, response=response)
103
+
104
+
105
+ StatementKind = Literal["income", "balance_sheet", "cash_flow"]
106
+
107
+
108
+ class ScreenerFilter(TypedDict):
109
+ field: str
110
+ operator: Literal["gt", "lt", "gte", "lte", "eq", "in"]
111
+ value: Any
112
+
113
+
114
+ class ScreenerOrderBy(TypedDict, total=False):
115
+ field: str
116
+ direction: Literal["asc", "desc", "ASC", "DESC"]
117
+
118
+
119
+ class Client:
120
+ def __init__(self, api_key: str | None = None, *, base_url: str = "https://api.quantset.dev",
121
+ max_credits_per_request: int | None = None, workflow_id: str | None = None):
122
+ self.max_credits_per_request = _credit_limit(max_credits_per_request)
123
+ self.workflow_id = workflow_id
124
+ self._http = httpx.Client(
125
+ base_url=base_url.rstrip("/") + "/api/v1/",
126
+ headers={"X-API-Key": api_key or os.getenv("QUANTSET_API_KEY") or "mw_demo"},
127
+ timeout=30,
128
+ )
129
+
130
+ def close(self):
131
+ self._http.close()
132
+
133
+ def __enter__(self):
134
+ return self
135
+
136
+ def __exit__(self, *_):
137
+ self.close()
138
+
139
+ def get(self, path: str, **params) -> Any:
140
+ """Return one decoded API response. Paths are relative to /api/v1."""
141
+ return self.get_with_receipt(path, **params).data
142
+
143
+ def post(self, path: str, body: dict[str, Any]) -> Any:
144
+ """Submit a JSON body to an operation under /api/v1."""
145
+ return self.post_with_receipt(path, body).data
146
+
147
+ def get_with_receipt(self, path: str, *, max_credits: int | None = None, workflow_id: str | None = None, **params) -> BilledResponse:
148
+ return self._request("GET", path, params=params, max_credits=max_credits, workflow_id=workflow_id)
149
+
150
+ def post_with_receipt(self, path: str, body: dict[str, Any], *, max_credits: int | None = None, workflow_id: str | None = None) -> BilledResponse:
151
+ return self._request("POST", path, body=body, max_credits=max_credits, workflow_id=workflow_id)
152
+
153
+ def rate_card(self) -> dict[str, Any]:
154
+ """Read the immutable version and billing rules effective now."""
155
+ return self.get("billing/rate-card")
156
+
157
+ def estimate_credit_cost(self, method: str, path: str, *, params=None, body=None) -> dict[str, Any]:
158
+ request = {"method": method, "path": "/" + path.removeprefix("/api/v1/").lstrip("/")}
159
+ if params is not None:
160
+ request["params"] = params
161
+ if body is not None:
162
+ request["body"] = body
163
+ return self.post("billing/estimate", request)
164
+
165
+ def _request(self, method: str, path: str, *, params=None, body=None, max_credits=None, workflow_id=None) -> BilledResponse:
166
+ if (
167
+ not path
168
+ or path.startswith("//")
169
+ or urlsplit(path).scheme
170
+ or any(c in path for c in "?#")
171
+ or "\\" in unquote(path)
172
+ or ".." in unquote(path).split("/")
173
+ ):
174
+ raise ValueError("Expected a relative API path with query parameters passed separately")
175
+ path = path.removeprefix("/api/v1/").removeprefix("/")
176
+ limits = [n for n in (self.max_credits_per_request, _credit_limit(max_credits)) if n is not None]
177
+ headers = {"X-Max-Credits": str(min(limits))} if limits else {}
178
+ workflow = self.workflow_id if workflow_id is None else workflow_id
179
+ if workflow is not None:
180
+ headers["X-Workflow-Id"] = workflow
181
+ response = self._http.request(method, "./" + path, params=_query_params(params or {}), json=body, headers=headers)
182
+ if not response.is_success:
183
+ raise QuantsetError(response)
184
+ data = response.text if params and params.get("format") == "csv" else response.json()
185
+ return BilledResponse(data, CreditReceipt.from_response(response))
186
+
187
+ def _page(self, path: str, **params) -> Result:
188
+ result = self.get_with_receipt(path, **params)
189
+ return self._parse_page(result.data, result.receipt)
190
+
191
+ @staticmethod
192
+ def _parse_page(raw, receipt=None) -> Result:
193
+ wire_fields = Result.__dataclass_fields__.keys() - {"receipt", "page_receipts"}
194
+ if (
195
+ not isinstance(raw, dict)
196
+ or not isinstance(raw.get("data"), list)
197
+ or not wire_fields <= raw.keys()
198
+ ):
199
+ raise ValueError("Expected a Quantset JSON page. Use get() for other response formats")
200
+ return Result(**{key: raw[key] for key in wire_fields}, receipt=receipt)
201
+
202
+ def paginate(self, path: str, *, max_pages: int | None = None, credit_budget: int | None = None, **params) -> Iterator[Result]:
203
+ """Yield pages in API order and pin subsequent reads to the initial snapshot."""
204
+ seen = {params.get("cursor")}
205
+ snapshot = params.get("snapshot_id")
206
+ if max_pages is not None and (type(max_pages) is not int or max_pages < 1):
207
+ raise ValueError("max_pages must be a positive integer")
208
+ remaining = max_pages
209
+ credits = _credit_limit(credit_budget)
210
+ while remaining is None or remaining > 0:
211
+ call_params = dict(params)
212
+ if credits is not None:
213
+ cap = _credit_limit(call_params.get("max_credits"))
214
+ call_params["max_credits"] = credits if cap is None else min(credits, cap)
215
+ page = self._page(path, **call_params)
216
+ if credits is not None:
217
+ cost = page.receipt.credit_cost
218
+ if cost is None or cost > credits:
219
+ raise RuntimeError("Missing or inconsistent credit receipt on a budgeted read")
220
+ credits -= cost
221
+ if snapshot is not None and page.snapshot_id != snapshot:
222
+ raise RuntimeError("Quantset changed snapshots during pagination")
223
+ snapshot = page.snapshot_id
224
+ cursor = page.next_cursor
225
+ if cursor is not None and cursor in seen:
226
+ raise RuntimeError("Quantset returned a repeated cursor")
227
+ yield page
228
+ if cursor is None or credits == 0:
229
+ return
230
+ if snapshot is None:
231
+ raise RuntimeError("Quantset returned a continuation without a snapshot")
232
+ if remaining is not None:
233
+ remaining -= 1
234
+ seen.add(cursor)
235
+ params.update(cursor=cursor, snapshot_id=snapshot)
236
+
237
+ def prices(
238
+ self,
239
+ ticker: str,
240
+ *,
241
+ start: str | None = None,
242
+ end: str | None = None,
243
+ limit: int | None = None,
244
+ basis: Literal["raw", "comparable"] = "raw",
245
+ cursor: str | None = None,
246
+ snapshot_id: str | None = None,
247
+ ) -> Result:
248
+ """Read one daily price page, oldest first within the page."""
249
+ return self._page(
250
+ "prices", ticker=ticker, start=start, end=end, limit=limit, basis=basis,
251
+ cursor=cursor, snapshot_id=snapshot_id,
252
+ )
253
+
254
+ def price_history(
255
+ self,
256
+ ticker: str,
257
+ *,
258
+ max_pages: int,
259
+ credit_budget: int | None = None,
260
+ start: str | None = None,
261
+ end: str | None = None,
262
+ limit: int | None = None,
263
+ basis: Literal["raw", "comparable"] = "raw",
264
+ cursor: str | None = None,
265
+ snapshot_id: str | None = None,
266
+ ) -> Result:
267
+ """Read up to max_pages daily price pages and combine rows in ascending date order."""
268
+ if type(max_pages) is not int or max_pages < 1:
269
+ raise ValueError("max_pages must be a positive integer")
270
+ pages = list(self.paginate(
271
+ "prices", ticker=ticker, max_pages=max_pages, credit_budget=credit_budget, start=start, end=end,
272
+ limit=limit, basis=basis, cursor=cursor, snapshot_id=snapshot_id,
273
+ ))
274
+ newest = pages[0]
275
+ newest.page_receipts = tuple(page.receipt for page in pages if page.receipt is not None)
276
+ if len(pages) > 1:
277
+ newest.receipt = None
278
+ newest.data = [row for page in reversed(pages) for row in page.data]
279
+ newest.next_cursor = pages[-1].next_cursor
280
+ return newest
281
+
282
+ def statements(
283
+ self,
284
+ kind: StatementKind,
285
+ tickers: Sequence[str],
286
+ *,
287
+ limit_per_instrument: int = 8,
288
+ period: str = "annual",
289
+ **params,
290
+ ) -> Result:
291
+ if kind not in ("income", "balance_sheet", "cash_flow"):
292
+ raise ValueError("Expected income, balance_sheet, or cash_flow")
293
+ return self._page(
294
+ "financial-statements/" + kind,
295
+ tickers=_ticker_list(tickers),
296
+ limit_per_instrument=limit_per_instrument,
297
+ period=period,
298
+ **params,
299
+ )
300
+
301
+ def income(self, tickers: Sequence[str], **params) -> Result:
302
+ return self.statements("income", tickers, **params)
303
+
304
+ def balance_sheet(self, tickers: Sequence[str], **params) -> Result:
305
+ return self.statements("balance_sheet", tickers, **params)
306
+
307
+ def cash_flow(self, tickers: Sequence[str], **params) -> Result:
308
+ return self.statements("cash_flow", tickers, **params)
309
+
310
+ def quotes(self, tickers: Sequence[str], **params) -> Result:
311
+ return self._page("quotes", tickers=_ticker_list(tickers), **params)
312
+
313
+ def instruments(self, **params) -> Result:
314
+ return self._page("instruments", **params)
315
+
316
+ def intraday(self, ticker: str, **params) -> Result:
317
+ return self._page("intraday", ticker=ticker, **params)
318
+
319
+ def snapshot(self, ticker: str, **params) -> Result:
320
+ return self._page("snapshots", ticker=ticker, **params)
321
+
322
+ def fundamentals(self, **params) -> Result:
323
+ return self._page("fundamentals", **params)
324
+
325
+ def screener(self, **params) -> Result:
326
+ return self._page("screener", **params)
327
+
328
+ def analyst_consensus(self, ticker: str, **params) -> Result:
329
+ return self._page("analyst-consensus", ticker=ticker, **params)
330
+
331
+ def estimates(self, ticker: str, **params) -> Result:
332
+ return self._page("estimates", ticker=ticker, **params)
333
+
334
+ def earnings(self, ticker: str, **params) -> Result:
335
+ return self._page("earnings", ticker=ticker, **params)
336
+
337
+ def corporate_actions(self, ticker: str, **params) -> Result:
338
+ return self._page("calendar/corporate-actions", ticker=ticker, **params)
339
+
340
+ def etf_holdings(self, ticker: str, **params) -> Result:
341
+ return self._page("etf-holdings", ticker=ticker, **params)
342
+
343
+ def instrument(self, instrument_id: str, **params) -> Result:
344
+ return self._page("instruments/" + quote(instrument_id, safe=":"), **params)
345
+
346
+ def sec_facts(self, *, ticker: str | None = None, issuer_cik: str | None = None, **params) -> Result:
347
+ if (ticker is None) == (issuer_cik is None):
348
+ raise ValueError("Provide exactly one of ticker or issuer_cik")
349
+ return self._page("sec/company-facts", ticker=ticker, issuer_cik=issuer_cik, **params)
350
+
351
+ def search_screener(
352
+ self,
353
+ filters: Sequence[ScreenerFilter],
354
+ *,
355
+ namespace: Literal["us", "global"] = "us",
356
+ as_of: str | None = None,
357
+ currency: str = "USD",
358
+ percent_format: Literal["percent", "decimal"] = "percent",
359
+ order_by: ScreenerOrderBy | None = None,
360
+ limit: int = 25,
361
+ ) -> Result:
362
+ body = dict(filters=list(filters), namespace=namespace, as_of=as_of, currency=currency,
363
+ percent_format=percent_format, order_by=order_by, limit=limit)
364
+ result = self.post_with_receipt("screener/search", body)
365
+ return self._parse_page(result.data, result.receipt)
366
+
367
+ def line_items(
368
+ self,
369
+ tickers: Sequence[str],
370
+ line_items: Sequence[str],
371
+ *,
372
+ period: Literal["annual", "quarterly", "ttm"] = "annual",
373
+ start: str | None = None,
374
+ end: str | None = None,
375
+ limit_per_instrument: int = 4,
376
+ ) -> Result:
377
+ body = dict(tickers=_ticker_list(tickers), line_items=list(line_items), period=period, start=start, end=end,
378
+ limit_per_instrument=limit_per_instrument)
379
+ result = self.post_with_receipt("financial-statements/line-items", body)
380
+ return self._parse_page(result.data, result.receipt)
381
+
382
+ def macro(self, series_ids: str | None = None, **params) -> Result:
383
+ return self._page("macro/indicators", series_ids=series_ids, **params)
384
+
385
+ def macro_series(self, **params) -> Result:
386
+ return self._page("macro/series", **params)
387
+
388
+ def treasury_yields(self, **params) -> Result:
389
+ return self._page("macro/treasury-yields", **params)
390
+
391
+ def fx(self, base_currency: str | None = None, **params) -> Result:
392
+ return self._page("fx/rates", base_currency=base_currency, **params)
393
+
394
+
395
+ P = ParamSpec("P")
396
+ T = TypeVar("T")
397
+
398
+
399
+ def _shortcut(method: Callable[Concatenate[Client, P], T]) -> Callable[P, T]:
400
+ def call(*args: P.args, **kwargs: P.kwargs) -> T:
401
+ with Client() as client:
402
+ return method(client, *args, **kwargs)
403
+
404
+ call.__name__ = method.__name__
405
+ call.__doc__ = method.__doc__
406
+ return call
407
+
408
+
409
+ get = _shortcut(Client.get)
410
+ get_with_receipt = _shortcut(Client.get_with_receipt)
411
+ post_with_receipt = _shortcut(Client.post_with_receipt)
412
+ rate_card = _shortcut(Client.rate_card)
413
+ estimate_credit_cost = _shortcut(Client.estimate_credit_cost)
414
+ post = _shortcut(Client.post)
415
+ prices = _shortcut(Client.prices)
416
+ price_history = _shortcut(Client.price_history)
417
+ instrument = _shortcut(Client.instrument)
418
+ instruments = _shortcut(Client.instruments)
419
+ quotes = _shortcut(Client.quotes)
420
+ intraday = _shortcut(Client.intraday)
421
+ snapshot = _shortcut(Client.snapshot)
422
+ fundamentals = _shortcut(Client.fundamentals)
423
+ statements = _shortcut(Client.statements)
424
+ income = _shortcut(Client.income)
425
+ balance_sheet = _shortcut(Client.balance_sheet)
426
+ cash_flow = _shortcut(Client.cash_flow)
427
+ analyst_consensus = _shortcut(Client.analyst_consensus)
428
+ estimates = _shortcut(Client.estimates)
429
+ earnings = _shortcut(Client.earnings)
430
+ corporate_actions = _shortcut(Client.corporate_actions)
431
+ etf_holdings = _shortcut(Client.etf_holdings)
432
+ sec_facts = _shortcut(Client.sec_facts)
433
+ macro = _shortcut(Client.macro)
434
+ macro_series = _shortcut(Client.macro_series)
435
+ treasury_yields = _shortcut(Client.treasury_yields)
436
+ fx = _shortcut(Client.fx)
437
+ screener = _shortcut(Client.screener)
438
+ search_screener = _shortcut(Client.search_screener)
439
+ line_items = _shortcut(Client.line_items)
440
+
441
+
442
+ def paginate(path: str, **params) -> Iterator[Result]:
443
+ with Client() as client:
444
+ yield from client.paginate(path, **params)
@@ -0,0 +1,224 @@
1
+ import json
2
+ from pathlib import Path
3
+
4
+ import httpx
5
+ import pytest
6
+
7
+
8
+ @pytest.fixture
9
+ def qs(monkeypatch):
10
+ # A standalone release test imports the installed wheel. Also support a source checkout.
11
+ try:
12
+ import quantset
13
+ except ModuleNotFoundError as exc:
14
+ if exc.name != "quantset":
15
+ raise
16
+ monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "src"))
17
+ import quantset
18
+ return quantset
19
+
20
+
21
+ def envelope(data=(), cursor=None, snapshot="s1"):
22
+ return {
23
+ "data": list(data),
24
+ "schema_version": "1.0",
25
+ "snapshot_id": snapshot,
26
+ "next_cursor": cursor,
27
+ "total_count": None,
28
+ "provenance": {"basis": "fixture"},
29
+ }
30
+
31
+
32
+ @pytest.fixture
33
+ def wire(monkeypatch):
34
+ original = httpx.Client
35
+ requests = []
36
+
37
+ def configure(*responses):
38
+ replies = iter(responses)
39
+
40
+ def serve(request):
41
+ requests.append(request)
42
+ return next(replies)
43
+
44
+ monkeypatch.setattr(
45
+ httpx, "Client", lambda **kw: original(transport=httpx.MockTransport(serve), **kw)
46
+ )
47
+ return requests
48
+
49
+ return configure
50
+
51
+
52
+ @pytest.mark.parametrize(
53
+ ("name", "args", "path", "params"),
54
+ [
55
+ ("instruments", (), "instruments", {}),
56
+ ("quotes", (["aapl", "global:SHEL.L"],), "quotes", {"tickers": "aapl,global:SHEL.L"}),
57
+ ("intraday", ("NVDA",), "intraday", {"ticker": "NVDA"}),
58
+ ("snapshot", ("crypto:BTCUSDT",), "snapshots", {"ticker": "crypto:BTCUSDT"}),
59
+ ("fundamentals", (), "fundamentals", {}),
60
+ (
61
+ "statements",
62
+ ("income", ["nvda", "AAPL"]),
63
+ "financial-statements/income",
64
+ {"tickers": "nvda,AAPL"},
65
+ ),
66
+ ("income", (["NVDA"],), "financial-statements/income", {"limit_per_instrument": "8"}),
67
+ ("balance_sheet", (["aapl"],), "financial-statements/balance_sheet", {"tickers": "aapl"}),
68
+ ("cash_flow", (["aapl"],), "financial-statements/cash_flow", {"tickers": "aapl"}),
69
+ ("analyst_consensus", ("7203.T",), "analyst-consensus", {"ticker": "7203.T"}),
70
+ ("estimates", ("aapl",), "estimates", {"ticker": "aapl"}),
71
+ ("earnings", ("NVDA",), "earnings", {"ticker": "NVDA"}),
72
+ ("corporate_actions", ("aapl",), "calendar/corporate-actions", {"ticker": "aapl"}),
73
+ ("etf_holdings", ("ivv",), "etf-holdings", {"ticker": "ivv"}),
74
+ ("macro", ("UNRATE",), "macro/indicators", {"series_ids": "UNRATE"}),
75
+ ("macro_series", (), "macro/series", {}),
76
+ ("treasury_yields", (), "macro/treasury-yields", {}),
77
+ ("fx", ("GBP,EUR",), "fx/rates", {"base_currency": "GBP,EUR"}),
78
+ ("screener", (), "screener", {}),
79
+ ],
80
+ )
81
+ def test_routes(qs, wire, name, args, path, params):
82
+ requests = wire(httpx.Response(200, json=envelope()))
83
+ assert getattr(qs, name)(*args, snapshot_id="s1").snapshot_id == "s1"
84
+ url = requests[0].url
85
+ assert url.path == "/api/v1/" + path
86
+ for key, expected in params.items():
87
+ assert url.params[key] == expected
88
+ assert url.params["snapshot_id"] == "s1"
89
+
90
+
91
+ def test_single_request_history_and_explicit_limit(qs, wire):
92
+ requests = wire(
93
+ httpx.Response(200, json=envelope([{"date": "1962-01-02"}])),
94
+ httpx.Response(200, json=envelope(cursor="older")),
95
+ )
96
+ with qs.Client() as client:
97
+ assert client.prices("IBM", start="1962-01-01").data[0]["date"] == "1962-01-02"
98
+ assert client.prices("IBM", limit=2).next_cursor == "older"
99
+ assert [r.url.params.get("limit") for r in requests] == [None, "2"]
100
+
101
+
102
+ def test_long_prices_and_lazy_pagination(qs, wire):
103
+ responses = [
104
+ httpx.Response(200, json=envelope([{"day": day}], cursor)) for day, cursor in [(3, "c"), (1, None)]
105
+ ]
106
+ requests = wire(*responses, *responses)
107
+ assert [r["day"] for r in qs.price_history("aapl", max_pages=2).data] == [1, 3]
108
+ iterator = qs.paginate("screener", has_fundamentals=False)
109
+ assert len(requests) == 2
110
+ assert [p.data[0]["day"] for p in iterator] == [3, 1]
111
+ for index in [1, 3]:
112
+ assert requests[index].url.params["snapshot_id"] == "s1"
113
+ assert requests[index].url.params["cursor"] == "c"
114
+ assert requests[-1].url.params["has_fundamentals"] == "false"
115
+
116
+
117
+ @pytest.mark.parametrize("second", [envelope(cursor="older"), envelope(snapshot="s2")])
118
+ def test_pagination_rejects_invalid_continuations(qs, wire, second):
119
+ wire(httpx.Response(200, json=envelope(cursor="older")), httpx.Response(200, json=second))
120
+ with pytest.raises(RuntimeError):
121
+ list(qs.paginate("screener"))
122
+
123
+
124
+ def test_raw_shapes_csv_and_auth(qs, wire, monkeypatch):
125
+ monkeypatch.setenv("QUANTSET_API_KEY", "env-key")
126
+ requests = wire(
127
+ httpx.Response(200, json={"resources": []}),
128
+ httpx.Response(200, json=[{"symbol": "IBM"}]),
129
+ httpx.Response(200, text="date,close\n"),
130
+ )
131
+ assert qs.get("capabilities") == {"resources": []}
132
+ with qs.Client("explicit") as client:
133
+ assert client.get("/api/v1/fmp/stable/profile", symbol="IBM") == [{"symbol": "IBM"}]
134
+ assert client.get("/quotes", format="csv") == "date,close\n"
135
+ for path in ("https://example.org/", "//other.test/path", "%2e%2e/admin"):
136
+ with pytest.raises(ValueError):
137
+ client.get(path)
138
+ assert [r.headers["X-API-Key"] for r in requests] == ["env-key", "explicit", "explicit"]
139
+
140
+
141
+ @pytest.mark.parametrize(
142
+ ("status", "body", "retry"),
143
+ [
144
+ (403, {"detail": "Requires the Pro plan"}, None),
145
+ (429, {"detail": "Monthly request allowance exhausted"}, "12"),
146
+ (422, {"code": "ambiguous_instrument", "detail": "Choose a candidate", "field": "ticker",
147
+ "candidates": ["us:BTC", "crypto:BTCUSDT"]}, None),
148
+ ],
149
+ )
150
+ def test_http_errors_retain_detail_and_retry_after(qs, wire, status, body, retry):
151
+ wire(httpx.Response(status, json=body, headers={"Retry-After": retry} if retry else {}))
152
+ with pytest.raises(httpx.HTTPStatusError) as error:
153
+ qs.get("estimates", ticker="IBM")
154
+ assert isinstance(error.value, qs.QuantsetError)
155
+ assert error.value.response.status_code == status
156
+ assert error.value.detail == body["detail"]
157
+ assert error.value.retry_after == retry
158
+ assert body["detail"] in str(error.value)
159
+ assert error.value.code == body.get("code")
160
+ assert error.value.field == body.get("field")
161
+ assert error.value.candidates == body.get("candidates")
162
+ if retry:
163
+ assert "Retry-After: 12" in str(error.value)
164
+
165
+
166
+ def test_canonical_host_and_separate_sec_selectors(qs, wire):
167
+ requests = wire(httpx.Response(200, json=envelope()), httpx.Response(200, json=envelope()))
168
+ assert qs.sec_facts(issuer_cik="0001045810").data == []
169
+ assert qs.sec_facts(ticker="7203.T").data == []
170
+ for request, params in zip(requests, ({"issuer_cik": "0001045810"}, {"ticker": "7203.T"})):
171
+ assert request.url.host == "api.quantset.dev"
172
+ assert request.url.path == "/api/v1/sec/company-facts"
173
+ assert dict(request.url.params) == params
174
+
175
+
176
+ def test_explicit_page_budget_retains_continuation(qs, wire):
177
+ requests = wire(httpx.Response(200, json=envelope([{"date": "2026-11-01"}], cursor="next")))
178
+ assert qs.price_history("NVDA", max_pages=1).next_cursor == "next"
179
+ assert len(requests) == 1
180
+
181
+
182
+ def test_structured_posts_serialize_arrays_as_json(qs, wire):
183
+ import json
184
+
185
+ requests = wire(httpx.Response(200, json=envelope()), httpx.Response(200, json=envelope()))
186
+ qs.line_items(["NVDA", "AAPL"], ["revenue"])
187
+ qs.search_screener([{"field": "revenue", "operator": "gt", "value": 1000}])
188
+ assert [request.method for request in requests] == ["POST", "POST"]
189
+ assert json.loads(requests[0].content)["tickers"] == ["NVDA", "AAPL"]
190
+ assert json.loads(requests[1].content)["filters"][0]["operator"] == "gt"
191
+
192
+
193
+ def test_quote_budget_and_per_request_receipt(qs, wire):
194
+ requests = wire(
195
+ httpx.Response(200, json={"maximum_credits": 2}),
196
+ httpx.Response(200, json=envelope(), headers={
197
+ "X-Credit-Cost": "1", "X-Credits-Remaining": "99",
198
+ "X-Rate-Card-Version": "test", "X-Request-Id": "rq_1",
199
+ }),
200
+ )
201
+ client = qs.Client(max_credits_per_request=7)
202
+ quote = client.estimate_credit_cost("GET", "/prices", params={"ticker": "NVDA", "limit": 251})
203
+ assert quote["maximum_credits"] == 2
204
+ assert requests[0].url.path == "/api/v1/billing/estimate"
205
+ assert json.loads(requests[0].content)["params"]["limit"] == 251
206
+ result = client.get_with_receipt("prices", ticker="NVDA", limit=251, max_credits=2)
207
+ assert requests[1].headers["X-Max-Credits"] == "2"
208
+ assert result.receipt.credit_cost == 1 and result.receipt.credits_remaining == 99
209
+ assert result.receipt.rate_card_version == "test" and result.receipt.request_id == "rq_1"
210
+ assert result.data["schema_version"] == "1.0"
211
+
212
+
213
+ def test_history_credit_budget_uses_actual_receipts(qs, wire):
214
+ requests = wire(*[
215
+ httpx.Response(200, json=envelope([{"date": day}], cursor=cursor),
216
+ headers={"X-Credit-Cost": str(cost), "X-Request-Id": cursor})
217
+ for day, cursor, cost in [("2025-02-01", "page2", 1), ("2025-01-01", "page3", 2)]
218
+ ])
219
+ client = qs.Client(workflow_id="income-review", max_credits_per_request=10)
220
+ history = client.price_history("NVDA", limit=250, max_pages=5, credit_budget=3)
221
+ assert [r.headers["X-Max-Credits"] for r in requests] == ["3", "2"]
222
+ assert all(r.headers["X-Workflow-Id"] == "income-review" for r in requests)
223
+ assert [r.credit_cost for r in history.page_receipts] == [1, 2]
224
+ assert history.receipt is None and history.next_cursor == "page3"