: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(financial-modelling): add key metrics, ratios, dividends and earnings tables (#107406)
Tom Owers84aa3a99e37d
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.mdindex 2e833b223335..0c7441d4b9ad 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@@ -3086,14 +3086,14 @@ Note: The docs are a client-rendered playground, but the full endpoint catalog i## FinancialModelling — **thin**-Today (8): `balance_sheet_statements`, `cash_flow_statements`, `company_profiles`, `dividends_calendar`, `earnings_calendar`, `historical_prices`, `income_statements`, `stock_list`+Today (14): `balance_sheet_statements`, `cash_flow_statements`, `company_profiles`, `dividends`, `dividends_calendar`, `earnings`, `earnings_calendar`, `historical_prices`, `income_statements`, `key_metrics`, `key_metrics_ttm`, `ratios`, `ratios_ttm`, `stock_list`Diffed against: <https://site.financialmodelingprep.com/developer/docs/stable>-- [ ] `/stable/key-metrics (and key-metrics-ttm)` — FMP's headline per-company metric set; nothing equivalent is synced today (high)-- [ ] `/stable/ratios (and ratios-ttm)` — valuation and profitability ratios derived from the statements we already sync (high)-- [ ] `/stable/dividends` — actual per-symbol dividend history; only the forward dividends_calendar is synced (high)-- [ ] `/stable/earnings` — historical actual vs estimated EPS and revenue per symbol; only the forward earnings_calendar is synced (high)+- [x] `/stable/key-metrics (and key-metrics-ttm)` — FMP's headline per-company metric set; nothing equivalent is synced today (high). Added as `key_metrics` (annual periods) and `key_metrics_ttm` (one current row per symbol).+- [x] `/stable/ratios (and ratios-ttm)` — valuation and profitability ratios derived from the statements we already sync (high). Added as `ratios` and `ratios_ttm`.+- [x] `/stable/dividends` — actual per-symbol dividend history; only the forward dividends_calendar is synced (high). Added as `dividends`.+- [x] `/stable/earnings` — historical actual vs estimated EPS and revenue per symbol; only the forward earnings_calendar is synced (high). Added as `earnings`.- [ ] `/stable/splits` — split history, required to make historical_prices comparable across time (high)- [ ] `/stable/available-exchanges, /stable/available-sectors, /stable/available-industries` — lookup tables resolving the exchange, sector and industry codes carried on stock_list and company_profiles (high)- [ ] `/stable/historical-market-capitalization (and /stable/market-capitalization)` — market cap time series, the standard size dimension for any equity analysis (medium)@@ -3103,7 +3103,7 @@ Diffed against: <https://site.financialmodelingprep.com/developer/docs/stable>- [ ] `/stable/insider-trading/search and /insider-trading/statistics` — insider transaction records, a widely used signal table (medium)- [ ] `/stable/revenue-product-segmentation and /stable/revenue-geographic-segmentation` — revenue breakdown dimensions that the income statement alone cannot provide (medium)-Note: The stable docs page lists ~230 endpoints; PostHog exposes 8. Other sizeable untapped families: financial-growth and \*-growth, enterprise-values, DCF endpoints, financial-scores, grades/ratings-historical, SEC filings search, ETF and fund holdings, economic-indicators and treasury-rates, congressional trading, index constituents, news, technical indicators, and the \*-bulk endpoints that would make warehouse-scale loads far cheaper. financialmodelingprep.com/stable/openapi.json exists but returns 401 without a key, and the site 403s default curl user agents - a browser UA on the docs page returns the full endpoint list.+Note: The stable docs page lists ~230 endpoints; PostHog exposes 14. None of the six paths added above accept a `from`/`to` filter — they take `symbol`, `limit` (capped at 1000, no page cursor) and, on the non-TTM pair, `period` — so all six sync as full refresh. The TTM endpoints return a single always-current row per symbol with no fiscal date, so they are keyed on `symbol` alone and carry no partition key. Other sizeable untapped families: financial-growth and \*-growth, enterprise-values, DCF endpoints, financial-scores, grades/ratings-historical, SEC filings search, ETF and fund holdings, economic-indicators and treasury-rates, congressional trading, index constituents, news, technical indicators, and the \*-bulk endpoints that would make warehouse-scale loads far cheaper. financialmodelingprep.com/stable/openapi.json exists but returns 401 without a key, and the site 403s default curl user agents - a browser UA on the docs page returns the full endpoint list.## Finnhub — **thin**diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/canonical_descriptions.pyindex eddc4998a4a7..2e7c21664d8b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/canonical_descriptions.py@@ -68,6 +68,87 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"reportedCurrency": "Currency the statement is reported in.",},},+ "key_metrics": {+ "description": "Headline financial metrics per symbol and fiscal period: market cap, enterprise value, returns and yields.",+ "docs_url": _DOCS,+ "columns": {+ "symbol": "Ticker symbol the metrics belong to.",+ "date": "Fiscal-period end date the metrics cover.",+ "fiscalYear": "Fiscal year the period falls in.",+ "period": "Reporting period of the metrics (annual).",+ "marketCap": "Market capitalization at the period end.",+ "enterpriseValue": "Enterprise value at the period end.",+ "returnOnEquity": "Net income divided by shareholder equity, as a fraction.",+ "freeCashFlowYield": "Free cash flow divided by market capitalization, as a fraction.",+ },+ },+ "ratios": {+ "description": "Valuation, profitability, liquidity and leverage ratios per symbol and fiscal period.",+ "docs_url": _DOCS,+ "columns": {+ "symbol": "Ticker symbol the ratios belong to.",+ "date": "Fiscal-period end date the ratios cover.",+ "fiscalYear": "Fiscal year the period falls in.",+ "period": "Reporting period of the ratios (annual).",+ "grossProfitMargin": "Gross profit divided by revenue, as a fraction.",+ "operatingProfitMargin": "Operating income divided by revenue, as a fraction.",+ "netProfitMargin": "Net income divided by revenue, as a fraction.",+ "currentRatio": "Current assets divided by current liabilities.",+ "returnOnEquity": "Net income divided by shareholder equity, as a fraction.",+ },+ },+ "key_metrics_ttm": {+ "description": "Trailing twelve-month key metrics per symbol. One always-current row per symbol, replaced on every sync.",+ "docs_url": _DOCS,+ "columns": {+ "symbol": "Ticker symbol the metrics belong to.",+ "marketCap": "Current market capitalization.",+ "enterpriseValueTTM": "Enterprise value over the trailing twelve months.",+ "returnOnEquityTTM": "Return on equity over the trailing twelve months, as a fraction.",+ "freeCashFlowYieldTTM": "Free cash flow yield over the trailing twelve months, as a fraction.",+ "currentRatioTTM": "Current assets divided by current liabilities over the trailing twelve months.",+ },+ },+ "ratios_ttm": {+ "description": "Trailing twelve-month financial ratios per symbol. One always-current row per symbol, replaced on every sync.",+ "docs_url": _DOCS,+ "columns": {+ "symbol": "Ticker symbol the ratios belong to.",+ "grossProfitMarginTTM": "Gross profit margin over the trailing twelve months, as a fraction.",+ "operatingProfitMarginTTM": "Operating profit margin over the trailing twelve months, as a fraction.",+ "netProfitMarginTTM": "Net profit margin over the trailing twelve months, as a fraction.",+ "currentRatioTTM": "Current assets divided by current liabilities over the trailing twelve months.",+ "returnOnEquityTTM": "Return on equity over the trailing twelve months, as a fraction.",+ },+ },+ "dividends": {+ "description": "Dividend history for each symbol you sync, including the amount, yield and the record, payment and declaration dates.",+ "docs_url": _DOCS,+ "columns": {+ "symbol": "Ticker symbol paying the dividend.",+ "date": "Ex-dividend date.",+ "dividend": "Dividend amount per share.",+ "adjDividend": "Dividend amount per share, adjusted for splits.",+ "yield": "Dividend yield at the ex-dividend date, as a fraction.",+ "frequency": "How often the dividend is paid (for example quarterly or annually).",+ "recordDate": "Date used to determine shareholders eligible for the dividend.",+ "paymentDate": "Date the dividend is paid.",+ "declarationDate": "Date the company announced the dividend.",+ },+ },+ "earnings": {+ "description": "Reported earnings per symbol: actual against estimated earnings per share and revenue for each announcement.",+ "docs_url": _DOCS,+ "columns": {+ "symbol": "Ticker symbol reporting earnings.",+ "date": "Date of the earnings announcement.",+ "epsActual": "Reported earnings per share, empty until the announcement.",+ "epsEstimated": "Consensus estimated earnings per share.",+ "revenueActual": "Reported revenue, empty until the announcement.",+ "revenueEstimated": "Consensus estimated revenue.",+ "lastUpdated": "When Financial Modeling Prep last changed the row.",+ },+ },"historical_prices": {"description": "End-of-day OHLCV price history per symbol, filtered server-side by trading date.","docs_url": _DOCS,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/settings.pyindex df641def4927..25e01eb76e64 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/settings.py@@ -8,6 +8,10 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment# to every request (see financial_modelling.py).FINANCIAL_MODELLING_BASE_URL = "https://financialmodelingprep.com/stable"+# Endpoints that accept `limit` cap it at 1000 and offer no page cursor, so ask for the maximum.+# Left off, FMP falls back to a handful of records and silently truncates the symbol's history.+FINANCIAL_MODELLING_MAX_LIMIT = "1000"+@dataclassclass FinancialModellingEndpointConfig:@@ -88,6 +92,61 @@ FINANCIAL_MODELLING_ENDPOINTS: dict[str, FinancialModellingEndpointConfig] = {partition_key="date",extra_params={"period": "annual"},),+ # FMP's headline per-company metric set (market cap, enterprise value, returns, yields) per+ # fiscal period. Takes `limit` and `period` but no `from`/`to`, so it is full refresh.+ "key_metrics": FinancialModellingEndpointConfig(+ name="key_metrics",+ path="key-metrics",+ primary_keys=["symbol", "date", "period"],+ fan_out_over_symbols=True,+ partition_key="date",+ extra_params={"period": "annual", "limit": FINANCIAL_MODELLING_MAX_LIMIT},+ ),+ # Valuation, profitability, liquidity and leverage ratios per fiscal period. Same shape and+ # parameters as key_metrics.+ "ratios": FinancialModellingEndpointConfig(+ name="ratios",+ path="ratios",+ primary_keys=["symbol", "date", "period"],+ fan_out_over_symbols=True,+ partition_key="date",+ extra_params={"period": "annual", "limit": FINANCIAL_MODELLING_MAX_LIMIT},+ ),+ # Trailing-twelve-month snapshot of the key metrics. One always-current row per symbol with no+ # fiscal `date`, so it is keyed on the symbol alone and replaced in full on every sync.+ "key_metrics_ttm": FinancialModellingEndpointConfig(+ name="key_metrics_ttm",+ path="key-metrics-ttm",+ primary_keys=["symbol"],+ fan_out_over_symbols=True,+ ),+ # Trailing-twelve-month snapshot of the ratios. Same one-row-per-symbol shape as key_metrics_ttm.+ "ratios_ttm": FinancialModellingEndpointConfig(+ name="ratios_ttm",+ path="ratios-ttm",+ primary_keys=["symbol"],+ fan_out_over_symbols=True,+ ),+ # Actual dividend history per symbol (ex-date, record, payment, amount, yield). Unlike the+ # market-wide dividends_calendar it takes no `from`/`to`, so it is full refresh.+ "dividends": FinancialModellingEndpointConfig(+ name="dividends",+ path="dividends",+ primary_keys=["symbol", "date"],+ fan_out_over_symbols=True,+ partition_key="date",+ extra_params={"limit": FINANCIAL_MODELLING_MAX_LIMIT},+ ),+ # Reported earnings per symbol: actual vs estimated EPS and revenue. The market-wide+ # earnings_calendar covers the forward schedule; this is the per-symbol history behind it.+ "earnings": FinancialModellingEndpointConfig(+ name="earnings",+ path="earnings",+ primary_keys=["symbol", "date"],+ fan_out_over_symbols=True,+ partition_key="date",+ extra_params={"limit": FINANCIAL_MODELLING_MAX_LIMIT},+ ),# End-of-day OHLCV history per symbol. Honors `from`/`to`, so this is the one symbol-keyed# endpoint we sync incrementally on the trading `date`."historical_prices": FinancialModellingEndpointConfig(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.pyindex 988802637b95..f45555b0b5a0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.py@@ -3,7 +3,7 @@ from typing import Anyimport pytestimport time_machine-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patchimport requestsfrom parameterized import parameterized@@ -231,6 +231,48 @@ class TestGetRowsFanOut:assert fetched == ["MSFT", "GOOGL"]+class TestGetRowsRequestParams:+ def _params_for(self, endpoint: str, **kwargs: Any) -> dict[str, Any]:+ captured: dict[str, Any] = {}++ def fake_fetch(session: Any, path: str, params: dict[str, Any], api_key: str, logger: Any) -> Any:+ captured.update(params)+ return []++ with patch.object(financial_modelling, "_fetch_page", fake_fetch):+ list(+ get_rows(+ api_key="k",+ endpoint=endpoint,+ symbols=["AAPL"],+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ **kwargs,+ )+ )+ return captured++ @parameterized.expand([("key_metrics",), ("ratios",), ("dividends",), ("earnings",)])+ def test_requests_the_maximum_page_size(self, endpoint: str) -> None:+ # These endpoints have no page cursor, so dropping `limit` truncates the symbol's history+ # to FMP's small default instead of failing.+ assert self._params_for(endpoint)["limit"] == "1000"++ @parameterized.expand([("key_metrics",), ("ratios",), ("dividends",), ("earnings",), ("key_metrics_ttm",)])+ def test_no_date_window_is_sent(self, endpoint: str) -> None:+ # None of these accept `from`/`to`, so a watermark must not leak into the query.+ params = self._params_for(+ endpoint,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-01-01",+ )+ assert "from" not in params+ assert "to" not in params++ def test_ttm_endpoint_sends_only_the_symbol(self) -> None:+ assert self._params_for("key_metrics_ttm") == {"symbol": "AAPL"}++class TestGetRowsMarketWide:def test_single_request_no_symbol(self, monkeypatch: Any) -> None:manager = _FakeResumableManager()@@ -262,6 +304,13 @@ class TestFinancialModellingSourceResponse:[("stock_list", ["symbol"]),("income_statements", ["symbol", "date", "period"]),+ ("key_metrics", ["symbol", "date", "period"]),+ ("ratios", ["symbol", "date", "period"]),+ # The TTM endpoints return one always-current row per symbol, with no fiscal date.+ ("key_metrics_ttm", ["symbol"]),+ ("ratios_ttm", ["symbol"]),+ ("dividends", ["symbol", "date"]),+ ("earnings", ["symbol", "date"]),("historical_prices", ["symbol", "date"]),("earnings_calendar", ["symbol", "date"]),]@@ -287,10 +336,11 @@ class TestFinancialModellingSourceResponse:assert response.partition_mode == "datetime"assert response.partition_keys == ["date"]- def test_unpartitioned_endpoint_has_no_partitioning(self) -> None:+ @parameterized.expand([("company_profiles",), ("key_metrics_ttm",), ("ratios_ttm",)])+ def test_unpartitioned_endpoint_has_no_partitioning(self, endpoint: str) -> None:response = financial_modelling_source(api_key="k",- endpoint="company_profiles",+ endpoint=endpoint,symbols=["AAPL"],logger=MagicMock(),resumable_source_manager=MagicMock(),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling_source.pyindex 48cab0e42819..478c71ed2a2c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling_source.py@@ -43,6 +43,12 @@ class TestGetSchemas:("stock_list", False),("company_profiles", False),("income_statements", False),+ ("key_metrics", False),+ ("ratios", False),+ ("key_metrics_ttm", False),+ ("ratios_ttm", False),+ ("dividends", False),+ ("earnings", False),("historical_prices", True),("earnings_calendar", True),("dividends_calendar", True),