From 6f4bc8e6c3004325b149f11ed89dff82798383f6 Mon Sep 17 00:00:00 2001 From: alexpipipi Date: Thu, 26 Nov 2026 13:22:44 +0100 Subject: [PATCH] feat(etf-holdings): add ETF Holdings API (beta) --- CHANGELOG.md | 5 + eodhd/APIs/EtfHoldingsAPI.py | 93 ++++++++++++++++++ eodhd/APIs/__init__.py | 1 + eodhd/apiclient.py | 46 +++++++++ tests/test_etf_holdings.py | 180 +++++++++++++++++++++++++++++++++++ 5 files changed, 325 insertions(+) create mode 100644 eodhd/APIs/EtfHoldingsAPI.py create mode 100644 tests/test_etf_holdings.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b77cc8..25fe470 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ All notable changes to this package are documented here. The format follows ## [Unreleased] +### Added + +- **ETF Holdings API (beta, US-listed ETFs only, SEC N-PORT):** `get_etf_holdings(ticker)` + and `get_etf_held_by(ticker, page_offset, page_limit)`. 10 API calls per request. + ## [1.4.0] — 2026-08-28 The first release since **1.0.32 (2024-12-18)**. Twenty months of work reached `main` diff --git a/eodhd/APIs/EtfHoldingsAPI.py b/eodhd/APIs/EtfHoldingsAPI.py new file mode 100644 index 0000000..fb775ff --- /dev/null +++ b/eodhd/APIs/EtfHoldingsAPI.py @@ -0,0 +1,93 @@ +# APIs/EtfHoldingsAPI.py + +from urllib.parse import quote + +from .BaseAPI import BaseAPI + + +class EtfHoldingsAPI(BaseAPI): + """ + Wrapper for the ETF Holdings API (beta, SEC N-PORT data, US-listed ETFs only): + + GET /api/etf/holdings/{ticker} + GET /api/etf/security/{ticker}/held-by + + Notes: + - Both endpoints return a JSON envelope { data, meta, links }. + - Each request costs 10 API calls. Plans: Fundamentals Data Feed and All-In-One. + - Neither endpoint documents `fmt`; the response is always JSON (the shared + request helper appends fmt=json, which the server ignores - see the smoke test). + - On 404 the JSON error body carries a `code` such as FUND_NOT_FOUND, + NOT_COVERED or NO_HOLDINGS_YET; it is in EODHDHTTPError.response_body. + """ + + _HELD_BY_MAX_LIMIT = 5000 + + def get_holdings(self, api_token: str, ticker: str): + """ + GET /api/etf/holdings/{ticker} + + Holdings of one US-listed ETF, all positions in one response (large funds + can be several MB). `ticker` is the ETF ticker with or without the `.US` + suffix (e.g. "VTI" or "VTI.US"). Other exchanges return 422. + + Cost: 10 API calls per request. The demo token works for VTI. + + Notes: + - `data.Holdings` is an empty list (not an object) for a fund with no positions. + """ + ticker = self._blank_to_none(ticker) + if ticker is None: + raise ValueError("ticker is required.") + + return self._rest_get_method( + api_key=api_token, + endpoint="etf", + uri=f"holdings/{quote(str(ticker).strip(), safe='')}", + querystring="", + ) + + def get_held_by( + self, + api_token: str, + ticker: str, + page_offset: int = None, + page_limit: int = None, + ): + """ + GET /api/etf/security/{ticker}/held-by + + Funds that hold a given security, sorted by weight descending. `ticker` is + the looked-up security (e.g. "NVDA", or "ASML.AS" for a foreign listing), + not a fund. + + Query params: + page[offset] - zero-based, default 0 + page[limit] - 1 to 5000, default 100 + + Cost: 10 API calls per request. The demo token is rejected (403). + """ + ticker = self._blank_to_none(ticker) + if ticker is None: + raise ValueError("ticker is required.") + + query_string = "" + if page_offset is not None: + page_offset = self._coerce_page_int("page_offset", page_offset) + if page_offset < 0: + raise ValueError("page_offset must be >= 0.") + query_string += f"&page[offset]={page_offset}" + if page_limit is not None: + page_limit = self._coerce_page_int("page_limit", page_limit) + if page_limit < 1: + raise ValueError("page_limit must be >= 1.") + if page_limit > self._HELD_BY_MAX_LIMIT: + raise ValueError(f"page_limit must be <= {self._HELD_BY_MAX_LIMIT}.") + query_string += f"&page[limit]={page_limit}" + + return self._rest_get_method( + api_key=api_token, + endpoint="etf", + uri=f"security/{quote(str(ticker).strip(), safe='')}/held-by", + querystring=query_string, + ) diff --git a/eodhd/APIs/__init__.py b/eodhd/APIs/__init__.py index 3bea31b..ae8d8bf 100644 --- a/eodhd/APIs/__init__.py +++ b/eodhd/APIs/__init__.py @@ -39,6 +39,7 @@ from .InterestRatesAPI import InterestRatesAPI from .RealEstate import RealEstateAPI from .InsiderTransactionsV2API import InsiderTransactionsV2API +from .EtfHoldingsAPI import EtfHoldingsAPI #Marketplace endpoints from .MPIndexComponentsAPI import MPIndexComponentsAPI diff --git a/eodhd/apiclient.py b/eodhd/apiclient.py index 728f264..6da8a62 100644 --- a/eodhd/apiclient.py +++ b/eodhd/apiclient.py @@ -57,6 +57,7 @@ from eodhd.APIs import SanctionsAPI from eodhd.APIs import InterestRatesAPI from eodhd.APIs import RealEstateAPI +from eodhd.APIs import EtfHoldingsAPI #Marketplace endpoints from eodhd.APIs import MPIndexComponentsAPI @@ -2057,6 +2058,51 @@ def get_real_estate_detailed_series(self, code): api_token=self._api_key, code=code, ) + # ------------------------------------------------------------------ + # ETF Holdings API (/api/etf) - beta + # ------------------------------------------------------------------ + def get_etf_holdings(self, ticker: str) -> dict: + """ + ETF Holdings (beta): holdings of one US-listed ETF, from SEC N-PORT filings. + Endpoint: GET /api/etf/holdings/{ticker} + + Beta API, US-listed ETFs only (other exchanges return 422). + Cost: 10 API calls per request. Plans: Fundamentals Data Feed and All-In-One. + The demo token works for VTI. + + Args: + ticker [REQUIRED] - US ETF ticker, with or without .US (e.g. "VTI", "XLE.US") + Returns: dict envelope { data, meta, links }. All positions come in one + response (large funds are several MB). data.Holdings is an empty list, + not an object, for a fund with no positions. + For more information visit: https://eodhd.com/financial-apis/etf-holdings-api + """ + api_call = EtfHoldingsAPI(session=self._session, timeout=self._timeout) + return api_call.get_holdings(api_token=self._api_key, ticker=ticker) + + def get_etf_held_by(self, ticker: str, page_offset: int = None, page_limit: int = None) -> dict: + """ + ETF Holdings (beta): funds that hold a given security (reverse lookup). + Endpoint: GET /api/etf/security/{ticker}/held-by + + Beta API, US-listed ETFs only. + Cost: 10 API calls per request. Plans: Fundamentals Data Feed and All-In-One. + The demo token is rejected (403) on this endpoint. + + Args: + ticker [REQUIRED] - the security to look up, not a fund (e.g. "NVDA", "ASML.AS") + page_offset [OPTIONAL] - zero-based, default 0 + page_limit [OPTIONAL] - 1..5000, default 100 + Returns: dict envelope { data, meta, links }; data.funds is sorted by weight + descending, links.next is a relative URL or None on the last page. + For more information visit: https://eodhd.com/financial-apis/etf-holdings-api + """ + api_call = EtfHoldingsAPI(session=self._session, timeout=self._timeout) + return api_call.get_held_by( + api_token=self._api_key, ticker=ticker, + page_offset=page_offset, page_limit=page_limit, + ) + class ScannerClient: """Scanner class""" diff --git a/tests/test_etf_holdings.py b/tests/test_etf_holdings.py new file mode 100644 index 0000000..312510f --- /dev/null +++ b/tests/test_etf_holdings.py @@ -0,0 +1,180 @@ +"""Tests for EtfHoldingsAPI (ETF Holdings, beta, SEC N-PORT, US-listed ETFs only).""" + +import pytest +from unittest.mock import MagicMock + +from eodhd import APIClient +from eodhd.APIs.EtfHoldingsAPI import EtfHoldingsAPI +from eodhd.errors import EODHDHTTPError + + +@pytest.fixture +def mock_session(): + return MagicMock() + + +def _make_api(session): + return EtfHoldingsAPI(session=session) + + +def _mock_response(session, data=None, status=200, text=""): + resp = MagicMock() + resp.status_code = status + resp.text = text + resp.json.return_value = data if data is not None else {"data": {}, "meta": [], "links": []} + session.get.return_value = resp + + +HOLDINGS_BODY = { + "data": { + "General": {"Code": "XLE", "Type": "ETF", "Exchange": "US", "Is_Complete": True}, + "Holdings": { + "XOM.US": {"Code": "XOM", "Exchange": "US", "Name": "Exxon Mobil Corp", + "Assets_%": 23.1, "Shares": 1000.0, "Value_USD": 100000.0}, + }, + "Top_10_Holdings": {}, + "Holdings_Count": 1, + "Asset_Allocation": {}, + "Sector_Weights": {}, + "World_Regions": {}, + "Performance": None, + }, + "meta": [], + "links": [], +} + +HELD_BY_BODY = { + "data": { + "security": {"ticker": "NVDA", "exchange": "US", "name": "NVIDIA Corp"}, + "held_by_count": 791, + "funds": [{"ticker": "VTI", "name": "Vanguard Total Stock Market ETF", "weight": 6.1, + "shares": 1.0, "value_usd": 2.0, "report_date": "2026-09-30"}], + }, + "meta": {"total": 791, "offset": 0, "limit": 3}, + "links": {"next": "/api/etf/security/NVDA/held-by?page%5Boffset%5D=3&page%5Blimit%5D=3"}, +} + + +# --- holdings --- + +def test_holdings_url(mock_session): + _mock_response(mock_session, HOLDINGS_BODY) + result = _make_api(mock_session).get_holdings(api_token="test1234567890123456", ticker="XLE") + + call_url = mock_session.get.call_args[0][0] + assert call_url.startswith("https://eodhd.com/api/etf/holdings/XLE?api_token=test1234567890123456") + assert "page[" not in call_url + assert result["data"]["Holdings_Count"] == 1 + + +def test_holdings_ticker_with_suffix_is_encoded(mock_session): + _mock_response(mock_session) + _make_api(mock_session).get_holdings(api_token="t", ticker="VTI.US") + assert "/etf/holdings/VTI.US?" in mock_session.get.call_args[0][0] + + +def test_holdings_blank_ticker_raises(mock_session): + with pytest.raises(ValueError): + _make_api(mock_session).get_holdings(api_token="t", ticker=" ") + mock_session.get.assert_not_called() + + +def test_holdings_empty_list_edge_case(mock_session): + """A fund with no positions returns Holdings as an empty list, not an object.""" + body = {"data": {"General": {"Code": "GAID"}, "Holdings": [], "Top_10_Holdings": [], + "Holdings_Count": 0}, "meta": [], "links": []} + _mock_response(mock_session, body) + result = _make_api(mock_session).get_holdings(api_token="t", ticker="GAID") + assert result["data"]["Holdings"] == [] + assert result["data"]["Holdings_Count"] == 0 + + +def test_holdings_404_raises_with_code_in_body(mock_session): + body = {"errors": [{"status": "404", "title": "Symbol not found", "code": "NOT_COVERED", + "detail": "This ticker is outside ETF holdings coverage."}]} + _mock_response(mock_session, body, status=404, text="NOT_COVERED") + with pytest.raises(EODHDHTTPError) as exc: + _make_api(mock_session).get_holdings(api_token="t", ticker="GLD") + assert exc.value.status_code == 404 + assert "NOT_COVERED" in exc.value.response_body + + +# --- held-by --- + +def test_held_by_url_and_pagination(mock_session): + _mock_response(mock_session, HELD_BY_BODY) + result = _make_api(mock_session).get_held_by( + api_token="test1234567890123456", ticker="NVDA", page_offset=0, page_limit=3) + + call_url = mock_session.get.call_args[0][0] + assert "/api/etf/security/NVDA/held-by?api_token=test1234567890123456" in call_url + assert "&page[offset]=0" in call_url + assert "&page[limit]=3" in call_url + assert result["data"]["held_by_count"] == 791 + assert result["links"]["next"] is not None + + +def test_held_by_no_pagination_params_by_default(mock_session): + _mock_response(mock_session, HELD_BY_BODY) + _make_api(mock_session).get_held_by(api_token="t", ticker="XOM") + assert "page[" not in mock_session.get.call_args[0][0] + + +def test_held_by_foreign_ticker_is_url_encoded(mock_session): + _mock_response(mock_session, HELD_BY_BODY) + _make_api(mock_session).get_held_by(api_token="t", ticker="ASML.AS") + assert "/etf/security/ASML.AS/held-by?" in mock_session.get.call_args[0][0] + + +def test_held_by_limit_up_to_5000_allowed(mock_session): + _mock_response(mock_session, HELD_BY_BODY) + _make_api(mock_session).get_held_by(api_token="t", ticker="NVDA", page_limit=5000) + assert "&page[limit]=5000" in mock_session.get.call_args[0][0] + + +@pytest.mark.parametrize("kwargs", [ + {"page_limit": 5001}, {"page_limit": 0}, {"page_offset": -1}, + {"page_limit": True}, {"page_offset": 1.5}, +]) +def test_held_by_invalid_pagination_raises(mock_session, kwargs): + with pytest.raises(ValueError): + _make_api(mock_session).get_held_by(api_token="t", ticker="NVDA", **kwargs) + mock_session.get.assert_not_called() + + +def test_held_by_blank_ticker_raises(mock_session): + with pytest.raises(ValueError): + _make_api(mock_session).get_held_by(api_token="t", ticker="") + + +def test_held_by_past_the_end_is_empty_funds(mock_session): + body = {"data": {"security": {"ticker": "NVDA"}, "held_by_count": 791, "funds": []}, + "meta": {"total": 791, "offset": 5000, "limit": 100}, "links": {"next": None}} + _mock_response(mock_session, body) + result = _make_api(mock_session).get_held_by(api_token="t", ticker="NVDA", page_offset=5000) + assert result["data"]["funds"] == [] + assert result["links"]["next"] is None + + +def test_held_by_403_raises(mock_session): + _mock_response(mock_session, status=403, text="Forbidden") + mock_session.get.return_value.json.side_effect = ValueError("not json") + with pytest.raises(EODHDHTTPError) as exc: + _make_api(mock_session).get_held_by(api_token="demo", ticker="NVDA") + assert exc.value.status_code == 403 + + +# --- APIClient facade --- + +def test_client_facade_methods(mock_session): + client = APIClient("test1234567890123456") + client._session = mock_session + _mock_response(mock_session, HOLDINGS_BODY) + client.get_etf_holdings("XLE") + assert "/api/etf/holdings/XLE?api_token=test1234567890123456" in mock_session.get.call_args[0][0] + + _mock_response(mock_session, HELD_BY_BODY) + client.get_etf_held_by("NVDA", page_offset=3, page_limit=3) + url = mock_session.get.call_args[0][0] + assert "/api/etf/security/NVDA/held-by?api_token=test1234567890123456" in url + assert "&page[offset]=3" in url and "&page[limit]=3" in url