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 stockdata import source (#72641)

Tom Owers929bcec4c687
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 03351f006e38..ade9f0659c92 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -508,6 +508,7 @@ the row lists both.
| statuscake | HTTP | requests | ✅ |
| statuspage | HTTP | requests | ✅ |
| stigg | HTTP | requests | ✅ |
+| stockdata | HTTP | requests + `rest_source.RESTClient` | ✅ |
| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| stytch | HTTP | requests | ✅ |
| sumo_logic | HTTP | requests | ✅ |
@@ -942,7 +943,6 @@ doesn't conflict with concurrent PRs.
- spotify_ads
- spotlercrm
- statsig
-- stockdata
- strava
- streamelements
- streamlabs
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stockdata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stockdata.py
index 8167819f1dff..1c577ffbee7f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stockdata.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stockdata.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class StockDataSourceConfig(config.Config):
- pass
+ api_token: str
+ symbols: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/canonical_descriptions.py
new file mode 100644
index 000000000000..2ccdb72dc978
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/canonical_descriptions.py
@@ -0,0 +1,106 @@
+"""Canonical, documentation-sourced descriptions for StockData.org endpoints and columns.
+
+Sourced from the official StockData.org API documentation (https://www.stockdata.org/documentation).
+Keyed by the endpoint names in `settings.py` `STOCKDATA_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://www.stockdata.org/documentation"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "news": {
+ "description": "Financial and market news articles with identified entities and per-entity sentiment scores.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "uuid": "Unique identifier of the article. Guaranteed unique per article.",
+ "title": "Title of the article.",
+ "description": "Meta description of the article.",
+ "keywords": "Meta keywords of the article.",
+ "snippet": "The first 60 characters of the article body.",
+ "url": "URL of the article.",
+ "image_url": "URL of the article's featured image.",
+ "language": "Language of the article's source.",
+ "published_at": "UTC datetime the article was published (ISO 8601).",
+ "source": "Domain of the article's source.",
+ "relevance_score": "Relevance score based on the search parameter; null when no search was used.",
+ "entities": "Entities (symbols) identified in the article, each with match score, sentiment score, and highlighted text.",
+ "similar": "Similar articles grouped with this one.",
+ },
+ },
+ "quote": {
+ "description": "Latest price and trading-day snapshot per symbol.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "ticker": "Ticker symbol of the instrument.",
+ "name": "Name of the company or instrument.",
+ "exchange_short": "Short code of the exchange the instrument trades on.",
+ "exchange_long": "Full name of the exchange the instrument trades on.",
+ "mic_code": "Market identifier code (MIC) of the exchange.",
+ "currency": "Currency the price is quoted in.",
+ "price": "Latest trade price.",
+ "day_high": "Highest price of the current trading day.",
+ "day_low": "Lowest price of the current trading day.",
+ "day_open": "Opening price of the current trading day.",
+ "52_week_high": "Highest price over the trailing 52 weeks.",
+ "52_week_low": "Lowest price over the trailing 52 weeks.",
+ "market_cap": "Market capitalization of the instrument.",
+ "previous_close_price": "Closing price of the previous trading day.",
+ "previous_close_price_time": "Datetime of the previous close.",
+ "day_change": "Price change over the current trading day.",
+ "volume": "Trading volume of the current trading day.",
+ "is_extended_hours_price": "Whether the price was captured during extended trading hours.",
+ "last_trade_time": "Datetime of the last executed trade.",
+ },
+ },
+ "eod": {
+ "description": "End-of-day (daily OHLCV) stock prices per symbol.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "UTC datetime of the end-of-day data point (ISO 8601).",
+ "ticker": "Ticker symbol of the instrument.",
+ "open": "Opening price of the trading day.",
+ "high": "Highest price reached during the trading day.",
+ "low": "Lowest price reached during the trading day.",
+ "close": "Closing price of the trading day.",
+ "volume": "Trading volume of the day.",
+ },
+ },
+ "intraday": {
+ "description": "Intraday (hourly OHLCV) stock prices per symbol.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "UTC datetime of the intraday data point (ISO 8601).",
+ "ticker": "Ticker symbol of the instrument.",
+ "open": "Opening price of the interval.",
+ "high": "Highest price reached during the interval.",
+ "low": "Lowest price reached during the interval.",
+ "close": "Closing price of the interval.",
+ "volume": "Trading volume of the interval.",
+ "is_extended_hours": "Whether the data point falls within extended trading hours.",
+ },
+ },
+ "dividends": {
+ "description": "Historical dividend payouts per symbol.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "ticker": "Ticker symbol of the instrument.",
+ "date": "Date the dividend was paid (YYYY-MM-DD).",
+ "amount": "Dividend amount paid per share.",
+ },
+ },
+ "splits": {
+ "description": "Historical stock splits per symbol.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "ticker": "Ticker symbol of the instrument.",
+ "date": "Date the stock split took effect (YYYY-MM-DD).",
+ "numerator": "Numerator of the split ratio.",
+ "denominator": "Denominator of the split ratio.",
+ "ratio": 'Split ratio as a string (e.g. "2:1").',
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/settings.py
new file mode 100644
index 000000000000..9cb89908f182
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/settings.py
@@ -0,0 +1,118 @@
+import dataclasses
+from typing import Any, Literal
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# StockData.org windows the price feeds server-side with `date_from` and the news feed with
+# `published_after`, so those endpoints sync incrementally. Dividends and splits document no date
+# filter, so they are full refresh only.
+_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+_PUBLISHED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "published_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "published_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+class StockDataEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str]
+ # Price endpoints require a `symbols` query param; news accepts it as an optional filter.
+ requires_symbols: bool = False
+ accepts_symbols: bool = False
+ # Empty list = full refresh only (no server-side date filter).
+ incremental_fields: list[IncrementalField] = dataclasses.field(default_factory=list)
+ # The server-side filter param the incremental watermark maps onto.
+ incremental_param: Literal["date_from", "published_after"] | None = None
+ # Stable datetime column for datetime partitioning (`date` / `published_at` never change).
+ partition_key: str | None = None
+ # Static request params (interval, sort). Kept declarative so transport branches stay minimal.
+ params: dict[str, Any] = dataclasses.field(default_factory=dict)
+ # EOD/intraday rows nest OHLCV under item["data"]; the transport flattens it into the row root.
+ flatten_data: bool = False
+ # Only the news feed paginates (page param, 20,000-result cap); price endpoints return one page.
+ paginated: bool = False
+ # The order rows actually arrive in. News is newest-first and can't be flipped (sort_order is
+ # only valid with the entity-score sorts); price feeds are requested with sort=asc.
+ sort_mode: Literal["asc", "desc"] = "asc"
+ description: str | None = None
+
+
+STOCKDATA_ENDPOINTS: dict[str, StockDataEndpointConfig] = {
+ "news": StockDataEndpointConfig(
+ name="news",
+ path="/news/all",
+ primary_keys=["uuid"],
+ accepts_symbols=True,
+ incremental_fields=_PUBLISHED_AT_INCREMENTAL_FIELDS,
+ incremental_param="published_after",
+ partition_key="published_at",
+ params={"sort": "published_on"},
+ paginated=True,
+ sort_mode="desc",
+ description="Financial and market news articles with per-entity sentiment scores. Optionally filtered to the configured symbols. Incremental on published_at.",
+ ),
+ "quote": StockDataEndpointConfig(
+ name="quote",
+ path="/data/quote",
+ primary_keys=["ticker"],
+ requires_symbols=True,
+ description="Latest price and trading-day snapshot per symbol (one row per symbol). Requires symbols. Full refresh.",
+ ),
+ "eod": StockDataEndpointConfig(
+ name="eod",
+ path="/data/eod",
+ primary_keys=["ticker", "date"],
+ requires_symbols=True,
+ incremental_fields=_DATE_INCREMENTAL_FIELDS,
+ incremental_param="date_from",
+ partition_key="date",
+ params={"sort": "asc", "interval": "day"},
+ flatten_data=True,
+ description="End-of-day (daily OHLCV) stock prices per symbol. Requires symbols. Incremental on date.",
+ ),
+ "intraday": StockDataEndpointConfig(
+ name="intraday",
+ path="/data/intraday",
+ primary_keys=["ticker", "date"],
+ requires_symbols=True,
+ incremental_fields=_DATE_INCREMENTAL_FIELDS,
+ incremental_param="date_from",
+ partition_key="date",
+ # The hour interval allows a 180-day request window (minute allows only 7 days), which
+ # suits scheduled warehouse syncs far better.
+ params={"sort": "asc", "interval": "hour"},
+ flatten_data=True,
+ description="Intraday (hourly OHLCV) stock prices per symbol. Requires symbols. Incremental on date.",
+ ),
+ "dividends": StockDataEndpointConfig(
+ name="dividends",
+ path="/data/dividends",
+ primary_keys=["ticker", "date"],
+ requires_symbols=True,
+ partition_key="date",
+ description="Historical dividend payouts per symbol. Requires symbols and a Standard or higher StockData.org plan. Full refresh.",
+ ),
+ "splits": StockDataEndpointConfig(
+ name="splits",
+ path="/data/splits",
+ primary_keys=["ticker", "date"],
+ requires_symbols=True,
+ partition_key="date",
+ description="Historical stock splits per symbol. Requires symbols and a Standard or higher StockData.org plan. Full refresh.",
+ ),
+}
+
+ENDPOINTS = tuple(STOCKDATA_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/source.py
index 9ba7312a7e95..734587a46425 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/source.py
@@ -1,32 +1,153 @@
-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.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.stockdata import (
StockDataSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.settings import STOCKDATA_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.stockdata import (
+ StockDataResumeConfig,
+ stockdata_source,
+ validate_credentials as validate_stockdata_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class StockDataSource(SimpleSource[StockDataSourceConfig]):
+class StockDataSource(ResumableSource[StockDataSourceConfig, StockDataResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v1",)
+ default_version = "v1"
+ api_docs_url = "https://www.stockdata.org/documentation"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.STOCKDATA
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.stockdata.org": "Your StockData.org API token is invalid. Generate a new token in your StockData.org dashboard, then reconnect.",
+ "402 Client Error: Payment Required for url: https://api.stockdata.org": "Your StockData.org plan's usage limit has been reached. Upgrade your plan or wait for the quota to reset, then resync.",
+ "403 Client Error: Forbidden for url: https://api.stockdata.org": "Your StockData.org plan does not grant access to this data (e.g. dividends and splits require a Standard or higher plan). Upgrade your plan or deselect the restricted tables, then resync.",
+ # The price tables need at least one symbol; without one the sync can never make
+ # progress, so fail permanently with a fix-it message rather than retrying.
+ "StockData.org API error [missing_symbols]": "One or more of the selected tables (quote, EOD, intraday, dividends, splits) requires symbols. Add symbols to the source configuration, then resync.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: StockDataSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint.name,
+ # Only news (published_after) and the EOD/intraday price feeds (date_from) expose a
+ # server-side date filter; quote, dividends, and splits are full refresh only.
+ supports_incremental=bool(endpoint.incremental_fields),
+ supports_append=bool(endpoint.incremental_fields),
+ incremental_fields=list(endpoint.incremental_fields),
+ description=endpoint.description,
+ )
+ for endpoint in STOCKDATA_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: StockDataSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_stockdata_credentials(config.api_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[StockDataResumeConfig]:
+ return ResumableSourceManager[StockDataResumeConfig](inputs, StockDataResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: StockDataSourceConfig,
+ resumable_source_manager: ResumableSourceManager[StockDataResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return stockdata_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ symbols=config.symbols,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.STOCK_DATA,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
- label="StockData",
+ label="StockData.org",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your StockData.org API token to pull market news with sentiment plus quote, end-of-day, intraday, dividend, and split price data into the PostHog Data warehouse.
+
+You can find your API token in your [StockData.org dashboard](https://www.stockdata.org/dashboard).
+
+Add one or more comma-separated **symbols** (e.g. `AAPL,MSFT,TSLA`) to sync the price tables (quote, EOD, intraday, dividends, splits) — those endpoints require at least one symbol. The news table works without symbols (all market news) and is filtered to your symbols when they are set.
+
+Note: StockData.org plans are limited by daily request quotas (100 requests/day on the free plan), and some tables (dividends, splits) require a Standard or higher plan.""",
iconPath="/static/services/stockdata.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/stockdata",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="symbols",
+ label="Symbols",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="AAPL,MSFT,TSLA",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/stockdata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/stockdata.py
new file mode 100644
index 000000000000..1e7fba4379f9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/stockdata.py
@@ -0,0 +1,239 @@
+import logging
+import dataclasses
+from datetime import date, datetime
+from typing import Any, Optional
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.settings import STOCKDATA_ENDPOINTS
+
+logger = logging.getLogger(__name__)
+
+STOCKDATA_BASE_URL = "https://api.stockdata.org/v1"
+# StockData.org caps any paginated news result set at 20,000 records (limit × page); requesting
+# beyond it can't return more rows, so pagination stops there and logs the truncation.
+MAX_NEWS_RESULTS = 20_000
+
+
+class StockDataResumeConfig:
+ # Number of the next news page to fetch — StockData.org uses page-number pagination.
+ next_page: int
+
+
+def _format_date(value: Any) -> str:
+ """Format an incremental cursor for the `date_from` filter (StockData.org expects YYYY-MM-DD)."""
+ # datetime is a subclass of date, so this covers both.
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%d")
+ # A stored string cursor is already an ISO timestamp/date — keep just the date portion.
+ return str(value)[:10]
+
+
+def _format_datetime(value: Any) -> str:
+ """Format an incremental cursor for `published_after` (accepted down to YYYY-MM-DDTHH:MM:SS)."""
+ if isinstance(value, datetime):
+ return value.strftime("%Y-%m-%dT%H:%M:%S")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%d")
+ # A stored string cursor is an ISO timestamp — drop any sub-second/timezone suffix.
+ return str(value)[:19]
+
+
+def _flatten_ohlcv(row: dict[str, Any]) -> dict[str, Any]:
+ """EOD/intraday rows arrive as `{date, ticker, data: {open, high, ...}}` — lift the nested
+ OHLCV object into the row root so the table gets proper columns."""
+ nested = row.get("data")
+ if not isinstance(nested, dict):
+ return row
+ flat = {key: value for key, value in row.items() if key != "data"}
+ flat.update(nested)
+ return flat
+
+
+class StockDataNewsPaginator(PageNumberPaginator):
+ """Page-number paginator that stops on the documented 20,000-result cap.
+
+ The news response's `meta` block carries `found` (total matches), `limit` (page size), and
+ `page`, so the paginator stops after the last real page instead of paying an extra empty-page
+ request, and terminates cleanly at the result-set cap instead of erroring past it.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(base_page=1, page_param="page", stop_after_empty_page=True)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if data is None or len(data) == 0:
+ self._has_next_page = False
+ return
+
+ self.page += 1
+
+ try:
+ body = response.json()
+ except ValueError:
+ body = None
+ meta = body.get("meta") if isinstance(body, dict) else None
+ if isinstance(meta, dict):
+ found = meta.get("found")
+ limit = meta.get("limit")
+ page = meta.get("page")
+ if (
+ isinstance(found, int)
+ and isinstance(limit, int)
+ and isinstance(page, int)
+ and not isinstance(limit, bool)
+ and limit > 0
+ ):
+ fetched = page * limit
+ if fetched >= found:
+ self._has_next_page = False
+ return
+ if fetched >= MAX_NEWS_RESULTS:
+ logger.info(
+ "StockData.org news pagination reached the API's %s-result cap; %s matching "
+ "articles were not fetched. Older articles sync as the incremental watermark advances.",
+ MAX_NEWS_RESULTS,
+ found - fetched,
+ )
+ self._has_next_page = False
+ return
+
+ self._has_next_page = True
+
+
+def stockdata_source(
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[StockDataResumeConfig],
+ symbols: str | None = None,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = STOCKDATA_ENDPOINTS[endpoint]
+ normalized_symbols = _normalize_symbols(symbols)
+
+ if config.requires_symbols and not normalized_symbols:
+ # Selecting a price table with no symbols is a permanent misconfiguration; fail loud with
+ # a fix-it message rather than issuing a request that can never make progress.
+ raise ValueError(
+ f"StockData.org API error [missing_symbols]: the '{endpoint}' table requires one or more "
+ "symbols. Add symbols to the source configuration, then resync."
+ )
+
+ params: dict[str, Any] = dict(config.params)
+ if (config.requires_symbols or config.accepts_symbols) and normalized_symbols:
+ params["symbols"] = normalized_symbols
+ if config.incremental_param and db_incremental_field_last_value is not None:
+ if config.incremental_param == "published_after":
+ params["published_after"] = _format_datetime(db_incremental_field_last_value)
+ else:
+ params["date_from"] = _format_date(db_incremental_field_last_value)
+
+ resource: EndpointResource = {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": params,
+ "data_selector": "data",
+ # A 200 body without `data` means an error envelope or a changed shape — fail loud,
+ # don't sync 0 rows.
+ "data_selector_required": True,
+ },
+ }
+ if config.flatten_data:
+ resource["data_map"] = _flatten_ohlcv
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": STOCKDATA_BASE_URL,
+ # api_token rides in the query string (the API's only auth method); the framework auth
+ # redacts its value from every logged URL, captured sample, and raised error message.
+ "auth": {"type": "api_key", "api_key": api_token, "name": "api_token", "location": "query"},
+ "paginator": StockDataNewsPaginator() if config.paginated else "single_page",
+ },
+ "resources": [resource],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if config.paginated and resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = {"page": resume.next_page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only while a next page remains; save AFTER a page is yielded so a crash re-yields
+ # the last page (merge dedupes on primary key) rather than skipping it.
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(StockDataResumeConfig(next_page=int(state["page"])))
+
+ rest_resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ # An empty result set can arrive as `"data": {}` rather than `"data": []` — drop the stray
+ # empty object instead of syncing it as a junk row.
+ rest_resource.add_filter(bool)
+
+ partition_kwargs: dict[str, Any] = {}
+ if config.partition_key is not None:
+ partition_kwargs = {
+ "partition_count": 1,
+ "partition_size": 1,
+ "partition_mode": "datetime",
+ "partition_format": "month",
+ "partition_keys": [config.partition_key],
+ }
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: rest_resource,
+ primary_keys=config.primary_keys,
+ # Price feeds are requested with sort=asc; news is served newest-first and its sort order
+ # can't be flipped, so it declares desc and the watermark checkpoints at end of sync.
+ sort_mode=config.sort_mode,
+ **partition_kwargs,
+ )
+
+
+def _normalize_symbols(symbols: str | None) -> str:
+ if not symbols:
+ return ""
+ return ",".join(symbol.strip().upper() for symbol in symbols.split(",") if symbol.strip())
+
+
+def validate_credentials(api_token: str) -> tuple[bool, str | None]:
+ # `/entity/type/list` is a static reference endpoint available on every plan and takes no
+ # params, so it's the cheapest probe that the token is genuine (one request against plans
+ # with daily request quotas).
+ session = make_tracked_session(redact_values=(api_token,))
+ try:
+ response = session.get(f"{STOCKDATA_BASE_URL}/entity/type/list", params={"api_token": api_token}, timeout=10)
+ except Exception:
+ return False, "Could not connect to StockData.org. Please try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 402:
+ # The token is genuine — the plan's usage limit is just exhausted right now. Don't block
+ # source creation on a quota that resets.
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid StockData.org API token"
+ return False, f"StockData.org returned an unexpected response (HTTP {response.status_code})"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/tests/test_stockdata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/tests/test_stockdata.py
new file mode 100644
index 000000000000..163f46b70de7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/tests/test_stockdata.py
@@ -0,0 +1,409 @@
+import json
+from datetime import date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.stockdata import stockdata
+from products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.settings import STOCKDATA_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.stockdata import (
+ StockDataResumeConfig,
+ _format_date,
+ _format_datetime,
+ stockdata_source,
+ validate_credentials,
+)
+
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+# validate_credentials builds its own tracked session in the stockdata module.
+STOCKDATA_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.stockdata.make_tracked_session"
+)
+
+
+def _news_page(data: list[dict[str, Any]], *, found: int, limit: int, page: int) -> Response:
+ return _response({"meta": {"found": found, "returned": len(data), "limit": limit, "page": page}, "data": data})
+
+
+def _data_page(data: Any, *, drop_data: bool = False) -> Response:
+ body: dict[str, Any] = {"meta": {}}
+ if not drop_data:
+ body["data"] = data
+ return _response(body)
+
+
+def _response(body: Any, *, status: int = 200, reason: str = "OK") -> Response:
+ resp = Response()
+ resp.status_code = status
+ resp.reason = reason
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ resp.url = "https://api.stockdata.org/v1/news/all?api_token=supersecret&page=1"
+ return resp
+
+
+def _make_manager(resume_state: StockDataResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and snapshot each request's params AT SEND TIME.
+
+ ``request.params`` is one dict mutated in place across pages, so inspecting it after the run
+ shows only the final state — snapshot a copy when each request is prepared instead.
+ """
+ session.headers = {}
+ param_snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ param_snapshots.append(dict(request.params or {}))
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return param_snapshots
+
+
+def _rows(source_response: Any) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+def _source(
+ endpoint: str = "news",
+ manager: mock.MagicMock | None = None,
+ *,
+ symbols: str | None = None,
+ db_incremental_field_last_value: Any = None,
+) -> Any:
+ return stockdata_source(
+ "supersecret",
+ endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager or _make_manager(),
+ symbols=symbols,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+
+
+class TestCursorFormatting:
+ @parameterized.expand(
+ [
+ ("datetime", datetime(2021, 4, 9, 12, 30), "2021-04-09"),
+ ("date", date(2021, 4, 9), "2021-04-09"),
+ ("iso_string", "2021-04-09T00:00:00+0000", "2021-04-09"),
+ ]
+ )
+ def test_format_date(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_date(value) == expected
+
+ @parameterized.expand(
+ [
+ ("datetime", datetime(2021, 4, 9, 12, 30, 5), "2021-04-09T12:30:05"),
+ ("date", date(2021, 4, 9), "2021-04-09"),
+ ("iso_string_with_tz", "2021-04-09T12:30:05.123456Z", "2021-04-09T12:30:05"),
+ ]
+ )
+ def test_format_datetime(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_datetime(value) == expected
+
+
+class TestNewsPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_until_found_reached(self, MockSession) -> None:
+ session = MockSession.return_value
+ page1 = [{"uuid": f"u{i}"} for i in range(100)]
+ page2 = [{"uuid": f"u{i}"} for i in range(100, 150)]
+ params = _wire(
+ session,
+ [_news_page(page1, found=150, limit=100, page=1), _news_page(page2, found=150, limit=100, page=2)],
+ )
+
+ rows = _rows(_source("news"))
+
+ assert len(rows) == 150
+ assert params[0]["page"] == 1
+ assert params[1]["page"] == 2
+ assert session.send.call_count == 2
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stops_at_20k_result_cap(self, MockSession) -> None:
+ # limit × page can't exceed 20,000; requesting past it errors, so pagination must stop there.
+ session = MockSession.return_value
+ page1 = [{"uuid": f"u{i}"} for i in range(3)]
+ page2 = [{"uuid": f"v{i}"} for i in range(3)]
+ _wire(
+ session,
+ [
+ _news_page(page1, found=50_000, limit=10_000, page=1),
+ _news_page(page2, found=50_000, limit=10_000, page=2),
+ ],
+ )
+
+ rows = _rows(_source("news"))
+
+ assert len(rows) == 6
+ assert session.send.call_count == 2
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stops_on_empty_first_page(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_news_page([], found=0, limit=100, page=1)])
+
+ assert _rows(_source("news")) == []
+ assert session.send.call_count == 1
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_page(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_news_page([{"uuid": "u1"}], found=1, limit=100, page=3)])
+
+ _rows(_source("news", manager=_make_manager(StockDataResumeConfig(next_page=3))))
+
+ # The first request must start from the persisted page, not page 1.
+ assert params[0]["page"] == 3
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_saves_state_after_yielding_a_page(self, MockSession) -> None:
+ session = MockSession.return_value
+ page1 = [{"uuid": f"u{i}"} for i in range(100)]
+ page2 = [{"uuid": f"u{i}"} for i in range(100, 200)]
+ _wire(
+ session,
+ [_news_page(page1, found=200, limit=100, page=1), _news_page(page2, found=200, limit=100, page=2)],
+ )
+
+ manager = _make_manager()
+ _rows(_source("news", manager=manager))
+
+ # State saved once, with the next page to resume from, only while more pages remain.
+ manager.save_state.assert_called_once_with(StockDataResumeConfig(next_page=2))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_missing_data_key_raises_loudly(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_data_page(None, drop_data=True)])
+
+ # A 200 body without "data" (an error envelope or changed shape) fails loud rather than
+ # silently syncing 0 rows.
+ with pytest.raises(ValueError, match="matched nothing"):
+ _rows(_source("news"))
+
+
+class TestRequestParams:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_news_sorts_by_published_on_and_omits_symbols_by_default(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_news_page([{"uuid": "u1"}], found=1, limit=100, page=1)])
+
+ _rows(_source("news", symbols=None))
+
+ assert params[0]["sort"] == "published_on"
+ assert "symbols" not in params[0]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_news_filters_by_normalized_symbols_when_configured(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_news_page([{"uuid": "u1"}], found=1, limit=100, page=1)])
+
+ _rows(_source("news", symbols=" aapl, msft ,"))
+
+ assert params[0]["symbols"] == "AAPL,MSFT"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_news_incremental_passes_published_after_watermark(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_news_page([{"uuid": "u1"}], found=1, limit=100, page=1)])
+
+ _rows(_source("news", db_incremental_field_last_value=datetime(2021, 4, 9, 12, 30, 5)))
+
+ assert params[0]["published_after"] == "2021-04-09T12:30:05"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_eod_requests_ascending_day_interval_with_date_from_watermark(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_data_page([{"ticker": "AAPL", "date": "2021-04-09", "data": {}}])])
+
+ _rows(_source("eod", symbols="AAPL", db_incremental_field_last_value="2021-04-09T00:00:00+0000"))
+
+ assert params[0]["sort"] == "asc"
+ assert params[0]["interval"] == "day"
+ assert params[0]["symbols"] == "AAPL"
+ assert params[0]["date_from"] == "2021-04-09"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_intraday_uses_hour_interval(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_data_page([])])
+
+ _rows(_source("intraday", symbols="AAPL"))
+
+ assert params[0]["interval"] == "hour"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_no_watermark_params_on_first_incremental_sync(self, MockSession) -> None:
+ # A first incremental sync has no stored watermark, so no server-side filter should be sent.
+ session = MockSession.return_value
+ params = _wire(session, [_data_page([])])
+
+ _rows(_source("eod", symbols="AAPL", db_incremental_field_last_value=None))
+
+ assert "date_from" not in params[0]
+
+
+class TestRequiresSymbols:
+ @parameterized.expand([("quote",), ("eod",), ("intraday",), ("dividends",), ("splits",)])
+ def test_price_endpoints_require_symbols(self, endpoint: str) -> None:
+ # Selecting a price table with no symbols is a permanent misconfiguration.
+ with pytest.raises(ValueError) as exc:
+ _source(endpoint, symbols=None)
+ assert "[missing_symbols]" in str(exc.value)
+
+ def test_blank_symbols_treated_as_missing(self) -> None:
+ with pytest.raises(ValueError) as exc:
+ _source("eod", symbols=" , ")
+ assert "[missing_symbols]" in str(exc.value)
+
+
+class TestRowShapes:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_eod_rows_flatten_nested_ohlcv(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _data_page(
+ [
+ {
+ "ticker": "AAPL",
+ "date": "2021-04-09T00:00:00.000000Z",
+ "data": {"open": 1.0, "high": 2.0, "low": 0.5, "close": 1.5, "volume": 100},
+ }
+ ]
+ )
+ ],
+ )
+
+ rows = _rows(_source("eod", symbols="AAPL"))
+
+ assert rows == [
+ {
+ "ticker": "AAPL",
+ "date": "2021-04-09T00:00:00.000000Z",
+ "open": 1.0,
+ "high": 2.0,
+ "low": 0.5,
+ "close": 1.5,
+ "volume": 100,
+ }
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_data_object_yields_no_rows(self, MockSession) -> None:
+ # StockData.org signals an empty result set as `"data": {}` — it must not become a junk row.
+ session = MockSession.return_value
+ _wire(session, [_data_page({})])
+
+ assert _rows(_source("quote", symbols="AAPL")) == []
+
+
+class TestHttpErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", 401, "Unauthorized"),
+ ("payment_required", 402, "Payment Required"),
+ ("forbidden", 403, "Forbidden"),
+ ]
+ )
+ @mock.patch("tenacity.nap.time.sleep")
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_permanent_status_raises_without_leaking_token(
+ self, _name: str, status: int, reason: str, MockSession, _sleep
+ ) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response({"error": {"code": "x"}}, status=status, reason=reason)])
+
+ with pytest.raises(requests.HTTPError) as exc:
+ _rows(_source("news"))
+
+ # The api_token rides in the query string, so it must be redacted out of the error message
+ # that becomes the user-visible `latest_error`.
+ assert str(status) in str(exc.value)
+ assert "supersecret" not in str(exc.value)
+ # Permanent credential/plan/quota problem — not retried.
+ assert session.send.call_count == 1
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ ("news", ["uuid"], "published_at", "desc"),
+ ("quote", ["ticker"], None, "asc"),
+ ("eod", ["ticker", "date"], "date", "asc"),
+ ("intraday", ["ticker", "date"], "date", "asc"),
+ ("dividends", ["ticker", "date"], "date", "asc"),
+ ("splits", ["ticker", "date"], "date", "asc"),
+ ]
+ )
+ def test_source_response_keys_partitioning_and_sort(
+ self, endpoint: str, expected_keys: list[str], expected_partition: str | None, expected_sort: str
+ ) -> None:
+ response = _source(endpoint, symbols="AAPL")
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ assert response.sort_mode == expected_sort
+ if expected_partition is None:
+ assert response.partition_keys is None
+ else:
+ assert response.partition_keys == [expected_partition]
+ assert response.partition_mode == "datetime"
+
+ def test_every_endpoint_builds_a_source_response(self) -> None:
+ for endpoint in STOCKDATA_ENDPOINTS:
+ response = _source(endpoint, symbols="AAPL")
+ assert response.name == endpoint
+ assert callable(response.items)
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("quota_exhausted_token_still_genuine", 402, True),
+ ("unauthorized", 401, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:
+ response = mock.MagicMock()
+ response.status_code = status
+ session = mock.MagicMock()
+ session.get.return_value = response
+ with mock.patch(STOCKDATA_SESSION_PATCH, return_value=session):
+ ok, message = validate_credentials("k")
+ assert ok is expected
+ if expected:
+ assert message is None
+ else:
+ assert message
+
+ def test_handles_network_error(self) -> None:
+ session = mock.MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with mock.patch(STOCKDATA_SESSION_PATCH, return_value=session):
+ ok, message = validate_credentials("k")
+ assert ok is False
+ assert message
+
+
+def test_module_exposes_base_url() -> None:
+ assert stockdata.STOCKDATA_BASE_URL == "https://api.stockdata.org/v1"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/tests/test_stockdata_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/tests/test_stockdata_source.py
new file mode 100644
index 000000000000..af178ac3dd74
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stockdata/tests/test_stockdata_source.py
@@ -0,0 +1,140 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.source import StockDataSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.stockdata import StockDataResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_INCREMENTAL = {"news": "published_at", "eod": "date", "intraday": "date"}
+_FULL_REFRESH_ONLY = {"quote", "dividends", "splits"}
+
+
+def _make_config(api_token: str = "token", symbols: str | None = "AAPL") -> Any:
+ config = MagicMock()
+ config.api_token = api_token
+ config.symbols = symbols
+ return config
+
+
+class TestStockDataSource:
+ def test_source_type(self) -> None:
+ assert StockDataSource().source_type == ExternalDataSourceType.STOCKDATA
+
+ def test_source_config_fields(self) -> None:
+ config = StockDataSource().get_source_config
+ assert [f.name for f in config.fields] == ["api_token", "symbols"]
+
+ api_token_field = config.fields[0]
+ assert isinstance(api_token_field, SourceFieldInputConfig)
+ # The API token is a secret credential, so it must render as a password input.
+ assert api_token_field.type == "password"
+ assert api_token_field.secret is True
+ assert api_token_field.required is True
+
+ symbols_field = config.fields[1]
+ assert isinstance(symbols_field, SourceFieldInputConfig)
+ # Symbols are only needed for the price tables (news works without), so the field is optional.
+ assert symbols_field.required is False
+ assert symbols_field.secret is False
+
+ def test_source_config_is_released_as_alpha(self) -> None:
+ config = StockDataSource().get_source_config
+ # The source must be visible to users: unreleasedSource hides the connector entirely, and
+ # newness is expressed with the alpha release status instead.
+ assert not config.unreleasedSource
+ assert config.releaseStatus == "alpha"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/stockdata"
+
+ def test_get_schemas_returns_all_endpoints(self) -> None:
+ schemas = StockDataSource().get_schemas(_make_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_marks_incremental_endpoints(self) -> None:
+ schemas = {s.name: s for s in StockDataSource().get_schemas(_make_config(), team_id=1)}
+ for name, field in _INCREMENTAL.items():
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert [f["field"] for f in schemas[name].incremental_fields] == [field]
+ for name in _FULL_REFRESH_ONLY:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = StockDataSource().get_schemas(_make_config(), team_id=1, names=["news", "eod"])
+ assert {s.name for s in schemas} == {"news", "eod"}
+
+ @parameterized.expand(
+ [
+ ("valid", (True, None)),
+ ("invalid", (False, "Invalid StockData.org API token")),
+ ]
+ )
+ def test_validate_credentials_passes_probe_result_through(
+ self, _name: str, probe_result: tuple[bool, str | None]
+ ) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.source.validate_stockdata_credentials",
+ return_value=probe_result,
+ ):
+ assert StockDataSource().validate_credentials(_make_config(), team_id=1) == probe_result
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = StockDataSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is StockDataResumeConfig
+
+ def test_source_for_pipeline_plumbs_symbols_and_keys(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "eod"
+ inputs.logger = MagicMock()
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2021-04-09"
+
+ response = StockDataSource().source_for_pipeline(_make_config("abc", "AAPL,MSFT"), MagicMock(), inputs)
+
+ assert response.name == "eod"
+ assert response.primary_keys == ["ticker", "date"]
+
+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "quote"
+ inputs.logger = MagicMock()
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "should-be-ignored"
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stockdata.source.stockdata_source"
+ ) as mocked:
+ StockDataSource().source_for_pipeline(_make_config(), MagicMock(), inputs)
+ # A full-refresh run must never forward a stale watermark to the transport.
+ assert mocked.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ @parameterized.expand(
+ [
+ ("http_unauthorized", "401 Client Error: Unauthorized for url: https://api.stockdata.org"),
+ ("http_payment_required", "402 Client Error: Payment Required for url: https://api.stockdata.org"),
+ ("http_forbidden", "403 Client Error: Forbidden for url: https://api.stockdata.org"),
+ ("missing_symbols", "StockData.org API error [missing_symbols]"),
+ ]
+ )
+ def test_non_retryable_errors_cover_permanent_failures(self, _name: str, expected_key: str) -> None:
+ errors = StockDataSource().get_non_retryable_errors()
+ assert expected_key in errors
+ assert errors[expected_key]
+
+ def test_canonical_descriptions_keyed_by_endpoint(self) -> None:
+ descriptions = StockDataSource().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 "news" in descriptions
+ assert "eod" in descriptions