Skip to content

: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.

feat(data-warehouse): implement alpha_vantage import source (#67815)

Tom Owers1974a42cf48e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 7aaba208cc36..c74959e16633 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -50,6 +50,7 @@ the row lists both.
| aircall | HTTP | requests | ✅ |
| airtable | HTTP | requests | ✅ |
| algolia | HTTP | requests | ✅ |
+| alpha_vantage | HTTP | requests | ✅ |
| amazon_ads | HTTP | requests | ✅ |
| amplitude | HTTP | requests | ✅ |
| apify_dataset | HTTP | requests | ✅ |
@@ -366,7 +367,6 @@ doesn't conflict with concurrent PRs.
- airops
- akeneo
- alpaca_broker_api
-- alpha_vantage
- amazon_ads
- amazon_cloudwatch
- amazon_eventbridge
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.py
new file mode 100644
index 000000000000..32aff594d005
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/alpha_vantage.py
@@ -0,0 +1,281 @@
+import re
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.settings import (
+ ALPHA_VANTAGE_ENDPOINTS,
+ AlphaVantageEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+
+ALPHA_VANTAGE_BASE_URL = "https://www.alphavantage.co/query"
+
+# The connector issues one outbound request per symbol for every selected table, so an unbounded
+# symbol list lets a saved config fan out into arbitrarily many requests/retries per scheduled sync.
+# Cap the distinct-symbol count to keep worker time and third-party quota bounded.
+MAX_SYMBOLS = 100
+
+# Strips the ordinal prefix Alpha Vantage puts on time-series/quote keys (e.g. "1. open" -> "open",
+# "07. latest trading day" -> "latest trading day").
+_ORDINAL_PREFIX = re.compile(r"^\d+\.\s*")
+
+
+class AlphaVantageRetryableError(Exception):
+ pass
+
+
+class AlphaVantageAPIError(Exception):
+ pass
+
+
+def _normalize_key(key: str) -> str:
+ """Turn an Alpha Vantage response key into a snake_case column name.
+
+ e.g. "07. latest trading day" -> "latest_trading_day", "1. open" -> "open".
+ """
+ stripped = _ORDINAL_PREFIX.sub("", key).strip()
+ 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)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AlphaVantageRetryableError(f"Alpha Vantage API error (retryable): status={response.status_code}")
+
+ if not response.ok:
+ # Don't use raise_for_status(): response.url carries the apikey query param, and the raised
+ # message is later logged via str(error) outside the tracked session's redaction.
+ kind = "Client Error" if response.status_code < 500 else "Server Error"
+ safe_url = response.url.split("?", 1)[0]
+ raise requests.HTTPError(
+ f"{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.
+ 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']}")
+
+ return body
+
+
+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.
+ series = next(
+ (value for key, value in body.items() if key != "Meta Data" and isinstance(value, dict)),
+ None,
+ )
+ if series is None:
+ return
+ for date_str, values in series.items():
+ if not isinstance(values, dict):
+ continue
+ row: dict[str, Any] = {"symbol": symbol, "date": date_str}
+ for key, value in values.items():
+ row[_normalize_key(key)] = value
+ yield row
+
+
+def _parse_quote(body: dict[str, Any], symbol: str) -> Iterator[dict[str, Any]]:
+ quote = body.get("Global Quote")
+ if not isinstance(quote, dict) or not quote:
+ return
+ row: dict[str, Any] = {"symbol": symbol}
+ for key, value in quote.items():
+ row[_normalize_key(key)] = value
+ yield row
+
+
+def _parse_overview(body: dict[str, Any], symbol: str) -> Iterator[dict[str, Any]]:
+ # OVERVIEW is already a flat object; an empty {} means "no fundamentals for this symbol".
+ if not any(key for key in body if key != "Meta Data"):
+ return
+ # Normalize the PascalCase response keys (e.g. "PERatio", "MarketCapitalization") the same way as
+ # every other parser, and let the injected snake_case `symbol` override the response's own
+ # "Symbol" key so the table has a single primary-key column rather than a Symbol/symbol pair.
+ row: dict[str, Any] = {_normalize_key(key): value for key, value in body.items()}
+ row["symbol"] = symbol
+ yield row
+
+
+def _parse_reports(body: dict[str, Any], symbol: str) -> Iterator[dict[str, Any]]:
+ for report_type, block_key in (("annual", "annualReports"), ("quarterly", "quarterlyReports")):
+ reports = body.get(block_key)
+ if not isinstance(reports, list):
+ continue
+ for report in reports:
+ if isinstance(report, dict):
+ # Access the primary-key field directly so a missing fiscalDateEnding raises instead of
+ # silently yielding a row without its key.
+ yield {
+ "symbol": symbol,
+ "report_type": report_type,
+ "fiscalDateEnding": report["fiscalDateEnding"],
+ **report,
+ }
+
+
+def _parse_earnings(body: dict[str, Any], symbol: str) -> Iterator[dict[str, Any]]:
+ for report_type, block_key in (("annual", "annualEarnings"), ("quarterly", "quarterlyEarnings")):
+ reports = body.get(block_key)
+ if not isinstance(reports, list):
+ continue
+ for report in reports:
+ if isinstance(report, dict):
+ # Access the primary-key field directly so a missing fiscalDateEnding raises instead of
+ # silently yielding a row without its key.
+ yield {
+ "symbol": symbol,
+ "report_type": report_type,
+ "fiscalDateEnding": report["fiscalDateEnding"],
+ **report,
+ }
+
+
+_PARSERS = {
+ "time_series": _parse_time_series,
+ "quote": _parse_quote,
+ "overview": _parse_overview,
+ "reports": _parse_reports,
+ "earnings": _parse_earnings,
+}
+
+
+def parse_symbols(symbols: str) -> list[str]:
+ """Split the user's comma-separated symbols field into a de-duplicated, upper-cased list."""
+ seen: set[str] = set()
+ result: list[str] = []
+ for raw in symbols.split(","):
+ symbol = raw.strip().upper()
+ if symbol and symbol not in seen:
+ seen.add(symbol)
+ result.append(symbol)
+ return result
+
+
+def validate_symbols(symbols: str) -> tuple[list[str], str | None]:
+ """Parse and bound the symbols field. Returns the parsed list plus a user-facing error, if any.
+
+ Enforces both a lower bound (at least one symbol) and an upper bound (MAX_SYMBOLS distinct
+ symbols) so neither an empty config nor an oversized one that fans out into runaway syncs can be
+ saved or run.
+ """
+ parsed = parse_symbols(symbols)
+ if not parsed:
+ return parsed, "Enter at least one symbol (e.g. IBM, AAPL)"
+ if len(parsed) > MAX_SYMBOLS:
+ return parsed, f"Too many symbols ({len(parsed)}); enter at most {MAX_SYMBOLS} distinct symbols."
+ return parsed, None
+
+
+def _request_params(config: AlphaVantageEndpointConfig, symbol: str, api_key: str) -> dict[str, Any]:
+ params: dict[str, Any] = {"function": config.function, "symbol": symbol, "apikey": api_key}
+ # Time-series functions default to the latest 100 points; ask for the full history for a warehouse.
+ if config.kind == "time_series":
+ params["outputsize"] = "full"
+ return params
+
+
+def get_rows(
+ api_key: str,
+ symbols: list[str],
+ endpoint: str,
+ 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,))
+
+ # 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:
+ # A permanent quota/premium error (AlphaVantageAPIError) or transport failure (HTTPError)
+ # affects every symbol equally, so let it propagate and fail the whole sync rather than
+ # syncing a partial set of symbols.
+ body = _fetch(session, _request_params(config, symbol, api_key), logger)
+
+ if "Error Message" in body:
+ # Scoped to one symbol (unknown ticker / unsupported for this function). Skip it so one bad
+ # symbol doesn't fail the whole sync; the rest of the configured symbols still sync.
+ logger.warning(f"Alpha Vantage: skipping symbol {symbol} for {endpoint}: {body['Error Message']}")
+ continue
+
+ rows = list(parser(body, symbol))
+ if rows:
+ yield rows
+
+
+def alpha_vantage_source(
+ api_key: str,
+ symbols: list[str],
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = ALPHA_VANTAGE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(api_key=api_key, symbols=symbols, endpoint=endpoint, logger=logger),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Confirm the API key is usable by issuing one cheap probe request.
+
+ Note: Alpha Vantage does not strictly verify free-tier keys on many endpoints (a syntactically
+ valid but unregistered key still returns data), so this mainly confirms the key is present and the
+ API is reachable and not returning a missing-key / quota envelope.
+ """
+ if not api_key.strip():
+ return False
+
+ params = {"function": "GLOBAL_QUOTE", "symbol": "IBM", "apikey": api_key}
+ try:
+ session = make_tracked_session(redact_values=(api_key,))
+ response = session.get(ALPHA_VANTAGE_BASE_URL, params=params, timeout=10)
+ except Exception:
+ return False
+
+ if response.status_code != 200:
+ return False
+
+ try:
+ body = response.json()
+ except ValueError:
+ return False
+
+ if not isinstance(body, dict):
+ return False
+
+ # "Error Message" -> missing/invalid apikey; "Information" -> quota exhausted / demo key.
+ return "Error Message" not in body and "Information" not in body
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.py
new file mode 100644
index 000000000000..eeba39d6dc4b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/canonical_descriptions.py
@@ -0,0 +1,134 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the official Alpha Vantage API docs (https://www.alphavantage.co/documentation/).
+# Column names match the normalized shape the transport emits (ordinal prefixes stripped, snake_cased).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "time_series_daily": {
+ "description": "Daily open/high/low/close/volume price bars for each configured symbol.",
+ "docs_url": "https://www.alphavantage.co/documentation/#daily",
+ "columns": {
+ "symbol": "The ticker symbol the bar belongs to.",
+ "date": "Trading day of the bar (YYYY-MM-DD).",
+ "open": "Opening price for the trading day.",
+ "high": "Highest price during the trading day.",
+ "low": "Lowest price during the trading day.",
+ "close": "Closing price for the trading day.",
+ "volume": "Number of shares traded during the day.",
+ },
+ },
+ "time_series_weekly": {
+ "description": "Weekly open/high/low/close/volume price bars for each configured symbol.",
+ "docs_url": "https://www.alphavantage.co/documentation/#weekly",
+ "columns": {
+ "symbol": "The ticker symbol the bar belongs to.",
+ "date": "Last trading day of the week (YYYY-MM-DD).",
+ "open": "Opening price for the week.",
+ "high": "Highest price during the week.",
+ "low": "Lowest price during the week.",
+ "close": "Closing price for the week.",
+ "volume": "Number of shares traded during the week.",
+ },
+ },
+ "time_series_monthly": {
+ "description": "Monthly open/high/low/close/volume price bars for each configured symbol.",
+ "docs_url": "https://www.alphavantage.co/documentation/#monthly",
+ "columns": {
+ "symbol": "The ticker symbol the bar belongs to.",
+ "date": "Last trading day of the month (YYYY-MM-DD).",
+ "open": "Opening price for the month.",
+ "high": "Highest price during the month.",
+ "low": "Lowest price during the month.",
+ "close": "Closing price for the month.",
+ "volume": "Number of shares traded during the month.",
+ },
+ },
+ "global_quote": {
+ "description": "Latest price and trading-day snapshot for each configured symbol (one row per symbol).",
+ "docs_url": "https://www.alphavantage.co/documentation/#latestprice",
+ "columns": {
+ "symbol": "The ticker symbol.",
+ "open": "Opening price for the latest trading day.",
+ "high": "Highest price for the latest trading day.",
+ "low": "Lowest price for the latest trading day.",
+ "price": "Most recent price.",
+ "volume": "Shares traded on the latest trading day.",
+ "latest_trading_day": "Date of the latest trading day (YYYY-MM-DD).",
+ "previous_close": "Closing price of the previous trading day.",
+ "change": "Absolute price change from the previous close.",
+ "change_percent": "Percentage price change from the previous close.",
+ },
+ },
+ "company_overview": {
+ "description": "Company fundamentals, valuation ratios, and descriptive information per symbol.",
+ "docs_url": "https://www.alphavantage.co/documentation/#company-overview",
+ "columns": {
+ "symbol": "The ticker symbol.",
+ "name": "Company name.",
+ "description": "Company description.",
+ "exchange": "Exchange the security trades on.",
+ "currency": "Reporting currency.",
+ "country": "Country of incorporation.",
+ "sector": "Sector the company operates in.",
+ "industry": "Industry classification.",
+ "marketcapitalization": "Market capitalization.",
+ "peratio": "Price-to-earnings ratio.",
+ "dividendyield": "Annual dividend yield.",
+ "eps": "Earnings per share.",
+ },
+ },
+ "income_statement": {
+ "description": "Annual and quarterly income statements per symbol; one row per report period.",
+ "docs_url": "https://www.alphavantage.co/documentation/#income-statement",
+ "columns": {
+ "symbol": "The ticker symbol.",
+ "report_type": "Whether the row is an 'annual' or 'quarterly' report.",
+ "fiscalDateEnding": "Fiscal period end date (YYYY-MM-DD).",
+ "reportedCurrency": "Currency the figures are reported in.",
+ "totalRevenue": "Total revenue for the period.",
+ "grossProfit": "Gross profit for the period.",
+ "operatingIncome": "Operating income for the period.",
+ "netIncome": "Net income for the period.",
+ },
+ },
+ "balance_sheet": {
+ "description": "Annual and quarterly balance sheets per symbol; one row per report period.",
+ "docs_url": "https://www.alphavantage.co/documentation/#balance-sheet",
+ "columns": {
+ "symbol": "The ticker symbol.",
+ "report_type": "Whether the row is an 'annual' or 'quarterly' report.",
+ "fiscalDateEnding": "Fiscal period end date (YYYY-MM-DD).",
+ "reportedCurrency": "Currency the figures are reported in.",
+ "totalAssets": "Total assets at period end.",
+ "totalLiabilities": "Total liabilities at period end.",
+ "totalShareholderEquity": "Total shareholder equity at period end.",
+ },
+ },
+ "cash_flow": {
+ "description": "Annual and quarterly cash-flow statements per symbol; one row per report period.",
+ "docs_url": "https://www.alphavantage.co/documentation/#cash-flow",
+ "columns": {
+ "symbol": "The ticker symbol.",
+ "report_type": "Whether the row is an 'annual' or 'quarterly' report.",
+ "fiscalDateEnding": "Fiscal period end date (YYYY-MM-DD).",
+ "reportedCurrency": "Currency the figures are reported in.",
+ "operatingCashflow": "Cash generated by operating activities.",
+ "capitalExpenditures": "Capital expenditures for the period.",
+ },
+ },
+ "earnings": {
+ "description": "Annual and quarterly reported earnings per share per symbol; one row per report period.",
+ "docs_url": "https://www.alphavantage.co/documentation/#earnings",
+ "columns": {
+ "symbol": "The ticker symbol.",
+ "report_type": "Whether the row is an 'annual' or 'quarterly' report.",
+ "fiscalDateEnding": "Fiscal period end date (YYYY-MM-DD).",
+ "reportedDate": "Date the earnings were reported (quarterly only).",
+ "reportedEPS": "Reported earnings per share.",
+ "estimatedEPS": "Analyst-estimated earnings per share (quarterly only).",
+ "surprise": "Difference between reported and estimated EPS (quarterly only).",
+ "surprisePercentage": "Percentage EPS surprise (quarterly only).",
+ },
+ },
+}
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.py
new file mode 100644
index 000000000000..babf344df9e3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/settings.py
@@ -0,0 +1,107 @@
+import dataclasses
+from typing import Literal
+
+# 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.
+#
+# 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"]
+
+
+class AlphaVantageEndpointConfig:
+ name: str
+ # The Alpha Vantage `function` query-param value (e.g. TIME_SERIES_DAILY).
+ function: str
+ kind: ParseKind
+ # Unique across the whole table. Every endpoint fans out over the user's configured symbols, so
+ # 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.
+ partition_key: str | None = None
+ description: str | None = None
+ # Whether the table is selected for sync by default in the UI. Kept modest by default because the
+ # free tier is rate limited (~25 requests/day), and each selected table costs one request/symbol.
+ should_sync_default: bool = True
+
+
+ALPHA_VANTAGE_ENDPOINTS: dict[str, AlphaVantageEndpointConfig] = {
+ "time_series_daily": AlphaVantageEndpointConfig(
+ name="time_series_daily",
+ function="TIME_SERIES_DAILY",
+ kind="time_series",
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ description="Daily open/high/low/close/volume bars per symbol (20+ years of history). Full refresh.",
+ ),
+ "time_series_weekly": AlphaVantageEndpointConfig(
+ name="time_series_weekly",
+ function="TIME_SERIES_WEEKLY",
+ kind="time_series",
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ description="Weekly open/high/low/close/volume bars per symbol. Full refresh.",
+ should_sync_default=False,
+ ),
+ "time_series_monthly": AlphaVantageEndpointConfig(
+ name="time_series_monthly",
+ function="TIME_SERIES_MONTHLY",
+ kind="time_series",
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ description="Monthly open/high/low/close/volume bars per symbol. Full refresh.",
+ should_sync_default=False,
+ ),
+ "global_quote": AlphaVantageEndpointConfig(
+ name="global_quote",
+ function="GLOBAL_QUOTE",
+ kind="quote",
+ primary_keys=["symbol"],
+ description="Latest price and trading-day snapshot per symbol (one row per symbol). Full refresh.",
+ ),
+ "company_overview": AlphaVantageEndpointConfig(
+ name="company_overview",
+ function="OVERVIEW",
+ kind="overview",
+ primary_keys=["symbol"],
+ description="Company fundamentals, ratios, and descriptive fields per symbol (one row per symbol). Full refresh.",
+ ),
+ "income_statement": AlphaVantageEndpointConfig(
+ name="income_statement",
+ function="INCOME_STATEMENT",
+ kind="reports",
+ primary_keys=["symbol", "fiscalDateEnding", "report_type"],
+ partition_key="fiscalDateEnding",
+ description="Annual and quarterly income statements per symbol. One row per report. Full refresh.",
+ ),
+ "balance_sheet": AlphaVantageEndpointConfig(
+ name="balance_sheet",
+ function="BALANCE_SHEET",
+ kind="reports",
+ primary_keys=["symbol", "fiscalDateEnding", "report_type"],
+ partition_key="fiscalDateEnding",
+ description="Annual and quarterly balance sheets per symbol. One row per report. Full refresh.",
+ ),
+ "cash_flow": AlphaVantageEndpointConfig(
+ name="cash_flow",
+ function="CASH_FLOW",
+ kind="reports",
+ primary_keys=["symbol", "fiscalDateEnding", "report_type"],
+ partition_key="fiscalDateEnding",
+ description="Annual and quarterly cash-flow statements per symbol. One row per report. Full refresh.",
+ ),
+ "earnings": AlphaVantageEndpointConfig(
+ name="earnings",
+ function="EARNINGS",
+ kind="earnings",
+ primary_keys=["symbol", "fiscalDateEnding", "report_type"],
+ partition_key="fiscalDateEnding",
+ description="Annual and quarterly reported EPS (with estimates and surprise) per symbol. One row per report. Full refresh.",
+ ),
+}
+
+ENDPOINTS = tuple(ALPHA_VANTAGE_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/source.py
index 0c087e487cfe..ad9389b565fd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/source.py
@@ -1,30 +1,148 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.alpha_vantage import (
+ alpha_vantage_source,
+ validate_credentials as validate_alpha_vantage_credentials,
+ validate_symbols,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.settings import (
+ ALPHA_VANTAGE_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AlphaVantageSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class AlphaVantageSource(SimpleSource[AlphaVantageSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ALPHAVANTAGE
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Alpha Vantage returns HTTP 200 with an "Information" envelope when the daily quota is
+ # exhausted or the dataset is premium-only; retrying within the same run can never satisfy
+ # it, so fail fast. The next scheduled sync retries once the quota resets.
+ "Alpha Vantage API error [rate_limit_or_premium]": "Alpha Vantage returned a rate-limit or premium-only message. The free tier is limited to ~25 requests/day and some datasets require a paid plan. Wait for the quota to reset or upgrade your plan, then resync.",
+ "Alpha Vantage API error [unexpected_response]": "Alpha Vantage returned an unexpected response. Please try again later.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AlphaVantageSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Alpha Vantage has no server-side updated-at cursor, so every table is full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint.name,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ detected_primary_keys=endpoint.primary_keys,
+ should_sync_default=endpoint.should_sync_default,
+ description=endpoint.description,
+ )
+ for endpoint in ALPHA_VANTAGE_ENDPOINTS.values()
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: AlphaVantageSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ _, symbols_error = validate_symbols(config.symbols)
+ if symbols_error:
+ return False, symbols_error
+
+ if validate_alpha_vantage_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Alpha Vantage API key"
+
+ def source_for_pipeline(self, config: AlphaVantageSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ # Re-validate here so a previously-saved oversized symbol list can't trigger a runaway sync.
+ symbols, symbols_error = validate_symbols(config.symbols)
+ if symbols_error:
+ raise ValueError(f"Alpha Vantage source misconfigured: {symbols_error}")
+
+ return alpha_vantage_source(
+ api_key=config.api_key,
+ symbols=symbols,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.ALPHA_VANTAGE,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="Alpha Vantage",
- iconPath="/static/services/alpha_vantage.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ keywords=["stocks", "market data", "financial", "equities", "fundamentals"],
+ caption="""Enter your Alpha Vantage API key and the stock symbols you want to track to pull market data and company fundamentals into the PostHog Data warehouse.
+
+You can claim a free API key on the [Alpha Vantage support page](https://www.alphavantage.co/support/#api-key).
+
+Note: the free tier is limited to roughly 25 requests per day, and each selected table costs one request per symbol on every sync. Some datasets require a paid plan.""",
+ iconPath="/static/services/alpha_vantage.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/alpha-vantage",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="symbols",
+ label="Symbols (comma-separated)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="IBM, AAPL, MSFT",
+ secret=False,
+ ),
+ ],
+ ),
)
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.py
new file mode 100644
index 000000000000..6a09ca3a7ff8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/tests/test_alpha_vantage.py
@@ -0,0 +1,295 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.alpha_vantage import (
+ AlphaVantageAPIError,
+ AlphaVantageRetryableError,
+ _fetch,
+ _normalize_key,
+ _parse_earnings,
+ _parse_overview,
+ _parse_quote,
+ _parse_reports,
+ _parse_time_series,
+ _request_params,
+ alpha_vantage_source,
+ get_rows,
+ parse_symbols,
+ validate_credentials,
+ validate_symbols,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.settings import (
+ ALPHA_VANTAGE_ENDPOINTS,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.alpha_vantage"
+
+
+def _response(*, body: Any = None, status: int = 200, ok: bool = True) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ response.reason = "Client Error" if status < 500 else "Server Error"
+ # Real requests responses expose the full URL (apikey included) on `response.url`.
+ response.url = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM&apikey=supersecret"
+ response.json.return_value = body if body is not None else {}
+ return response
+
+
+def _session_returning(responses: list[MagicMock]) -> MagicMock:
+ session = MagicMock()
+ session.get.side_effect = responses
+ return session
+
+
+def _collect_rows(batches: Any) -> list[dict]:
+ rows: list[dict] = []
+ for batch in batches:
+ rows.extend(batch)
+ return rows
+
+
+class TestAlphaVantage:
+ @parameterized.expand(
+ [
+ ("ordinal", "1. open", "open"),
+ ("ordinal_spaces", "07. latest trading day", "latest_trading_day"),
+ ("percent_words", "10. change percent", "change_percent"),
+ ("already_clean", "symbol", "symbol"),
+ ]
+ )
+ def test_normalize_key(self, _name: str, raw: str, expected: str) -> None:
+ assert _normalize_key(raw) == expected
+
+ @parameterized.expand(
+ [
+ ("dedup_upper_strip", " ibm, AAPL ,, msft, IBM ", ["IBM", "AAPL", "MSFT"]),
+ ("empty", "", []),
+ ("only_commas", " , , ", []),
+ ("single", "tsla", ["TSLA"]),
+ ]
+ )
+ def test_parse_symbols(self, _name: str, raw: str, expected: list[str]) -> None:
+ assert parse_symbols(raw) == expected
+
+ def test_parse_time_series_strips_prefixes_and_injects_symbol(self) -> None:
+ body = {
+ "Meta Data": {"whatever": 1},
+ "Time Series (Daily)": {
+ "2024-01-05": {"1. open": "1", "2. high": "2", "3. low": "0.5", "4. close": "1.5", "5. volume": "100"}
+ },
+ }
+ rows = list(_parse_time_series(body, "IBM"))
+ assert rows == [
+ {
+ "symbol": "IBM",
+ "date": "2024-01-05",
+ "open": "1",
+ "high": "2",
+ "low": "0.5",
+ "close": "1.5",
+ "volume": "100",
+ }
+ ]
+
+ def test_parse_time_series_handles_varying_block_label(self) -> None:
+ # Weekly/monthly functions label the block differently, so the parser must not hardcode "Daily".
+ body = {"Meta Data": {}, "Weekly Time Series": {"2024-01-05": {"1. open": "1", "4. close": "2"}}}
+ rows = list(_parse_time_series(body, "AAPL"))
+ assert rows == [{"symbol": "AAPL", "date": "2024-01-05", "open": "1", "close": "2"}]
+
+ def test_parse_time_series_empty(self) -> None:
+ assert list(_parse_time_series({"Meta Data": {}}, "IBM")) == []
+
+ def test_parse_quote_injects_symbol_and_snake_cases(self) -> None:
+ body = {
+ "Global Quote": {
+ "01. symbol": "IBM",
+ "05. price": "286.25",
+ "07. latest trading day": "2026-07-01",
+ "10. change percent": "1.79%",
+ }
+ }
+ assert list(_parse_quote(body, "IBM")) == [
+ {"symbol": "IBM", "price": "286.25", "latest_trading_day": "2026-07-01", "change_percent": "1.79%"}
+ ]
+
+ def test_parse_quote_empty(self) -> None:
+ assert list(_parse_quote({"Global Quote": {}}, "IBM")) == []
+
+ def test_parse_overview_normalizes_keys_and_dedupes_symbol(self) -> None:
+ # PascalCase response keys must be normalized like every other parser, and the response's own
+ # "Symbol" must collapse into the single injected "symbol" column rather than a Symbol/symbol pair.
+ rows = list(_parse_overview({"Symbol": "IBM", "Name": "IBM Corp", "PERatio": "20.5"}, "IBM"))
+ assert rows == [{"symbol": "IBM", "name": "IBM Corp", "peratio": "20.5"}]
+
+ def test_parse_overview_empty(self) -> None:
+ assert list(_parse_overview({}, "IBM")) == []
+
+ def test_parse_reports_flattens_annual_and_quarterly(self) -> None:
+ body = {
+ "symbol": "IBM",
+ "annualReports": [{"fiscalDateEnding": "2025-12-31", "totalRevenue": "1"}],
+ "quarterlyReports": [{"fiscalDateEnding": "2025-09-30"}],
+ }
+ assert list(_parse_reports(body, "IBM")) == [
+ {"symbol": "IBM", "report_type": "annual", "fiscalDateEnding": "2025-12-31", "totalRevenue": "1"},
+ {"symbol": "IBM", "report_type": "quarterly", "fiscalDateEnding": "2025-09-30"},
+ ]
+
+ def test_parse_earnings_flattens_annual_and_quarterly(self) -> None:
+ body = {
+ "symbol": "IBM",
+ "annualEarnings": [{"fiscalDateEnding": "2025-12-31", "reportedEPS": "11.5"}],
+ "quarterlyEarnings": [{"fiscalDateEnding": "2025-09-30", "reportedEPS": "2.6"}],
+ }
+ assert list(_parse_earnings(body, "IBM")) == [
+ {"symbol": "IBM", "report_type": "annual", "fiscalDateEnding": "2025-12-31", "reportedEPS": "11.5"},
+ {"symbol": "IBM", "report_type": "quarterly", "fiscalDateEnding": "2025-09-30", "reportedEPS": "2.6"},
+ ]
+
+ @parameterized.expand(
+ [("reports", _parse_reports, "annualReports"), ("earnings", _parse_earnings, "annualEarnings")]
+ )
+ def test_parse_raises_when_primary_key_missing(self, _name: str, parser: Any, block_key: str) -> None:
+ # fiscalDateEnding is a primary key; a report missing it must raise rather than silently yield an
+ # unkeyed row that breaks downstream deduplication.
+ body = {block_key: [{"totalRevenue": "1"}]}
+ with pytest.raises(KeyError):
+ list(parser(body, "IBM"))
+
+ @parameterized.expand(
+ [
+ ("valid", "IBM, AAPL", ["IBM", "AAPL"], None),
+ ("empty", " ", [], "Enter at least one symbol (e.g. IBM, AAPL)"),
+ ("at_limit", ",".join(f"SYM{i}" for i in range(100)), None, None),
+ ("over_limit", ",".join(f"SYM{i}" for i in range(101)), None, "Too many symbols"),
+ ]
+ )
+ def test_validate_symbols_bounds_the_list(
+ self, _name: str, raw: str, expected_parsed: list[str] | None, expected_error_fragment: str | None
+ ) -> None:
+ parsed, error = validate_symbols(raw)
+ if expected_parsed is not None:
+ assert parsed == expected_parsed
+ if expected_error_fragment is None:
+ assert error is None
+ else:
+ assert error is not None and expected_error_fragment in error
+
+ def test_request_params_adds_outputsize_full_only_for_time_series(self) -> None:
+ ts = _request_params(ALPHA_VANTAGE_ENDPOINTS["time_series_daily"], "IBM", "KEY")
+ assert ts == {"function": "TIME_SERIES_DAILY", "symbol": "IBM", "apikey": "KEY", "outputsize": "full"}
+ quote = _request_params(ALPHA_VANTAGE_ENDPOINTS["global_quote"], "IBM", "KEY")
+ assert "outputsize" not in quote
+
+ def test_fetch_returns_body_on_success(self) -> None:
+ session = _session_returning([_response(body={"Global Quote": {"01. symbol": "IBM"}})])
+ assert _fetch(session, {"function": "GLOBAL_QUOTE"}, MagicMock()) == {"Global Quote": {"01. symbol": "IBM"}}
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ def test_fetch_http_client_error_does_not_leak_apikey(self, _name: str, status: int) -> None:
+ session = _session_returning([_response(status=status, ok=False)])
+ with pytest.raises(requests.HTTPError) as exc:
+ _fetch(session, {"function": "GLOBAL_QUOTE"}, MagicMock())
+ # The apikey must never appear in the error message — it's logged downstream via str(error).
+ assert "supersecret" not in str(exc.value)
+ assert "apikey" not in str(exc.value)
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_fetch_retryable_status_retries_then_raises(self, _name: str, status: int) -> None:
+ session = _session_returning([_response(status=status, ok=False)] * 5)
+ with patch("time.sleep"), pytest.raises(AlphaVantageRetryableError):
+ _fetch(session, {"function": "GLOBAL_QUOTE"}, MagicMock())
+ assert session.get.call_count == 5
+
+ def test_fetch_note_envelope_is_retryable(self) -> None:
+ # Alpha Vantage signals the per-minute throttle with an HTTP 200 "Note" body.
+ session = _session_returning([_response(body={"Note": "call frequency limit"})] * 5)
+ with patch("time.sleep"), pytest.raises(AlphaVantageRetryableError):
+ _fetch(session, {"function": "GLOBAL_QUOTE"}, MagicMock())
+ assert session.get.call_count == 5
+
+ def test_fetch_information_envelope_is_permanent(self) -> None:
+ session = _session_returning([_response(body={"Information": "daily limit reached"})])
+ with pytest.raises(AlphaVantageAPIError) as exc:
+ _fetch(session, {"function": "GLOBAL_QUOTE"}, MagicMock())
+ assert "rate_limit_or_premium" in str(exc.value)
+
+ def test_fetch_non_dict_body_is_permanent(self) -> None:
+ session = _session_returning([_response(body=["unexpected"])])
+ with pytest.raises(AlphaVantageAPIError) as exc:
+ _fetch(session, {"function": "GLOBAL_QUOTE"}, MagicMock())
+ assert "unexpected_response" in str(exc.value)
+
+ def test_get_rows_fans_out_over_symbols(self) -> None:
+ responses = [
+ _response(body={"Global Quote": {"01. symbol": "IBM", "05. price": "1"}}),
+ _response(body={"Global Quote": {"01. symbol": "AAPL", "05. price": "2"}}),
+ ]
+ with patch(f"{MODULE}.make_tracked_session", return_value=_session_returning(responses)):
+ rows = _collect_rows(get_rows("KEY", ["IBM", "AAPL"], "global_quote", MagicMock()))
+ assert [(r["symbol"], r["price"]) for r in rows] == [("IBM", "1"), ("AAPL", "2")]
+
+ def test_get_rows_skips_symbol_on_error_message(self) -> None:
+ # An unknown ticker returns an HTTP 200 "Error Message" scoped to that symbol; the rest sync.
+ responses = [
+ _response(body={"Error Message": "Invalid API call"}),
+ _response(body={"Global Quote": {"01. symbol": "AAPL", "05. price": "2"}}),
+ ]
+ with patch(f"{MODULE}.make_tracked_session", return_value=_session_returning(responses)):
+ rows = _collect_rows(get_rows("KEY", ["BADSYM", "AAPL"], "global_quote", MagicMock()))
+ assert [r["symbol"] for r in rows] == ["AAPL"]
+
+ def test_get_rows_propagates_permanent_quota_error(self) -> None:
+ responses = [_response(body={"Information": "premium endpoint"})]
+ with patch(f"{MODULE}.make_tracked_session", return_value=_session_returning(responses)):
+ with pytest.raises(AlphaVantageAPIError):
+ _collect_rows(get_rows("KEY", ["IBM"], "global_quote", MagicMock()))
+
+ @parameterized.expand(
+ [
+ ("time_series_daily", ["symbol", "date"], "date"),
+ ("global_quote", ["symbol"], None),
+ ("company_overview", ["symbol"], None),
+ ("income_statement", ["symbol", "fiscalDateEnding", "report_type"], "fiscalDateEnding"),
+ ("earnings", ["symbol", "fiscalDateEnding", "report_type"], "fiscalDateEnding"),
+ ]
+ )
+ def test_alpha_vantage_source_maps_primary_keys_and_partitioning(
+ self, endpoint: str, expected_keys: list[str], partition_key: str | None
+ ) -> None:
+ response = alpha_vantage_source("KEY", ["IBM"], endpoint, MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ if partition_key is None:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+
+ @parameterized.expand(
+ [
+ ("empty_key", "", 200, {}, False),
+ ("error_message", "KEY", 200, {"Error Message": "invalid apikey"}, False),
+ ("information", "KEY", 200, {"Information": "daily limit"}, False),
+ ("non_200", "KEY", 500, {}, False),
+ ("valid", "KEY", 200, {"Global Quote": {"01. symbol": "IBM"}}, True),
+ ]
+ )
+ def test_validate_credentials(self, _name: str, api_key: str, status: int, body: dict, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(body=body, status=status, ok=status == 200)
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ assert validate_credentials(api_key) is expected
+
+ def test_validate_credentials_empty_key_skips_request(self) -> None:
+ with patch(f"{MODULE}.make_tracked_session") as make_session:
+ assert validate_credentials(" ") is False
+ make_session.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/tests/test_alpha_vantage_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/tests/test_alpha_vantage_source.py
new file mode 100644
index 000000000000..6203d8ba7088
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/tests/test_alpha_vantage_source.py
@@ -0,0 +1,147 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.source import AlphaVantageSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.source"
+
+
+def _make_config(api_key: str = "key", symbols: str = "IBM, AAPL") -> Any:
+ config = MagicMock()
+ config.api_key = api_key
+ config.symbols = symbols
+ return config
+
+
+class TestAlphaVantageSource:
+ def test_source_type(self) -> None:
+ assert AlphaVantageSource().source_type == ExternalDataSourceType.ALPHAVANTAGE
+
+ def test_source_config_has_api_key_and_symbols_fields(self) -> None:
+ config = AlphaVantageSource().get_source_config
+ assert [f.name for f in config.fields] == ["api_key", "symbols"]
+ api_key_field, symbols_field = config.fields
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ # The API key is a secret credential, so it must render as a password input.
+ assert api_key_field.type == "password"
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+ # Symbols are not secret and drive the per-symbol fan-out.
+ assert isinstance(symbols_field, SourceFieldInputConfig)
+ assert symbols_field.type == "text"
+ assert symbols_field.secret is False
+ assert symbols_field.required is True
+
+ def test_source_config_stays_unreleased_alpha(self) -> None:
+ config = AlphaVantageSource().get_source_config
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == "alpha"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/alpha-vantage"
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static endpoint catalog with no I/O, so the public docs can render tables.
+ assert AlphaVantageSource.lists_tables_without_credentials is True
+
+ def test_get_schemas_returns_every_endpoint_as_full_refresh(self) -> None:
+ schemas = AlphaVantageSource().get_schemas(_make_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Alpha Vantage has no server-side updated-at cursor, so nothing supports incremental.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_exposes_primary_keys(self) -> None:
+ schemas = {s.name: s for s in AlphaVantageSource().get_schemas(_make_config(), team_id=1)}
+ assert schemas["time_series_daily"].detected_primary_keys == ["symbol", "date"]
+ assert schemas["income_statement"].detected_primary_keys == ["symbol", "fiscalDateEnding", "report_type"]
+ assert schemas["global_quote"].detected_primary_keys == ["symbol"]
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = AlphaVantageSource().get_schemas(_make_config(), team_id=1, names=["earnings", "global_quote"])
+ assert {s.name for s in schemas} == {"earnings", "global_quote"}
+
+ @parameterized.expand(
+ [
+ ("valid", "KEY", "IBM", True, True, None),
+ ("invalid_key", "KEY", "IBM", False, False, "Invalid Alpha Vantage API key"),
+ ("no_symbols", "KEY", " ", True, False, "Enter at least one symbol (e.g. IBM, AAPL)"),
+ (
+ "too_many_symbols",
+ "KEY",
+ ",".join(f"S{i}" for i in range(101)),
+ True,
+ False,
+ "Too many symbols (101); enter at most 100 distinct symbols.",
+ ),
+ ]
+ )
+ def test_validate_credentials(
+ self,
+ _name: str,
+ api_key: str,
+ symbols: str,
+ probe_result: bool,
+ expected_ok: bool,
+ expected_message: str | None,
+ ) -> None:
+ with patch(f"{MODULE}.validate_alpha_vantage_credentials", return_value=probe_result):
+ ok, message = AlphaVantageSource().validate_credentials(_make_config(api_key, symbols), team_id=1)
+ assert ok is expected_ok
+ assert message == expected_message
+
+ def test_validate_credentials_skips_probe_without_symbols(self) -> None:
+ # No point probing the API key if there are no symbols to sync — fail fast on symbols first.
+ with patch(f"{MODULE}.validate_alpha_vantage_credentials") as probe:
+ ok, _ = AlphaVantageSource().validate_credentials(_make_config(symbols=""), team_id=1)
+ assert ok is False
+ probe.assert_not_called()
+
+ def test_source_for_pipeline_plumbs_symbols_and_key(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "time_series_daily"
+ inputs.logger = MagicMock()
+ with patch(f"{MODULE}.alpha_vantage_source") as source_fn:
+ AlphaVantageSource().source_for_pipeline(_make_config("abc", "ibm, aapl"), inputs)
+ source_fn.assert_called_once()
+ kwargs = source_fn.call_args.kwargs
+ assert kwargs["api_key"] == "abc"
+ # Symbols are parsed (upper-cased, de-duplicated) before handing off to the transport.
+ assert kwargs["symbols"] == ["IBM", "AAPL"]
+ assert kwargs["endpoint"] == "time_series_daily"
+
+ def test_source_for_pipeline_rejects_oversized_symbol_list(self) -> None:
+ # A previously-saved oversized config must fail the run instead of fanning out into a runaway sync.
+ inputs = MagicMock()
+ inputs.schema_name = "time_series_daily"
+ inputs.logger = MagicMock()
+ oversized = _make_config("abc", ",".join(f"S{i}" for i in range(101)))
+ with patch(f"{MODULE}.alpha_vantage_source") as source_fn:
+ with pytest.raises(ValueError, match="Too many symbols"):
+ AlphaVantageSource().source_for_pipeline(oversized, inputs)
+ source_fn.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("quota", "Alpha Vantage API error [rate_limit_or_premium]"),
+ ("unexpected", "Alpha Vantage API error [unexpected_response]"),
+ ]
+ )
+ def test_non_retryable_errors_cover_permanent_failures(self, _name: str, expected_key: str) -> None:
+ errors = AlphaVantageSource().get_non_retryable_errors()
+ assert expected_key in errors
+ assert errors[expected_key]
+
+ def test_canonical_descriptions_keyed_by_endpoint(self) -> None:
+ descriptions = AlphaVantageSource().get_canonical_descriptions()
+ # Every documented entry must map to a real endpoint or the docs render orphaned tables.
+ assert set(descriptions.keys()) <= set(ENDPOINTS)
+ assert "time_series_daily" in descriptions
+ assert "earnings" in descriptions
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 94eebe294a33..98391a472840 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -219,7 +219,8 @@ class AlpacaBrokerAPISourceConfig(config.Config):
@config.config
class AlphaVantageSourceConfig(config.Config):
- pass
+ api_key: str
+ symbols: str
@config.config