:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse_sources): add Alpha Vantage listing, dividend, split and adjusted price tables (#98311)
Tom Owersd241e06b2401
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex ed1558f5030d..84e1afeb732b 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -256,7 +256,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/algolia/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py1 products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/amplitude.py1 products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/settings.pydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 2e3f5e0836e6..9af584b6b8a7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -231,14 +231,14 @@ Note: Verified against the published OpenAPI spec linked from https://alguna.com## AlphaVantage — **thin**-Today (9): `balance_sheet`, `cash_flow`, `company_overview`, `earnings`, `global_quote`, `income_statement`, `time_series_daily`, `time_series_monthly`, `time_series_weekly`+Today (13): `balance_sheet`, `cash_flow`, `company_overview`, `dividends`, `earnings`, `global_quote`, `income_statement`, `listing_status`, `splits`, `time_series_daily`, `time_series_daily_adjusted`, `time_series_monthly`, `time_series_weekly`Diffed against: <https://www.alphavantage.co/documentation/>-- [ ] `LISTING_STATUS` — lookup table of every listed and delisted symbol with exchange, asset type and IPO/delisting dates - resolves the tickers already synced (high)-- [ ] `TIME_SERIES_DAILY_ADJUSTED` — split/dividend-adjusted closes, required for any correct return or backtest calculation (high)-- [ ] `DIVIDENDS` — corporate action history per symbol (high)-- [ ] `SPLITS` — split history needed to reconcile the unadjusted price series already synced (high)+- [x] `LISTING_STATUS` — lookup table of every listed and delisted symbol with exchange, asset type and IPO/delisting dates - resolves the tickers already synced (high)+- [x] `TIME_SERIES_DAILY_ADJUSTED` — split/dividend-adjusted closes, required for any correct return or backtest calculation (high)+- [x] `DIVIDENDS` — corporate action history per symbol (high)+- [x] `SPLITS` — split history needed to reconcile the unadjusted price series already synced (high)- [ ] `NEWS_SENTIMENT` — news and sentiment feed - the vendor's headline alternative-data product (high)- [ ] `EARNINGS_CALENDAR` — upcoming earnings dates to join against the earnings table already synced (medium)- [ ] `INSIDER_TRANSACTIONS` — insider buy/sell transaction rows per symbol (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/alpha_vantage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/alpha_vantage.pyindex 3eb5a1c28b5f..d8d70a5fb152 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/alpha_vantage.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/alpha_vantage.py@@ -1,4 +1,7 @@+import ioimport re+import csv+import jsonfrom collections.abc import Iteratorfrom typing import Any@@ -24,6 +27,18 @@ MAX_SYMBOLS = 100# "07. latest trading day" -> "latest trading day")._ORDINAL_PREFIX = re.compile(r"^\d+\.\s*")+# LISTING_STATUS covers the whole market in one call per state. Both states are synced: the table's+# value is asset-lifecycle and survivorship research, which needs the delisted side too.+LISTING_STATES = ("active", "delisted")++# Each state returns ~15k rows, so yield in chunks rather than one oversized batch.+LISTING_CHUNK_SIZE = 5000++# Alpha Vantage writes an absent value as one of these placeholder strings rather than JSON null or an+# empty CSV cell (e.g. `delistingDate=null` on an active listing, `payment_date=None` on an old+# dividend), which would otherwise land in the warehouse as literal text in a date column.+_NULL_PLACEHOLDERS = frozenset({"none", "null", ""})+class AlphaVantageRetryableError(Exception):pass@@ -42,17 +57,13 @@ def _normalize_key(key: str) -> str:return stripped.replace(" ", "_").lower()-@retry(- retry=retry_if_exception_type((AlphaVantageRetryableError, requests.ReadTimeout, requests.ConnectionError)),- stop=stop_after_attempt(5),- # Alpha Vantage's free per-minute throttle resets on a ~60s window, so back off long enough to- # clear it before the last attempt.- wait=wait_exponential_jitter(initial=2, max=60),- reraise=True,-)-def _fetch(session: requests.Session, params: dict[str, Any], logger: FilteringBoundLogger) -> dict[str, Any]:- response = session.get(ALPHA_VANTAGE_BASE_URL, params=params, timeout=60)+def _nullable(value: Any) -> Any:+ if isinstance(value, str) and value.strip().lower() in _NULL_PLACEHOLDERS:+ return None+ return value++def _raise_for_status(response: requests.Response) -> None:if response.status_code == 429 or response.status_code >= 500:raise AlphaVantageRetryableError(f"Alpha Vantage API error (retryable): status={response.status_code}")@@ -65,22 +76,65 @@ def _fetch(session: requests.Session, params: dict[str, Any], logger: FilteringBf"{response.status_code} {kind}: {response.reason} for url: {safe_url}", response=response)- body = response.json()- if not isinstance(body, dict):- raise AlphaVantageAPIError("Alpha Vantage API error [unexpected_response]: response was not a JSON object")- # Alpha Vantage signals problems with HTTP 200 and a body-level message rather than a status code:- # "Note" -> per-minute rate limit; transient, so retry with backoff.- # "Information" -> daily quota exhausted, premium-only dataset, or the shared demo key; permanent.- # "Error Message"-> missing/invalid apikey or an unrecognized function/symbol; permanent.+def _raise_for_envelope(body: dict[str, Any]) -> None:+ """Alpha Vantage signals problems with HTTP 200 and a body-level message rather than a status code.++ "Note" -> per-minute rate limit; transient, so the caller retries with backoff.+ "Information" -> daily quota exhausted, premium-only dataset, or the shared demo key; permanent.++ "Error Message" (missing/invalid apikey, unrecognized function/symbol) is left to the caller,+ because for per-symbol functions it is scoped to the one symbol rather than the whole sync.+ """if "Note" in body:raise AlphaVantageRetryableError(f"Alpha Vantage API error (retryable) [rate_limit]: {body['Note']}")if "Information" in body:raise AlphaVantageAPIError(f"Alpha Vantage API error [rate_limit_or_premium]: {body['Information']}")++@retry(+ retry=retry_if_exception_type((AlphaVantageRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ # Alpha Vantage's free per-minute throttle resets on a ~60s window, so back off long enough to+ # clear it before the last attempt.+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch(session: requests.Session, params: dict[str, Any], logger: FilteringBoundLogger) -> dict[str, Any]:+ response = session.get(ALPHA_VANTAGE_BASE_URL, params=params, timeout=60)+ _raise_for_status(response)++ body = response.json()+ if not isinstance(body, dict):+ raise AlphaVantageAPIError("Alpha Vantage API error [unexpected_response]: response was not a JSON object")++ _raise_for_envelope(body)return body+@retry(+ retry=retry_if_exception_type((AlphaVantageRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch_csv(session: requests.Session, params: dict[str, Any]) -> str | None:+ """Fetch a CSV-only function. Returns None when Alpha Vantage answered with JSON instead of a CSV body.++ LISTING_STATUS has no `datatype` param and always replies with CSV, but it still reports errors as+ a JSON envelope, so branch on the payload rather than on what was requested.+ """+ response = session.get(ALPHA_VANTAGE_BASE_URL, params=params, timeout=120)+ _raise_for_status(response)++ text = response.text+ if not text.lstrip().startswith("{"):+ return text++ _raise_for_envelope(json.loads(text))+ return None++def _parse_time_series(body: dict[str, Any], symbol: str) -> Iterator[dict[str, Any]]:# The label of the series block varies per function ("Time Series (Daily)", "Weekly Time Series",# ...), so pick the first non-metadata block whose value is a dict of date -> OHLCV.@@ -155,12 +209,50 @@ def _parse_earnings(body: dict[str, Any], symbol: str) -> Iterator[dict[str, Any}+def _parse_corporate_action(body: dict[str, Any], symbol: str) -> Iterator[dict[str, Any]]:+ # DIVIDENDS and SPLITS both answer with {"symbol": ..., "data": [{...}, ...]}.+ data = body.get("data")+ if not isinstance(data, list):+ return+ for entry in data:+ if not isinstance(entry, dict):+ continue+ row: dict[str, Any] = {key: _nullable(value) for key, value in entry.items()}+ # The entries are not symbol-tagged, so the requested symbol is the only source for the column.+ row["symbol"] = symbol+ yield row+++def _listing_status_rows(+ session: requests.Session, api_key: str, logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ for state in LISTING_STATES:+ params = {"function": "LISTING_STATUS", "state": state, "apikey": api_key}+ listing = _fetch_csv(session, params)+ if listing is None:+ # A key that is not entitled to a state gets an empty JSON object instead of a CSV body.+ # Skip it so the other state still syncs.+ logger.warning(f"Alpha Vantage: no listing returned for state={state}")+ continue++ batch: list[dict[str, Any]] = []+ for row in csv.DictReader(io.StringIO(listing)):+ # DictReader parks any surplus cells under a None key, which has no column to land in.+ batch.append({key: _nullable(value) for key, value in row.items() if key is not None})+ if len(batch) >= LISTING_CHUNK_SIZE:+ yield batch+ batch = []+ if batch:+ yield batch++_PARSERS = {"time_series": _parse_time_series,"quote": _parse_quote,"overview": _parse_overview,"reports": _parse_reports,"earnings": _parse_earnings,+ "corporate_action": _parse_corporate_action,}@@ -206,10 +298,16 @@ def get_rows(logger: FilteringBoundLogger,) -> Iterator[list[dict[str, Any]]]:config = ALPHA_VANTAGE_ENDPOINTS[endpoint]- parser = _PARSERS[config.kind]# apikey rides as a query param on every request, so mask its value from logged URLs and samples.session = make_tracked_session(redact_values=(api_key,))+ if config.kind == "listing":+ # The whole market listing arrives in one call per state, so the configured symbols don't apply.+ yield from _listing_status_rows(session, api_key, logger)+ return++ parser = _PARSERS[config.kind]+# One request per symbol (no pagination); yield each symbol's rows as a list and let the pipeline# batch. A symbol's full time series is bounded (~20 years), so it comfortably fits in memory.for symbol in symbols:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/canonical_descriptions.pyindex eeba39d6dc4b..6ea4bddae23c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/canonical_descriptions.py@@ -131,4 +131,56 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"surprisePercentage": "Percentage EPS surprise (quarterly only).",},},+ "time_series_daily_adjusted": {+ "description": "Daily price bars for each configured symbol with the split/dividend-adjusted close and the split and dividend events behind it. Requires a paid Alpha Vantage plan.",+ "docs_url": "https://www.alphavantage.co/documentation/#dailyadj",+ # The adjusted columns are named from the docs prose; the endpoint is premium, so their exact+ # response keys could not be confirmed against a live call.+ "columns": {+ "symbol": "The ticker symbol the bar belongs to.",+ "date": "Trading day of the bar (YYYY-MM-DD).",+ "open": "Raw as-traded opening price for the trading day.",+ "high": "Raw as-traded highest price during the trading day.",+ "low": "Raw as-traded lowest price during the trading day.",+ "close": "Raw as-traded closing price for the trading day.",+ "adjusted_close": "Closing price adjusted for splits and dividend payouts.",+ "volume": "Number of shares traded during the day.",+ "dividend_amount": "Dividend paid per share on this trading day, if any.",+ "split_coefficient": "Split ratio applied on this trading day (1.0 when there was no split).",+ },+ },+ "dividends": {+ "description": "Historical and declared dividend distributions for each configured symbol; one row per distribution.",+ "docs_url": "https://www.alphavantage.co/documentation/#dividends",+ "columns": {+ "symbol": "The ticker symbol the distribution belongs to.",+ "ex_dividend_date": "Date the share started trading without the right to the dividend (YYYY-MM-DD).",+ "declaration_date": "Date the dividend was announced. Empty for older distributions.",+ "record_date": "Date shareholders had to be on the register to qualify. Empty for older distributions.",+ "payment_date": "Date the dividend was paid out. Empty for older distributions.",+ "amount": "Dividend amount paid per share.",+ },+ },+ "splits": {+ "description": "Historical stock split events for each configured symbol; one row per split.",+ "docs_url": "https://www.alphavantage.co/documentation/#splits",+ "columns": {+ "symbol": "The ticker symbol the split belongs to.",+ "effective_date": "Date the split took effect (YYYY-MM-DD).",+ "split_factor": "Ratio of shares after the split to shares before it.",+ },+ },+ "listing_status": {+ "description": "Every active and delisted US stock and ETF, for asset-lifecycle and survivorship research. Covers the whole market rather than the configured symbols.",+ "docs_url": "https://www.alphavantage.co/documentation/#listing-status",+ "columns": {+ "symbol": "The ticker symbol.",+ "name": "Name of the company or fund.",+ "exchange": "Exchange the asset trades on (e.g. NYSE, NASDAQ, BATS).",+ "assetType": "Whether the asset is a Stock or an ETF.",+ "ipoDate": "Date the asset was first listed (YYYY-MM-DD).",+ "delistingDate": "Date the asset was delisted (YYYY-MM-DD). Empty while it is still listed.",+ "status": "Whether the asset is 'Active' or 'Delisted'.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/settings.pyindex babf344df9e3..e4429d526473 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/settings.py@@ -1,6 +1,7 @@-import dataclassesfrom typing import Literal+from posthog.dataclasses import frozen+# Alpha Vantage exposes every dataset through a single /query endpoint selected by a `function`# parameter. Each function returns a bespoke JSON shape, so endpoints are grouped by a `kind` that# tells the transport how to parse and normalize the response into flat rows.@@ -8,10 +9,10 @@ from typing import Literal# There is no pagination and no server-side incremental cursor (no `updated_after`/`since` filter),# so every table is full refresh only. Time-series data is naturally append-only by date, so# re-pulled rows dedupe on the primary key at merge time.-ParseKind = Literal["time_series", "quote", "overview", "reports", "earnings"]+ParseKind = Literal["time_series", "quote", "overview", "reports", "earnings", "corporate_action", "listing"]+@frozenclass AlphaVantageEndpointConfig:name: str# The Alpha Vantage `function` query-param value (e.g. TIME_SERIES_DAILY).@@ -21,7 +22,8 @@ class AlphaVantageEndpointConfig:# the injected `symbol` is always part of the key.primary_keys: list[str]# A stable date column used for datetime partitioning. Never a mutable field. None for snapshot- # tables (latest quote, company overview) that hold one row per symbol.+ # tables (latest quote, company overview) and for the low-volume corporate-action and listing+ # tables, where monthly partitions would hold a handful of rows each.partition_key: str | None = Nonedescription: str | None = None# Whether the table is selected for sync by default in the UI. Kept modest by default because the@@ -38,6 +40,15 @@ ALPHA_VANTAGE_ENDPOINTS: dict[str, AlphaVantageEndpointConfig] = {partition_key="date",description="Daily open/high/low/close/volume bars per symbol (20+ years of history). Full refresh.",),+ "time_series_daily_adjusted": AlphaVantageEndpointConfig(+ name="time_series_daily_adjusted",+ function="TIME_SERIES_DAILY_ADJUSTED",+ kind="time_series",+ primary_keys=["symbol", "date"],+ partition_key="date",+ description="Daily bars per symbol with split/dividend-adjusted close, dividend amount, and split coefficient (25+ years of history). Requires a paid Alpha Vantage plan. Full refresh.",+ should_sync_default=False,+ ),"time_series_weekly": AlphaVantageEndpointConfig(name="time_series_weekly",function="TIME_SERIES_WEEKLY",@@ -102,6 +113,31 @@ ALPHA_VANTAGE_ENDPOINTS: dict[str, AlphaVantageEndpointConfig] = {partition_key="fiscalDateEnding",description="Annual and quarterly reported EPS (with estimates and surprise) per symbol. One row per report. Full refresh.",),+ "dividends": AlphaVantageEndpointConfig(+ name="dividends",+ function="DIVIDENDS",+ kind="corporate_action",+ primary_keys=["symbol", "ex_dividend_date"],+ description="Historical and declared dividend distributions per symbol. One row per distribution. Full refresh.",+ should_sync_default=False,+ ),+ "splits": AlphaVantageEndpointConfig(+ name="splits",+ function="SPLITS",+ kind="corporate_action",+ primary_keys=["symbol", "effective_date"],+ description="Historical stock split events per symbol. One row per split. Full refresh.",+ should_sync_default=False,+ ),+ "listing_status": AlphaVantageEndpointConfig(+ name="listing_status",+ function="LISTING_STATUS",+ kind="listing",+ # Not symbol-scoped, so `symbol` alone is not enough: a delisted ticker can later be reused by+ # a different active company, and the same ticker can be delisted more than once.+ primary_keys=["symbol", "status", "ipoDate"],+ description="Every active and delisted US stock and ETF with its exchange, asset type, and IPO/delisting dates. Covers the whole market rather than the configured symbols. Full refresh.",+ ),}ENDPOINTS = tuple(ALPHA_VANTAGE_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/tests/test_alpha_vantage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/tests/test_alpha_vantage.pyindex 6a09ca3a7ff8..7e5d9cc3f40a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/tests/test_alpha_vantage.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/tests/test_alpha_vantage.py@@ -7,10 +7,15 @@ import requestsfrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.alpha_vantage import (+ LISTING_CHUNK_SIZE,+ LISTING_STATES,AlphaVantageAPIError,AlphaVantageRetryableError,_fetch,+ _fetch_csv,+ _listing_status_rows,_normalize_key,+ _parse_corporate_action,_parse_earnings,_parse_overview,_parse_quote,@@ -41,6 +46,12 @@ def _response(*, body: Any = None, status: int = 200, ok: bool = True) -> MagicMreturn response+def _text_response(text: str, *, status: int = 200, ok: bool = True) -> MagicMock:+ response = _response(status=status, ok=ok)+ response.text = text+ return response++def _session_returning(responses: list[MagicMock]) -> MagicMock:session = MagicMock()session.get.side_effect = responses@@ -106,6 +117,86 @@ class TestAlphaVantage:def test_parse_time_series_empty(self) -> None:assert list(_parse_time_series({"Meta Data": {}}, "IBM")) == []+ def test_parse_time_series_normalizes_the_adjusted_columns(self) -> None:+ # TIME_SERIES_DAILY_ADJUSTED rides the same parser but carries three extra ordinal-prefixed+ # columns, so the adjusted fields must land as their own snake_case columns.+ body = {+ "Meta Data": {},+ "Time Series (Daily)": {+ "2024-01-05": {+ "1. open": "1",+ "4. close": "1.5",+ "5. adjusted close": "1.4",+ "6. volume": "100",+ "7. dividend amount": "0.0",+ "8. split coefficient": "1.0",+ }+ },+ }+ assert list(_parse_time_series(body, "IBM")) == [+ {+ "symbol": "IBM",+ "date": "2024-01-05",+ "open": "1",+ "close": "1.5",+ "adjusted_close": "1.4",+ "volume": "100",+ "dividend_amount": "0.0",+ "split_coefficient": "1.0",+ }+ ]++ def test_parse_corporate_action_injects_symbol_and_nulls_placeholders(self) -> None:+ # Old dividends carry the literal string "None" for the dates that were never recorded, which+ # would otherwise land as text in a date column.+ body = {+ "symbol": "IBM",+ "data": [+ {+ "ex_dividend_date": "2026-08-10",+ "declaration_date": "2026-07-22",+ "record_date": "2026-08-10",+ "payment_date": "2026-09-10",+ "amount": "1.69",+ },+ {+ "ex_dividend_date": "1999-02-08",+ "declaration_date": "None",+ "record_date": "None",+ "payment_date": "None",+ "amount": "0.22",+ },+ ],+ }+ assert list(_parse_corporate_action(body, "IBM")) == [+ {+ "symbol": "IBM",+ "ex_dividend_date": "2026-08-10",+ "declaration_date": "2026-07-22",+ "record_date": "2026-08-10",+ "payment_date": "2026-09-10",+ "amount": "1.69",+ },+ {+ "symbol": "IBM",+ "ex_dividend_date": "1999-02-08",+ "declaration_date": None,+ "record_date": None,+ "payment_date": None,+ "amount": "0.22",+ },+ ]++ def test_parse_corporate_action_handles_splits_shape(self) -> None:+ body = {"symbol": "IBM", "data": [{"effective_date": "2021-11-04", "split_factor": "1.0460"}]}+ assert list(_parse_corporate_action(body, "IBM")) == [+ {"symbol": "IBM", "effective_date": "2021-11-04", "split_factor": "1.0460"}+ ]++ @parameterized.expand([("missing_data", {"symbol": "IBM"}), ("not_a_list", {"symbol": "IBM", "data": {}})])+ def test_parse_corporate_action_empty(self, _name: str, body: dict) -> None:+ assert list(_parse_corporate_action(body, "IBM")) == []+def test_parse_quote_injects_symbol_and_snake_cases(self) -> None:body = {"Global Quote": {@@ -252,6 +343,79 @@ class TestAlphaVantage:with pytest.raises(AlphaVantageAPIError):_collect_rows(get_rows("KEY", ["IBM"], "global_quote", MagicMock()))+ def test_fetch_csv_returns_the_csv_body(self) -> None:+ session = _session_returning([_text_response("symbol,status\nIBM,Active\n")])+ assert _fetch_csv(session, {"function": "LISTING_STATUS"}) == "symbol,status\nIBM,Active\n"++ def test_fetch_csv_returns_none_for_an_empty_json_body(self) -> None:+ # A key that is not entitled to a state gets `{}` back instead of a CSV body.+ session = _session_returning([_text_response("{}")])+ assert _fetch_csv(session, {"function": "LISTING_STATUS"}) is None++ def test_fetch_csv_information_envelope_is_permanent(self) -> None:+ session = _session_returning([_text_response('{"Information": "daily limit reached"}')])+ with pytest.raises(AlphaVantageAPIError) as exc:+ _fetch_csv(session, {"function": "LISTING_STATUS"})+ assert "rate_limit_or_premium" in str(exc.value)++ def test_fetch_csv_note_envelope_is_retryable(self) -> None:+ session = _session_returning([_text_response('{"Note": "call frequency limit"}')] * 5)+ with patch("time.sleep"), pytest.raises(AlphaVantageRetryableError):+ _fetch_csv(session, {"function": "LISTING_STATUS"})+ assert session.get.call_count == 5++ def test_listing_status_rows_covers_both_states_and_nulls_placeholders(self) -> None:+ active = "symbol,name,exchange,assetType,ipoDate,delistingDate,status\nIBM,IBM Corp,NYSE,Stock,1962-01-02,null,Active\n"+ delisted = "symbol,name,exchange,assetType,ipoDate,delistingDate,status\nOLD,Old Co,NYSE,Stock,1998-01-02,2014-07-10,Delisted\n"+ session = _session_returning([_text_response(active), _text_response(delisted)])+ rows = _collect_rows(_listing_status_rows(session, "KEY", MagicMock()))+ assert [session.get.call_args_list[i].kwargs["params"]["state"] for i in range(2)] == ["active", "delisted"]+ assert rows == [+ {+ "symbol": "IBM",+ "name": "IBM Corp",+ "exchange": "NYSE",+ "assetType": "Stock",+ "ipoDate": "1962-01-02",+ # The vendor writes "null" rather than leaving the cell empty.+ "delistingDate": None,+ "status": "Active",+ },+ {+ "symbol": "OLD",+ "name": "Old Co",+ "exchange": "NYSE",+ "assetType": "Stock",+ "ipoDate": "1998-01-02",+ "delistingDate": "2014-07-10",+ "status": "Delisted",+ },+ ]++ def test_listing_status_rows_skips_a_state_with_no_csv(self) -> None:+ active = "symbol,status\nIBM,Active\n"+ session = _session_returning([_text_response(active), _text_response("{}")])+ logger = MagicMock()+ rows = _collect_rows(_listing_status_rows(session, "KEY", logger))+ assert [r["symbol"] for r in rows] == ["IBM"]+ logger.warning.assert_called_once()++ def test_listing_status_rows_chunks_large_listings(self) -> None:+ header = "symbol,status\n"+ body = header + "".join(f"SYM{i},Active\n" for i in range(LISTING_CHUNK_SIZE + 1))+ session = _session_returning([_text_response(body), _text_response("{}")])+ batches = list(_listing_status_rows(session, "KEY", MagicMock()))+ assert [len(batch) for batch in batches] == [LISTING_CHUNK_SIZE, 1]++ def test_get_rows_does_not_fan_out_the_listing_over_symbols(self) -> None:+ # LISTING_STATUS covers the whole market, so the request count must not scale with the symbols.+ responses = [_text_response("symbol,status\nIBM,Active\n"), _text_response("{}")]+ session = _session_returning(responses)+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ rows = _collect_rows(get_rows("KEY", ["IBM", "AAPL", "MSFT"], "listing_status", MagicMock()))+ assert session.get.call_count == len(LISTING_STATES)+ assert rows == [{"symbol": "IBM", "status": "Active"}]+@parameterized.expand([("time_series_daily", ["symbol", "date"], "date"),