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 finage import source (#66766)

Tom Owers542a456935cd
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 a10a96541534..e75f71aa2eaf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -143,6 +143,7 @@ the row lists both.
| ezofficeinventory | HTTP | requests | ✅ |
| factorial | HTTP | requests + `rest_source.RESTClient` | ✅ |
| fillout | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| finage | HTTP | requests | ✅ |
| financial_modelling | HTTP | requests | ✅ |
| finnhub | HTTP | requests | ✅ |
| finnworlds | HTTP | requests | ✅ |
@@ -397,7 +398,6 @@ doesn't conflict with concurrent PRs.
- fastly
- fauna
- feishu
-- finage
- firebase
- firebolt
- flexmail
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/canonical_descriptions.py
new file mode 100644
index 000000000000..897c2d650668
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/canonical_descriptions.py
@@ -0,0 +1,49 @@
+"""Canonical, documentation-sourced descriptions for Finage endpoints and columns.
+
+Sourced from the official Finage API reference (https://finage.co.uk/docs). Keyed by the endpoint
+names in `settings.py` `FINAGE_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+Finage table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "last_quote": {
+ "description": "The latest bid/ask quote for each tracked stock symbol.",
+ "docs_url": "https://finage.co.uk/docs/api/stock-last-quote",
+ "columns": {
+ "symbol": "Ticker symbol the quote is for (e.g. AAPL).",
+ "ask": "Most recent ask price.",
+ "bid": "Most recent bid price.",
+ "asize": "Size available at the ask price.",
+ "bsize": "Size available at the bid price.",
+ "timestamp": "Unix epoch (milliseconds) at which the quote was last updated.",
+ },
+ },
+ "last_trade": {
+ "description": "The latest executed trade for each tracked stock symbol.",
+ "docs_url": "https://finage.co.uk/docs/api/stock-last-trade",
+ "columns": {
+ "symbol": "Ticker symbol the trade is for (e.g. AAPL).",
+ "price": "Price the last trade executed at.",
+ "size": "Number of shares in the last trade.",
+ "timestamp": "Unix epoch (milliseconds) at which the trade occurred.",
+ },
+ },
+ "aggregates": {
+ "description": "Historical daily OHLCV bars for each tracked stock symbol.",
+ "docs_url": "https://finage.co.uk/docs/api/stock-market-aggregates-api",
+ "columns": {
+ "symbol": "Ticker symbol the bar is for (e.g. AAPL).",
+ "date": "ISO date (YYYY-MM-DD) of the bar, derived from `t`. Used as the partition key.",
+ "o": "Open price for the bar.",
+ "h": "Highest price during the bar.",
+ "l": "Lowest price during the bar.",
+ "c": "Close price for the bar.",
+ "v": "Trading volume during the bar.",
+ "t": "Unix epoch (milliseconds) at the start of the bar.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/finage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/finage.py
new file mode 100644
index 000000000000..88563dd4b23c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/finage.py
@@ -0,0 +1,286 @@
+import re
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+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.finage.settings import (
+ FINAGE_ENDPOINTS,
+ FinageEndpointConfig,
+)
+
+FINAGE_BASE_URL = "https://api.finage.co.uk"
+
+# Daily OHLCV bars are the canonical historical-price grain. Finer intervals (minute/hour) explode row
+# counts and are better served by the WebSocket feed, so the aggregate window is fixed to daily here.
+AGG_MULTIPLIER = 1
+AGG_TIMESPAN = "day"
+# Finage caps `limit` at 50000. A symbol can't accumulate that many daily bars (~200 years), so one
+# request per symbol covers the whole window without pagination.
+AGG_LIMIT = 50000
+DEFAULT_START_DATE = "2020-01-01"
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+# Each symbol costs one request per point-in-time sync and one 50k-row fetch per aggregate sync, so the
+# list is a fan-out multiplier. Cap it so a member can't save thousands of symbols and blow up every sync.
+MAX_SYMBOLS = 100
+# US tickers are short and alphanumeric; dots/hyphens cover class shares (e.g. BRK.B, BF-B).
+SYMBOL_PATTERN = re.compile(r"^[A-Z0-9][A-Z0-9.\-]{0,11}$")
+# Finage's US stock history doesn't meaningfully predate this; a floor rejects typos and unbounded ranges.
+MIN_START_DATE = "2000-01-01"
+
+
+class FinageRetryableError(Exception):
+ """Raised for 429 / 5xx so tenacity retries; terminal statuses (401/403/404) are not wrapped."""
+
+
+class FinageConfigError(ValueError):
+ """Raised when the user-supplied symbols / start_date fail validation."""
+
+
+def parse_symbols(symbols: str) -> list[str]:
+ """Split the user's comma-separated symbol field into a clean, de-duplicated, upper-cased list."""
+ seen: set[str] = set()
+ parsed: list[str] = []
+ for raw in symbols.split(","):
+ symbol = raw.strip().upper()
+ if symbol and symbol not in seen:
+ seen.add(symbol)
+ parsed.append(symbol)
+ return parsed
+
+
+def validate_source_config(symbols: list[str], start_date: str) -> None:
+ """Reject oversized symbol lists, malformed tickers, and out-of-range start dates before a sync runs.
+
+ Each symbol fans out into its own Finage request (and, for aggregates, up to a 50k-row fetch), so an
+ unbounded symbol list or a start date in the distant past is a resource-exhaustion vector. Raises
+ `FinageConfigError` with a user-facing message on the first problem found.
+ """
+ if not symbols:
+ raise FinageConfigError("Enter at least one stock symbol to sync.")
+ if len(symbols) > MAX_SYMBOLS:
+ raise FinageConfigError(
+ f"Too many symbols ({len(symbols)}). Enter at most {MAX_SYMBOLS} comma-separated stock symbols."
+ )
+ invalid = [s for s in symbols if not SYMBOL_PATTERN.match(s)]
+ if invalid:
+ preview = ", ".join(invalid[:5])
+ raise FinageConfigError(f"Invalid stock symbol(s): {preview}. Use US tickers like AAPL, MSFT, BRK.B.")
+
+ try:
+ parsed_start = datetime.strptime(start_date, "%Y-%m-%d").replace(tzinfo=UTC).date()
+ except ValueError:
+ raise FinageConfigError(f"Invalid backfill start date '{start_date}'. Use the format YYYY-MM-DD.")
+ floor = datetime.strptime(MIN_START_DATE, "%Y-%m-%d").date()
+ today = datetime.now(UTC).date()
+ if parsed_start < floor:
+ raise FinageConfigError(f"Backfill start date must be on or after {MIN_START_DATE}.")
+ if parsed_start > today:
+ raise FinageConfigError("Backfill start date can't be in the future.")
+
+
+def _ms_to_date(timestamp_ms: Any) -> str | None:
+ """Convert a Finage millisecond epoch timestamp to an ISO date string for partitioning."""
+ if timestamp_ms is None:
+ return None
+ try:
+ return datetime.fromtimestamp(int(timestamp_ms) / 1000, tz=UTC).date().isoformat()
+ except (ValueError, TypeError, OverflowError, OSError):
+ return None
+
+
+def _today() -> str:
+ return datetime.now(UTC).date().isoformat()
+
+
+@retry(
+ retry=retry_if_exception_type((FinageRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_json(
+ session: requests.Session,
+ path: str,
+ api_key: str,
+ logger: FilteringBoundLogger,
+ params: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ request_params: dict[str, Any] = {"apikey": api_key, **(params or {})}
+ url = f"{FINAGE_BASE_URL}{path}"
+ response = session.get(url, params=request_params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise FinageRetryableError(f"Finage API error (retryable): status={response.status_code}, path={path}")
+
+ # 401 (bad/missing key) and 403 (plan doesn't cover this data) are permanent — surface them as an
+ # HTTPError so `get_non_retryable_errors` can match and stop the sync. The URL query carries the raw
+ # apikey, so strip it: the default `raise_for_status` message embeds the full URL (credential and all)
+ # into the exception, which is then written to error logs. Dropping the query keeps the matchable
+ # `... for url: https://api.finage.co.uk/<path>` prefix without leaking the key.
+ if response.status_code >= 400:
+ safe_url = (response.url or "").split("?", 1)[0]
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {safe_url}",
+ response=response,
+ )
+
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> int | None:
+ """Probe a basic stock endpoint and return the HTTP status code (or None on a transport error).
+
+ `/last/stock/AAPL` needs only a stocks subscription, so it's the cheapest genuine token check.
+ """
+ try:
+ # Redact the key so the probe URL is never persisted raw in tracked logs / sample capture.
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ f"{FINAGE_BASE_URL}/last/stock/AAPL", params={"apikey": api_key}, timeout=10
+ )
+ return response.status_code
+ except Exception:
+ return None
+
+
+def _handle_symbol_http_error(exc: requests.HTTPError, logger: FilteringBoundLogger, what: str) -> None:
+ """Re-raise auth/plan failures (401/403) to stop the whole sync; warn-and-skip any other per-symbol error."""
+ status = exc.response.status_code if exc.response is not None else None
+ if status in (401, 403):
+ raise exc
+ logger.warning(f"Finage: {what} failed (status={status}), skipping")
+
+
+def _iter_point_in_time_rows(
+ session: requests.Session,
+ api_key: str,
+ symbols: list[str],
+ config: FinageEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield the single current quote/trade object per symbol.
+
+ A per-symbol error (unknown ticker, no data) is logged and skipped so one bad symbol doesn't fail
+ the whole sync; auth/plan failures (401/403) propagate from `_fetch_json` and stop it.
+ """
+ for symbol in symbols:
+ path = config.path.format(symbol=symbol)
+ try:
+ data = _fetch_json(session, path, api_key, logger)
+ except requests.HTTPError as exc:
+ _handle_symbol_http_error(exc, logger, f"{config.name} request for {symbol}")
+ continue
+
+ if not isinstance(data, dict) or not data or data.get("error"):
+ logger.warning(f"Finage: {config.name} returned no data for {symbol}, skipping")
+ continue
+
+ # The endpoint already returns `symbol`, but pin it from our request so the key is never empty.
+ data.setdefault("symbol", symbol)
+ yield [data]
+
+
+def _iter_aggregate_rows(
+ session: requests.Session,
+ api_key: str,
+ symbols: list[str],
+ config: FinageEndpointConfig,
+ start_date: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield historical OHLCV bars for each symbol over [start_date, today].
+
+ Full refresh: the whole window is re-fetched every sync and de-duplicated on `[symbol, t]` at
+ merge time. `sort=asc` matches `SourceResponse.sort_mode`.
+ """
+ to_date = _today()
+ for symbol in symbols:
+ path = config.path.format(
+ symbol=symbol,
+ multiplier=AGG_MULTIPLIER,
+ timespan=AGG_TIMESPAN,
+ from_date=start_date,
+ to_date=to_date,
+ )
+ try:
+ data = _fetch_json(session, path, api_key, logger, params={"limit": AGG_LIMIT, "sort": "asc"})
+ except requests.HTTPError as exc:
+ _handle_symbol_http_error(exc, logger, f"aggregates request for {symbol}")
+ continue
+
+ results = data.get("results") if isinstance(data, dict) else None
+ if not results:
+ continue
+
+ if len(results) >= AGG_LIMIT:
+ logger.warning(f"Finage: aggregates for {symbol} hit the {AGG_LIMIT}-row limit; older bars truncated")
+
+ response_symbol = data.get("symbol", symbol)
+ rows = []
+ for bar in results:
+ # `t` is the primary/partition key. A missing key raises KeyError; a present-but-unparseable
+ # value converts to None, which `datetime` partitioning would silently bucket into the fallback
+ # 1970-01 partition. Reject both so corrupt upstream data fails fast instead of misbucketing.
+ date = _ms_to_date(bar["t"])
+ if date is None:
+ raise ValueError(
+ f"Finage aggregates for {response_symbol} returned a bar with an invalid timestamp: {bar['t']!r}"
+ )
+ rows.append({**bar, "symbol": response_symbol, "date": date})
+ yield rows
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ symbols: list[str],
+ start_date: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = FINAGE_ENDPOINTS[endpoint]
+ # One session reused across every symbol so urllib3 keeps the connection alive. Redact the key
+ # so the `apikey` query value is never persisted raw in tracked logs / sample capture. Disable the
+ # adapter's default retry policy: `_fetch_json` already retries 429/5xx with tenacity, and stacking a
+ # second urllib3 retry layer would multiply backoff and let long `Retry-After` waits bypass its cap.
+ session = make_tracked_session(redact_values=(api_key,), retry=Retry(total=0))
+
+ if config.is_aggregate:
+ yield from _iter_aggregate_rows(session, api_key, symbols, config, start_date, logger)
+ else:
+ yield from _iter_point_in_time_rows(session, api_key, symbols, config, logger)
+
+
+def finage_source(
+ api_key: str,
+ endpoint: str,
+ symbols: list[str],
+ start_date: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = FINAGE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ symbols=symbols,
+ start_date=start_date,
+ logger=logger,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/settings.py
new file mode 100644
index 000000000000..ab9746775040
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/settings.py
@@ -0,0 +1,58 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass
+class FinageEndpointConfig:
+ name: str
+ # Finage path template. `{symbol}` is filled per symbol; aggregate paths additionally fill
+ # `{multiplier}` / `{timespan}` / `{from_date}` / `{to_date}`.
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["symbol"])
+ # Stable datetime column to partition on (only the aggregate bars have one). Never a value that
+ # changes after a row is first written.
+ partition_key: str | None = None
+ # True for the historical OHLCV aggregate endpoint: returns a `results` array of bars windowed by
+ # a date range in the path, rather than a single point-in-time object.
+ is_aggregate: bool = False
+ should_sync_default: bool = True
+
+
+# US-stock scope for the initial release. Finage exposes the same path shapes for forex/crypto/indices
+# (e.g. `/last/forex/{symbol}`, `/agg/crypto/{symbol}/...`), so adding other asset classes later is a
+# matter of parameterizing the market segment.
+#
+# Paths and response shapes are taken from the public Finage docs (https://finage.co.uk/docs); they
+# could not be curl-verified against the live API because that requires a paid key. The aggregate and
+# quote shapes are well documented; `last_trade` (`/last/trade/stock/{symbol}` -> {symbol, price, size,
+# timestamp}) is the least certain and should be confirmed once a key is available.
+FINAGE_ENDPOINTS: dict[str, FinageEndpointConfig] = {
+ "last_quote": FinageEndpointConfig(
+ name="last_quote",
+ path="/last/stock/{symbol}",
+ primary_keys=["symbol"],
+ ),
+ "last_trade": FinageEndpointConfig(
+ name="last_trade",
+ path="/last/trade/stock/{symbol}",
+ primary_keys=["symbol"],
+ ),
+ "aggregates": FinageEndpointConfig(
+ name="aggregates",
+ path="/agg/stock/{symbol}/{multiplier}/{timespan}/{from_date}/{to_date}",
+ # The bar timestamp `t` is only unique within a symbol, so the symbol is part of the key —
+ # otherwise fan-out rows from different symbols collide and every merge multi-matches them.
+ primary_keys=["symbol", "t"],
+ partition_key="date",
+ is_aggregate=True,
+ ),
+}
+
+ENDPOINTS = tuple(FINAGE_ENDPOINTS.keys())
+
+# Finage has no cross-resource `updated_after` cursor. Quote/trade endpoints are point-in-time, and
+# the aggregate endpoint fans out per symbol — concatenating per-symbol bar streams isn't globally
+# ascending, so a single watermark can't be checkpointed safely. Every endpoint therefore ships full
+# refresh, and there are no advertised incremental fields.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in FINAGE_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/source.py
index 133fbb1d8f31..403b623e552a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/source.py
@@ -1,19 +1,49 @@
-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.finage.finage import (
+ DEFAULT_START_DATE,
+ FinageConfigError,
+ finage_source,
+ parse_symbols,
+ validate_credentials as validate_finage_credentials,
+ validate_source_config,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.finage.settings import ENDPOINTS, FINAGE_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FinageSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_ENDPOINT_DESCRIPTIONS = {
+ "last_quote": "Latest bid/ask quote per symbol. Point-in-time snapshot, full refresh.",
+ "last_trade": "Latest trade (price and size) per symbol. Point-in-time snapshot, full refresh.",
+ "aggregates": "Historical daily OHLCV bars per symbol from the backfill start date. Full refresh.",
+}
+
@SourceRegistry.register
class FinageSource(SimpleSource[FinageSourceConfig]):
+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to render
+ # in public docs without credentials.
+ lists_tables_without_credentials = True
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FINAGE
@@ -24,7 +54,118 @@ class FinageSource(SimpleSource[FinageSourceConfig]):
name=SchemaExternalDataSourceType.FINAGE,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="Finage",
- iconPath="/static/services/finage.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Finage API key and the symbols you want to sync to pull market data into the PostHog Data warehouse.
+
+You can find your API key in the [Finage dashboard](https://finage.co.uk/dashboard) after subscribing to a plan. The key needs access to the **US stocks** endpoints.""",
+ iconPath="/static/services/finage.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/finage",
+ keywords=["stocks", "market data", "ohlcv", "finance"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="symbols",
+ label="Symbols",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="AAPL,MSFT,TSLA",
+ secret=False,
+ caption="Comma-separated list of US stock symbols to sync, e.g. `AAPL,MSFT,TSLA`.",
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Backfill start date",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder=DEFAULT_START_DATE,
+ secret=False,
+ caption=f"Earliest date (`YYYY-MM-DD`) to pull historical aggregate bars from. Defaults to `{DEFAULT_START_DATE}`.",
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.finage.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.finage.co.uk": "Your Finage API key is invalid or has been revoked. Generate a new key in your Finage dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.finage.co.uk": "Your Finage plan does not include access to this data. Upgrade your Finage subscription or remove the affected tables, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: FinageSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = FINAGE_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=endpoint_config.should_sync_default,
+ detected_primary_keys=endpoint_config.primary_keys,
+ description=_ENDPOINT_DESCRIPTIONS.get(endpoint),
+ )
+
+ schemas = [_build_schema(endpoint) 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: FinageSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ validate_source_config(parse_symbols(config.symbols), config.start_date or DEFAULT_START_DATE)
+ except FinageConfigError as exc:
+ return False, str(exc)
+
+ status = validate_finage_credentials(config.api_key)
+
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Invalid Finage API key. Generate a new key in your Finage dashboard and try again."
+ if status == 403:
+ # Valid token, but the plan doesn't cover this endpoint. Accept at source-create (the user
+ # can upgrade later); only fail when validating a specific schema.
+ if schema_name is None:
+ return True, None
+ return False, "Your Finage plan does not include access to this data. Upgrade your subscription to sync it."
+
+ return False, "Could not validate Finage credentials. Please check your API key and try again."
+
+ def source_for_pipeline(self, config: FinageSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ symbols = parse_symbols(config.symbols)
+ start_date = config.start_date or DEFAULT_START_DATE
+ # Re-validate here so a source saved before these guards existed can't fan out a runaway sync.
+ validate_source_config(symbols, start_date)
+ return finage_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ symbols=symbols,
+ start_date=start_date,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage.py
new file mode 100644
index 000000000000..f304ac1d6962
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage.py
@@ -0,0 +1,311 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.finage import finage
+from products.warehouse_sources.backend.temporal.data_imports.sources.finage.finage import (
+ AGG_LIMIT,
+ MAX_SYMBOLS,
+ MIN_START_DATE,
+ FinageConfigError,
+ FinageRetryableError,
+ finage_source,
+ get_rows,
+ parse_symbols,
+ validate_credentials,
+ validate_source_config,
+)
+
+
+def _response(status: int, body: dict[str, Any] | None = None) -> mock.Mock:
+ response = mock.Mock(spec=requests.Response)
+ response.status_code = status
+ # `_fetch_json` builds its own sanitized HTTPError from these for terminal statuses.
+ response.url = "https://api.finage.co.uk/x?apikey=secret"
+ response.reason = "Error"
+ if status >= 400:
+
+ def _raise() -> None:
+ raise requests.HTTPError(f"{status} Client Error: x for url: https://api.finage.co.uk/x", response=response)
+
+ response.raise_for_status.side_effect = _raise
+ else:
+ response.raise_for_status.return_value = None
+ response.json.return_value = body or {}
+ return response
+
+
+def _http_error(status: int) -> requests.HTTPError:
+ response = mock.Mock(spec=requests.Response)
+ response.status_code = status
+ return requests.HTTPError(response=response)
+
+
[email protected](autouse=True)
+def _no_retry_sleep():
+ # tenacity sleeps between retries; zero it so the retry tests don't actually wait.
+ finage._fetch_json.retry.sleep = lambda *args, **kwargs: None # type: ignore[attr-defined]
+ yield
+
+
+class TestParseSymbols:
+ @parameterized.expand(
+ [
+ ("simple", "AAPL,MSFT,TSLA", ["AAPL", "MSFT", "TSLA"]),
+ ("whitespace", " aapl , MSFT , tsla ", ["AAPL", "MSFT", "TSLA"]),
+ ("lowercase_upcased", "aapl", ["AAPL"]),
+ ("dedupe_preserves_order", "AAPL,aapl,MSFT,AAPL", ["AAPL", "MSFT"]),
+ ("trailing_commas", "AAPL,,MSFT,", ["AAPL", "MSFT"]),
+ ("empty", "", []),
+ ("only_separators", " , , ", []),
+ ]
+ )
+ def test_parse_symbols(self, _name: str, raw: str, expected: list[str]) -> None:
+ assert parse_symbols(raw) == expected
+
+
+class TestValidateSourceConfig:
+ def test_accepts_valid_config(self) -> None:
+ # Class-share tickers with dots/hyphens are valid; a start date inside the window is fine.
+ validate_source_config(["AAPL", "BRK.B", "BF-B"], "2021-06-01")
+
+ @parameterized.expand(
+ [
+ ("no_symbols", [], "2021-01-01", "at least one"),
+ ("too_many", [f"SYM{i}" for i in range(MAX_SYMBOLS + 1)], "2021-01-01", "Too many symbols"),
+ ("bad_ticker", ["AAPL", "not a ticker"], "2021-01-01", "Invalid stock symbol"),
+ ("malformed_date", ["AAPL"], "06/01/2021", "YYYY-MM-DD"),
+ ("date_before_floor", ["AAPL"], "1990-01-01", MIN_START_DATE),
+ ("future_date", ["AAPL"], "2999-01-01", "future"),
+ ]
+ )
+ def test_rejects_invalid_config(self, _name: str, symbols: list[str], start_date: str, expected: str) -> None:
+ with pytest.raises(FinageConfigError) as exc:
+ validate_source_config(symbols, start_date)
+ assert expected in str(exc.value)
+
+
+class TestMsToDate:
+ @parameterized.expand(
+ [
+ ("epoch_millis", 1580860800000, "2020-02-05"),
+ ("string_millis", "1580947200000", "2020-02-06"),
+ ("none", None, None),
+ ("garbage", "not-a-number", None),
+ ]
+ )
+ def test_ms_to_date(self, _name: str, value: Any, expected: str | None) -> None:
+ assert finage._ms_to_date(value) == expected
+
+
+class TestFetchJson:
+ def test_returns_json_on_200(self) -> None:
+ session = mock.Mock()
+ session.get.return_value = _response(200, {"symbol": "AAPL"})
+ assert finage._fetch_json(session, "/last/stock/AAPL", "k", mock.Mock()) == {"symbol": "AAPL"}
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_terminal_statuses_raise_without_retry(self, _name: str, status: int) -> None:
+ session = mock.Mock()
+ session.get.return_value = _response(status)
+ with pytest.raises(requests.HTTPError):
+ finage._fetch_json(session, "/x", "k", mock.Mock())
+ # Terminal statuses are surfaced immediately — never retried.
+ assert session.get.call_count == 1
+
+ def test_terminal_error_message_strips_apikey_but_keeps_matchable_prefix(self) -> None:
+ response = mock.Mock(spec=requests.Response)
+ response.status_code = 403
+ response.reason = "Forbidden"
+ response.url = (
+ "https://api.finage.co.uk/agg/stock/AAPL/1/day/2020-01-01/2024-01-01?apikey=secret123&limit=50000"
+ )
+ session = mock.Mock()
+ session.get.return_value = response
+ with pytest.raises(requests.HTTPError) as exc_info:
+ finage._fetch_json(session, "/agg/stock/AAPL", "secret123", mock.Mock())
+ message = str(exc_info.value)
+ # The raw key must never reach the error message (and thus the non-retryable error logs).
+ assert "secret123" not in message
+ assert "apikey" not in message
+ # The prefix `get_non_retryable_errors` matches on must survive the sanitization.
+ assert "403 Client Error: Forbidden for url: https://api.finage.co.uk" in message
+
+ def test_retries_then_succeeds_on_5xx(self) -> None:
+ session = mock.Mock()
+ session.get.side_effect = [_response(500), _response(503), _response(200, {"ok": True})]
+ assert finage._fetch_json(session, "/x", "k", mock.Mock()) == {"ok": True}
+ assert session.get.call_count == 3
+
+ def test_429_exhausts_retries(self) -> None:
+ session = mock.Mock()
+ session.get.side_effect = [_response(429)] * 5
+ with pytest.raises(FinageRetryableError):
+ finage._fetch_json(session, "/x", "k", mock.Mock())
+ assert session.get.call_count == 5
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200), ("unauthorized", 401), ("forbidden", 403)])
+ def test_returns_status_code(self, _name: str, status: int) -> None:
+ with mock.patch.object(finage, "make_tracked_session") as make_session:
+ make_session.return_value.get.return_value = _response(status)
+ assert validate_credentials("key") == status
+
+ def test_returns_none_on_transport_error(self) -> None:
+ with mock.patch.object(finage, "make_tracked_session") as make_session:
+ make_session.return_value.get.side_effect = requests.ConnectionError()
+ assert validate_credentials("key") is None
+
+
+class TestGetRows:
+ @parameterized.expand([("last_quote",), ("last_trade",)])
+ def test_point_in_time_fans_out_per_symbol(self, endpoint: str) -> None:
+ payloads = [{"symbol": "AAPL", "price": 1.0}, {"symbol": "MSFT", "price": 2.0}]
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", side_effect=payloads),
+ ):
+ batches = list(get_rows("k", endpoint, ["AAPL", "MSFT"], "2020-01-01", mock.Mock()))
+
+ # One batch (single-element list) per symbol.
+ assert [row for batch in batches for row in batch] == payloads
+
+ def test_point_in_time_pins_symbol_when_missing(self) -> None:
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", side_effect=[{"ask": 1.0, "bid": 0.9}]),
+ ):
+ batches = list(get_rows("k", "last_quote", ["AAPL"], "2020-01-01", mock.Mock()))
+
+ assert batches[0][0]["symbol"] == "AAPL"
+
+ @parameterized.expand([("error_body", {"error": "no data"}), ("empty", {})])
+ def test_point_in_time_skips_symbols_without_data(self, _name: str, bad_payload: dict) -> None:
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", side_effect=[bad_payload, {"symbol": "MSFT", "price": 2.0}]),
+ ):
+ batches = list(get_rows("k", "last_trade", ["BAD", "MSFT"], "2020-01-01", mock.Mock()))
+
+ rows = [row for batch in batches for row in batch]
+ assert rows == [{"symbol": "MSFT", "price": 2.0}]
+
+ def test_point_in_time_404_skips_but_401_propagates(self) -> None:
+ # A bad ticker (404) is skipped; the next symbol still syncs.
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", side_effect=[_http_error(404), {"symbol": "MSFT"}]),
+ ):
+ batches = list(get_rows("k", "last_quote", ["BAD", "MSFT"], "2020-01-01", mock.Mock()))
+ assert [row for batch in batches for row in batch] == [{"symbol": "MSFT"}]
+
+ # An auth failure (401) must fail the whole sync, not be swallowed per-symbol.
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", side_effect=[_http_error(401)]),
+ ):
+ with pytest.raises(requests.HTTPError):
+ list(get_rows("k", "last_quote", ["AAPL"], "2020-01-01", mock.Mock()))
+
+ def test_aggregates_injects_symbol_and_date_and_preserves_bar(self) -> None:
+ payload = {
+ "symbol": "AAPL",
+ "totalResults": 2,
+ "results": [
+ {"o": 1, "h": 2, "l": 0.5, "c": 1.5, "v": 100, "t": 1580860800000},
+ {"o": 1.5, "h": 2.5, "l": 1, "c": 2, "v": 200, "t": 1580947200000},
+ ],
+ }
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", side_effect=[payload]),
+ ):
+ batches = list(get_rows("k", "aggregates", ["AAPL"], "2020-02-05", mock.Mock()))
+
+ rows = [row for batch in batches for row in batch]
+ assert rows[0] == {
+ "o": 1,
+ "h": 2,
+ "l": 0.5,
+ "c": 1.5,
+ "v": 100,
+ "t": 1580860800000,
+ "symbol": "AAPL",
+ "date": "2020-02-05",
+ }
+ assert rows[1]["date"] == "2020-02-06"
+
+ def test_aggregates_requests_ascending_with_limit(self) -> None:
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", return_value={"results": []}) as fetch,
+ ):
+ list(get_rows("k", "aggregates", ["AAPL"], "2020-01-01", mock.Mock()))
+
+ # sort=asc must match SourceResponse.sort_mode so the pipeline orders rows correctly.
+ _args, kwargs = fetch.call_args
+ assert kwargs["params"] == {"limit": AGG_LIMIT, "sort": "asc"}
+
+ def test_aggregates_skips_symbols_with_no_results(self) -> None:
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(
+ finage,
+ "_fetch_json",
+ side_effect=[{"results": []}, {"symbol": "MSFT", "results": [{"t": 1580860800000, "c": 1}]}],
+ ),
+ ):
+ batches = list(get_rows("k", "aggregates", ["NODATA", "MSFT"], "2020-01-01", mock.Mock()))
+
+ rows = [row for batch in batches for row in batch]
+ assert len(rows) == 1
+ assert rows[0]["symbol"] == "MSFT"
+
+ @parameterized.expand([("missing_t", {"c": 1}), ("unparseable_t", {"t": "not-a-number", "c": 1})])
+ def test_aggregates_rejects_bars_with_bad_timestamp(self, _name: str, bad_bar: dict) -> None:
+ # `t` is the partition key. A missing key or an unparseable value would otherwise land the bar in
+ # the fallback 1970-01 partition; both must fail the sync instead of silently misbucketing.
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", side_effect=[{"symbol": "AAPL", "results": [bad_bar]}]),
+ ):
+ with pytest.raises((KeyError, ValueError)):
+ list(get_rows("k", "aggregates", ["AAPL"], "2020-01-01", mock.Mock()))
+
+ def test_disables_adapter_retry_so_tenacity_is_the_only_retry_layer(self) -> None:
+ # The urllib3 adapter's DEFAULT_RETRY would stack on top of `_fetch_json`'s tenacity retries,
+ # multiplying backoff. `get_rows` must opt the session out with retry=Retry(total=0).
+ with (
+ mock.patch.object(finage, "make_tracked_session") as make_session,
+ mock.patch.object(finage, "_fetch_json", return_value={"results": []}),
+ ):
+ list(get_rows("k", "aggregates", ["AAPL"], "2020-01-01", mock.Mock()))
+
+ _args, kwargs = make_session.call_args
+ assert kwargs["retry"].total == 0
+
+
+class TestFinageSourceResponse:
+ @parameterized.expand(
+ [
+ ("last_quote", ["symbol"], None, None),
+ ("last_trade", ["symbol"], None, None),
+ ("aggregates", ["symbol", "t"], "datetime", ["date"]),
+ ]
+ )
+ def test_source_response_shape(
+ self, endpoint: str, primary_keys: list[str], partition_mode: str | None, partition_keys: list[str] | None
+ ) -> None:
+ response = finage_source("k", endpoint, ["AAPL"], "2020-01-01", mock.Mock())
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.partition_mode == partition_mode
+ assert response.partition_keys == partition_keys
+ assert response.sort_mode == "asc"
+ if partition_mode == "datetime":
+ assert response.partition_format == "month"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage_source.py
new file mode 100644
index 000000000000..159add3a9f15
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage_source.py
@@ -0,0 +1,136 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.finage import source as finage_source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.finage.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.finage.source import FinageSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FinageSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestFinageSource:
+ def setup_method(self):
+ self.source = FinageSource()
+ self.team_id = 123
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.FINAGE
+
+ def test_source_config_metadata(self):
+ config = self.source.get_source_config
+ assert config.label == "Finage"
+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Stays hidden until the connector graduates from alpha.
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/finage"
+
+ def test_source_config_fields(self):
+ fields = {f.name: f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig)}
+ assert set(fields) == {"api_key", "symbols", "start_date"}
+
+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD
+ assert fields["api_key"].required is True
+ assert fields["api_key"].secret is True
+
+ assert fields["symbols"].required is True
+ assert fields["symbols"].secret is False
+
+ # The backfill window is optional and defaults in code.
+ assert fields["start_date"].required is False
+
+ def test_get_schemas_full_refresh_only(self):
+ schemas = self.source.get_schemas(self._config(), self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Finage has no server-side updated_after cursor, so every table is full refresh.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_primary_keys(self):
+ schemas = {s.name: s for s in self.source.get_schemas(self._config(), self.team_id)}
+ assert schemas["last_quote"].detected_primary_keys == ["symbol"]
+ # Fan-out child key includes the symbol so bars from different symbols don't collide.
+ assert schemas["aggregates"].detected_primary_keys == ["symbol", "t"]
+
+ def test_get_schemas_names_filter(self):
+ schemas = self.source.get_schemas(self._config(), self.team_id, names=["aggregates"])
+ assert [s.name for s in schemas] == ["aggregates"]
+
+ def test_lists_tables_without_credentials(self):
+ # Static catalog with no I/O — safe for public docs.
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {t["name"] for t in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ [
+ "401 Client Error: Unauthorized for url: https://api.finage.co.uk",
+ "403 Client Error: Forbidden for url: https://api.finage.co.uk",
+ ],
+ )
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ @pytest.mark.parametrize(
+ "status,schema_name,expected_valid",
+ [
+ (200, None, True),
+ (401, None, False),
+ # 403 = valid token, plan gap. Accepted at source-create, rejected for a specific schema.
+ (403, None, True),
+ (403, "aggregates", False),
+ (None, None, False),
+ (500, None, False),
+ ],
+ )
+ def test_validate_credentials(self, status, schema_name, expected_valid):
+ with mock.patch.object(finage_source_module, "validate_finage_credentials", return_value=status):
+ valid, message = self.source.validate_credentials(self._config(), self.team_id, schema_name=schema_name)
+ assert valid is expected_valid
+ if not expected_valid:
+ assert message
+
+ def test_validate_credentials_rejects_bad_config_before_probing(self):
+ # A malformed symbol list must be rejected without ever calling the Finage API.
+ with mock.patch.object(finage_source_module, "validate_finage_credentials") as probe:
+ valid, message = self.source.validate_credentials(self._config(symbols="not a ticker"), self.team_id)
+ assert valid is False
+ assert message
+ probe.assert_not_called()
+
+ def test_source_for_pipeline_plumbing(self):
+ config = self._config(symbols=" aapl , msft ", start_date="2021-06-01")
+ inputs = mock.Mock(schema_name="aggregates")
+ with mock.patch.object(finage_source_module, "finage_source") as build:
+ self.source.source_for_pipeline(config, inputs)
+
+ _args, kwargs = build.call_args
+ assert kwargs["endpoint"] == "aggregates"
+ assert kwargs["symbols"] == ["AAPL", "MSFT"]
+ assert kwargs["start_date"] == "2021-06-01"
+ assert kwargs["api_key"] == "secret"
+
+ def test_source_for_pipeline_defaults_start_date(self):
+ config = self._config(start_date="")
+ inputs = mock.Mock(schema_name="last_quote")
+ with mock.patch.object(finage_source_module, "finage_source") as build:
+ self.source.source_for_pipeline(config, inputs)
+
+ _args, kwargs = build.call_args
+ assert kwargs["start_date"] == finage_source_module.DEFAULT_START_DATE
+
+ def _config(self, symbols: str = "AAPL", start_date: str | None = None) -> FinageSourceConfig:
+ return FinageSourceConfig(api_key="secret", symbols=symbols, start_date=start_date)
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 a3f9da603a9f..553234f4b9ac 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
@@ -1152,7 +1152,9 @@ class FilloutSourceConfig(config.Config):
@config.config
class FinageSourceConfig(config.Config):
- pass
+ api_key: str
+ symbols: str
+ start_date: str | None = None
@config.config