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 simfin import source (#72632)

Tom Owers5bdda863e85e
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 36c9695d0e3b..acbc69ef45d0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -483,6 +483,7 @@ the row lists both.
| shortcut | HTTP | requests | ✅ |
| shortio | HTTP | requests | ✅ |
| signoz | HTTP | requests | ✅ |
+| simfin | HTTP | requests | ✅ |
| simplecast | HTTP | requests | ✅ |
| simplesat | HTTP | requests | ✅ |
| skyvern | HTTP | requests | ✅ |
@@ -929,7 +930,6 @@ doesn't conflict with concurrent PRs.
- sigma_computing
- signnow
- sim
-- simfin
- simplecast
- simplesat
- singular
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/simfin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/simfin.py
index 110694b74367..d86ab79e9e3a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/simfin.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/simfin.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class SimFinSourceConfig(config.Config):
- pass
+ api_key: str
+ tickers: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/canonical_descriptions.py
new file mode 100644
index 000000000000..39a76feeebc0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/canonical_descriptions.py
@@ -0,0 +1,115 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Statement tables share the company wrapper fields plus the standardized statement metadata columns;
+# the per-metric columns (Revenue, Total Assets, ...) vary by statement template and fall back to the
+# LLM with the docs_url below.
+_COMPANY_COLUMNS = {
+ "id": "SimFin's unique identifier for the company.",
+ "name": "Company name.",
+ "ticker": "Stock ticker symbol of the company.",
+ "currency": "ISO currency code the figures are reported in.",
+ "isin": "International Securities Identification Number of the company.",
+}
+
+_STATEMENT_COLUMNS = {
+ **_COMPANY_COLUMNS,
+ "fiscal_period": "Fiscal period of the statement (Q1-Q4, FY, H1, H2 or nine-month).",
+ "fiscal_year": "Fiscal year of the statement (the company's fiscal year, not the calendar year).",
+ "report_date": "End date of the reporting period.",
+ "publish_date": "Date the statement was first published.",
+ "restated": "Whether the figures have been restated since first publication.",
+ "source": "Source filing the statement was derived from.",
+ "ttm": "Whether the row represents a trailing-twelve-month aggregate.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "companies": {
+ "description": "Catalog of every company in the SimFin database with its identifiers and sector classification.",
+ "docs_url": "https://simfin.readme.io/reference/list-1",
+ "columns": {
+ "id": "SimFin's unique identifier for the company.",
+ "name": "Company name.",
+ "ticker": "Stock ticker symbol of the company.",
+ "isin": "International Securities Identification Number of the company.",
+ "sectorCode": "Numeric code of the company's sector.",
+ "sectorName": "Name of the company's sector.",
+ "industryName": "Name of the company's industry.",
+ },
+ },
+ "company_details": {
+ "description": "Detailed company profile for each configured ticker, including market, fiscal-year end and headcount.",
+ "docs_url": "https://simfin.readme.io/reference/general-1",
+ "columns": {
+ "id": "SimFin's unique identifier for the company.",
+ "name": "Company name.",
+ "ticker": "Stock ticker symbol of the company.",
+ "isin": "International Securities Identification Number of the company.",
+ "sectorCode": "Numeric code of the company's sector.",
+ "sectorName": "Name of the company's sector.",
+ "industryName": "Name of the company's industry.",
+ "market": "Market the company's primary listing trades in (e.g. US, DE).",
+ "endFy": "Month the company's fiscal year ends in.",
+ "numEmployees": "Number of employees.",
+ "companyDescription": "Free-text description of the company's business.",
+ },
+ },
+ "income_statements": {
+ "description": "Standardized profit & loss statements, one row per company, fiscal year and period.",
+ "docs_url": "https://simfin.readme.io/reference/statements-1",
+ "columns": _STATEMENT_COLUMNS,
+ },
+ "balance_sheets": {
+ "description": "Standardized balance sheets, one row per company, fiscal year and period.",
+ "docs_url": "https://simfin.readme.io/reference/statements-1",
+ "columns": _STATEMENT_COLUMNS,
+ },
+ "cash_flow_statements": {
+ "description": "Standardized cash-flow statements, one row per company, fiscal year and period.",
+ "docs_url": "https://simfin.readme.io/reference/statements-1",
+ "columns": _STATEMENT_COLUMNS,
+ },
+ "derived_ratios": {
+ "description": "Derived ratios and indicators (EBITDA, free cash flow, margins, per-share figures), one row per company, fiscal year and period.",
+ "docs_url": "https://simfin.readme.io/reference/statements-1",
+ "columns": _STATEMENT_COLUMNS,
+ },
+ "share_prices": {
+ "description": "Daily split-adjusted share prices with trading volume and dividends, one row per company and trading day.",
+ "docs_url": "https://simfin.readme.io/reference/prices-1",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "date": "Trading day the price row refers to.",
+ "opening_price": "Opening price on the trading day.",
+ "highest_price": "Highest traded price on the trading day.",
+ "lowest_price": "Lowest traded price on the trading day.",
+ "last_closing_price": "Unadjusted closing price on the trading day.",
+ "adjusted_closing_price": "Closing price adjusted for splits and dividends.",
+ "trading_volume": "Number of shares traded on the trading day.",
+ "dividend_paid": "Dividend per share paid on the trading day, if any.",
+ "common_shares_outstanding": "Common shares outstanding on the trading day.",
+ },
+ },
+ "common_shares_outstanding": {
+ "description": "Point-in-time common shares outstanding, one row per company and change date.",
+ "docs_url": "https://simfin.readme.io/reference/shares-1",
+ "columns": {
+ "id": "SimFin's unique identifier for the company.",
+ "date": "Date the share count applies from.",
+ "common_shares_outstanding": "Number of common shares outstanding at that date.",
+ },
+ },
+ "weighted_shares_outstanding": {
+ "description": "Basic and diluted weighted shares outstanding per fiscal period, one row per company, fiscal year and period.",
+ "docs_url": "https://simfin.readme.io/reference/weighted-shares-1",
+ "columns": {
+ "id": "SimFin's unique identifier for the company.",
+ "date": "End date of the fiscal period the share counts are weighted over.",
+ "fiscal_year": "Fiscal year of the period.",
+ "period": "Fiscal period (Q1-Q4, FY, H1, H2 or nine-month).",
+ "basic_shares_outstanding": "Weighted average basic shares outstanding over the period.",
+ "diluted_shares_outstanding": "Weighted average diluted shares outstanding over the period.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/settings.py
new file mode 100644
index 000000000000..9fc3e188b5c3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/settings.py
@@ -0,0 +1,126 @@
+import dataclasses
+from typing import Literal, Optional
+
+# SimFin Web API v3 (https://backend.simfin.com/api/v3) is plain REST/JSON authenticated with an
+# `Authorization: api-key <KEY>` header. There is no pagination on any of the endpoints below and no
+# server-side change cursor (`updated_after`/`since`), so every table is full refresh only. The
+# `start`/`end` params on statements/prices filter by the *record's* own date, and price history is
+# split-adjusted retroactively, so they cannot safely drive incremental sync.
+#
+# The "compact" response format is columnar (`columns` + `data` arrays, wrapped per company for the
+# ticker-scoped endpoints) — each `kind` below tells the transport how to reshape it into flat rows.
+ParseKind = Literal[
+ "companies",
+ "company_details",
+ "statements",
+ "prices",
+ "common_shares",
+ "weighted_shares",
+]
+
+# All fiscal periods SimFin models. Requested explicitly (rather than relying on an undocumented
+# server default) so quarterly, annual, and half-year/nine-month interim reports all land.
+ALL_PERIODS = "q1,q2,q3,q4,fy,h1,h2,nine_month"
+
+
+class SimFinEndpointConfig:
+ name: str
+ # Path relative to the versioned API base, e.g. "companies/statements/compact".
+ path: str
+ kind: ParseKind
+ # Unique across the whole table. Ticker-scoped endpoints fan out over the user's configured
+ # tickers, and every reshaped row carries the company `id`, so it's always part of the key.
+ primary_keys: list[str]
+ # Static query params for this endpoint (e.g. which statement type to request).
+ params: Optional[dict[str, str]] = None
+ # Whether the endpoint is requested once per configured ticker. `companies/list` is the only
+ # account-wide endpoint; everything else is scoped to a ticker.
+ fan_out_tickers: bool = True
+ # A stable date column used for datetime partitioning. Never a mutable field. None for
+ # small/snapshot tables (company catalog and details).
+ partition_key: Optional[str] = None
+ description: Optional[str] = None
+ should_sync_default: bool = True
+
+
+SIMFIN_ENDPOINTS: dict[str, SimFinEndpointConfig] = {
+ "companies": SimFinEndpointConfig(
+ name="companies",
+ path="companies/list",
+ kind="companies",
+ primary_keys=["id"],
+ fan_out_tickers=False,
+ description="Catalog of every company in the SimFin database (SimFin ID, ticker, name, ISIN, sector and industry). One row per company. Full refresh.",
+ ),
+ "company_details": SimFinEndpointConfig(
+ name="company_details",
+ path="companies/general/compact",
+ kind="company_details",
+ primary_keys=["id"],
+ description="Detailed company profile (market, fiscal-year end, employee count, business description) for each configured ticker. One row per company. Full refresh.",
+ ),
+ "income_statements": SimFinEndpointConfig(
+ name="income_statements",
+ path="companies/statements/compact",
+ kind="statements",
+ params={"statements": "pl", "period": ALL_PERIODS},
+ primary_keys=["id", "fiscal_year", "fiscal_period"],
+ partition_key="report_date",
+ description="Standardized profit & loss statements for each configured ticker, all fiscal years and periods. One row per company, fiscal year and period. Full refresh.",
+ ),
+ "balance_sheets": SimFinEndpointConfig(
+ name="balance_sheets",
+ path="companies/statements/compact",
+ kind="statements",
+ params={"statements": "bs", "period": ALL_PERIODS},
+ primary_keys=["id", "fiscal_year", "fiscal_period"],
+ partition_key="report_date",
+ description="Standardized balance sheets for each configured ticker, all fiscal years and periods. One row per company, fiscal year and period. Full refresh.",
+ ),
+ "cash_flow_statements": SimFinEndpointConfig(
+ name="cash_flow_statements",
+ path="companies/statements/compact",
+ kind="statements",
+ params={"statements": "cf", "period": ALL_PERIODS},
+ primary_keys=["id", "fiscal_year", "fiscal_period"],
+ partition_key="report_date",
+ description="Standardized cash-flow statements for each configured ticker, all fiscal years and periods. One row per company, fiscal year and period. Full refresh.",
+ ),
+ "derived_ratios": SimFinEndpointConfig(
+ name="derived_ratios",
+ path="companies/statements/compact",
+ kind="statements",
+ params={"statements": "derived", "period": ALL_PERIODS},
+ primary_keys=["id", "fiscal_year", "fiscal_period"],
+ partition_key="report_date",
+ description="Derived ratios and indicators (EBITDA, free cash flow, margins, per-share figures) for each configured ticker, all fiscal years and periods. Full refresh.",
+ should_sync_default=False,
+ ),
+ "share_prices": SimFinEndpointConfig(
+ name="share_prices",
+ path="companies/prices/compact",
+ kind="prices",
+ primary_keys=["id", "date"],
+ partition_key="date",
+ description="Daily share prices (split-adjusted) with volume and dividends for each configured ticker. One row per company and trading day. Full refresh.",
+ ),
+ "common_shares_outstanding": SimFinEndpointConfig(
+ name="common_shares_outstanding",
+ path="companies/common-shares-outstanding",
+ kind="common_shares",
+ primary_keys=["id", "date"],
+ description="Point-in-time common shares outstanding for each configured ticker. One row per company and change date. Full refresh.",
+ should_sync_default=False,
+ ),
+ "weighted_shares_outstanding": SimFinEndpointConfig(
+ name="weighted_shares_outstanding",
+ path="companies/weighted-shares-outstanding",
+ kind="weighted_shares",
+ primary_keys=["id", "date", "fiscal_year", "period"],
+ description="Basic and diluted weighted shares outstanding per fiscal period for each configured ticker. One row per company, fiscal year and period. Full refresh.",
+ should_sync_default=False,
+ ),
+}
+
+ENDPOINTS = tuple(SIMFIN_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/simfin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/simfin.py
new file mode 100644
index 000000000000..49b51a381d0f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/simfin.py
@@ -0,0 +1,245 @@
+import re
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+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.simfin.settings import (
+ SIMFIN_ENDPOINTS,
+ SimFinEndpointConfig,
+)
+
+SIMFIN_BASE_URL = "https://backend.simfin.com/api"
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+# The connector issues one outbound request per ticker for every selected table, so an unbounded
+# ticker list lets a saved config fan out into arbitrarily many requests per scheduled sync. Cap the
+# distinct-ticker count to keep worker time and third-party quota bounded.
+MAX_TICKERS = 100
+
+# Company-level fields SimFin wraps around each ticker-scoped compact payload; injected into every
+# reshaped row so child rows are self-describing.
+_COMPANY_FIELDS = ("id", "name", "ticker", "currency", "isin")
+
+
+class SimFinAPIError(Exception):
+ pass
+
+
+def _normalize_column_name(name: str) -> str:
+ """Turn a SimFin compact column label into a snake_case column name.
+
+ e.g. "Fiscal Year" -> "fiscal_year", "Adjusted Closing Price" -> "adjusted_closing_price".
+ """
+ return re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")
+
+
+def parse_tickers(tickers: str) -> list[str]:
+ """Split the user's comma-separated tickers field into a de-duplicated, upper-cased list."""
+ seen: set[str] = set()
+ result: list[str] = []
+ for raw in tickers.split(","):
+ ticker = raw.strip().upper()
+ if ticker and ticker not in seen:
+ seen.add(ticker)
+ result.append(ticker)
+ return result
+
+
+def validate_tickers(tickers: str) -> tuple[list[str], str | None]:
+ """Parse and bound the tickers field. Returns the parsed list plus a user-facing error, if any."""
+ parsed = parse_tickers(tickers)
+ if not parsed:
+ return parsed, "Enter at least one ticker (e.g. AAPL, MSFT)"
+ if len(parsed) > MAX_TICKERS:
+ return parsed, f"Too many tickers ({len(parsed)}); enter at most {MAX_TICKERS} distinct tickers."
+ return parsed, None
+
+
+def _make_session(api_key: str) -> requests.Session:
+ # The key rides in the Authorization header on every request; mask its literal value from logged
+ # URLs, headers, and captured samples.
+ return make_tracked_session(
+ headers={"Authorization": f"api-key {api_key}", "Accept": "application/json"},
+ redact_values=(api_key,),
+ )
+
+
+def _fetch_json(session: requests.Session, url: str, params: dict[str, Any]) -> Any:
+ # The tracked session already retries 429/5xx with backoff, so a non-ok status here is final.
+ # The URL carries no secrets (auth is a header), so raise_for_status' message is safe to log.
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+ response.raise_for_status()
+ return response.json()
+
+
+def _zip_rows(columns: list[Any], data: list[Any], normalize: bool = True) -> Iterator[dict[str, Any]]:
+ names = [_normalize_column_name(str(column)) if normalize else str(column) for column in columns]
+ for row in data:
+ if isinstance(row, list):
+ yield dict(zip(names, row))
+
+
+def _parse_companies(body: Any, ticker: Optional[str]) -> Iterator[dict[str, Any]]:
+ # /companies/list returns a flat array of company objects with machine-friendly keys.
+ if not isinstance(body, list):
+ raise SimFinAPIError("SimFin API error [unexpected_response]: expected a JSON array of companies")
+ for company in body:
+ if isinstance(company, dict):
+ yield company
+
+
+def _parse_company_details(body: Any, ticker: Optional[str]) -> Iterator[dict[str, Any]]:
+ # /companies/general/compact returns a single columnar object: {"columns": [...], "data": [[...]]}.
+ # Its column names are already camelCase identifiers matching /companies/list, so keep them as-is.
+ if not isinstance(body, dict):
+ raise SimFinAPIError("SimFin API error [unexpected_response]: expected a columnar JSON object")
+ yield from _zip_rows(body.get("columns") or [], body.get("data") or [], normalize=False)
+
+
+def _parse_statements(body: Any, ticker: Optional[str]) -> Iterator[dict[str, Any]]:
+ # /companies/statements/compact returns one item per company, each wrapping per-statement
+ # columnar blocks: [{"id": ..., "ticker": ..., "statements": [{"statement", "columns", "data"}]}].
+ if not isinstance(body, list):
+ raise SimFinAPIError("SimFin API error [unexpected_response]: expected a JSON array of statement items")
+ for item in body:
+ if not isinstance(item, dict):
+ continue
+ company = {field: item.get(field) for field in _COMPANY_FIELDS}
+ for statement in item.get("statements") or []:
+ if not isinstance(statement, dict):
+ continue
+ for row in _zip_rows(statement.get("columns") or [], statement.get("data") or []):
+ yield {**company, **row}
+
+
+def _parse_prices(body: Any, ticker: Optional[str]) -> Iterator[dict[str, Any]]:
+ # /companies/prices/compact returns one columnar item per company:
+ # [{"id": ..., "ticker": ..., "columns": [...], "data": [[...], ...]}].
+ if not isinstance(body, list):
+ raise SimFinAPIError("SimFin API error [unexpected_response]: expected a JSON array of price items")
+ for item in body:
+ if not isinstance(item, dict):
+ continue
+ company = {field: item.get(field) for field in _COMPANY_FIELDS}
+ for row in _zip_rows(item.get("columns") or [], item.get("data") or []):
+ yield {**company, **row}
+
+
+# The shares-outstanding endpoints return positional arrays without column headers. Field order is
+# undocumented but stable, matching SimFin's official API clients.
+_COMMON_SHARES_COLUMNS = ["id", "date", "common_shares_outstanding"]
+_WEIGHTED_SHARES_COLUMNS = [
+ "id",
+ "date",
+ "fiscal_year",
+ "period",
+ "basic_shares_outstanding",
+ "diluted_shares_outstanding",
+]
+
+
+def _parse_common_shares(body: Any, ticker: Optional[str]) -> Iterator[dict[str, Any]]:
+ if not isinstance(body, list):
+ raise SimFinAPIError("SimFin API error [unexpected_response]: expected a JSON array of share rows")
+ yield from _zip_rows(_COMMON_SHARES_COLUMNS, body, normalize=False)
+
+
+def _parse_weighted_shares(body: Any, ticker: Optional[str]) -> Iterator[dict[str, Any]]:
+ if not isinstance(body, list):
+ raise SimFinAPIError("SimFin API error [unexpected_response]: expected a JSON array of share rows")
+ yield from _zip_rows(_WEIGHTED_SHARES_COLUMNS, body, normalize=False)
+
+
+_PARSERS = {
+ "companies": _parse_companies,
+ "company_details": _parse_company_details,
+ "statements": _parse_statements,
+ "prices": _parse_prices,
+ "common_shares": _parse_common_shares,
+ "weighted_shares": _parse_weighted_shares,
+}
+
+
+def _endpoint_url(config: SimFinEndpointConfig, api_version: str) -> str:
+ return f"{SIMFIN_BASE_URL}/{api_version}/{config.path}"
+
+
+def get_rows(
+ api_key: str,
+ tickers: list[str],
+ endpoint: str,
+ api_version: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = SIMFIN_ENDPOINTS[endpoint]
+ parser = _PARSERS[config.kind]
+ session = _make_session(api_key)
+ url = _endpoint_url(config, api_version)
+
+ if not config.fan_out_tickers:
+ rows = list(parser(_fetch_json(session, url, dict(config.params or {})), None))
+ if rows:
+ yield rows
+ return
+
+ # One request per ticker (no pagination); a single ticker's full history is bounded (a few
+ # thousand statement rows, ~10k daily price rows), so each response comfortably fits in memory
+ # and the pipeline batches downstream. Per-ticker requests also stay within the request shape
+ # every SimFin plan tier allows.
+ for ticker in tickers:
+ params = dict(config.params or {})
+ params["ticker"] = ticker
+ rows = list(parser(_fetch_json(session, url, params), ticker))
+ if rows:
+ yield rows
+ else:
+ # An unknown ticker or a dataset outside the account's plan comes back empty rather than
+ # as an error; skip it so the rest of the configured tickers still sync.
+ logger.warning(f"SimFin: no rows returned for ticker {ticker} on {endpoint}")
+
+
+def simfin_source(
+ api_key: str,
+ tickers: list[str],
+ endpoint: str,
+ api_version: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = SIMFIN_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key, tickers=tickers, endpoint=endpoint, api_version=api_version, logger=logger
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def validate_credentials(api_key: str, api_version: str) -> bool:
+ """Confirm the API key is genuine with one cheap probe request.
+
+ Uses the company-details endpoint scoped to a single well-known ticker so the probe stays small;
+ an invalid or unconfirmed key returns 401.
+ """
+ if not api_key.strip():
+ return False
+
+ session = _make_session(api_key)
+ url = _endpoint_url(SIMFIN_ENDPOINTS["company_details"], api_version)
+ try:
+ response = session.get(url, params={"ticker": "AAPL"}, timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False
+
+ return response.status_code == 200
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/source.py
index 010e24ddda4b..573d4814ae13 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/source.py
@@ -1,30 +1,148 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.simfin import SimFinSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.simfin.settings import SIMFIN_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.simfin.simfin import (
+ simfin_source,
+ validate_credentials as validate_simfin_credentials,
+ validate_tickers,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class SimFinSource(SimpleSource[SimFinSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v3",)
+ default_version = "v3"
+ api_docs_url = "https://simfin.readme.io/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SIMFIN
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://backend.simfin.com": "Your SimFin API key is invalid or your account e-mail is not confirmed. Check the key in the SimFin app and reconnect.",
+ "403 Client Error: Forbidden for url: https://backend.simfin.com": "Your SimFin plan does not include access to this dataset. Upgrade your SimFin plan or deselect the table.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.simfin.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SimFinSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # SimFin has no server-side change cursor (statement/price date filters scope the record's
+ # own date, and price history is split-adjusted retroactively), so every table is full
+ # refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint.name,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ detected_primary_keys=endpoint.primary_keys,
+ should_sync_default=endpoint.should_sync_default,
+ description=endpoint.description,
+ )
+ for endpoint in SIMFIN_ENDPOINTS.values()
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: SimFinSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ _, tickers_error = validate_tickers(config.tickers)
+ if tickers_error:
+ return False, tickers_error
+
+ if validate_simfin_credentials(config.api_key, self.default_version):
+ return True, None
+
+ return False, "Invalid SimFin API key"
+
+ def source_for_pipeline(self, config: SimFinSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ # Re-validate here so a previously-saved oversized ticker list can't trigger a runaway sync.
+ tickers, tickers_error = validate_tickers(config.tickers)
+ if tickers_error:
+ raise ValueError(f"SimFin source misconfigured: {tickers_error}")
+
+ return simfin_source(
+ api_key=config.api_key,
+ tickers=tickers,
+ endpoint=inputs.schema_name,
+ api_version=self.resolve_api_version(inputs.api_version),
+ logger=inputs.logger,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SIM_FIN,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="SimFin",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["financial data", "fundamentals", "stocks", "equities", "share prices"],
+ caption="""Enter your SimFin API key and the stock tickers you want to track to pull standardized financial statements, share prices and company data into the PostHog Data warehouse.
+
+You can find your API key in the [SimFin app](https://app.simfin.com/data-api) (confirm your account e-mail first).
+
+Note: each selected table costs one request per ticker on every sync, and SimFin rate limits requests per second by plan tier. Historical depth and some datasets depend on your SimFin plan.""",
iconPath="/static/services/simfin.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/simfin",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="tickers",
+ label="Tickers (comma-separated)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="AAPL, MSFT, GOOG",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/tests/test_simfin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/tests/test_simfin.py
new file mode 100644
index 000000000000..1545e78d61a2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/tests/test_simfin.py
@@ -0,0 +1,321 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.simfin.simfin import (
+ SimFinAPIError,
+ _normalize_column_name,
+ _parse_common_shares,
+ _parse_companies,
+ _parse_company_details,
+ _parse_prices,
+ _parse_statements,
+ _parse_weighted_shares,
+ get_rows,
+ parse_tickers,
+ simfin_source,
+ validate_credentials,
+ validate_tickers,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.simfin.simfin"
+
+
+def _response(*, body: Any = None, status: int = 200) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.json.return_value = body if body is not None else []
+ if status >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(
+ f"{status} Client Error: Unauthorized for url: https://backend.simfin.com/api/v3/companies/list",
+ response=response,
+ )
+ else:
+ response.raise_for_status.return_value = None
+ return response
+
+
+def _session_returning(responses: list[MagicMock]) -> MagicMock:
+ session = MagicMock()
+ session.get.side_effect = responses
+ return session
+
+
+def _collect_rows(batches: Any) -> list[dict]:
+ rows: list[dict] = []
+ for batch in batches:
+ rows.extend(batch)
+ return rows
+
+
+class TestSimFin:
+ @parameterized.expand(
+ [
+ ("spaces", "Fiscal Year", "fiscal_year"),
+ ("multi_word", "Adjusted Closing Price", "adjusted_closing_price"),
+ ("punctuation", "Adj. Close", "adj_close"),
+ ("already_clean", "date", "date"),
+ ]
+ )
+ def test_normalize_column_name(self, _name: str, raw: str, expected: str) -> None:
+ assert _normalize_column_name(raw) == expected
+
+ @parameterized.expand(
+ [
+ ("dedup_upper_strip", " aapl, MSFT ,, goog, AAPL ", ["AAPL", "MSFT", "GOOG"]),
+ ("empty", "", []),
+ ("only_commas", " , , ", []),
+ ("dotted_class_share", "brk.b", ["BRK.B"]),
+ ]
+ )
+ def test_parse_tickers(self, _name: str, raw: str, expected: list[str]) -> None:
+ assert parse_tickers(raw) == expected
+
+ @parameterized.expand(
+ [
+ ("valid", "AAPL, MSFT", None),
+ ("empty", " ", "Enter at least one ticker (e.g. AAPL, MSFT)"),
+ ("over_limit", ",".join(f"T{i}" for i in range(101)), "Too many tickers"),
+ ]
+ )
+ def test_validate_tickers_bounds_the_list(self, _name: str, raw: str, expected_error_fragment: str | None) -> None:
+ _, error = validate_tickers(raw)
+ if expected_error_fragment is None:
+ assert error is None
+ else:
+ assert error is not None and expected_error_fragment in error
+
+ def test_parse_statements_reshapes_columns_and_injects_company_fields(self) -> None:
+ body = [
+ {
+ "id": 111052,
+ "name": "Apple Inc",
+ "ticker": "AAPL",
+ "currency": "USD",
+ "isin": "US0378331005",
+ "statements": [
+ {
+ "statement": "PL",
+ "columns": ["Fiscal Period", "Fiscal Year", "Report Date", "Revenue"],
+ "data": [["Q1", 2024, "2023-12-30", 119575000000], ["FY", 2024, "2024-09-28", 391035000000]],
+ }
+ ],
+ }
+ ]
+ rows = list(_parse_statements(body, "AAPL"))
+ assert rows == [
+ {
+ "id": 111052,
+ "name": "Apple Inc",
+ "ticker": "AAPL",
+ "currency": "USD",
+ "isin": "US0378331005",
+ "fiscal_period": "Q1",
+ "fiscal_year": 2024,
+ "report_date": "2023-12-30",
+ "revenue": 119575000000,
+ },
+ {
+ "id": 111052,
+ "name": "Apple Inc",
+ "ticker": "AAPL",
+ "currency": "USD",
+ "isin": "US0378331005",
+ "fiscal_period": "FY",
+ "fiscal_year": 2024,
+ "report_date": "2024-09-28",
+ "revenue": 391035000000,
+ },
+ ]
+
+ def test_parse_statements_skips_companies_without_statements(self) -> None:
+ assert list(_parse_statements([{"id": 1, "ticker": "AAPL", "statements": None}], "AAPL")) == []
+
+ def test_parse_prices_reshapes_columns_and_injects_company_fields(self) -> None:
+ body = [
+ {
+ "id": 111052,
+ "name": "Apple Inc",
+ "ticker": "AAPL",
+ "currency": "USD",
+ "columns": ["Date", "Adjusted Closing Price", "Trading Volume"],
+ "data": [["2024-05-07", 182.4, 45000000]],
+ }
+ ]
+ rows = list(_parse_prices(body, "AAPL"))
+ assert rows == [
+ {
+ "id": 111052,
+ "name": "Apple Inc",
+ "ticker": "AAPL",
+ "currency": "USD",
+ "isin": None,
+ "date": "2024-05-07",
+ "adjusted_closing_price": 182.4,
+ "trading_volume": 45000000,
+ }
+ ]
+
+ def test_parse_companies_yields_objects_as_returned(self) -> None:
+ body = [{"id": 111052, "ticker": "AAPL", "name": "Apple Inc", "sectorCode": 101}]
+ assert list(_parse_companies(body, None)) == body
+
+ def test_parse_company_details_keeps_camel_case_columns(self) -> None:
+ # Column names on this endpoint are already camelCase identifiers matching /companies/list;
+ # normalizing them would make the two company tables' column names diverge.
+ body = {"columns": ["id", "ticker", "sectorCode", "numEmployees"], "data": [[111052, "AAPL", 101, 164000]]}
+ assert list(_parse_company_details(body, "AAPL")) == [
+ {"id": 111052, "ticker": "AAPL", "sectorCode": 101, "numEmployees": 164000}
+ ]
+
+ def test_parse_common_shares_maps_positional_rows(self) -> None:
+ body = [[111052, "2024-05-07", 15334082000]]
+ assert list(_parse_common_shares(body, "AAPL")) == [
+ {"id": 111052, "date": "2024-05-07", "common_shares_outstanding": 15334082000}
+ ]
+
+ def test_parse_weighted_shares_maps_positional_rows(self) -> None:
+ body = [[111052, "2024-09-28", 2024, "FY", 15343783000, 15408095000]]
+ assert list(_parse_weighted_shares(body, "AAPL")) == [
+ {
+ "id": 111052,
+ "date": "2024-09-28",
+ "fiscal_year": 2024,
+ "period": "FY",
+ "basic_shares_outstanding": 15343783000,
+ "diluted_shares_outstanding": 15408095000,
+ }
+ ]
+
+ @parameterized.expand(
+ [
+ ("companies_dict", _parse_companies, {"error": "nope"}),
+ ("details_list", _parse_company_details, [{"id": 1}]),
+ ("statements_dict", _parse_statements, {"columns": []}),
+ ("prices_dict", _parse_prices, {"columns": []}),
+ ("common_shares_dict", _parse_common_shares, {"data": []}),
+ ("weighted_shares_dict", _parse_weighted_shares, {"data": []}),
+ ]
+ )
+ def test_parsers_raise_on_unexpected_shape(self, _name: str, parser: Any, body: Any) -> None:
+ # An upstream response-shape change must fail the sync loudly, not silently truncate the table.
+ with pytest.raises(SimFinAPIError):
+ list(parser(body, "AAPL"))
+
+ def test_get_rows_fans_out_one_request_per_ticker_with_endpoint_params(self) -> None:
+ responses = [
+ _response(
+ body=[
+ {
+ "id": 1,
+ "ticker": "AAPL",
+ "statements": [{"statement": "PL", "columns": ["Fiscal Year"], "data": [[2024]]}],
+ }
+ ]
+ ),
+ _response(
+ body=[
+ {
+ "id": 2,
+ "ticker": "MSFT",
+ "statements": [{"statement": "PL", "columns": ["Fiscal Year"], "data": [[2023]]}],
+ }
+ ]
+ ),
+ ]
+ session = _session_returning(responses)
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ rows = _collect_rows(get_rows("KEY", ["AAPL", "MSFT"], "income_statements", "v3", MagicMock()))
+
+ assert [(r["ticker"], r["fiscal_year"]) for r in rows] == [("AAPL", 2024), ("MSFT", 2023)]
+ urls = [call.args[0] for call in session.get.call_args_list]
+ assert urls == ["https://backend.simfin.com/api/v3/companies/statements/compact"] * 2
+ params = [call.kwargs["params"] for call in session.get.call_args_list]
+ assert params[0]["ticker"] == "AAPL"
+ assert params[1]["ticker"] == "MSFT"
+ # The statement type must ride on every request or the table silently fills with the API default.
+ assert all(p["statements"] == "pl" for p in params)
+
+ def test_get_rows_companies_is_a_single_request_without_ticker(self) -> None:
+ session = _session_returning([_response(body=[{"id": 1, "ticker": "AAPL"}])])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ rows = _collect_rows(get_rows("KEY", ["AAPL", "MSFT"], "companies", "v3", MagicMock()))
+ assert rows == [{"id": 1, "ticker": "AAPL"}]
+ assert session.get.call_count == 1
+ assert "ticker" not in session.get.call_args.kwargs["params"]
+
+ def test_get_rows_skips_empty_ticker_but_syncs_the_rest(self) -> None:
+ responses = [
+ _response(body=[]),
+ _response(body=[{"id": 2, "ticker": "MSFT", "columns": ["Date"], "data": [["2024-05-07"]]}]),
+ ]
+ logger = MagicMock()
+ with patch(f"{MODULE}.make_tracked_session", return_value=_session_returning(responses)):
+ rows = _collect_rows(get_rows("KEY", ["BADTICKER", "MSFT"], "share_prices", "v3", logger))
+ assert [r["ticker"] for r in rows] == ["MSFT"]
+ logger.warning.assert_called_once()
+
+ def test_get_rows_propagates_http_errors(self) -> None:
+ # The raised message must keep the "401 Client Error ... backend.simfin.com" shape that
+ # get_non_retryable_errors keys on, so bad credentials fail permanently instead of retrying.
+ session = _session_returning([_response(status=401)])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ with pytest.raises(requests.HTTPError, match="401 Client Error: Unauthorized for url"):
+ _collect_rows(get_rows("KEY", ["AAPL"], "share_prices", "v3", MagicMock()))
+
+ def test_session_carries_auth_header_and_redacts_key(self) -> None:
+ with patch(f"{MODULE}.make_tracked_session") as make_session:
+ make_session.return_value = _session_returning([_response(body=[])])
+ _collect_rows(get_rows("SECRETKEY", [], "companies", "v3", MagicMock()))
+ kwargs = make_session.call_args.kwargs
+ assert kwargs["headers"]["Authorization"] == "api-key SECRETKEY"
+ assert kwargs["redact_values"] == ("SECRETKEY",)
+
+ @parameterized.expand(
+ [
+ ("companies", ["id"], None),
+ ("income_statements", ["id", "fiscal_year", "fiscal_period"], "report_date"),
+ ("share_prices", ["id", "date"], "date"),
+ ("weighted_shares_outstanding", ["id", "date", "fiscal_year", "period"], None),
+ ]
+ )
+ def test_simfin_source_maps_primary_keys_and_partitioning(
+ self, endpoint: str, expected_keys: list[str], partition_key: str | None
+ ) -> None:
+ response = simfin_source("KEY", ["AAPL"], endpoint, "v3", MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ if partition_key is None:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+
+ @parameterized.expand(
+ [
+ ("valid", "KEY", 200, True),
+ ("unauthorized", "KEY", 401, False),
+ ("forbidden", "KEY", 403, False),
+ ]
+ )
+ def test_validate_credentials(self, _name: str, api_key: str, status: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(status=status)
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ assert validate_credentials(api_key, "v3") is expected
+
+ def test_validate_credentials_empty_key_skips_request(self) -> None:
+ with patch(f"{MODULE}.make_tracked_session") as make_session:
+ assert validate_credentials(" ", "v3") is False
+ make_session.assert_not_called()
+
+ def test_validate_credentials_network_error_returns_false(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ assert validate_credentials("KEY", "v3") is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/tests/test_simfin_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/tests/test_simfin_source.py
new file mode 100644
index 000000000000..c2ae8fbda6f8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simfin/tests/test_simfin_source.py
@@ -0,0 +1,151 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.simfin.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.simfin.source import SimFinSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.simfin.source"
+
+
+def _make_config(api_key: str = "key", tickers: str = "AAPL, MSFT") -> Any:
+ config = MagicMock()
+ config.api_key = api_key
+ config.tickers = tickers
+ return config
+
+
+class TestSimFinSource:
+ def test_source_type(self) -> None:
+ assert SimFinSource().source_type == ExternalDataSourceType.SIMFIN
+
+ def test_source_config_has_api_key_and_tickers_fields(self) -> None:
+ config = SimFinSource().get_source_config
+ assert [f.name for f in config.fields] == ["api_key", "tickers"]
+ api_key_field, tickers_field = config.fields
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ # The API key is a secret credential, so it must render as a password input.
+ assert api_key_field.type == "password"
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+ # Tickers are not secret and drive the per-ticker fan-out.
+ assert isinstance(tickers_field, SourceFieldInputConfig)
+ assert tickers_field.type == "text"
+ assert tickers_field.secret is False
+ assert tickers_field.required is True
+
+ def test_source_config_is_released_as_alpha(self) -> None:
+ config = SimFinSource().get_source_config
+ # unreleasedSource hides the connector entirely; a finished source must ship visible.
+ assert not config.unreleasedSource
+ assert config.releaseStatus == "alpha"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/simfin"
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static endpoint catalog with no I/O, so the public docs can render tables.
+ assert SimFinSource.lists_tables_without_credentials is True
+
+ def test_get_schemas_returns_every_endpoint_as_full_refresh(self) -> None:
+ schemas = SimFinSource().get_schemas(_make_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # SimFin has no server-side change cursor, so nothing supports incremental.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_exposes_primary_keys(self) -> None:
+ schemas = {s.name: s for s in SimFinSource().get_schemas(_make_config(), team_id=1)}
+ assert schemas["companies"].detected_primary_keys == ["id"]
+ assert schemas["income_statements"].detected_primary_keys == ["id", "fiscal_year", "fiscal_period"]
+ assert schemas["share_prices"].detected_primary_keys == ["id", "date"]
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = SimFinSource().get_schemas(_make_config(), team_id=1, names=["companies", "share_prices"])
+ assert {s.name for s in schemas} == {"companies", "share_prices"}
+
+ @parameterized.expand(
+ [
+ ("valid", "KEY", "AAPL", True, True, None),
+ ("invalid_key", "KEY", "AAPL", False, False, "Invalid SimFin API key"),
+ ("no_tickers", "KEY", " ", True, False, "Enter at least one ticker (e.g. AAPL, MSFT)"),
+ (
+ "too_many_tickers",
+ "KEY",
+ ",".join(f"T{i}" for i in range(101)),
+ True,
+ False,
+ "Too many tickers (101); enter at most 100 distinct tickers.",
+ ),
+ ]
+ )
+ def test_validate_credentials(
+ self,
+ _name: str,
+ api_key: str,
+ tickers: str,
+ probe_result: bool,
+ expected_ok: bool,
+ expected_message: str | None,
+ ) -> None:
+ with patch(f"{MODULE}.validate_simfin_credentials", return_value=probe_result):
+ ok, message = SimFinSource().validate_credentials(_make_config(api_key, tickers), team_id=1)
+ assert ok is expected_ok
+ assert message == expected_message
+
+ def test_validate_credentials_skips_probe_without_tickers(self) -> None:
+ # No point probing the API key if there are no tickers to sync — fail fast on tickers first.
+ with patch(f"{MODULE}.validate_simfin_credentials") as probe:
+ ok, _ = SimFinSource().validate_credentials(_make_config(tickers=""), team_id=1)
+ assert ok is False
+ probe.assert_not_called()
+
+ def test_source_for_pipeline_plumbs_tickers_key_and_version(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "share_prices"
+ inputs.api_version = None
+ inputs.logger = MagicMock()
+ with patch(f"{MODULE}.simfin_source") as source_fn:
+ SimFinSource().source_for_pipeline(_make_config("abc", "aapl, msft"), inputs)
+ source_fn.assert_called_once()
+ kwargs = source_fn.call_args.kwargs
+ assert kwargs["api_key"] == "abc"
+ # Tickers are parsed (upper-cased, de-duplicated) before handing off to the transport.
+ assert kwargs["tickers"] == ["AAPL", "MSFT"]
+ assert kwargs["endpoint"] == "share_prices"
+ # An unpinned source resolves to the default vendor API version.
+ assert kwargs["api_version"] == "v3"
+
+ def test_source_for_pipeline_rejects_oversized_ticker_list(self) -> None:
+ # A previously-saved oversized config must fail the run instead of fanning out into a runaway sync.
+ inputs = MagicMock()
+ inputs.schema_name = "share_prices"
+ inputs.logger = MagicMock()
+ oversized = _make_config("abc", ",".join(f"T{i}" for i in range(101)))
+ with patch(f"{MODULE}.simfin_source") as source_fn:
+ with pytest.raises(ValueError, match="Too many tickers"):
+ SimFinSource().source_for_pipeline(oversized, inputs)
+ source_fn.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://backend.simfin.com"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://backend.simfin.com"),
+ ]
+ )
+ def test_non_retryable_errors_cover_permanent_failures(self, _name: str, expected_key: str) -> None:
+ errors = SimFinSource().get_non_retryable_errors()
+ assert expected_key in errors
+ assert errors[expected_key]
+
+ def test_canonical_descriptions_keyed_by_endpoint(self) -> None:
+ descriptions = SimFinSource().get_canonical_descriptions()
+ # Every documented entry must map to a real endpoint or the docs render orphaned tables.
+ assert set(descriptions.keys()) <= set(ENDPOINTS)
+ assert "income_statements" in descriptions
+ assert "share_prices" in descriptions