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(alpha-vantage): add news, earnings calendar, insider and holdings tables (#99195)

Tom Owersbb38d6b8db26
diff --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.md
index c3494dea8f29..cf0d57137f41 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
@@ -238,7 +238,7 @@ Note: Verified against the published OpenAPI spec linked from https://alguna.com
## AlphaVantage — **thin**
-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`
+Today (17): `balance_sheet`, `cash_flow`, `company_overview`, `dividends`, `earnings`, `earnings_calendar`, `global_quote`, `income_statement`, `insider_transactions`, `institutional_holdings`, `listing_status`, `news_sentiment`, `splits`, `time_series_daily`, `time_series_daily_adjusted`, `time_series_monthly`, `time_series_weekly`
Diffed against: <https://www.alphavantage.co/documentation/>
@@ -246,16 +246,16 @@ Diffed against: <https://www.alphavantage.co/documentation/>
- [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)
-- [ ] `INSTITUTIONAL_HOLDINGS` — institutional holder positions per symbol (medium)
+- [x] `NEWS_SENTIMENT` — news and sentiment feed - the vendor's headline alternative-data product (high)
+- [x] `EARNINGS_CALENDAR` — upcoming earnings dates to join against the earnings table already synced (medium)
+- [x] `INSIDER_TRANSACTIONS` — insider buy/sell transaction rows per symbol (medium)
+- [x] `INSTITUTIONAL_HOLDINGS` — institutional holder positions per symbol (medium)
- [ ] `SHARES_OUTSTANDING` — share count history, needed for per-share and market-cap metrics (medium)
- [ ] `EARNINGS_ESTIMATES` — analyst estimates to compare against reported earnings (medium)
- [ ] `ETF_PROFILE` — ETF holdings and sector breakdown, the ETF counterpart to company_overview (medium)
- [ ] `REAL_GDP, CPI, TREASURY_YIELD, FEDERAL_FUNDS_RATE, UNEMPLOYMENT` — macro indicator series commonly joined against equity data (medium)
-Note: Single /query endpoint parameterized by `function=`; the docs page exposes ~140 anchored functions and PostHog surfaces 9. Beyond the listed gaps, TIME_SERIES_INTRADAY, TIME_SERIES_WEEKLY_ADJUSTED/MONTHLY_ADJUSTED, the FX and digital-currency series, the commodities family and ~60 technical indicators are also absent, though indicators are cheaply derivable in the warehouse.
+Note: Single /query endpoint parameterized by `function=`; the docs page exposes ~140 anchored functions and PostHog surfaces 17. Beyond the listed gaps, TIME_SERIES_INTRADAY, TIME_SERIES_WEEKLY_ADJUSTED/MONTHLY_ADJUSTED, the FX and digital-currency series, the commodities family and ~60 technical indicators are also absent, though indicators are cheaply derivable in the warehouse.
## AmazonAds — **thin**
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
index d8d70a5fb152..703045045d63 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
@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vant
ALPHA_VANTAGE_ENDPOINTS,
AlphaVantageEndpointConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -31,8 +32,21 @@ _ORDINAL_PREFIX = re.compile(r"^\d+\.\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
+# The CSV functions return tens of thousands of rows in one body, so yield in chunks.
+CSV_CHUNK_SIZE = 5000
+
+# The widest horizon the function offers, for the same single request as the 3-month default.
+EARNINGS_CALENDAR_HORIZON = "12month"
+
+# NEWS_SENTIMENT has no cursor pagination; `limit` caps one response at 1000 articles. The page cap
+# bounds the time-window walk in `_news_rows` over a symbol with a very deep archive.
+NEWS_PAGE_LIMIT = 1000
+NEWS_MAX_PAGES = 20
+
+# `time_from` takes YYYYMMDDTHHMM, one granularity coarser than `time_published`.
+_NEWS_MINUTE_LENGTH = len("YYYYMMDDTHHMM")
+
+_CSV_ENVELOPE_KEYS = ("Information", "Error Message", "Note")
# 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
@@ -112,6 +126,29 @@ def _fetch(session: requests.Session, params: dict[str, Any], logger: FilteringB
return body
+def _raise_for_csv_envelope(csv_text: str) -> None:
+ """Detect a JSON error envelope that leaked into a CSV body one character per column.
+
+ A refused CSV function answers with the normal header and then the envelope's key spread across
+ the columns ("I,n,f,o,r,m,a" for "Information"), rather than with a JSON body. Only the key
+ survives the vendor's truncation to the header's column count, so the check is a prefix match
+ against the keys `_raise_for_envelope` handles, with the same split between the transient
+ throttle and the permanent quota/premium refusal.
+ """
+ lines = csv_text.splitlines()
+ if len(lines) < 2:
+ return
+
+ joined = lines[1].replace(",", "").strip()
+ if not joined:
+ return
+
+ if "Note".startswith(joined):
+ raise AlphaVantageRetryableError(f"Alpha Vantage API error (retryable) [rate_limit]: {joined}")
+ if any(key.startswith(joined) for key in _CSV_ENVELOPE_KEYS):
+ raise AlphaVantageAPIError(f"Alpha Vantage API error [rate_limit_or_premium]: {joined}")
+
+
@retry(
retry=retry_if_exception_type((AlphaVantageRetryableError, requests.ReadTimeout, requests.ConnectionError)),
stop=stop_after_attempt(5),
@@ -129,12 +166,25 @@ def _fetch_csv(session: requests.Session, params: dict[str, Any]) -> str | None:
text = response.text
if not text.lstrip().startswith("{"):
+ _raise_for_csv_envelope(text)
return text
_raise_for_envelope(json.loads(text))
return None
+def _csv_row_chunks(csv_text: str) -> Iterator[list[dict[str, Any]]]:
+ batch: list[dict[str, Any]] = []
+ for row in csv.DictReader(io.StringIO(csv_text)):
+ # 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) >= CSV_CHUNK_SIZE:
+ yield batch
+ batch = []
+ if batch:
+ yield batch
+
+
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.
@@ -223,6 +273,55 @@ def _parse_corporate_action(body: dict[str, Any], symbol: str) -> Iterator[dict[
yield row
+def _parse_news(body: dict[str, Any], symbol: str) -> Iterator[dict[str, Any]]:
+ feed = body.get("feed")
+ if not isinstance(feed, list):
+ return
+ for article in feed:
+ if not isinstance(article, dict):
+ continue
+ # `topics` and `ticker_sentiment` stay nested: the pipeline writes nested values as JSON
+ # strings, which keeps the column type stable across syncs where an article carries none.
+ yield {
+ "symbol": symbol,
+ "url": article["url"],
+ **article,
+ }
+
+
+def _parse_insider(body: dict[str, Any], symbol: str) -> Iterator[dict[str, Any]]:
+ data = body.get("data")
+ if not isinstance(data, list):
+ return
+ for entry in data:
+ if not isinstance(entry, dict):
+ continue
+ yield {
+ **{key: _nullable(value) for key, value in entry.items()},
+ "transaction_date": entry["transaction_date"],
+ # The response tags each row with `ticker`; `symbol` is the column every other table in
+ # this source joins on, so it is injected here too.
+ "symbol": symbol,
+ }
+
+
+def _parse_institutional(body: dict[str, Any], symbol: str) -> Iterator[dict[str, Any]]:
+ holdings = body.get("holdings")
+ if not isinstance(holdings, list):
+ return
+ # One function means one table, so the symbol-level ownership totals ride on every holder row.
+ totals = {key: _nullable(value) for key, value in body.items() if key not in ("holdings", "symbol")}
+ for holding in holdings:
+ if not isinstance(holding, dict):
+ continue
+ yield {
+ **totals,
+ **{key: _nullable(value) for key, value in holding.items()},
+ "holder_name": holding["holder_name"],
+ "symbol": symbol,
+ }
+
+
def _listing_status_rows(
session: requests.Session, api_key: str, logger: FilteringBoundLogger
) -> Iterator[list[dict[str, Any]]]:
@@ -235,15 +334,69 @@ def _listing_status_rows(
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
+ yield from _csv_row_chunks(listing)
+
+
+def _earnings_calendar_rows(
+ session: requests.Session, api_key: str, logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ params = {"function": "EARNINGS_CALENDAR", "horizon": EARNINGS_CALENDAR_HORIZON, "apikey": api_key}
+ calendar = _fetch_csv(session, params)
+ if calendar is None:
+ logger.warning("Alpha Vantage: no earnings calendar returned")
+ return
+
+ yield from _csv_row_chunks(calendar)
+
+
+def _news_rows(
+ session: requests.Session,
+ api_key: str,
+ symbol: str,
+ time_from: str | None,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ # Each page resumes from the minute the previous one ended on, so that minute's articles come back
+ # twice. Track what this symbol already yielded so one batch sequence never carries a row twice.
+ seen_urls: set[str] = set()
+
+ for _ in range(NEWS_MAX_PAGES):
+ params: dict[str, Any] = {
+ "function": "NEWS_SENTIMENT",
+ "tickers": symbol,
+ "limit": NEWS_PAGE_LIMIT,
+ # Oldest first, so the watermark advances monotonically and a full page can be resumed.
+ "sort": "EARLIEST",
+ "apikey": api_key,
+ }
+ if time_from:
+ params["time_from"] = time_from
+
+ body = _fetch(session, params, logger)
+ if "Error Message" in body:
+ # Scoped to this ticker, so the rest of the symbols still sync.
+ logger.warning(f"Alpha Vantage: skipping symbol {symbol} for news_sentiment: {body['Error Message']}")
+ return
+
+ articles = list(_parse_news(body, symbol))
+ rows = [article for article in articles if article["url"] not in seen_urls]
+ seen_urls.update(article["url"] for article in rows)
+ if rows:
+ yield rows
+
+ if len(articles) < NEWS_PAGE_LIMIT:
+ return
+
+ next_time_from = max((str(article.get("time_published") or "") for article in articles), default="")[
+ :_NEWS_MINUTE_LENGTH
+ ]
+ if len(next_time_from) < _NEWS_MINUTE_LENGTH or next_time_from == time_from:
+ # Nothing to advance to, so another request would repeat the page forever.
+ logger.warning(f"Alpha Vantage: stopping news_sentiment walk for {symbol}; cursor did not advance")
+ return
+ time_from = next_time_from
+
+ logger.warning(f"Alpha Vantage: hit the {NEWS_MAX_PAGES}-page cap for news_sentiment on {symbol}")
_PARSERS = {
@@ -253,6 +406,8 @@ _PARSERS = {
"reports": _parse_reports,
"earnings": _parse_earnings,
"corporate_action": _parse_corporate_action,
+ "insider": _parse_insider,
+ "institutional": _parse_institutional,
}
@@ -283,19 +438,41 @@ def validate_symbols(symbols: str) -> tuple[list[str], str | None]:
return parsed, None
-def _request_params(config: AlphaVantageEndpointConfig, symbol: str, api_key: str) -> dict[str, Any]:
+def _request_params(
+ config: AlphaVantageEndpointConfig,
+ symbol: str,
+ api_key: str,
+ db_incremental_field_last_value: Any = None,
+) -> 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"
+
+ if config.kind == "insider":
+ # INSIDER_TRANSACTIONS filters server-side on a whole-day `from` bound, so an incremental run
+ # re-reads only the watermark day onwards; merge dedupes that day's overlap.
+ since = parse_datetime_value(db_incremental_field_last_value)
+ if since is not None:
+ params["from"] = since.strftime("%Y-%m-%d")
+
return params
+def _news_time_from(db_incremental_field_last_value: Any) -> str | None:
+ """Format an incremental watermark as the minute-granular value `time_from` accepts."""
+ watermark = parse_datetime_value(db_incremental_field_last_value)
+ if watermark is None:
+ return None
+ return watermark.strftime("%Y%m%dT%H%M")
+
+
def get_rows(
api_key: str,
symbols: list[str],
endpoint: str,
logger: FilteringBoundLogger,
+ db_incremental_field_last_value: Any = None,
) -> Iterator[list[dict[str, Any]]]:
config = ALPHA_VANTAGE_ENDPOINTS[endpoint]
# apikey rides as a query param on every request, so mask its value from logged URLs and samples.
@@ -306,6 +483,17 @@ def get_rows(
yield from _listing_status_rows(session, api_key, logger)
return
+ if config.kind == "calendar":
+ # The whole market's schedule arrives in one call, so the configured symbols don't apply either.
+ yield from _earnings_calendar_rows(session, api_key, logger)
+ return
+
+ if config.kind == "news":
+ time_from = _news_time_from(db_incremental_field_last_value)
+ for symbol in symbols:
+ yield from _news_rows(session, api_key, symbol, time_from, logger)
+ return
+
parser = _PARSERS[config.kind]
# One request per symbol (no pagination); yield each symbol's rows as a list and let the pipeline
@@ -314,7 +502,7 @@ def get_rows(
# 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)
+ body = _fetch(session, _request_params(config, symbol, api_key, db_incremental_field_last_value), logger)
if "Error Message" in body:
# Scoped to one symbol (unknown ticker / unsupported for this function). Skip it so one bad
@@ -332,18 +520,26 @@ def alpha_vantage_source(
symbols: list[str],
endpoint: str,
logger: FilteringBoundLogger,
+ db_incremental_field_last_value: Any = None,
) -> SourceResponse:
config = ALPHA_VANTAGE_ENDPOINTS[endpoint]
return SourceResponse(
name=endpoint,
- items=lambda: get_rows(api_key=api_key, symbols=symbols, endpoint=endpoint, logger=logger),
+ items=lambda: get_rows(
+ api_key=api_key,
+ symbols=symbols,
+ endpoint=endpoint,
+ logger=logger,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
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,
+ sort_mode=config.sort_mode,
)
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
index 6ea4bddae23c..c624961623a9 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
@@ -170,6 +170,63 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"split_factor": "Ratio of shares after the split to shares before it.",
},
},
+ "insider_transactions": {
+ "description": "Insider buy and sell transactions by executives, directors and other key stakeholders of each configured symbol; one row per filing.",
+ "docs_url": "https://www.alphavantage.co/documentation/#insider-transactions",
+ "columns": {
+ "symbol": "The ticker symbol the filing belongs to.",
+ "ticker": "Ticker as reported by Alpha Vantage on the filing.",
+ "transaction_date": "Date the transaction took place (YYYY-MM-DD).",
+ "executive": "Name of the insider who transacted.",
+ "executive_title": "Role the insider holds at the company.",
+ "security_type": "Type of security transacted (e.g. Common Stock, Phantom Stock, Rst. Stock Unit).",
+ "acquisition_or_disposal": "'A' when the insider acquired shares, 'D' when they disposed of them.",
+ "shares": "Number of shares in the transaction.",
+ "share_price": "Price per share. Zero for grants and other transactions with no cash consideration.",
+ },
+ },
+ "institutional_holdings": {
+ "description": "Institutional ownership of each configured symbol; one row per holder, with the symbol's overall institutional totals repeated on every row.",
+ "docs_url": "https://www.alphavantage.co/documentation/#institutional-holdings",
+ "columns": {
+ "symbol": "The ticker symbol the holding belongs to.",
+ "holder_name": "Name of the institution holding the position.",
+ "shares_held": "Shares the institution holds as of its last report.",
+ "shares_changed": "Change in shares held since the institution's previous report.",
+ "shares_changed_percentage": "Change in shares held as a percentage of the previous position.",
+ "change_type": "How the position moved: increased, decreased, unchanged, initiated, or sold out.",
+ "last_reported": "Date of the institution's most recent report (YYYY-MM-DD).",
+ "total_institutional_holders": "Number of institutions holding the symbol.",
+ "total_institutional_shares": "Total shares of the symbol held by institutions.",
+ "holders_with_increased_holdings": "Number of institutions that increased their position.",
+ "shares_with_increased_holdings": "Shares added across institutions that increased their position.",
+ "holders_with_decreased_holdings": "Number of institutions that decreased their position.",
+ "shares_with_decreased_holdings": "Shares removed across institutions that decreased their position.",
+ "holders_with_unchanged_holdings": "Number of institutions that left their position unchanged.",
+ "shares_with_unchanged_holdings": "Shares held across institutions that left their position unchanged.",
+ "total_institutional_ownership_percentage": "Share of the company held by institutions, as a percentage.",
+ },
+ },
+ "news_sentiment": {
+ "description": "Market news articles mentioning each configured symbol, with article-level and per-ticker sentiment scores; one row per article per symbol.",
+ "docs_url": "https://www.alphavantage.co/documentation/#news-sentiment",
+ "columns": {
+ "symbol": "The configured ticker the article was matched on.",
+ "url": "Link to the article.",
+ "title": "Headline of the article.",
+ "time_published": "Publication timestamp in YYYYMMDDTHHMMSS format.",
+ "authors": "Authors credited on the article, as a JSON array.",
+ "summary": "Short summary of the article.",
+ "banner_image": "Link to the article's lead image.",
+ "source": "Name of the news outlet.",
+ "category_within_source": "Section the outlet filed the article under.",
+ "source_domain": "Domain the article was published on.",
+ "topics": "Topics the article covers with their relevance scores, as a JSON array.",
+ "overall_sentiment_score": "Sentiment of the article overall, from bearish (negative) to bullish (positive).",
+ "overall_sentiment_label": "Sentiment score bucketed into Bearish, Somewhat-Bearish, Neutral, Somewhat_Bullish, or Bullish.",
+ "ticker_sentiment": "Per-ticker relevance and sentiment scores for every ticker the article mentions, as a JSON array.",
+ },
+ },
"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",
@@ -183,4 +240,17 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"status": "Whether the asset is 'Active' or 'Delisted'.",
},
},
+ "earnings_calendar": {
+ "description": "Company earnings scheduled over the next 12 months, with the consensus EPS estimate. Covers the whole market rather than the configured symbols.",
+ "docs_url": "https://www.alphavantage.co/documentation/#earnings-calendar",
+ "columns": {
+ "symbol": "The ticker symbol expected to report.",
+ "name": "Name of the company.",
+ "reportDate": "Date the company is expected to report (YYYY-MM-DD).",
+ "fiscalDateEnding": "End of the fiscal period being reported (YYYY-MM-DD).",
+ "estimate": "Consensus analyst EPS estimate for the period.",
+ "currency": "Currency the estimate is denominated in.",
+ "timeOfTheDay": "Whether the report is expected before market open or after close.",
+ },
+ },
}
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
index e4429d526473..1a713a229542 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,15 +1,32 @@
+from dataclasses import field
from typing import Literal
from posthog.dataclasses import frozen
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
# 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", "corporate_action", "listing"]
+# No function paginates. Most carry no server-side cursor either (no `updated_after`/`since` filter),
+# so they are full refresh only, and re-pulled rows dedupe on the primary key at merge time.
+# NEWS_SENTIMENT (`time_from`) and INSIDER_TRANSACTIONS (`from`) are the two that do filter.
+ParseKind = Literal[
+ "time_series",
+ "quote",
+ "overview",
+ "reports",
+ "earnings",
+ "corporate_action",
+ "listing",
+ "news",
+ "calendar",
+ "insider",
+ "institutional",
+]
@frozen
@@ -18,8 +35,8 @@ class AlphaVantageEndpointConfig:
# 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.
+ # Unique across the whole table. Every per-symbol endpoint fans out over the user's configured
+ # symbols, so `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) and for the low-volume corporate-action and listing
@@ -29,6 +46,13 @@ class AlphaVantageEndpointConfig:
# 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
+ # Advertised cursor options. Only set where the function takes a server-side timestamp filter;
+ # an empty list means the table is full refresh only. Never append-capable, because those filters
+ # are coarser than the stored cursor, so every run re-delivers the rows on the boundary and only
+ # a merge can dedupe them.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # The order rows actually arrive in, which the pipeline's cursor watermark trusts.
+ sort_mode: SortMode = "asc"
ALPHA_VANTAGE_ENDPOINTS: dict[str, AlphaVantageEndpointConfig] = {
@@ -129,6 +153,48 @@ ALPHA_VANTAGE_ENDPOINTS: dict[str, AlphaVantageEndpointConfig] = {
description="Historical stock split events per symbol. One row per split. Full refresh.",
should_sync_default=False,
),
+ "insider_transactions": AlphaVantageEndpointConfig(
+ name="insider_transactions",
+ function="INSIDER_TRANSACTIONS",
+ kind="insider",
+ # Alpha Vantage issues no transaction id, so the filing's own fields are the only identity
+ # available, and two identical filings on one day collapse into a single row.
+ primary_keys=[
+ "symbol",
+ "transaction_date",
+ "executive",
+ "security_type",
+ "acquisition_or_disposal",
+ "shares",
+ "share_price",
+ ],
+ partition_key="transaction_date",
+ incremental_fields=[incremental_field("transaction_date", IncrementalFieldType.Date)],
+ # Newest filing first, and the function takes no sort parameter.
+ sort_mode="desc",
+ description="Insider buy and sell transactions by executives, directors and other key stakeholders per symbol. One row per filing. Supports incremental sync.",
+ should_sync_default=False,
+ ),
+ "institutional_holdings": AlphaVantageEndpointConfig(
+ name="institutional_holdings",
+ function="INSTITUTIONAL_HOLDINGS",
+ kind="institutional",
+ # `holder_name` repeats within a symbol, because separate filers share a display name and one
+ # name can appear twice for the same reporting date. The position makes the key unique.
+ primary_keys=["symbol", "holder_name", "last_reported", "shares_held"],
+ description="Institutional holder positions per symbol, each row carrying the symbol's overall institutional ownership totals. Roughly 4,000 holders per symbol. Full refresh.",
+ should_sync_default=False,
+ ),
+ "news_sentiment": AlphaVantageEndpointConfig(
+ name="news_sentiment",
+ function="NEWS_SENTIMENT",
+ kind="news",
+ primary_keys=["symbol", "url"],
+ partition_key="time_published",
+ incremental_fields=[incremental_field("time_published")],
+ description="Market news articles mentioning each symbol, with article-level and per-ticker sentiment scores. One row per article per symbol. Supports incremental sync.",
+ should_sync_default=False,
+ ),
"listing_status": AlphaVantageEndpointConfig(
name="listing_status",
function="LISTING_STATUS",
@@ -138,6 +204,13 @@ ALPHA_VANTAGE_ENDPOINTS: dict[str, AlphaVantageEndpointConfig] = {
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.",
),
+ "earnings_calendar": AlphaVantageEndpointConfig(
+ name="earnings_calendar",
+ function="EARNINGS_CALENDAR",
+ kind="calendar",
+ primary_keys=["symbol", "reportDate", "fiscalDateEnding"],
+ description="Company earnings scheduled over the next 12 months, with the consensus EPS estimate. 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/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/source.py
index 28c7f3b2b322..89b75a002cbc 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
@@ -64,13 +64,14 @@ class AlphaVantageSource(SimpleSource[AlphaVantageSourceConfig]):
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Alpha Vantage has no server-side updated-at cursor, so every table is full refresh only.
+ # Only the functions carrying a server-side time filter can sync incrementally, and none
+ # supports append. See `incremental_fields` in settings.py for why.
schemas = [
SourceSchema(
name=endpoint.name,
- supports_incremental=False,
+ supports_incremental=bool(endpoint.incremental_fields),
supports_append=False,
- incremental_fields=[],
+ incremental_fields=endpoint.incremental_fields,
detected_primary_keys=endpoint.primary_keys,
should_sync_default=endpoint.should_sync_default,
description=endpoint.description,
@@ -111,6 +112,9 @@ class AlphaVantageSource(SimpleSource[AlphaVantageSourceConfig]):
symbols=symbols,
endpoint=inputs.schema_name,
logger=inputs.logger,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
@property
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
index 7e5d9cc3f40a..1de3e558bbaf 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
@@ -1,3 +1,4 @@
+from datetime import UTC, datetime
from typing import Any
import pytest
@@ -7,16 +8,23 @@ import requests
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.alpha_vantage.alpha_vantage import (
- LISTING_CHUNK_SIZE,
+ CSV_CHUNK_SIZE,
+ EARNINGS_CALENDAR_HORIZON,
LISTING_STATES,
AlphaVantageAPIError,
AlphaVantageRetryableError,
+ _earnings_calendar_rows,
_fetch,
_fetch_csv,
_listing_status_rows,
+ _news_rows,
+ _news_time_from,
_normalize_key,
_parse_corporate_action,
_parse_earnings,
+ _parse_insider,
+ _parse_institutional,
+ _parse_news,
_parse_overview,
_parse_quote,
_parse_reports,
@@ -58,6 +66,23 @@ def _session_returning(responses: list[MagicMock]) -> MagicMock:
return session
+def _article(url: str, time_published: str) -> dict:
+ return {
+ "url": url,
+ "title": f"headline {url}",
+ "time_published": time_published,
+ "authors": [],
+ "topics": [{"topic": "technology", "relevance_score": "0.9"}],
+ "overall_sentiment_score": 0.4,
+ "overall_sentiment_label": "Bullish",
+ "ticker_sentiment": [{"ticker": "IBM", "ticker_sentiment_label": "Bullish"}],
+ }
+
+
+def _news_response(*articles: dict) -> MagicMock:
+ return _response(body={"items": str(len(articles)), "feed": list(articles)})
+
+
def _collect_rows(batches: Any) -> list[dict]:
rows: list[dict] = []
for batch in batches:
@@ -402,10 +427,10 @@ class TestAlphaVantage:
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))
+ body = header + "".join(f"SYM{i},Active\n" for i in range(CSV_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]
+ assert [len(batch) for batch in batches] == [CSV_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.
@@ -416,6 +441,307 @@ class TestAlphaVantage:
assert session.get.call_count == len(LISTING_STATES)
assert rows == [{"symbol": "IBM", "status": "Active"}]
+ def test_parse_news_injects_symbol_and_keeps_the_nested_blocks(self) -> None:
+ article = _article("https://news.example.com/a", "20260911T025650")
+ assert list(_parse_news({"feed": [article]}, "IBM")) == [{"symbol": "IBM", **article}]
+
+ @parameterized.expand([("missing_feed", {"items": "0"}), ("not_a_list", {"feed": {}})])
+ def test_parse_news_empty(self, _name: str, body: dict) -> None:
+ assert list(_parse_news(body, "IBM")) == []
+
+ def test_parse_news_raises_when_url_missing(self) -> None:
+ # `url` is a primary key; an article without one must raise rather than land unkeyed.
+ with pytest.raises(KeyError):
+ list(_parse_news({"feed": [{"title": "no link", "time_published": "20260911T025650"}]}, "IBM"))
+
+ def test_parse_insider_injects_symbol_alongside_the_reported_ticker(self) -> None:
+ body = {
+ "data": [
+ {
+ "transaction_date": "2026-08-27",
+ "ticker": "IBM",
+ "executive": "KRISHNA, ARVIND",
+ "executive_title": "Director, Chairman, President & CEO",
+ "security_type": "Phantom Stock",
+ "acquisition_or_disposal": "A",
+ "shares": "8375.5601",
+ "share_price": "238.79",
+ }
+ ]
+ }
+ assert list(_parse_insider(body, "IBM")) == [
+ {
+ "symbol": "IBM",
+ "transaction_date": "2026-08-27",
+ "ticker": "IBM",
+ "executive": "KRISHNA, ARVIND",
+ "executive_title": "Director, Chairman, President & CEO",
+ "security_type": "Phantom Stock",
+ "acquisition_or_disposal": "A",
+ "shares": "8375.5601",
+ "share_price": "238.79",
+ }
+ ]
+
+ def test_parse_insider_nulls_placeholders(self) -> None:
+ body = {"data": [{"transaction_date": "2026-08-27", "executive_title": "None"}]}
+ assert list(_parse_insider(body, "IBM")) == [
+ {"symbol": "IBM", "transaction_date": "2026-08-27", "executive_title": None}
+ ]
+
+ def test_parse_insider_raises_when_transaction_date_missing(self) -> None:
+ with pytest.raises(KeyError):
+ list(_parse_insider({"data": [{"executive": "NO DATE"}]}, "IBM"))
+
+ @parameterized.expand([("missing_data", {}), ("not_a_list", {"data": {}})])
+ def test_parse_insider_empty(self, _name: str, body: dict) -> None:
+ assert list(_parse_insider(body, "IBM")) == []
+
+ def test_parse_institutional_rides_the_symbol_totals_on_every_holder_row(self) -> None:
+ # One function means one table, so dropping the symbol-level totals would lose them entirely.
+ body = {
+ "symbol": "IBM",
+ "total_institutional_holders": "3932",
+ "total_institutional_ownership_percentage": "76%",
+ "holdings": [
+ {"holder_name": "VANGUARD GROUP INC", "shares_held": "97216131", "last_reported": "2025-12-31"},
+ {"holder_name": "BLACKROCK", "shares_held": "76763481", "last_reported": "2026-06-30"},
+ ],
+ }
+ assert list(_parse_institutional(body, "IBM")) == [
+ {
+ "symbol": "IBM",
+ "total_institutional_holders": "3932",
+ "total_institutional_ownership_percentage": "76%",
+ "holder_name": "VANGUARD GROUP INC",
+ "shares_held": "97216131",
+ "last_reported": "2025-12-31",
+ },
+ {
+ "symbol": "IBM",
+ "total_institutional_holders": "3932",
+ "total_institutional_ownership_percentage": "76%",
+ "holder_name": "BLACKROCK",
+ "shares_held": "76763481",
+ "last_reported": "2026-06-30",
+ },
+ ]
+
+ def test_parse_institutional_raises_when_holder_name_missing(self) -> None:
+ with pytest.raises(KeyError):
+ list(_parse_institutional({"symbol": "IBM", "holdings": [{"shares_held": "1"}]}, "IBM"))
+
+ @parameterized.expand([("missing_holdings", {"symbol": "IBM"}), ("not_a_list", {"holdings": {}})])
+ def test_parse_institutional_empty(self, _name: str, body: dict) -> None:
+ assert list(_parse_institutional(body, "IBM")) == []
+
+ @parameterized.expand(
+ [
+ ("none", None, None),
+ ("datetime", datetime(2026, 9, 11, 2, 56, 50, tzinfo=UTC), "20260911T0256"),
+ # A watermark reaches the source as whatever the pipeline persisted, which is a string for
+ # this table because `time_published` lands as the vendor's own compact format.
+ ("string", "20260911T025650", "20260911T0256"),
+ ("unparseable", "not a date", None),
+ ]
+ )
+ def test_news_time_from(self, _name: str, value: Any, expected: str | None) -> None:
+ assert _news_time_from(value) == expected
+
+ @parameterized.expand(
+ [
+ ("full_refresh", None, False),
+ ("incremental", datetime(2026, 8, 1, tzinfo=UTC), True),
+ ]
+ )
+ def test_request_params_adds_the_insider_from_filter_only_with_a_watermark(
+ self, _name: str, watermark: Any, expects_filter: bool
+ ) -> None:
+ params = _request_params(ALPHA_VANTAGE_ENDPOINTS["insider_transactions"], "IBM", "KEY", watermark)
+ assert params["function"] == "INSIDER_TRANSACTIONS"
+ if expects_filter:
+ assert params["from"] == "2026-08-01"
+ else:
+ assert "from" not in params
+
+ def test_request_params_ignores_a_watermark_for_a_full_refresh_function(self) -> None:
+ # Only INSIDER_TRANSACTIONS takes a server-side date bound; sending one elsewhere would be
+ # silently ignored by the API and misleading to a reader.
+ params = _request_params(
+ ALPHA_VANTAGE_ENDPOINTS["global_quote"], "IBM", "KEY", datetime(2026, 8, 1, tzinfo=UTC)
+ )
+ assert "from" not in params
+
+ def test_news_rows_stops_on_a_short_page(self) -> None:
+ session = _session_returning([_news_response(_article("https://a", "20260101T010000"))])
+ with patch(f"{MODULE}.NEWS_PAGE_LIMIT", 2):
+ rows = _collect_rows(_news_rows(session, "KEY", "IBM", None, MagicMock()))
+ assert [row["url"] for row in rows] == ["https://a"]
+ assert session.get.call_count == 1
+ params = session.get.call_args.kwargs["params"]
+ assert params["tickers"] == "IBM"
+ # Oldest-first, so the watermark advances monotonically and the walk can resume from the end.
+ assert params["sort"] == "EARLIEST"
+ assert "time_from" not in params
+
+ def test_news_rows_walks_forward_from_the_last_article_of_a_full_page(self) -> None:
+ session = _session_returning(
+ [
+ _news_response(_article("https://a", "20260101T010000"), _article("https://b", "20260102T020000")),
+ _news_response(_article("https://c", "20260103T030000")),
+ ]
+ )
+ with patch(f"{MODULE}.NEWS_PAGE_LIMIT", 2):
+ rows = _collect_rows(_news_rows(session, "KEY", "IBM", None, MagicMock()))
+ assert [row["url"] for row in rows] == ["https://a", "https://b", "https://c"]
+ # `time_from` is minute-granular, so the second page resumes from the last article's minute.
+ assert session.get.call_args_list[1].kwargs["params"]["time_from"] == "20260102T0200"
+
+ def test_news_rows_passes_through_the_starting_watermark(self) -> None:
+ session = _session_returning([_news_response(_article("https://a", "20260101T010000"))])
+ with patch(f"{MODULE}.NEWS_PAGE_LIMIT", 2):
+ _collect_rows(_news_rows(session, "KEY", "IBM", "20251231T2359", MagicMock()))
+ assert session.get.call_args.kwargs["params"]["time_from"] == "20251231T2359"
+
+ def test_news_rows_does_not_yield_the_boundary_article_twice(self) -> None:
+ # Resuming from a minute re-reads every article published in it, and a merge cannot dedupe
+ # within one batch sequence, so the walk has to drop what it already yielded.
+ repeated = _article("https://b", "20260102T020000")
+ session = _session_returning(
+ [
+ _news_response(_article("https://a", "20260101T010000"), repeated),
+ _news_response(repeated),
+ ]
+ )
+ with patch(f"{MODULE}.NEWS_PAGE_LIMIT", 2):
+ batches = list(_news_rows(session, "KEY", "IBM", None, MagicMock()))
+ assert [[row["url"] for row in batch] for batch in batches] == [["https://a", "https://b"]]
+
+ def test_news_rows_stops_when_the_cursor_cannot_advance(self) -> None:
+ # A full page that fits inside one minute would make the next request repeat it forever.
+ page = _news_response(_article("https://a", "20260101T010000"), _article("https://b", "20260101T010030"))
+ session = _session_returning([page, _news_response(_article("https://c", "20260101T010045"))])
+ logger = MagicMock()
+ with patch(f"{MODULE}.NEWS_PAGE_LIMIT", 2):
+ _collect_rows(_news_rows(session, "KEY", "IBM", "20260101T0100", logger))
+ assert session.get.call_count == 1
+ logger.warning.assert_called_once()
+
+ def test_news_rows_stops_on_an_unparseable_published_timestamp(self) -> None:
+ session = _session_returning(
+ [_news_response(_article("https://a", ""), _article("https://b", "")), _news_response()]
+ )
+ logger = MagicMock()
+ with patch(f"{MODULE}.NEWS_PAGE_LIMIT", 2):
+ rows = _collect_rows(_news_rows(session, "KEY", "IBM", None, logger))
+ assert [row["url"] for row in rows] == ["https://a", "https://b"]
+ assert session.get.call_count == 1
+ logger.warning.assert_called_once()
+
+ def test_news_rows_stops_at_the_page_cap(self) -> None:
+ pages = [_news_response(_article(f"https://{i}", f"2026010{i}T010000")) for i in range(1, 4)]
+ session = _session_returning(pages)
+ logger = MagicMock()
+ with patch(f"{MODULE}.NEWS_PAGE_LIMIT", 1), patch(f"{MODULE}.NEWS_MAX_PAGES", 2):
+ rows = _collect_rows(_news_rows(session, "KEY", "IBM", None, logger))
+ assert [row["url"] for row in rows] == ["https://1", "https://2"]
+ assert session.get.call_count == 2
+ logger.warning.assert_called_once()
+
+ def test_news_rows_skips_a_symbol_on_error_message(self) -> None:
+ session = _session_returning([_response(body={"Error Message": "Invalid API call"})])
+ logger = MagicMock()
+ assert _collect_rows(_news_rows(session, "KEY", "BADSYM", None, logger)) == []
+ logger.warning.assert_called_once()
+
+ def test_get_rows_fans_news_out_over_symbols_with_the_watermark(self) -> None:
+ responses = [
+ _news_response(_article("https://ibm", "20260101T010000")),
+ _news_response(_article("https://aapl", "20260101T020000")),
+ ]
+ session = _session_returning(responses)
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ rows = _collect_rows(get_rows("KEY", ["IBM", "AAPL"], "news_sentiment", MagicMock(), "20251231T235900"))
+ assert [(row["symbol"], row["url"]) for row in rows] == [("IBM", "https://ibm"), ("AAPL", "https://aapl")]
+ assert [call.kwargs["params"]["tickers"] for call in session.get.call_args_list] == ["IBM", "AAPL"]
+ assert all(call.kwargs["params"]["time_from"] == "20251231T2359" for call in session.get.call_args_list)
+
+ def test_earnings_calendar_rows_requests_the_widest_horizon_and_chunks(self) -> None:
+ header = "symbol,name,reportDate,fiscalDateEnding,estimate,currency,timeOfTheDay\n"
+ body = header + "".join(
+ f"SYM{i},Co {i},2026-10-22,2026-09-30,1.0,USD,post-market\n" for i in range(CSV_CHUNK_SIZE + 1)
+ )
+ session = _session_returning([_text_response(body)])
+ batches = list(_earnings_calendar_rows(session, "KEY", MagicMock()))
+ assert [len(batch) for batch in batches] == [CSV_CHUNK_SIZE, 1]
+ params = session.get.call_args.kwargs["params"]
+ assert params["function"] == "EARNINGS_CALENDAR"
+ assert params["horizon"] == EARNINGS_CALENDAR_HORIZON
+ # Market-wide, so the request carries no symbol.
+ assert "symbol" not in params
+ assert batches[0][0] == {
+ "symbol": "SYM0",
+ "name": "Co 0",
+ "reportDate": "2026-10-22",
+ "fiscalDateEnding": "2026-09-30",
+ "estimate": "1.0",
+ "currency": "USD",
+ "timeOfTheDay": "post-market",
+ }
+
+ def test_earnings_calendar_rows_skips_a_json_reply(self) -> None:
+ session = _session_returning([_text_response("{}")])
+ logger = MagicMock()
+ assert _collect_rows(_earnings_calendar_rows(session, "KEY", logger)) == []
+ logger.warning.assert_called_once()
+
+ def test_get_rows_does_not_fan_out_the_earnings_calendar_over_symbols(self) -> None:
+ header = "symbol,reportDate,fiscalDateEnding\n"
+ session = _session_returning([_text_response(header + "IBM,2026-10-22,2026-09-30\n")])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ rows = _collect_rows(get_rows("KEY", ["IBM", "AAPL", "MSFT"], "earnings_calendar", MagicMock()))
+ assert session.get.call_count == 1
+ assert rows == [{"symbol": "IBM", "reportDate": "2026-10-22", "fiscalDateEnding": "2026-09-30"}]
+
+ @parameterized.expand(
+ [
+ # Verbatim from the live API: a refused CSV function answers with the normal header and the
+ # envelope key spelled one character per column, not with a JSON body.
+ ("information", "Informa", AlphaVantageAPIError, "rate_limit_or_premium"),
+ ("error_message", "Error M", AlphaVantageAPIError, "rate_limit_or_premium"),
+ ("note", "Not", AlphaVantageRetryableError, "rate_limit"),
+ ]
+ )
+ def test_fetch_csv_detects_an_envelope_leaked_into_the_csv_body(
+ self, _name: str, leaked: str, expected_error: type[Exception], expected_marker: str
+ ) -> None:
+ header = "symbol,name,reportDate,fiscalDateEnding,estimate,currency,timeOfTheDay"
+ body = f"{header}\r\n{','.join(leaked)}\r\n"
+ session = _session_returning([_text_response(body)] * 5)
+ with patch("time.sleep"), pytest.raises(expected_error) as exc:
+ _fetch_csv(session, {"function": "EARNINGS_CALENDAR"})
+ assert expected_marker in str(exc.value)
+
+ def test_fetch_csv_accepts_a_real_data_row(self) -> None:
+ body = "symbol,name,reportDate\r\nIBM,International Business Machines,2026-10-22\r\n"
+ assert _fetch_csv(_session_returning([_text_response(body)]), {"function": "EARNINGS_CALENDAR"}) == body
+
+ def test_fetch_csv_accepts_a_header_only_body(self) -> None:
+ body = "symbol,name,reportDate\r\n"
+ assert _fetch_csv(_session_returning([_text_response(body)]), {"function": "EARNINGS_CALENDAR"}) == body
+
+ @parameterized.expand(
+ [
+ ("insider_is_newest_first", "insider_transactions", "desc"),
+ ("news_is_oldest_first", "news_sentiment", "asc"),
+ ("full_refresh_default", "time_series_daily", "asc"),
+ ]
+ )
+ def test_alpha_vantage_source_reports_the_order_rows_arrive_in(
+ self, _name: str, endpoint: str, expected: str
+ ) -> None:
+ assert alpha_vantage_source("KEY", ["IBM"], endpoint, MagicMock()).sort_mode == expected
+
@parameterized.expand(
[
("time_series_daily", ["symbol", "date"], "date"),
@@ -423,6 +749,9 @@ class TestAlphaVantage:
("company_overview", ["symbol"], None),
("income_statement", ["symbol", "fiscalDateEnding", "report_type"], "fiscalDateEnding"),
("earnings", ["symbol", "fiscalDateEnding", "report_type"], "fiscalDateEnding"),
+ ("news_sentiment", ["symbol", "url"], "time_published"),
+ ("earnings_calendar", ["symbol", "reportDate", "fiscalDateEnding"], None),
+ ("institutional_holdings", ["symbol", "holder_name", "last_reported", "shares_held"], None),
]
)
def test_alpha_vantage_source_maps_primary_keys_and_partitioning(
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
index 107400c3e587..ecbfb2ef4c28 100644
--- 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
@@ -40,13 +40,20 @@ class TestAlphaVantageSource:
# 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_marks_only_the_server_filtered_endpoints_incremental(self) -> None:
+ schemas = {s.name: s for s in AlphaVantageSource().get_schemas(_make_config(), team_id=1)}
+ assert set(schemas) == set(ENDPOINTS)
+ # Only NEWS_SENTIMENT (`time_from`) and INSIDER_TRANSACTIONS (`from`) filter server-side. A
+ # table that lost its cursor here would silently re-pull its whole history every sync; one that
+ # gained a bogus cursor would checkpoint a watermark the API never honoured.
+ incremental = {name for name, schema in schemas.items() if schema.supports_incremental}
+ assert incremental == {"news_sentiment", "insider_transactions"}
+ assert [f["field"] for f in schemas["news_sentiment"].incremental_fields] == ["time_published"]
+ assert [f["field"] for f in schemas["insider_transactions"].incremental_fields] == ["transaction_date"]
+ assert all(not schemas[name].incremental_fields for name in set(ENDPOINTS) - incremental)
+ # Both filters are coarser than the stored cursor, so every run re-delivers the boundary rows
+ # and only a merge can dedupe them — append would duplicate.
+ assert all(schema.supports_append is False for schema in schemas.values())
def test_get_schemas_exposes_primary_keys(self) -> None:
schemas = {s.name: s for s in AlphaVantageSource().get_schemas(_make_config(), team_id=1)}
@@ -94,10 +101,21 @@ class TestAlphaVantageSource:
assert ok is False
probe.assert_not_called()
- def test_source_for_pipeline_plumbs_symbols_and_key(self) -> None:
+ @parameterized.expand(
+ [
+ ("incremental", True, "2026-08-01", "2026-08-01"),
+ # A full refresh must not carry the stored watermark, or it would filter the API call.
+ ("full_refresh", False, "2026-08-01", None),
+ ]
+ )
+ def test_source_for_pipeline_plumbs_symbols_key_and_watermark(
+ self, _name: str, should_use_incremental_field: bool, last_value: str, expected_watermark: str | None
+ ) -> None:
inputs = MagicMock()
- inputs.schema_name = "time_series_daily"
+ inputs.schema_name = "insider_transactions"
inputs.logger = MagicMock()
+ inputs.should_use_incremental_field = should_use_incremental_field
+ inputs.db_incremental_field_last_value = last_value
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()
@@ -105,7 +123,8 @@ class TestAlphaVantageSource:
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"
+ assert kwargs["endpoint"] == "insider_transactions"
+ assert kwargs["db_incremental_field_last_value"] == expected_watermark
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.