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 finnhub import source (#66762)

Tom Owersdc96ada0fb17
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 bf90797fedda..2de149370304 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -113,6 +113,7 @@ the row lists both.
| everhour | HTTP | requests | ✅ |
| fillout | HTTP | requests + `rest_source.RESTClient` | ✅ |
| financial_modelling | HTTP | requests | ✅ |
+| finnhub | HTTP | requests | ✅ |
| finnworlds | HTTP | requests | ✅ |
| front | HTTP | requests | ✅ |
| fullstory | HTTP | requests | ✅ |
@@ -394,7 +395,6 @@ doesn't conflict with concurrent PRs.
- fauna
- feishu
- finage
-- finnhub
- firebase
- firebolt
- firehydrant
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/canonical_descriptions.py
new file mode 100644
index 000000000000..7d4e66829e7d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/canonical_descriptions.py
@@ -0,0 +1,164 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the official Finnhub API docs (https://finnhub.io/docs/api). Keyed by the
+# endpoint name returned by `get_schemas`. Partial coverage is fine — anything missing falls back to LLM
+# enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "stock_symbols": {
+ "description": "All tradable symbols for an exchange.",
+ "docs_url": "https://finnhub.io/docs/api/stock-symbols",
+ "columns": {
+ "symbol": "Symbol/ticker used to identify the security.",
+ "displaySymbol": "Display symbol shown on the exchange.",
+ "description": "Company or security name.",
+ "type": "Security type (e.g. Common Stock, ETP).",
+ "currency": "Trading currency of the security.",
+ "figi": "FIGI identifier for the security.",
+ "mic": "ISO 10383 market identifier code of the listing exchange.",
+ "isin": "ISIN identifier (premium field; may be empty).",
+ },
+ },
+ "market_news": {
+ "description": "Latest general market news articles.",
+ "docs_url": "https://finnhub.io/docs/api/market-news",
+ "columns": {
+ "id": "Unique news article identifier.",
+ "category": "News category.",
+ "datetime": "Published time as a Unix timestamp (seconds).",
+ "headline": "Article headline.",
+ "image": "URL of the article's image.",
+ "related": "Related stock symbols.",
+ "source": "Publisher of the article.",
+ "summary": "Article summary.",
+ "url": "URL of the original article.",
+ },
+ },
+ "ipo_calendar": {
+ "description": "Recent and upcoming IPOs within the requested date window.",
+ "docs_url": "https://finnhub.io/docs/api/ipo-calendar",
+ "columns": {
+ "symbol": "Ticker of the company going public.",
+ "date": "IPO date (YYYY-MM-DD).",
+ "exchange": "Exchange the company is listing on.",
+ "name": "Company name.",
+ "numberOfShares": "Number of shares offered.",
+ "price": "Offering price or price range.",
+ "status": "IPO status (e.g. expected, priced, withdrawn).",
+ "totalSharesValue": "Total value of the shares offered.",
+ },
+ },
+ "earnings_calendar": {
+ "description": "Recent and upcoming company earnings within the requested date window.",
+ "docs_url": "https://finnhub.io/docs/api/earnings-calendar",
+ "columns": {
+ "symbol": "Company ticker.",
+ "date": "Earnings report date (YYYY-MM-DD).",
+ "epsActual": "Actual earnings per share.",
+ "epsEstimate": "Estimated earnings per share.",
+ "revenueActual": "Actual revenue.",
+ "revenueEstimate": "Estimated revenue.",
+ "hour": "Time of day of the report (bmo = before market open, amc = after market close).",
+ "quarter": "Fiscal quarter.",
+ "year": "Fiscal year.",
+ },
+ },
+ "country": {
+ "description": "Reference list of supported countries and their metadata.",
+ "docs_url": "https://finnhub.io/docs/api/country",
+ "columns": {
+ "code2": "Two-letter ISO country code.",
+ "code3": "Three-letter ISO country code.",
+ "country": "Country name.",
+ "currency": "Country currency name.",
+ "currencyCode": "Country currency code.",
+ },
+ },
+ "company_profile": {
+ "description": "General profile of a company.",
+ "docs_url": "https://finnhub.io/docs/api/company-profile2",
+ "columns": {
+ "symbol": "Requested ticker the profile was fetched for.",
+ "ticker": "Company ticker as reported by Finnhub.",
+ "name": "Company name.",
+ "country": "Country of the company's headquarters.",
+ "currency": "Currency the company reports in.",
+ "exchange": "Listing exchange.",
+ "ipo": "IPO date.",
+ "marketCapitalization": "Market capitalization.",
+ "shareOutstanding": "Number of shares outstanding.",
+ "finnhubIndustry": "Finnhub industry classification.",
+ "weburl": "Company website URL.",
+ "logo": "URL of the company logo.",
+ },
+ },
+ "quote": {
+ "description": "Latest real-time quote snapshot for a symbol.",
+ "docs_url": "https://finnhub.io/docs/api/quote",
+ "columns": {
+ "symbol": "Requested ticker the quote was fetched for.",
+ "c": "Current price.",
+ "d": "Change versus the previous close.",
+ "dp": "Percentage change versus the previous close.",
+ "h": "High price of the day.",
+ "l": "Low price of the day.",
+ "o": "Open price of the day.",
+ "pc": "Previous close price.",
+ "t": "Quote time as a Unix timestamp (seconds).",
+ },
+ },
+ "company_news": {
+ "description": "Company-specific news articles within the requested date window.",
+ "docs_url": "https://finnhub.io/docs/api/company-news",
+ "columns": {
+ "id": "Unique news article identifier.",
+ "symbol": "Requested ticker the article was fetched for.",
+ "category": "News category.",
+ "datetime": "Published time as a Unix timestamp (seconds).",
+ "headline": "Article headline.",
+ "image": "URL of the article's image.",
+ "related": "Related stock symbols.",
+ "source": "Publisher of the article.",
+ "summary": "Article summary.",
+ "url": "URL of the original article.",
+ },
+ },
+ "basic_financials": {
+ "description": "Basic financial metrics (valuation, margins, growth) for a company.",
+ "docs_url": "https://finnhub.io/docs/api/company-basic-financials",
+ "columns": {
+ "symbol": "Requested ticker the metrics were fetched for.",
+ "metricType": "The requested metric grouping (e.g. all).",
+ "metric": "Object of point-in-time financial metrics.",
+ "series": "Object of time-series financial metrics (annual and quarterly).",
+ },
+ },
+ "recommendation_trends": {
+ "description": "Analyst recommendation trends for a company over time.",
+ "docs_url": "https://finnhub.io/docs/api/recommendation-trends",
+ "columns": {
+ "symbol": "Company ticker.",
+ "period": "Period the recommendation snapshot covers (YYYY-MM-DD).",
+ "buy": "Number of analysts recommending buy.",
+ "hold": "Number of analysts recommending hold.",
+ "sell": "Number of analysts recommending sell.",
+ "strongBuy": "Number of analysts recommending strong buy.",
+ "strongSell": "Number of analysts recommending strong sell.",
+ },
+ },
+ "earnings_surprises": {
+ "description": "Historical EPS estimate versus actual surprises for a company.",
+ "docs_url": "https://finnhub.io/docs/api/company-earnings",
+ "columns": {
+ "symbol": "Company ticker.",
+ "period": "Reporting period (YYYY-MM-DD).",
+ "actual": "Actual earnings per share.",
+ "estimate": "Estimated earnings per share.",
+ "surprise": "Difference between actual and estimated EPS.",
+ "surprisePercent": "Surprise as a percentage of the estimate.",
+ "quarter": "Fiscal quarter.",
+ "year": "Fiscal year.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py
new file mode 100644
index 000000000000..ebcb00e81df2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py
@@ -0,0 +1,254 @@
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub.settings import (
+ FINNHUB_ENDPOINTS,
+ FinnhubEndpointConfig,
+)
+
+FINNHUB_BASE_URL = "https://finnhub.io/api/v1"
+DEFAULT_EXCHANGE = "US"
+REQUEST_TIMEOUT_SECONDS = 60
+# Per-symbol endpoints fan out one request per ticker, so bound the parsed list to keep a
+# pathological Symbols value from spawning unbounded outbound requests (each with its own
+# retry loop). Real ticker symbols are short, so anything longer is dropped as noise.
+MAX_SYMBOLS = 500
+MAX_SYMBOL_LENGTH = 20
+
+
+class FinnhubRetryableError(Exception):
+ """Raised for 429 / 5xx responses so tenacity backs off and retries."""
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"X-Finnhub-Token": api_key, "Accept": "application/json"}
+
+
+def _parse_symbols(symbols: str | None, logger: FilteringBoundLogger | None = None) -> list[str]:
+ if not symbols:
+ return []
+ # Accept comma, whitespace, or newline separated tickers; normalize to upper-case and dedupe
+ # while preserving order so fan-out is deterministic.
+ raw = symbols.replace("\n", ",").replace(" ", ",").split(",")
+ seen: set[str] = set()
+ out: list[str] = []
+ for token in raw:
+ ticker = token.strip().upper()
+ # Drop oversized junk tokens — real tickers are short, and this stops a single huge
+ # value from being treated as a "symbol" we'd query.
+ if not ticker or len(ticker) > MAX_SYMBOL_LENGTH or ticker in seen:
+ continue
+ seen.add(ticker)
+ out.append(ticker)
+ if len(out) > MAX_SYMBOLS:
+ if logger is not None:
+ logger.warning(
+ f"Finnhub: {len(out)} symbols configured, capping per-symbol fan-out at {MAX_SYMBOLS}. "
+ "Reduce the Symbols list to sync the rest."
+ )
+ return out[:MAX_SYMBOLS]
+ return out
+
+
+def _to_date(value: Any) -> date:
+ """Coerce a stored incremental cursor (epoch seconds, datetime, date, or ISO string) to a date."""
+ if isinstance(value, datetime):
+ return value.astimezone(UTC).date() if value.tzinfo else value.date()
+ if isinstance(value, date):
+ return value
+ if isinstance(value, int | float):
+ return datetime.fromtimestamp(float(value), tz=UTC).date()
+ if isinstance(value, str):
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()
+ except ValueError:
+ return datetime.strptime(value[:10], "%Y-%m-%d").date()
+ raise ValueError(f"Cannot coerce incremental value {value!r} to a date")
+
+
+@retry(
+ retry=retry_if_exception_type((FinnhubRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(6),
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+)
+def _fetch(session: requests.Session, path: str, params: dict[str, Any], logger: FilteringBoundLogger) -> Any:
+ response = session.get(f"{FINNHUB_BASE_URL}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Finnhub returns 429 once the per-minute / per-second rate limit is hit; back off and retry.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise FinnhubRetryableError(f"Finnhub API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"Finnhub API error: status={response.status_code}, body={response.text}, path={path}")
+ # raise_for_status() would embed the full request URL in the exception, which is
+ # surfaced as the schema's latest_error. Finnhub authenticates via the X-Finnhub-Token
+ # header today, but rebuild the error from scheme/host/path only so a redirect or future
+ # query-param auth can never leak the api_key into stored error state. The "<status>
+ # Client Error: <reason> for url: https://finnhub.io" prefix stays stable for
+ # get_non_retryable_errors() matching.
+ safe = urlsplit(response.url)
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {safe.scheme}://{safe.netloc}{safe.path}",
+ response=response,
+ )
+
+ return response.json()
+
+
+def _extract_rows(data: Any, config: FinnhubEndpointConfig) -> list[dict[str, Any]]:
+ """Normalize a Finnhub response into a list of row dicts per the endpoint's shape."""
+ if config.single_object:
+ # Snapshot endpoints (quote/profile/metric) return a single object. Finnhub returns an
+ # empty object for an unknown symbol, which we skip.
+ return [data] if isinstance(data, dict) and data else []
+ if config.data_key:
+ rows = data.get(config.data_key) if isinstance(data, dict) else None
+ return rows or []
+ return data if isinstance(data, list) else []
+
+
+def _window(config: FinnhubEndpointConfig, last_value: Any) -> tuple[str, str]:
+ today = datetime.now(UTC).date()
+ if last_value is not None:
+ start = _to_date(last_value)
+ else:
+ start = today - timedelta(days=config.lookback_days)
+ end = today + timedelta(days=config.forward_days)
+ return start.isoformat(), end.isoformat()
+
+
+def _request_params(
+ config: FinnhubEndpointConfig,
+ symbol: str | None,
+ exchange: str | None,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if symbol is not None:
+ params["symbol"] = symbol
+ params.update(config.fixed_params)
+ if config.exchange_param:
+ params["exchange"] = exchange or DEFAULT_EXCHANGE
+ if config.windowed:
+ # Incremental endpoints advance `from` to the saved watermark; windowed full-refresh
+ # endpoints (calendars) always sweep the full rolling window.
+ last_value = db_incremental_field_last_value if should_use_incremental_field else None
+ params["from"], params["to"] = _window(config, last_value)
+ return params
+
+
+def _emit(rows: list[dict[str, Any]], symbol: str | None, config: FinnhubEndpointConfig) -> list[dict[str, Any]]:
+ if symbol is not None:
+ # Inject the requested ticker: several per-symbol endpoints (quote, company-news) omit it,
+ # and it's part of those tables' primary keys.
+ for row in rows:
+ row["symbol"] = symbol
+ if config.incremental_fields:
+ # Guarantee ascending order so the declared `sort_mode="asc"` matches the data the
+ # incremental watermark is checkpointed against, regardless of the API's response order.
+ # The watermark field is required, so a row missing it is a hard error rather than a
+ # silent epoch-0 sort that would corrupt the checkpoint.
+ watermark = config.incremental_fields[0]["field"]
+ rows.sort(key=lambda r: r[watermark])
+ return rows
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ symbols: str | None,
+ exchange: str | None,
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = FINNHUB_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ if config.requires_symbol:
+ tickers = _parse_symbols(symbols, logger)
+ if not tickers:
+ logger.warning(
+ f"Finnhub: endpoint '{endpoint}' needs symbols but none are configured; nothing to sync. "
+ "Add tickers to the source's Symbols field."
+ )
+ return
+ for ticker in tickers:
+ params = _request_params(
+ config, ticker, exchange, should_use_incremental_field, db_incremental_field_last_value
+ )
+ rows = _extract_rows(_fetch(session, config.path, params, logger), config)
+ if rows:
+ yield _emit(rows, ticker, config)
+ return
+
+ params = _request_params(config, None, exchange, should_use_incremental_field, db_incremental_field_last_value)
+ rows = _extract_rows(_fetch(session, config.path, params, logger), config)
+ if rows:
+ yield _emit(rows, None, config)
+
+
+def finnhub_source(
+ api_key: str,
+ endpoint: str,
+ symbols: str | None,
+ exchange: str | None,
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = FINNHUB_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ symbols=symbols,
+ exchange=exchange,
+ logger=logger,
+ should_use_incremental_field=should_use_incremental_field,
+ 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,
+ # Only the incremental endpoints get a sorted data contract — full-refresh endpoints
+ # emit in whatever order the API returns, so don't promise ascending order there.
+ sort_mode="asc" if config.incremental_fields else None,
+ )
+
+
+def validate_credentials(api_key: str, schema_name: str | None = None) -> tuple[bool, str | None]:
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ # `/quote` is a cheap, free-tier endpoint — enough to prove the token is genuine.
+ response = session.get(f"{FINNHUB_BASE_URL}/quote", params={"symbol": "AAPL"}, timeout=10)
+ except Exception:
+ return False, "Could not connect to Finnhub to validate the API key"
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Finnhub API key"
+ if response.status_code == 403:
+ # A genuine token whose plan tier doesn't cover this resource. Accept at source-create
+ # (schema_name is None) so users can still connect for the endpoints they do have; only
+ # report it as a problem when validating a specific schema.
+ if schema_name is None:
+ return True, None
+ return False, "Your Finnhub plan does not include access to this data"
+ return False, f"Finnhub credential check failed (HTTP {response.status_code})"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/settings.py
new file mode 100644
index 000000000000..69b1ed21f850
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/settings.py
@@ -0,0 +1,166 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class FinnhubEndpointConfig:
+ name: str
+ path: str
+ # JSON key the row array lives under (e.g. calendar endpoints wrap rows in
+ # `ipoCalendar`/`earningsCalendar`). None means the response is parsed directly.
+ data_key: Optional[str] = None
+ # The response is a single JSON object yielded as one row (quote, profile, basic
+ # financials) rather than a list.
+ single_object: bool = False
+ primary_keys: list[str] = field(default_factory=lambda: ["symbol"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable field used to partition the Delta table. Must be a "YYYY-MM-DD" date string
+ # (Finnhub's epoch-second timestamps aren't parsed by the datetime partitioner), and
+ # must never change for a given row — so never an `updated`/`lastSeen` style field.
+ partition_key: Optional[str] = None
+ # Per-symbol fan-out: the endpoint needs a `symbol` query param and is queried once per
+ # configured ticker, with the requested symbol injected into each emitted row.
+ requires_symbol: bool = False
+ # Static query params merged into every request for this endpoint (e.g. `metric=all`,
+ # `category=general`). Keeps an endpoint's full request shape in this one config.
+ fixed_params: dict[str, str] = field(default_factory=dict)
+ # The endpoint accepts the source-level `exchange` query param (defaulting to US).
+ exchange_param: bool = False
+ # Windowed endpoints accept `from`/`to` (YYYY-MM-DD) range params. `lookback_days`
+ # bounds how far back the initial/full window reaches; `forward_days` extends it into
+ # the future for forward-looking calendars (scheduled IPOs / earnings).
+ windowed: bool = False
+ lookback_days: int = 365
+ forward_days: int = 0
+ should_sync_default: bool = True
+ description: Optional[str] = None
+
+
+# Endpoints chosen to mirror the canonical Finnhub stream set (cross-referenced against the
+# Airbyte Finnhub connector) while staying on the free tier. Market-wide endpoints sync by
+# default; per-symbol endpoints are opt-in since they only return data when the user has
+# configured tickers.
+FINNHUB_ENDPOINTS: dict[str, FinnhubEndpointConfig] = {
+ # --- Market-wide reference / time-series (no symbol required) ---
+ "stock_symbols": FinnhubEndpointConfig(
+ name="stock_symbols",
+ path="/stock/symbol",
+ primary_keys=["symbol"],
+ exchange_param=True,
+ description="All tradable symbols for the configured exchange (default US). Full refresh.",
+ ),
+ "market_news": FinnhubEndpointConfig(
+ name="market_news",
+ path="/news",
+ primary_keys=["id"],
+ fixed_params={"category": "general"},
+ # Market news only supports a `minId` cursor, not a server-side date filter, so it's
+ # full refresh — the API returns the most recent general-market headlines each sync.
+ description="Latest general market news. Full refresh.",
+ ),
+ "ipo_calendar": FinnhubEndpointConfig(
+ name="ipo_calendar",
+ path="/calendar/ipo",
+ data_key="ipoCalendar",
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ windowed=True,
+ forward_days=180,
+ # `date` is the scheduled IPO date and can be in the future, so an incremental
+ # watermark on it would jump ahead and skip later-added near-term IPOs. Ship full
+ # refresh over a rolling past+future window instead; merge dedupes on the key.
+ description="Recent and upcoming IPOs over a rolling window. Full refresh.",
+ ),
+ "earnings_calendar": FinnhubEndpointConfig(
+ name="earnings_calendar",
+ path="/calendar/earnings",
+ data_key="earningsCalendar",
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ windowed=True,
+ forward_days=180,
+ # Same future-dating caveat as the IPO calendar — full refresh over a rolling window.
+ description="Recent and upcoming company earnings over a rolling window. Full refresh.",
+ ),
+ "country": FinnhubEndpointConfig(
+ name="country",
+ path="/country",
+ primary_keys=["code2"],
+ description="Reference list of supported countries and their metadata. Full refresh.",
+ ),
+ # --- Per-symbol fan-out (requires configured tickers) ---
+ "company_profile": FinnhubEndpointConfig(
+ name="company_profile",
+ path="/stock/profile2",
+ single_object=True,
+ requires_symbol=True,
+ primary_keys=["symbol"],
+ should_sync_default=False,
+ description="Company profile for each configured symbol. Full refresh.",
+ ),
+ "quote": FinnhubEndpointConfig(
+ name="quote",
+ path="/quote",
+ single_object=True,
+ requires_symbol=True,
+ primary_keys=["symbol"],
+ should_sync_default=False,
+ description="Latest real-time quote snapshot for each configured symbol. Full refresh.",
+ ),
+ "company_news": FinnhubEndpointConfig(
+ name="company_news",
+ path="/company-news",
+ requires_symbol=True,
+ # News articles can surface for more than one ticker, so the article id alone isn't
+ # unique table-wide — key on (id, symbol).
+ primary_keys=["id", "symbol"],
+ windowed=True,
+ lookback_days=365,
+ should_sync_default=False,
+ incremental_fields=[
+ {
+ "label": "datetime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "datetime",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ description="Company-specific news per configured symbol. Supports incremental sync on the published datetime.",
+ ),
+ "basic_financials": FinnhubEndpointConfig(
+ name="basic_financials",
+ path="/stock/metric",
+ single_object=True,
+ requires_symbol=True,
+ primary_keys=["symbol"],
+ fixed_params={"metric": "all"},
+ should_sync_default=False,
+ description="Basic financial metrics (valuation, margins, growth) per configured symbol. Full refresh.",
+ ),
+ "recommendation_trends": FinnhubEndpointConfig(
+ name="recommendation_trends",
+ path="/stock/recommendation",
+ requires_symbol=True,
+ primary_keys=["symbol", "period"],
+ partition_key="period",
+ should_sync_default=False,
+ description="Analyst recommendation trends per configured symbol. Full refresh.",
+ ),
+ "earnings_surprises": FinnhubEndpointConfig(
+ name="earnings_surprises",
+ path="/stock/earnings",
+ requires_symbol=True,
+ primary_keys=["symbol", "period"],
+ partition_key="period",
+ should_sync_default=False,
+ description="Historical EPS estimate vs actual surprises per configured symbol. Full refresh.",
+ ),
+}
+
+ENDPOINTS = tuple(FINNHUB_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in FINNHUB_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/source.py
index a442c9eae425..3443fac3189e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/source.py
@@ -1,30 +1,149 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub.finnhub import (
+ finnhub_source,
+ validate_credentials as validate_finnhub_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub.settings import (
+ ENDPOINTS,
+ FINNHUB_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FinnhubSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class FinnhubSource(SimpleSource[FinnhubSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FINNHUB
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A bad or revoked key surfaces as a 401 when `_fetch` calls `raise_for_status()`;
+ # an endpoint outside the plan tier surfaces as a 403. Neither is fixable by retrying,
+ # so stop the sync. Match the stable status text and base host, not the per-request path.
+ "401 Client Error: Unauthorized for url: https://finnhub.io": "Your Finnhub API key is invalid or has been revoked. Create a new key in your Finnhub dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://finnhub.io": "Your Finnhub plan does not include access to this data. Upgrade your plan or deselect the affected tables, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: FinnhubSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=FINNHUB_ENDPOINTS[endpoint].should_sync_default,
+ description=FINNHUB_ENDPOINTS[endpoint].description,
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ 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: FinnhubSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_finnhub_credentials(config.api_key, schema_name)
+
+ def source_for_pipeline(self, config: FinnhubSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return finnhub_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ symbols=config.symbols,
+ exchange=config.exchange,
+ logger=inputs.logger,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ 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.FINNHUB,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="Finnhub",
- iconPath="/static/services/finnhub.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Finnhub API key to pull market and company financial data into the PostHog Data warehouse.
+
+Create a free API key in your [Finnhub dashboard](https://finnhub.io/dashboard).
+
+Per-company tables (company profile, quote, company news, basic financials, recommendation trends, earnings surprises) are synced for each ticker you list in **Symbols**. Market-wide tables (stock symbols, market news, IPO calendar, earnings calendar, countries) sync without any symbols.
+
+Note: the free tier is rate limited to 60 requests/minute, and some endpoints require a paid plan.""",
+ iconPath="/static/services/finnhub.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/finnhub",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="symbols",
+ label="Symbols (comma-separated)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="AAPL, MSFT, GOOGL",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="exchange",
+ label="Exchange (for the stock symbols table)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="US",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
new file mode 100644
index 000000000000..63625ab66f32
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
@@ -0,0 +1,319 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub import finnhub
+from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub.finnhub import (
+ FINNHUB_BASE_URL,
+ _extract_rows,
+ _fetch,
+ _parse_symbols,
+ _request_params,
+ _to_date,
+ _window,
+ finnhub_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub.settings import FINNHUB_ENDPOINTS
+
+
+class TestParseSymbols:
+ @parameterized.expand(
+ [
+ ("comma", "AAPL,MSFT", ["AAPL", "MSFT"]),
+ ("comma_space", "AAPL, MSFT, GOOGL", ["AAPL", "MSFT", "GOOGL"]),
+ ("lowercase_uppercased", "aapl,msft", ["AAPL", "MSFT"]),
+ ("whitespace_separated", "AAPL MSFT", ["AAPL", "MSFT"]),
+ ("newline_separated", "AAPL\nMSFT", ["AAPL", "MSFT"]),
+ ("dedupes_preserving_order", "AAPL,MSFT,AAPL", ["AAPL", "MSFT"]),
+ ("strips_blanks", "AAPL,, ,MSFT", ["AAPL", "MSFT"]),
+ ("empty_string", "", []),
+ ("none", None, []),
+ ]
+ )
+ def test_parse_symbols(self, _name: str, raw: str | None, expected: list[str]) -> None:
+ assert _parse_symbols(raw) == expected
+
+ def test_drops_oversized_tokens(self) -> None:
+ # A pathologically long "symbol" is junk, not a ticker — it must not become a request.
+ oversized = "A" * (finnhub.MAX_SYMBOL_LENGTH + 1)
+ assert _parse_symbols(f"AAPL,{oversized},MSFT") == ["AAPL", "MSFT"]
+
+ def test_caps_fan_out_and_warns(self) -> None:
+ raw = ",".join(f"SYM{i}" for i in range(finnhub.MAX_SYMBOLS + 50))
+ logger = MagicMock()
+ parsed = _parse_symbols(raw, logger)
+ assert len(parsed) == finnhub.MAX_SYMBOLS
+ logger.warning.assert_called_once()
+
+
+class TestToDate:
+ @parameterized.expand(
+ [
+ ("epoch_seconds", 1577836800, date(2020, 1, 1)),
+ ("epoch_float", 1577836800.0, date(2020, 1, 1)),
+ ("aware_datetime", datetime(2021, 6, 15, 23, 0, tzinfo=UTC), date(2021, 6, 15)),
+ ("naive_datetime", datetime(2021, 6, 15, 12, 0), date(2021, 6, 15)),
+ ("date_passthrough", date(2022, 3, 4), date(2022, 3, 4)),
+ ("iso_string", "2022-03-04T10:11:12Z", date(2022, 3, 4)),
+ ("date_string", "2022-03-04", date(2022, 3, 4)),
+ ]
+ )
+ def test_to_date(self, _name: str, value: Any, expected: date) -> None:
+ assert _to_date(value) == expected
+
+
+class TestExtractRows:
+ def test_single_object_wraps_in_list(self) -> None:
+ rows = _extract_rows({"c": 1.0}, FINNHUB_ENDPOINTS["quote"])
+ assert rows == [{"c": 1.0}]
+
+ def test_single_object_empty_returns_nothing(self) -> None:
+ # Finnhub returns an empty object for an unknown symbol — that must not become a row.
+ assert _extract_rows({}, FINNHUB_ENDPOINTS["quote"]) == []
+
+ def test_data_key_unwraps_calendar(self) -> None:
+ payload = {"ipoCalendar": [{"symbol": "X", "date": "2020-01-01"}]}
+ assert _extract_rows(payload, FINNHUB_ENDPOINTS["ipo_calendar"]) == [{"symbol": "X", "date": "2020-01-01"}]
+
+ def test_data_key_missing_returns_empty(self) -> None:
+ assert _extract_rows({}, FINNHUB_ENDPOINTS["earnings_calendar"]) == []
+
+ def test_bare_array_passthrough(self) -> None:
+ rows = [{"symbol": "AAPL"}, {"symbol": "MSFT"}]
+ assert _extract_rows(rows, FINNHUB_ENDPOINTS["stock_symbols"]) == rows
+
+ def test_bare_array_non_list_returns_empty(self) -> None:
+ assert _extract_rows({"error": "boom"}, FINNHUB_ENDPOINTS["stock_symbols"]) == []
+
+
+class TestRequestParams:
+ def test_stock_symbols_defaults_exchange(self) -> None:
+ params = _request_params(FINNHUB_ENDPOINTS["stock_symbols"], None, "", False, None)
+ assert params == {"exchange": "US"}
+
+ def test_stock_symbols_uses_configured_exchange(self) -> None:
+ params = _request_params(FINNHUB_ENDPOINTS["stock_symbols"], None, "L", False, None)
+ assert params == {"exchange": "L"}
+
+ def test_market_news_sets_category(self) -> None:
+ params = _request_params(FINNHUB_ENDPOINTS["market_news"], None, "US", False, None)
+ assert params == {"category": "general"}
+
+ def test_basic_financials_sets_metric_and_symbol(self) -> None:
+ params = _request_params(FINNHUB_ENDPOINTS["basic_financials"], "AAPL", "US", False, None)
+ assert params == {"symbol": "AAPL", "metric": "all"}
+
+ @freeze_time("2024-06-15")
+ def test_calendar_window_is_full_rolling_window_when_not_incremental(self) -> None:
+ # Calendars are full refresh: a backwards lookback plus a forward window, ignoring any cursor.
+ params = _request_params(FINNHUB_ENDPOINTS["ipo_calendar"], None, "US", False, None)
+ assert params == {"from": "2023-06-16", "to": "2024-12-12"}
+
+ @freeze_time("2024-06-15")
+ def test_company_news_window_uses_incremental_cursor(self) -> None:
+ params = _request_params(FINNHUB_ENDPOINTS["company_news"], "AAPL", "US", True, 1704067200) # 2024-01-01
+ assert params == {"symbol": "AAPL", "from": "2024-01-01", "to": "2024-06-15"}
+
+ @freeze_time("2024-06-15")
+ def test_company_news_window_falls_back_to_lookback_without_cursor(self) -> None:
+ params = _request_params(FINNHUB_ENDPOINTS["company_news"], "AAPL", "US", True, None)
+ assert params == {"symbol": "AAPL", "from": "2023-06-16", "to": "2024-06-15"}
+
+
+class TestWindow:
+ @freeze_time("2024-06-15")
+ def test_forward_days_extends_into_future(self) -> None:
+ start, end = _window(FINNHUB_ENDPOINTS["earnings_calendar"], None)
+ assert start == "2023-06-16"
+ assert end == "2024-12-12"
+
+
+class TestGetRows:
+ @staticmethod
+ def _patch_fetch(monkeypatch: Any, by_symbol: dict[str | None, Any]) -> list[dict[str, Any]]:
+ calls: list[dict[str, Any]] = []
+
+ def fake_fetch(session: Any, path: str, params: dict[str, Any], logger: Any) -> Any:
+ calls.append({"path": path, "params": params})
+ return by_symbol[params.get("symbol")]
+
+ monkeypatch.setattr(finnhub, "_fetch", fake_fetch)
+ monkeypatch.setattr(finnhub, "make_tracked_session", lambda **_: MagicMock())
+ return calls
+
+ def test_market_wide_endpoint_single_request(self, monkeypatch: Any) -> None:
+ self._patch_fetch(monkeypatch, {None: [{"symbol": "AAPL"}, {"symbol": "MSFT"}]})
+ batches = list(get_rows(api_key="k", endpoint="stock_symbols", symbols=None, exchange="US", logger=MagicMock()))
+ assert batches == [[{"symbol": "AAPL"}, {"symbol": "MSFT"}]]
+
+ def test_fan_out_one_request_per_symbol_injecting_symbol(self, monkeypatch: Any) -> None:
+ calls = self._patch_fetch(
+ monkeypatch,
+ {"AAPL": {"c": 1.0}, "MSFT": {"c": 2.0}},
+ )
+ batches = list(get_rows(api_key="k", endpoint="quote", symbols="AAPL, MSFT", exchange="US", logger=MagicMock()))
+ # One batch per symbol, each carrying the injected ticker (quote omits it upstream).
+ assert batches == [[{"c": 1.0, "symbol": "AAPL"}], [{"c": 2.0, "symbol": "MSFT"}]]
+ assert [c["params"]["symbol"] for c in calls] == ["AAPL", "MSFT"]
+
+ def test_fan_out_skips_empty_symbol_responses(self, monkeypatch: Any) -> None:
+ # Unknown ticker → empty object → no batch yielded for it.
+ self._patch_fetch(monkeypatch, {"AAPL": {"c": 1.0}, "BOGUS": {}})
+ batches = list(get_rows(api_key="k", endpoint="quote", symbols="AAPL,BOGUS", exchange="US", logger=MagicMock()))
+ assert batches == [[{"c": 1.0, "symbol": "AAPL"}]]
+
+ def test_requires_symbol_with_no_symbols_yields_nothing_and_warns(self, monkeypatch: Any) -> None:
+ self._patch_fetch(monkeypatch, {})
+ logger = MagicMock()
+ batches = list(get_rows(api_key="k", endpoint="quote", symbols=None, exchange="US", logger=logger))
+ assert batches == []
+ logger.warning.assert_called_once()
+
+ def test_company_news_sorted_ascending_and_symbol_injected(self, monkeypatch: Any) -> None:
+ self._patch_fetch(
+ monkeypatch,
+ {"AAPL": [{"id": 2, "datetime": 200}, {"id": 1, "datetime": 100}]},
+ )
+ batches = list(
+ get_rows(
+ api_key="k",
+ endpoint="company_news",
+ symbols="AAPL",
+ exchange="US",
+ logger=MagicMock(),
+ )
+ )
+ assert batches == [
+ [
+ {"id": 1, "datetime": 100, "symbol": "AAPL"},
+ {"id": 2, "datetime": 200, "symbol": "AAPL"},
+ ]
+ ]
+
+ def test_company_news_missing_datetime_raises(self, monkeypatch: Any) -> None:
+ # `datetime` is the incremental watermark — a row missing it must fail loudly rather
+ # than silently sorting to epoch 0 and corrupting the checkpoint.
+ self._patch_fetch(monkeypatch, {"AAPL": [{"id": 1, "datetime": 100}, {"id": 2}]})
+ with pytest.raises(KeyError):
+ list(get_rows(api_key="k", endpoint="company_news", symbols="AAPL", exchange="US", logger=MagicMock()))
+
+ def test_calendar_unwraps_data_key(self, monkeypatch: Any) -> None:
+ self._patch_fetch(
+ monkeypatch,
+ {None: {"earningsCalendar": [{"symbol": "AAPL", "date": "2024-01-01"}]}},
+ )
+ batches = list(
+ get_rows(api_key="k", endpoint="earnings_calendar", symbols=None, exchange="US", logger=MagicMock())
+ )
+ assert batches == [[{"symbol": "AAPL", "date": "2024-01-01"}]]
+
+
+class TestFinnhubSource:
+ @parameterized.expand(
+ [
+ ("stock_symbols", ["symbol"], None, None),
+ ("market_news", ["id"], None, None),
+ ("ipo_calendar", ["symbol", "date"], "date", None),
+ ("earnings_calendar", ["symbol", "date"], "date", None),
+ ("country", ["code2"], None, None),
+ ("company_profile", ["symbol"], None, None),
+ ("quote", ["symbol"], None, None),
+ # Only the incremental endpoint advertises a sorted data contract.
+ ("company_news", ["id", "symbol"], None, "asc"),
+ ("recommendation_trends", ["symbol", "period"], "period", None),
+ ("earnings_surprises", ["symbol", "period"], "period", None),
+ ]
+ )
+ def test_source_response_keys_and_partitioning(
+ self, endpoint: str, expected_keys: list[str], partition_key: str | None, sort_mode: str | None
+ ) -> None:
+ response = finnhub_source(api_key="k", endpoint=endpoint, symbols="AAPL", exchange="US", logger=MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ assert response.sort_mode == sort_mode
+ if partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ else:
+ assert response.partition_keys is None
+
+
+class TestFetch:
+ @staticmethod
+ def _response(status_code: int, url: str, reason: str) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.reason = reason
+ response.url = url
+ response.text = "error body"
+ return response
+
+ def test_4xx_error_does_not_leak_api_key(self) -> None:
+ # Even if the key ever lands in the request URL (redirect / future query-param auth),
+ # the rebuilt HTTPError must contain only scheme/host/path — never the query string.
+ session = MagicMock()
+ session.get.return_value = self._response(
+ 401, "https://finnhub.io/api/v1/quote?token=SECRETKEY&symbol=AAPL", "Unauthorized"
+ )
+ with pytest.raises(requests.HTTPError) as exc:
+ _fetch(session, "/quote", {"symbol": "AAPL"}, MagicMock())
+ message = str(exc.value)
+ assert "SECRETKEY" not in message
+ assert message == "401 Client Error: Unauthorized for url: https://finnhub.io/api/v1/quote"
+
+ def test_4xx_error_keeps_non_retryable_prefix(self) -> None:
+ # get_non_retryable_errors() keys off this stable status/host prefix.
+ session = MagicMock()
+ session.get.return_value = self._response(403, "https://finnhub.io/api/v1/stock/metric", "Forbidden")
+ with pytest.raises(requests.HTTPError) as exc:
+ _fetch(session, "/stock/metric", {}, MagicMock())
+ assert str(exc.value).startswith("403 Client Error: Forbidden for url: https://finnhub.io")
+
+
+class TestValidateCredentials:
+ @staticmethod
+ def _session(status_code: int | None) -> MagicMock:
+ session = MagicMock()
+ if status_code is None:
+ session.get.side_effect = Exception("connection refused")
+ else:
+ session.get.return_value = MagicMock(status_code=status_code)
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, None, True),
+ ("unauthorized", 401, None, False),
+ ("forbidden_at_create_is_accepted", 403, None, True),
+ ("forbidden_for_schema_is_rejected", 403, "quote", False),
+ ("server_error", 500, None, False),
+ ("connection_error", None, None, False),
+ ]
+ )
+ def test_validate_credentials(
+ self, _name: str, status_code: int | None, schema_name: str | None, expected_valid: bool
+ ) -> None:
+ session = self._session(status_code)
+ with patch.object(finnhub, "make_tracked_session", lambda **_: session):
+ valid, _msg = validate_credentials("key", schema_name)
+ assert valid is expected_valid
+
+ def test_validate_credentials_probes_quote(self) -> None:
+ session = self._session(200)
+ with patch.object(finnhub, "make_tracked_session", lambda **_: session):
+ validate_credentials("key")
+ called_url = session.get.call_args[0][0]
+ assert called_url == f"{FINNHUB_BASE_URL}/quote"
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub_source.py
new file mode 100644
index 000000000000..652f9bdb4629
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub_source.py
@@ -0,0 +1,150 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub.source import FinnhubSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FinnhubSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config(**overrides: Any) -> FinnhubSourceConfig:
+ base: dict[str, Any] = {"api_key": "key", "symbols": "AAPL", "exchange": "US"}
+ base.update(overrides)
+ return FinnhubSourceConfig.from_dict(base)
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert FinnhubSource().source_type == ExternalDataSourceType.FINNHUB
+
+ def test_source_config_basics(self) -> None:
+ config = FinnhubSource().get_source_config
+ assert config.label == "Finnhub"
+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/finnhub"
+
+ def test_fields(self) -> None:
+ fields = {f.name: f for f in FinnhubSource().get_source_config.fields if isinstance(f, SourceFieldInputConfig)}
+ assert set(fields) == {"api_key", "symbols", "exchange"}
+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD
+ assert fields["api_key"].required is True
+ assert fields["api_key"].secret is True
+ # The fan-out and exchange fields must be optional so market-wide tables work alone.
+ assert fields["symbols"].required is False
+ assert fields["exchange"].required is False
+
+
+class TestGetSchemas:
+ def test_lists_all_endpoints(self) -> None:
+ schemas = FinnhubSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == {
+ "stock_symbols",
+ "market_news",
+ "ipo_calendar",
+ "earnings_calendar",
+ "country",
+ "company_profile",
+ "quote",
+ "company_news",
+ "basic_financials",
+ "recommendation_trends",
+ "earnings_surprises",
+ }
+
+ def test_only_company_news_is_incremental(self) -> None:
+ schemas = {s.name: s for s in FinnhubSource().get_schemas(_config(), team_id=1)}
+ incremental = {name for name, s in schemas.items() if s.supports_incremental}
+ assert incremental == {"company_news"}
+ assert schemas["company_news"].incremental_fields[0]["field"] == "datetime"
+
+ @parameterized.expand(
+ [
+ ("stock_symbols", True),
+ ("market_news", True),
+ ("ipo_calendar", True),
+ ("earnings_calendar", True),
+ ("country", True),
+ ("company_profile", False),
+ ("quote", False),
+ ("company_news", False),
+ ("basic_financials", False),
+ ("recommendation_trends", False),
+ ("earnings_surprises", False),
+ ]
+ )
+ def test_should_sync_default(self, endpoint: str, expected_default: bool) -> None:
+ # Per-symbol tables default off — they return nothing until the user lists tickers.
+ schemas = {s.name: s for s in FinnhubSource().get_schemas(_config(), team_id=1)}
+ assert schemas[endpoint].should_sync_default is expected_default
+
+ def test_names_filter(self) -> None:
+ schemas = FinnhubSource().get_schemas(_config(), team_id=1, names=["quote", "country"])
+ assert {s.name for s in schemas} == {"quote", "country"}
+
+
+class TestValidateCredentials:
+ def test_delegates_to_transport(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_validate(api_key: str, schema_name: str | None = None) -> tuple[bool, str | None]:
+ captured["api_key"] = api_key
+ captured["schema_name"] = schema_name
+ return True, None
+
+ monkeypatch.setattr(source_module, "validate_finnhub_credentials", fake_validate)
+ valid, msg = FinnhubSource().validate_credentials(_config(), team_id=1, schema_name="quote")
+ assert (valid, msg) == (True, None)
+ assert captured == {"api_key": "key", "schema_name": "quote"}
+
+
+class TestNonRetryableErrors:
+ def test_marks_auth_errors_non_retryable(self) -> None:
+ errors = FinnhubSource().get_non_retryable_errors()
+ assert any(k.startswith("401 Client Error") for k in errors)
+ assert any(k.startswith("403 Client Error") for k in errors)
+
+
+class TestCanonicalDescriptions:
+ def test_descriptions_keyed_by_endpoint_name(self) -> None:
+ descriptions = FinnhubSource().get_canonical_descriptions()
+ schema_names = {s.name for s in FinnhubSource().get_schemas(_config(), team_id=1)}
+ # Every documented key must be a real endpoint name so descriptions actually attach.
+ assert set(descriptions).issubset(schema_names)
+ assert "company_news" in descriptions
+
+
+class TestDocumentedTables:
+ def test_lists_tables_without_credentials(self) -> None:
+ assert FinnhubSource.lists_tables_without_credentials is True
+ tables = FinnhubSource().get_documented_tables()
+ assert len(tables) == 11
+
+
+class TestSourceForPipeline:
+ def test_plumbs_schema_into_source_response(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "company_news"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = None
+ inputs.logger = MagicMock()
+ # items is a lazy lambda, so building the response does not touch the network.
+ response = FinnhubSource().source_for_pipeline(_config(), inputs)
+ assert response.name == "company_news"
+ assert response.primary_keys == ["id", "symbol"]
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index e145fafb656a..fdb323711d27 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1134,7 +1134,9 @@ class FinancialModellingSourceConfig(config.Config):
@config.config
class FinnhubSourceConfig(config.Config):
- pass
+ api_key: str
+ symbols: str | None = None
+ exchange: str | None = None
@config.config