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(finnworlds): add identifier, insider and macro indicator tables (#107413)

Tom Owersbeaf71d993c5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 0ed113d59448..3ecc906363bf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -3132,12 +3132,12 @@ Today (11): `balance_sheets`, `bond_yields`, `cash_flows`, `company_information`
Diffed against: <https://finnworlds.com/documentation/>
-- [ ] `Company Identification` — ticker/ISIN/CIK lookup table that resolves the company identifiers every other synced table keys on (high)
-- [ ] `Historical Candlestick` — historical OHLC series; stock_prices only covers real-time quotes so there is no price history to analyze (high)
-- [ ] `Insider Transactions` — insider trade rows, a core analytical fact table absent from the current set (high)
+- [x] `Company Identification` — ticker/ISIN/CIK lookup table that resolves the company identifiers every other synced table keys on (high) — added as `company_identifiers` (`/identifiers`)
+- [x] `Historical Candlestick` — historical OHLC series; stock_prices only covers real-time quotes so there is no price history to analyze (high) — already synced: `stock_prices` calls `/historicalcandlestick`. The uncovered endpoint is the real-time quote one (`/stockprice`), not this one.
+- [x] `Insider Transactions` — insider trade rows, a core analytical fact table absent from the current set (high) — added as `insider_transactions`, one row per Form 4 transaction line
- [ ] `Market Exchanges` — lookup resolving the exchange codes carried on company and price rows (medium)
- [ ] `Stock Market Index` — index level series needed to benchmark the synced company data (medium)
-- [ ] `Macroeconomic Data` — macro indicator series, one of Finnworlds' headline datasets (medium)
+- [x] `Macroeconomic Data` — macro indicator series, one of Finnworlds' headline datasets (medium) — added as `macroeconomic_indicators` (`/macroindicator`), fanned out over a new countries field
- [ ] `Economic Calendar` — scheduled macro releases; useful for event-study joins against price data (medium)
- [ ] `Currency Exchange Rates` — FX rates required to normalize multi-currency financial statements (medium)
- [ ] `ETF Holdings` — fund-to-holding breakdown rows linking funds to already-synced companies (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/canonical_descriptions.py
index b33b9304d31d..1e74e9f2bde6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/canonical_descriptions.py
@@ -32,6 +32,26 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"about": "Free-text description of the company.",
},
},
+ "company_identifiers": {
+ "description": "Identifier and classification lookup for a company (ISIN, CUSIP, CIK, EIN, LEI, SIC).",
+ "docs_url": DOCS_URL,
+ "columns": {
+ "ticker": "Stock ticker symbol the identifiers were requested for.",
+ "name": "Canonical company name.",
+ "cik": "SEC Central Index Key for the company.",
+ "isin": "International Securities Identification Number.",
+ "cusip": "CUSIP identifier.",
+ "ein_employer_id": "Employer Identification Number.",
+ "lei": "Legal Entity Identifier.",
+ "series_id": "Fund series identifier, where the security has one.",
+ "item_type": "Security type (for example equity).",
+ "sector": "Industry sector the company belongs to.",
+ "industry": "Industry classification of the company.",
+ "sic_code": "Standard Industrial Classification code.",
+ "sic_name": "Standard Industrial Classification label.",
+ "previous_names": "Former company names with the date each one applied from.",
+ },
+ },
"income_statements": {
"description": "Income statement line items per reporting period for a company.",
"docs_url": DOCS_URL,
@@ -156,6 +176,49 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"url": "EDGAR index URL for the filing.",
},
},
+ "insider_transactions": {
+ "description": "Insider trades reported to the SEC on Form 4, one row per reported transaction line.",
+ "docs_url": DOCS_URL,
+ "columns": {
+ "ticker": "Stock ticker symbol the filing belongs to.",
+ "period_of_report": "Period the filing reports on.",
+ "transaction_table": "Whether the line comes from the non-derivative or derivative table.",
+ "transaction_index": "Position of the line within the API response for this ticker.",
+ "owner_cik": "SEC Central Index Key of the reporting insider.",
+ "owner_name": "Name of the reporting insider.",
+ "owner_is_director": "Whether the insider is a director of the company.",
+ "owner_is_officer": "Whether the insider is an officer of the company.",
+ "owner_is_ten_percent_owner": "Whether the insider holds at least ten percent of the company.",
+ "owner_is_other": "Whether the insider has another reportable relationship.",
+ "owner_title": "Title the insider reported (for example Senior Vice President).",
+ "security": "Security the transaction was in.",
+ "activity_date": "Date the transaction took place.",
+ "deemed_execution_date": "Deemed execution date, where one is reported.",
+ "transaction_code": "SEC transaction code (for example P for purchase, S for sale, M for exercise).",
+ "transaction_equity_swap": "Whether the transaction was part of an equity swap.",
+ "transaction_timeliness": "Whether the filing was late.",
+ "transaction_amounts_shares": "Number of shares transacted.",
+ "transaction_amounts_share_per_price": "Price per share.",
+ "transaction_amounts_currency": "Currency of the transaction price.",
+ "transaction_amounts_acquired_disposed_code": "Whether shares were acquired (A) or disposed of (D).",
+ "post_transaction_holding": "Shares held after the non-derivative transaction.",
+ "post_transaction_shares_owned": "Derivative securities held after the transaction.",
+ "ownership_nature_direct_or_indirect": "Whether the holding is direct (D) or indirect (I).",
+ "ownership_nature_ownership": "Description of an indirect holding.",
+ },
+ },
+ "macroeconomic_indicators": {
+ "description": "Reported outcomes of macroeconomic indicators for a country. Not company-specific.",
+ "docs_url": DOCS_URL,
+ "columns": {
+ "country": "Country the indicator was reported for.",
+ "report_name": "Name of the macroeconomic indicator (for example Business Confidence).",
+ "actual": "Value reported for this period.",
+ "previous": "Value reported for the preceding period.",
+ "unit": "Unit the value is measured in (for example percent, points, units).",
+ "report_date": "Period the value covers, as year and month.",
+ },
+ },
"bond_yields": {
"description": "Government bond yields by country and maturity. Global, not company-specific.",
"docs_url": DOCS_URL,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/finnworlds.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/finnworlds.py
index 3d69594e2464..829f355db972 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/finnworlds.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/finnworlds.py
@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.settings import (
FINNWORLDS_ENDPOINTS,
+ FanoutDimension,
FinnworldsEndpointConfig,
ResponseMode,
)
@@ -29,6 +30,9 @@ REQUEST_TIMEOUT_SECONDS = 60
# watchlist like the S&P 500 while rejecting paste-the-whole-exchange configs.
MAX_TICKERS = 500
+# Macroeconomic indicators fan out over countries the same way, and Finnworlds covers 196 of them.
+MAX_COUNTRIES = 200
+
class FinnworldsRetryableError(Exception):
"""A transient API error (429 / 5xx) worth retrying."""
@@ -62,6 +66,28 @@ def parse_tickers(raw: str | None) -> list[str]:
return tickers
+def parse_countries(raw: str | None) -> list[str]:
+ """Split the user's country list into the underscore-joined names the macro endpoint expects.
+
+ Only commas and newlines separate entries, so a space inside a name is kept as part of it and
+ written the way the API spells it ("United Kingdom" becomes "United_Kingdom"). Matching is
+ case-insensitive for de-duplication, but the user's spelling is what gets sent.
+ """
+ if not raw:
+ return []
+ seen: set[str] = set()
+ countries: list[str] = []
+ for token in re.split(r"[,\n]", raw):
+ country = "_".join(token.split())
+ if not country or country.casefold() in seen:
+ continue
+ seen.add(country.casefold())
+ countries.append(country)
+ if len(countries) > MAX_COUNTRIES:
+ raise ValueError(f"Too many countries: at most {MAX_COUNTRIES} are allowed per source.")
+ return countries
+
+
def _build_url(path: str, params: dict[str, str]) -> str:
return f"{FINNWORLDS_BASE_URL}/{path}?{urlencode(params)}"
@@ -120,6 +146,79 @@ def _raise_if_auth_error(error_message: str) -> None:
raise FinnworldsAuthError(f"Finnworlds authentication failed: {error_message}")
+def _flatten_nested(row: dict[str, Any]) -> dict[str, Any]:
+ """Merge one level of nested objects into the row, prefixing their keys with the object name."""
+ flat: dict[str, Any] = {}
+ for key, value in row.items():
+ if isinstance(value, dict):
+ for nested_key, nested_value in value.items():
+ flat[f"{key}_{nested_key}"] = nested_value
+ else:
+ flat[key] = value
+ return flat
+
+
+def _insider_owner_fields(owner: dict[str, Any]) -> dict[str, Any]:
+ owner_id = owner.get("owner_id")
+ owner_id = owner_id if isinstance(owner_id, dict) else {}
+ role = owner.get("owner_role")
+ role = role if isinstance(role, dict) else {}
+ return {
+ "owner_cik": owner_id.get("owner_cik"),
+ "owner_name": owner_id.get("name"),
+ "owner_is_director": role.get("is_director"),
+ "owner_is_officer": role.get("is_officer"),
+ "owner_is_ten_percent_owner": role.get("is_ten_percent_owner"),
+ "owner_is_other": role.get("is_other"),
+ "owner_title": role.get("insider"),
+ }
+
+
+def _insider_filing_rows(payload: dict[str, Any]) -> list[dict[str, Any]]:
+ """Expand SEC Form 4 filings into one row per reported transaction line.
+
+ A date range can return either one filing object or a list of them, so both are accepted. Joint
+ filers report the same lines, so a line is emitted once per reporting owner. The line index runs
+ across the whole response, because the API exposes no filing identifier to separate two filings
+ that share a period and an owner.
+ """
+ result = payload.get("result")
+ filings = result if isinstance(result, list) else [result]
+
+ rows: list[dict[str, Any]] = []
+ index = 0
+ for filing in filings:
+ if not isinstance(filing, dict):
+ continue
+ owners = [owner for owner in filing.get("reporting_owner") or [] if isinstance(owner, dict)] or [{}]
+ period_of_report = filing.get("period_of_report")
+
+ for table in ("non_derivative_table", "derivative_table"):
+ entries = filing.get(table)
+ if not isinstance(entries, list):
+ continue
+ for entry in entries:
+ if not isinstance(entry, dict):
+ continue
+ # Derivative lines wrap the transaction in a "derivatives" object; non-derivative ones don't.
+ inner = entry.get("derivatives", entry)
+ if not isinstance(inner, dict):
+ continue
+ line = _flatten_nested(inner)
+ index += 1
+ rows.extend(
+ {
+ **line,
+ **_insider_owner_fields(owner),
+ "period_of_report": period_of_report,
+ "transaction_table": table.removesuffix("_table"),
+ "transaction_index": index,
+ }
+ for owner in owners
+ )
+ return rows
+
+
def _extract_rows(payload: dict[str, Any], config: FinnworldsEndpointConfig) -> list[dict[str, Any]]:
result = payload.get("result", {})
result = result if isinstance(result, dict) else {}
@@ -136,6 +235,8 @@ def _extract_rows(payload: dict[str, Any], config: FinnworldsEndpointConfig) ->
rows = output if isinstance(output, list) else []
elif config.response_mode == ResponseMode.RESULT_KEY:
rows = result.get(config.data_key, []) if config.data_key else []
+ elif config.response_mode == ResponseMode.INSIDER_FILING:
+ rows = _insider_filing_rows(payload)
else: # TOP_LEVEL
rows = payload.get(config.data_key, []) if config.data_key else []
@@ -145,16 +246,16 @@ def _extract_rows(payload: dict[str, Any], config: FinnworldsEndpointConfig) ->
def _normalize_row(
- row: dict[str, Any], config: FinnworldsEndpointConfig, ticker: str | None, period: str | None
+ row: dict[str, Any], config: FinnworldsEndpointConfig, identifier: str | None, period: str | None
) -> dict[str, Any]:
"""Flatten configured nested objects and inject the identifiers the primary key relies on."""
for nested_key in config.flatten_keys:
nested = row.pop(nested_key, None)
if isinstance(nested, dict):
- # Injected ticker/period below take precedence, so merge the nested object first.
+ # Injected identifier/period below take precedence, so merge the nested object first.
row = {**nested, **row}
- if config.requires_ticker and ticker is not None:
- row["ticker"] = ticker
+ if config.fanout != FanoutDimension.NONE and identifier is not None:
+ row[config.fanout.value] = identifier
if config.include_period:
row["period"] = period or "annual"
return row
@@ -164,12 +265,12 @@ def _fetch_endpoint_rows(
session: requests.Session,
config: FinnworldsEndpointConfig,
api_key: str,
- ticker: str | None,
+ identifier: str | None,
logger: FilteringBoundLogger,
) -> list[dict[str, Any]]:
params: dict[str, str] = {"key": api_key}
- if ticker is not None:
- params["ticker"] = ticker
+ if identifier is not None:
+ params[config.fanout.value] = identifier
url = _build_url(config.path, params)
payload = _fetch(session, url, logger)
@@ -180,7 +281,7 @@ def _fetch_endpoint_rows(
# A non-auth error usually means "no data for this identifier" or a tier-gated endpoint; skip
# the identifier rather than failing the whole sync.
logger.warning(
- f"Finnworlds {config.name}: skipping ticker={ticker} due to API error: {error_message}",
+ f"Finnworlds {config.name}: skipping {config.fanout.value}={identifier} due to API error: {error_message}",
)
return []
@@ -193,18 +294,19 @@ def _fetch_endpoint_rows(
# The primary key for fundamentals is (ticker, period, date); without a real period every row
# falls back to "annual", which would silently merge quarterly rows. Surface it when it happens.
logger.warning(
- f"Finnworlds {config.name}: no period in response for ticker={ticker}; "
+ f"Finnworlds {config.name}: no period in response for ticker={identifier}; "
"defaulting to 'annual' (quarterly rows may collide on the primary key)",
)
rows = _extract_rows(payload, config)
- return [_normalize_row(row, config, ticker, period) for row in rows]
+ return [_normalize_row(row, config, identifier, period) for row in rows]
def get_rows(
api_key: str,
endpoint: str,
tickers: list[str],
+ countries: list[str],
logger: FilteringBoundLogger,
) -> Iterator[list[dict[str, Any]]]:
config = FINNWORLDS_ENDPOINTS[endpoint]
@@ -212,16 +314,20 @@ def get_rows(
# rides in the query string, so redact it from logged URLs and captured samples.
session = make_tracked_session(redact_values=(api_key,))
- if not config.requires_ticker:
+ if config.fanout == FanoutDimension.NONE:
rows = _fetch_endpoint_rows(session, config, api_key, None, logger)
if rows:
yield rows
return
- for ticker in tickers:
- rows = _fetch_endpoint_rows(session, config, api_key, ticker, logger)
+ identifiers = tickers if config.fanout == FanoutDimension.TICKER else countries
+ if not identifiers:
+ logger.warning(f"Finnworlds {config.name}: no {config.fanout.value} configured, so nothing to sync")
+
+ for identifier in identifiers:
+ rows = _fetch_endpoint_rows(session, config, api_key, identifier, logger)
if rows:
- # Yield one batch per ticker; the pipeline buffers and re-batches across tickers.
+ # Yield one batch per identifier; the pipeline buffers and re-batches across them.
yield rows
@@ -259,13 +365,14 @@ def finnworlds_source(
api_key: str,
endpoint: str,
tickers: list[str],
+ countries: list[str],
logger: FilteringBoundLogger,
) -> SourceResponse:
config = FINNWORLDS_ENDPOINTS[endpoint]
return SourceResponse(
name=endpoint,
- items=lambda: get_rows(api_key=api_key, endpoint=endpoint, tickers=tickers, logger=logger),
+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, tickers=tickers, countries=countries, logger=logger),
primary_keys=config.primary_keys,
partition_count=1,
partition_size=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/settings.py
index 8a3fabf25357..ec9bca3004f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/settings.py
@@ -3,6 +3,17 @@ from enum import StrEnum
from typing import Optional
+class FanoutDimension(StrEnum):
+ """The identifier a full sync iterates to cover an endpoint."""
+
+ # One request per configured ticker (most endpoints are keyed on a single company).
+ TICKER = "ticker"
+ # One request per configured country (macroeconomic indicators are keyed on a country).
+ COUNTRY = "country"
+ # A single request returns the whole dataset (bond yields).
+ NONE = "none"
+
+
class ResponseMode(StrEnum):
"""How rows are extracted from a Finnworlds JSON response.
@@ -21,19 +32,21 @@ class ResponseMode(StrEnum):
OUTPUT_BARE = "output_bare"
# result[<data_key>] is a list of records (analyst/company ratings live under result.analysts).
RESULT_KEY = "result_key"
+ # result is an SEC Form 4 document (or a list of them); rows are its transaction lines.
+ INSIDER_FILING = "insider_filing"
# <data_key> is a top-level list, outside the result envelope (SEC filings).
TOP_LEVEL = "top_level"
-@dataclass
+@dataclass(frozen=True)
class FinnworldsEndpointConfig:
name: str # warehouse table name (and ExternalDataSchema.name)
path: str # API path segment under https://api.finnworlds.com/api/v1/
response_mode: ResponseMode
data_key: Optional[str] = None # array/object key for OUTPUT_ARRAY / RESULT_KEY / TOP_LEVEL
# Most endpoints return data for a single identifier per call, so a full sync fans out over the
- # user's ticker list. Endpoints that return a global list (bond yields) set this False.
- requires_ticker: bool = True
+ # identifiers the user configured. The fan-out value is injected onto every row.
+ fanout: FanoutDimension = FanoutDimension.TICKER
# Inject result.basics.period into each row so fundamentals from different reporting periods don't
# collide on the (ticker, period, date) primary key.
include_period: bool = False
@@ -129,11 +142,34 @@ FINNWORLDS_ENDPOINTS: dict[str, FinnworldsEndpointConfig] = {
primary_keys=["ticker", "url"],
partition_key="date",
),
+ "company_identifiers": FinnworldsEndpointConfig(
+ name="company_identifiers",
+ path="identifiers",
+ response_mode=ResponseMode.OUTPUT_OBJECT,
+ primary_keys=["ticker"],
+ ),
+ "insider_transactions": FinnworldsEndpointConfig(
+ name="insider_transactions",
+ path="insidertransactions",
+ response_mode=ResponseMode.INSIDER_FILING,
+ # Transaction lines repeat security, date and code, and a ticker can file more than once in a
+ # period, so the line's position in the whole response is what separates them.
+ primary_keys=["ticker", "period_of_report", "owner_cik", "transaction_table", "transaction_index"],
+ partition_key="activity_date",
+ ),
+ "macroeconomic_indicators": FinnworldsEndpointConfig(
+ name="macroeconomic_indicators",
+ path="macroindicator",
+ response_mode=ResponseMode.OUTPUT_BARE,
+ fanout=FanoutDimension.COUNTRY,
+ primary_keys=["country", "report_name", "report_date"],
+ should_sync_default=False,
+ ),
"bond_yields": FinnworldsEndpointConfig(
name="bond_yields",
path="bonds",
response_mode=ResponseMode.OUTPUT_BARE,
- requires_ticker=False,
+ fanout=FanoutDimension.NONE,
primary_keys=["country", "type", "datetime"],
partition_key="datetime",
should_sync_default=False,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/source.py
index 455306d50210..a592f363bbd6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/source.py
@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.finnworlds import (
finnworlds_source,
+ parse_countries,
parse_tickers,
validate_credentials as validate_finnworlds_credentials,
)
@@ -89,6 +90,7 @@ class FinnworldsSource(SimpleSource[FinnworldsSourceConfig]):
) -> tuple[bool, str | None]:
try:
parse_tickers(config.tickers)
+ parse_countries(config.countries)
except ValueError as exc:
return False, str(exc)
@@ -99,6 +101,7 @@ class FinnworldsSource(SimpleSource[FinnworldsSourceConfig]):
api_key=config.api_key,
endpoint=inputs.schema_name,
tickers=parse_tickers(config.tickers),
+ countries=parse_countries(config.countries),
logger=inputs.logger,
)
@@ -113,7 +116,9 @@ class FinnworldsSource(SimpleSource[FinnworldsSourceConfig]):
You can find your API key in your [Finnworlds dashboard](https://finnworlds.com/dashboard/).
-Most datasets (fundamentals, prices, dividends, ratings) return data for one company per request, so enter the stock tickers you want to sync — the connector fetches each dataset for every ticker. Bond yields are global and ignore the ticker list.""",
+Most datasets (fundamentals, prices, dividends, ratings) return data for one company per request, so enter the stock tickers you want to sync — the connector fetches each dataset for every ticker. Bond yields are global and ignore the ticker list.
+
+Macroeconomic indicators are reported per country, so add the countries you want before you sync that table.""",
iconPath="/static/services/finnworlds.png",
docsUrl="https://posthog.com/docs/cdp/sources/finnworlds",
fields=cast(
@@ -131,10 +136,18 @@ Most datasets (fundamentals, prices, dividends, ratings) return data for one com
name="tickers",
label="Tickers",
type=SourceFieldInputConfigType.TEXTAREA,
- required=True,
+ required=False,
placeholder="AAPL, MSFT, GOOGL",
secret=False,
),
+ SourceFieldInputConfig(
+ name="countries",
+ label="Countries for macroeconomic indicators",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=False,
+ placeholder="United States, United Kingdom, Germany",
+ secret=False,
+ ),
],
),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds.py
index b84bcd49be5a..910aa88fc0ba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds.py
@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds
_payload_error,
finnworlds_source,
get_rows,
+ parse_countries,
parse_tickers,
validate_credentials,
)
@@ -79,6 +80,29 @@ class TestParseTickers:
parse_tickers(raw)
+class TestParseCountries:
+ @parameterized.expand(
+ [
+ ("comma_separated", "United_States,Germany", ["United_States", "Germany"]),
+ ("newline_separated", "United_States\nGermany", ["United_States", "Germany"]),
+ ("spaces_become_underscores", "United Kingdom, Germany", ["United_Kingdom", "Germany"]),
+ ("keeps_user_spelling", "germany", ["germany"]),
+ ("dedupes_case_insensitively", "Germany, germany", ["Germany"]),
+ ("strips_whitespace", " Germany ", ["Germany"]),
+ ("empty_string", "", []),
+ ("none", None, []),
+ ("only_separators", " , , ", []),
+ ]
+ )
+ def test_parse_countries(self, _name: str, raw: str | None, expected: list[str]) -> None:
+ assert parse_countries(raw) == expected
+
+ def test_over_max_countries_is_rejected(self) -> None:
+ raw = ",".join(f"Country{i}" for i in range(finnworlds.MAX_COUNTRIES + 1))
+ with pytest.raises(ValueError, match="Too many countries"):
+ parse_countries(raw)
+
+
class TestBuildUrl:
def test_includes_key_and_ticker(self) -> None:
url = _build_url("incomestatements", {"key": "secret", "ticker": "AAPL"})
@@ -186,7 +210,7 @@ class TestGetRows:
session = _session_returning(*responses)
with pytest.MonkeyPatch.context() as mp:
mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)
- batches = list(get_rows("key", "dividends", ["AAPL", "MSFT"], _logger()))
+ batches = list(get_rows("key", "dividends", ["AAPL", "MSFT"], [], _logger()))
assert len(batches) == 2
assert batches[0][0]["ticker"] == "AAPL"
@@ -196,7 +220,7 @@ class TestGetRows:
session = _session_returning(_response({"result": {"output": [{"country": "US", "type": "10Y"}]}}))
with pytest.MonkeyPatch.context() as mp:
mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)
- batches = list(get_rows("key", "bond_yields", ["AAPL"], _logger()))
+ batches = list(get_rows("key", "bond_yields", ["AAPL"], [], _logger()))
assert session.get.call_count == 1
assert batches == [[{"country": "US", "type": "10Y"}]]
@@ -206,7 +230,7 @@ class TestGetRows:
with pytest.MonkeyPatch.context() as mp:
mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)
with pytest.raises(FinnworldsAuthError):
- list(get_rows("bad", "dividends", ["AAPL"], _logger()))
+ list(get_rows("bad", "dividends", ["AAPL"], [], _logger()))
def test_non_auth_error_skips_ticker(self) -> None:
# First ticker has no data (non-auth error), second succeeds — the sync continues.
@@ -218,7 +242,7 @@ class TestGetRows:
logger = _logger()
with pytest.MonkeyPatch.context() as mp:
mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)
- batches = list(get_rows("key", "dividends", ["AAPL", "MSFT"], logger))
+ batches = list(get_rows("key", "dividends", ["AAPL", "MSFT"], [], logger))
assert len(batches) == 1
assert batches[0][0]["ticker"] == "MSFT"
@@ -228,7 +252,7 @@ class TestGetRows:
session = _session_returning()
with pytest.MonkeyPatch.context() as mp:
mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)
- batches = list(get_rows("key", "dividends", [], _logger()))
+ batches = list(get_rows("key", "dividends", [], [], _logger()))
assert batches == []
session.get.assert_not_called()
@@ -301,7 +325,7 @@ class TestFinnworldsSource:
@parameterized.expand([(name,) for name in FINNWORLDS_ENDPOINTS])
def test_source_response_primary_keys_and_partitioning(self, endpoint: str) -> None:
config: FinnworldsEndpointConfig = FINNWORLDS_ENDPOINTS[endpoint]
- response = finnworlds_source("key", endpoint, ["AAPL"], _logger())
+ response = finnworlds_source("key", endpoint, ["AAPL"], ["United_States"], _logger())
assert response.name == endpoint
assert response.primary_keys == config.primary_keys
@@ -327,3 +351,194 @@ class TestFinnworldsSource:
def test_all_response_modes_are_covered_by_an_endpoint(self) -> None:
used = {c.response_mode for c in FINNWORLDS_ENDPOINTS.values()}
assert used == set(ResponseMode)
+
+
+def _insider_payload(**overrides: Any) -> dict[str, Any]:
+ filing: dict[str, Any] = {
+ "period_of_report": "2025-08-21",
+ "reporting_owner": [
+ {
+ "owner_id": {"owner_cik": "1000001", "name": "Doe Jane"},
+ "owner_role": {
+ "is_director": 0,
+ "is_officer": 1,
+ "is_ten_percent_owner": 0,
+ "is_other": 0,
+ "insider": "Senior Vice President",
+ },
+ }
+ ],
+ "non_derivative_table": [
+ {
+ "security": "Common Stock",
+ "activity_date": "2025-08-21",
+ "transaction": {"code": "M", "equity_swap": "0"},
+ "transaction_amounts": {"shares": "8760", "share_per_price": "0", "acquired_disposed_code": "A"},
+ "post_transaction": {"holding": "55790"},
+ "ownership_nature": {"direct_or_indirect": "D", "ownership": ""},
+ },
+ {
+ "security": "Common Stock",
+ "activity_date": "2025-08-21",
+ "transaction": {"code": "M", "equity_swap": "0"},
+ "transaction_amounts": {"shares": "3940", "share_per_price": "0", "acquired_disposed_code": "A"},
+ "post_transaction": {"holding": "59730"},
+ "ownership_nature": {"direct_or_indirect": "D", "ownership": ""},
+ },
+ ],
+ "derivative_table": [
+ {
+ "derivatives": {
+ "security": "Restricted Stock Unit Award",
+ "activity_date": "2025-08-21",
+ "transaction": {"code": "M", "equity_swap": "0"},
+ "transaction_amounts": {"shares": "8760", "acquired_disposed_code": "D"},
+ "post_transaction": {"shares_owned": "17540"},
+ }
+ }
+ ],
+ "footnotes": [{"id": "F1", "text": "Rule 10b5-1 trading plan."}],
+ }
+ filing.update(overrides)
+ return {"status": {"code": 200, "message": "OK"}, "result": filing}
+
+
+class TestInsiderTransactions:
+ def test_expands_every_transaction_line(self) -> None:
+ rows = _extract_rows(_insider_payload(), FINNWORLDS_ENDPOINTS["insider_transactions"])
+
+ assert [(r["transaction_table"], r["transaction_index"]) for r in rows] == [
+ ("non_derivative", 1),
+ ("non_derivative", 2),
+ ("derivative", 3),
+ ]
+
+ def test_flattens_nested_transaction_objects(self) -> None:
+ rows = _extract_rows(_insider_payload(), FINNWORLDS_ENDPOINTS["insider_transactions"])
+
+ first = rows[0]
+ assert first["transaction_code"] == "M"
+ assert first["transaction_amounts_shares"] == "8760"
+ assert first["post_transaction_holding"] == "55790"
+ assert first["ownership_nature_direct_or_indirect"] == "D"
+ assert first["activity_date"] == "2025-08-21"
+
+ def test_unwraps_the_derivative_wrapper(self) -> None:
+ rows = _extract_rows(_insider_payload(), FINNWORLDS_ENDPOINTS["insider_transactions"])
+
+ derivative = rows[-1]
+ assert derivative["security"] == "Restricted Stock Unit Award"
+ assert derivative["post_transaction_shares_owned"] == "17540"
+ assert "derivatives" not in derivative
+
+ def test_carries_the_reporting_owner_and_period(self) -> None:
+ rows = _extract_rows(_insider_payload(), FINNWORLDS_ENDPOINTS["insider_transactions"])
+
+ assert rows[0]["owner_cik"] == "1000001"
+ assert rows[0]["owner_name"] == "Doe Jane"
+ assert rows[0]["owner_is_officer"] == 1
+ assert rows[0]["owner_title"] == "Senior Vice President"
+ assert rows[0]["period_of_report"] == "2025-08-21"
+
+ def test_joint_filers_each_get_a_row(self) -> None:
+ payload = _insider_payload(
+ reporting_owner=[
+ {"owner_id": {"owner_cik": "1", "name": "First Filer"}},
+ {"owner_id": {"owner_cik": "2", "name": "Second Filer"}},
+ ]
+ )
+ rows = _extract_rows(payload, FINNWORLDS_ENDPOINTS["insider_transactions"])
+
+ assert len(rows) == 6
+ assert {r["owner_cik"] for r in rows} == {"1", "2"}
+
+ def test_a_date_range_returning_several_filings(self) -> None:
+ # A single filing comes back as an object; a range can come back as a list of them.
+ payload = {"result": [_insider_payload()["result"], _insider_payload(period_of_report="2025-09-02")["result"]]}
+ rows = _extract_rows(payload, FINNWORLDS_ENDPOINTS["insider_transactions"])
+
+ assert len(rows) == 6
+ assert {r["period_of_report"] for r in rows} == {"2025-08-21", "2025-09-02"}
+
+ def test_primary_key_separates_every_row_of_a_filing(self) -> None:
+ # Lines in one filing repeat security, date and code, so without the line position they
+ # would collapse into a single row.
+ config = FINNWORLDS_ENDPOINTS["insider_transactions"]
+ rows = [_normalize_row(row, config, "AAPL", None) for row in _extract_rows(_insider_payload(), config)]
+
+ keys = {tuple(row[key] for key in config.primary_keys) for row in rows}
+ assert len(keys) == len(rows)
+
+ def test_primary_key_separates_two_filings_sharing_a_period_and_owner(self) -> None:
+ # The API exposes no filing identifier, so a ticker that files twice in one period would
+ # collide if the line index restarted per filing.
+ config = FINNWORLDS_ENDPOINTS["insider_transactions"]
+ payload = {"result": [_insider_payload()["result"], _insider_payload()["result"]]}
+ rows = [_normalize_row(row, config, "AAPL", None) for row in _extract_rows(payload, config)]
+
+ keys = {tuple(row[key] for key in config.primary_keys) for row in rows}
+ assert len(rows) == 6
+ assert len(keys) == 6
+
+ @parameterized.expand(
+ [
+ ("missing_result", {}),
+ ("result_is_a_string", {"result": "nope"}),
+ ("tables_wrong_shape", {"result": {"non_derivative_table": "nope", "derivative_table": None}}),
+ ("entries_not_objects", {"result": {"non_derivative_table": ["nope"]}}),
+ ]
+ )
+ def test_malformed_filings_degrade_gracefully(self, _name: str, payload: dict) -> None:
+ assert _extract_rows(payload, FINNWORLDS_ENDPOINTS["insider_transactions"]) == []
+
+
+class TestCompanyIdentifiers:
+ def test_emits_one_row_keeping_the_previous_names(self) -> None:
+ payload = {
+ "result": {
+ "basics": {"ticker": "AAPL"},
+ "output": {
+ "name": "Apple Inc.",
+ "cik": "320193",
+ "isin": "US0378331005",
+ "previous_names": [{"name": "APPLE COMPUTER INC", "from": "1994-01-26"}],
+ },
+ }
+ }
+ config = FINNWORLDS_ENDPOINTS["company_identifiers"]
+ rows = [_normalize_row(row, config, "AAPL", None) for row in _extract_rows(payload, config)]
+
+ assert len(rows) == 1
+ assert rows[0]["ticker"] == "AAPL"
+ assert rows[0]["cik"] == "320193"
+ assert rows[0]["previous_names"] == [{"name": "APPLE COMPUTER INC", "from": "1994-01-26"}]
+
+
+class TestCountryFanout:
+ def test_macro_requests_one_country_per_call_and_injects_it(self) -> None:
+ responses = [
+ _response({"result": {"output": [{"report_name": "Business Confidence", "actual": "-33"}]}}),
+ _response({"result": {"output": [{"report_name": "Business Confidence", "actual": "12"}]}}),
+ ]
+ session = _session_returning(*responses)
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)
+ batches = list(
+ get_rows("key", "macroeconomic_indicators", ["AAPL"], ["United_Kingdom", "Germany"], _logger())
+ )
+
+ requested = [call.args[0] for call in session.get.call_args_list]
+ assert "country=United_Kingdom" in requested[0]
+ assert "ticker=" not in requested[0]
+ assert [batch[0]["country"] for batch in batches] == ["United_Kingdom", "Germany"]
+
+ def test_no_countries_configured_makes_no_requests(self) -> None:
+ session = _session_returning()
+ logger = _logger()
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)
+ batches = list(get_rows("key", "macroeconomic_indicators", ["AAPL"], [], logger))
+
+ assert batches == []
+ session.get.assert_not_called()
+ logger.warning.assert_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds_source.py
index 66e5c0319ab1..7ebd14669a1c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds_source.py
@@ -4,7 +4,10 @@ import pytest
from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds import source as source_module
-from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.finnworlds import MAX_TICKERS
+from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.finnworlds import (
+ MAX_COUNTRIES,
+ MAX_TICKERS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.settings import (
ENDPOINTS,
FINNWORLDS_ENDPOINTS,
@@ -26,7 +29,7 @@ class TestFinnworldsSource:
def setup_method(self) -> None:
self.source = FinnworldsSource()
self.team_id = 123
- self.config = FinnworldsSourceConfig(api_key="fw-test", tickers="AAPL, MSFT")
+ self.config = FinnworldsSourceConfig(api_key="fw-test", tickers="AAPL, MSFT", countries="United Kingdom")
def test_lists_tables_without_credentials(self) -> None:
assert self.source.lists_tables_without_credentials is True
@@ -44,8 +47,10 @@ class TestFinnworldsSource:
def test_get_schemas_respects_should_sync_default(self) -> None:
schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
- # Bond yields fan out globally and are heavier, so they're off by default.
+ # Bond yields fan out globally and are heavier, so they're off by default. Macroeconomic
+ # indicators need countries configured, which the ticker-only setup does not have.
assert schemas["bond_yields"].should_sync_default is False
+ assert schemas["macroeconomic_indicators"].should_sync_default is False
assert schemas["dividends"].should_sync_default is True
def test_get_schemas_filtered_by_names(self) -> None:
@@ -82,6 +87,27 @@ class TestFinnworldsSource:
assert "Too many tickers" in message
probe.assert_not_called()
+ def test_validate_credentials_rejects_oversized_country_list(self) -> None:
+ config = FinnworldsSourceConfig(
+ api_key="fw-test", tickers="AAPL", countries=",".join(f"Country{i}" for i in range(MAX_COUNTRIES + 1))
+ )
+ with mock.patch.object(source_module, "validate_finnworlds_credentials") as probe:
+ ok, message = self.source.validate_credentials(config, self.team_id)
+ assert ok is False
+ assert message is not None
+ assert "Too many countries" in message
+ probe.assert_not_called()
+
+ def test_a_macro_only_source_needs_no_tickers(self) -> None:
+ config = FinnworldsSourceConfig(api_key="fw-test", countries="Germany")
+ inputs = _make_inputs(schema_name="macroeconomic_indicators")
+ with mock.patch.object(source_module, "finnworlds_source") as mocked:
+ self.source.source_for_pipeline(config, inputs)
+
+ _, kwargs = mocked.call_args
+ assert kwargs["tickers"] == []
+ assert kwargs["countries"] == ["Germany"]
+
def test_source_for_pipeline_plumbs_parsed_tickers(self) -> None:
inputs = _make_inputs(schema_name="dividends")
with mock.patch.object(source_module, "finnworlds_source") as mocked:
@@ -92,4 +118,5 @@ class TestFinnworldsSource:
assert kwargs["api_key"] == "fw-test"
assert kwargs["endpoint"] == "dividends"
assert kwargs["tickers"] == ["AAPL", "MSFT"]
+ assert kwargs["countries"] == ["United_Kingdom"]
assert kwargs["logger"] is inputs.logger
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/finnworlds.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/finnworlds.py
index c982d2ab9878..5a2b999405da 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/finnworlds.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/finnworlds.py
@@ -7,4 +7,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class FinnworldsSourceConfig(config.Config):
api_key: str
- tickers: str
+ tickers: str | None = None
+ countries: str | None = None