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): add seven Financial Modeling Prep tables (#107698)

Tom Owers4c849a394246
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 72a1bc9caec8..88b6951f3b59 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
@@ -3087,7 +3087,7 @@ Note: The docs are a client-rendered playground, but the full endpoint catalog i
## FinancialModelling — **thin**
-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`
+Today (21): `available_exchanges`, `available_industries`, `available_sectors`, `balance_sheet_statements`, `cash_flow_statements`, `company_profiles`, `dividends`, `dividends_calendar`, `earnings`, `earnings_calendar`, `historical_market_capitalization`, `historical_prices`, `income_statements`, `institutional_positions_summary`, `key_metrics`, `key_metrics_ttm`, `market_capitalization`, `ratios`, `ratios_ttm`, `splits`, `stock_list`
Diffed against: <https://site.financialmodelingprep.com/developer/docs/stable>
@@ -3095,16 +3095,16 @@ Diffed against: <https://site.financialmodelingprep.com/developer/docs/stable>
- [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)
+- [x] `/stable/splits` — split history, required to make historical_prices comparable across time (high). Added as `splits`.
+- [x] `/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). Added as `available_exchanges`, `available_sectors` and `available_industries`.
+- [x] `/stable/historical-market-capitalization (and /stable/market-capitalization)` — market cap time series, the standard size dimension for any equity analysis (medium). Added as `historical_market_capitalization` (incremental on `date`) and `market_capitalization` (current snapshot per symbol).
- [ ] `/stable/analyst-estimates and /stable/price-target-consensus` — forward estimates and consensus targets to compare against reported results (medium)
- [ ] `/stable/quote (and batch-quote)` — current price snapshot without pulling full historical series (medium)
-- [ ] `/stable/institutional-ownership/extract and /symbol-positions-summary` — 13F institutional holdings per symbol and per holder (medium)
+- [x] `/stable/institutional-ownership/extract and /symbol-positions-summary` — 13F institutional holdings per symbol and per holder (medium). Added as `institutional_positions_summary` from `/symbol-positions-summary`; `/institutional-ownership/extract` is keyed on a filer's `cik` with no `symbol` parameter, so it is not reachable from the ticker list the source is configured with and was skipped.
- [ ] `/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 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.
+Note: The stable docs page lists ~230 endpoints; PostHog exposes 21. None of the key-metrics, ratios, dividends or earnings paths 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. Of the later additions, only `/historical-market-capitalization` takes `from`/`to`, so it is the one that syncs incrementally on `date`; `/splits`, `/market-capitalization` and the three `available-*` lookups are full refresh. `/symbol-positions-summary` requires `year` and `quarter`, so it is fetched once per symbol per quarter over the last eight completed quarters and ships off by default. 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.py
index 2e7c21664d8b..f4aeb60fdb7d 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
@@ -185,4 +185,82 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"paymentDate": "Date the dividend is paid.",
},
},
+ "available_exchanges": {
+ "description": "Every stock exchange Financial Modeling Prep supports, resolving the exchange codes carried on stock_list and company_profiles.",
+ "docs_url": _DOCS,
+ "columns": {
+ "exchange": "Short exchange code, as it appears on stock_list and company_profiles.",
+ "name": "Full name of the exchange.",
+ "countryName": "Country the exchange operates in.",
+ "countryCode": "ISO country code of the exchange.",
+ "symbolSuffix": "Suffix appended to symbols traded on this exchange.",
+ "delay": "Delay applied to this exchange's price data.",
+ },
+ },
+ "available_sectors": {
+ "description": "Every sector classification Financial Modeling Prep assigns, resolving the sector values on company_profiles.",
+ "docs_url": _DOCS,
+ "columns": {
+ "sector": "Sector name, as it appears on company_profiles.",
+ },
+ },
+ "available_industries": {
+ "description": "Every industry classification Financial Modeling Prep assigns, resolving the industry values on company_profiles.",
+ "docs_url": _DOCS,
+ "columns": {
+ "industry": "Industry name, as it appears on company_profiles.",
+ },
+ },
+ "splits": {
+ "description": "Stock split history per symbol. Needed to compare historical_prices across a split.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol the split applies to.",
+ "date": "Date the split took effect.",
+ "numerator": "New shares issued for every `denominator` shares held.",
+ "denominator": "Shares held that the `numerator` shares replace.",
+ },
+ },
+ "market_capitalization": {
+ "description": "Current market capitalization per symbol: one always-current row, replaced on every sync.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol the valuation belongs to.",
+ "date": "Date the market capitalization was observed.",
+ "marketCap": "Market capitalization in the reporting currency.",
+ },
+ },
+ "historical_market_capitalization": {
+ "description": "Daily market capitalization history per symbol, the standard size dimension for equity analysis.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol the valuation belongs to.",
+ "date": "Date the market capitalization was observed.",
+ "marketCap": "Market capitalization in the reporting currency on that date.",
+ },
+ },
+ "institutional_positions_summary": {
+ "description": "Institutional 13F holdings summarized per symbol and calendar quarter: how many institutions hold the symbol, the shares and value they hold, and how both moved since the previous quarter.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol the holdings are in.",
+ "cik": "SEC Central Index Key of the company the symbol belongs to.",
+ "date": "End date of the reporting quarter.",
+ "investorsHolding": "Number of institutions reporting a position in the quarter.",
+ "investorsHoldingChange": "Change in the number of institutions holding since the previous quarter.",
+ "numberOf13Fshares": "Total shares held across all reported 13F positions.",
+ "numberOf13FsharesChange": "Change in total shares held since the previous quarter.",
+ "totalInvested": "Total value of the reported positions.",
+ "totalInvestedChange": "Change in total value since the previous quarter.",
+ "ownershipPercent": "Share of the company held by institutions, as a percentage.",
+ "ownershipPercentChange": "Change in institutional ownership percentage since the previous quarter.",
+ "newPositions": "Positions opened during the quarter.",
+ "increasedPositions": "Positions increased during the quarter.",
+ "reducedPositions": "Positions reduced during the quarter.",
+ "closedPositions": "Positions closed during the quarter.",
+ "totalCalls": "Total call options held across the reported positions.",
+ "totalPuts": "Total put options held across the reported positions.",
+ "putCallRatio": "Ratio of puts to calls held across the reported positions.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/financial_modelling.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/financial_modelling.py
index e185d87783a6..335a9d7fe1f9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/financial_modelling.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/financial_modelling.py
@@ -8,6 +8,8 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -168,6 +170,35 @@ def _window_params(
return {"from": from_date.isoformat(), "to": today.isoformat()}
+@frozen
+class _FiscalQuarter:
+ year: int
+ quarter: int
+
+
+def _recent_quarters(count: int, today: date) -> list[_FiscalQuarter]:
+ """The `count` most recently completed calendar quarters, newest first."""
+ year, quarter = today.year, (today.month - 1) // 3 + 1
+ quarters: list[_FiscalQuarter] = []
+ for _ in range(count):
+ quarter -= 1
+ if quarter == 0:
+ year, quarter = year - 1, 4
+ quarters.append(_FiscalQuarter(year=year, quarter=quarter))
+ return quarters
+
+
+def _period_params(config: FinancialModellingEndpointConfig) -> list[dict[str, str]]:
+ """One params overlay per request a symbol needs — a single empty overlay unless the endpoint
+ only answers for one quarter at a time."""
+ if not config.quarters_lookback:
+ return [{}]
+ return [
+ {"year": str(period.year), "quarter": str(period.quarter)}
+ for period in _recent_quarters(config.quarters_lookback, datetime.now(UTC).date())
+ ]
+
+
def get_rows(
api_key: str,
endpoint: str,
@@ -188,15 +219,18 @@ def get_rows(
if start_index:
logger.debug(f"Financial Modeling Prep: resuming {endpoint} from symbol index {start_index}")
+ periods = _period_params(config)
+
for offset, symbol in enumerate(symbols[start_index:]):
index = start_index + offset
- params: dict[str, Any] = {"symbol": symbol, **config.extra_params, **window}
- data = _fetch_page(session, config.path, params, api_key, logger)
- for row in _extract_rows(data, config.response_key):
- row.setdefault("symbol", symbol)
- batcher.batch(row)
- if batcher.should_yield():
- yield batcher.get_table()
+ for period in periods:
+ params: dict[str, Any] = {"symbol": symbol, **config.extra_params, **window, **period}
+ data = _fetch_page(session, config.path, params, api_key, logger)
+ for row in _extract_rows(data, config.response_key):
+ row.setdefault("symbol", symbol)
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
# Flush this symbol's rows before advancing the bookmark, so a crash re-fetches only from
# the next symbol (whose rows are not yet persisted) rather than dropping buffered rows.
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.py
index 25e01eb76e64..1ad3faebaeb1 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
@@ -1,6 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# Financial Modeling Prep "stable" API host. The legacy `/api/v3/` paths still work, but every
@@ -12,8 +14,13 @@ FINANCIAL_MODELLING_BASE_URL = "https://financialmodelingprep.com/stable"
# Left off, FMP falls back to a handful of records and silently truncates the symbol's history.
FINANCIAL_MODELLING_MAX_LIMIT = "1000"
+# 13F endpoints are scoped to one calendar quarter per request, so a symbol's series is built by
+# asking for each quarter in turn. Eight covers two years without multiplying the request count
+# past what a small key can afford.
+FINANCIAL_MODELLING_QUARTERS_LOOKBACK = 8
+
-@dataclass
+@frozen
class FinancialModellingEndpointConfig:
name: str
# Path under FINANCIAL_MODELLING_BASE_URL (no leading slash).
@@ -37,6 +44,9 @@ class FinancialModellingEndpointConfig:
response_key: Optional[str] = None
# First incremental sync is bounded to the last N days so we don't pull unbounded history in one go.
default_lookback_days: Optional[int] = None
+ # Set on endpoints that only answer for one calendar quarter at a time: the fan-out issues one
+ # request per symbol per quarter, walking back this many completed quarters.
+ quarters_lookback: Optional[int] = None
should_sync_default: bool = True
@@ -181,6 +191,71 @@ FINANCIAL_MODELLING_ENDPOINTS: dict[str, FinancialModellingEndpointConfig] = {
supports_date_window=True,
default_lookback_days=365 * 2,
),
+ # Lookup resolving the exchange codes carried on stock_list and company_profiles. One bounded
+ # market-wide request, no parameters.
+ "available_exchanges": FinancialModellingEndpointConfig(
+ name="available_exchanges",
+ path="available-exchanges",
+ primary_keys=["exchange"],
+ ),
+ # Lookup of every sector classification company_profiles can report.
+ "available_sectors": FinancialModellingEndpointConfig(
+ name="available_sectors",
+ path="available-sectors",
+ primary_keys=["sector"],
+ ),
+ # Lookup of every industry classification company_profiles can report.
+ "available_industries": FinancialModellingEndpointConfig(
+ name="available_industries",
+ path="available-industries",
+ primary_keys=["industry"],
+ ),
+ # Split history per symbol (split date and ratio). Needed to compare historical_prices across a
+ # split. Takes `symbol` and `limit` but no `from`/`to`, so full refresh.
+ "splits": FinancialModellingEndpointConfig(
+ name="splits",
+ path="splits",
+ primary_keys=["symbol", "date"],
+ fan_out_over_symbols=True,
+ partition_key="date",
+ extra_params={"limit": FINANCIAL_MODELLING_MAX_LIMIT},
+ ),
+ # Current market capitalization: one always-current row per symbol, so it is keyed on the symbol
+ # alone and replaced in full on every sync (same shape as the TTM endpoints).
+ "market_capitalization": FinancialModellingEndpointConfig(
+ name="market_capitalization",
+ path="market-capitalization",
+ primary_keys=["symbol"],
+ fan_out_over_symbols=True,
+ ),
+ # Daily market capitalization history per symbol. Honors `from`/`to`, so this syncs incrementally
+ # on the observation `date`. `limit` still has to be sent: it defaults to 100 and would otherwise
+ # truncate the window. The endpoint has no page cursor, so the first window must stay inside
+ # `limit` rows — a wider one silently drops its oldest days, and the watermark then skips past
+ # them forever.
+ "historical_market_capitalization": FinancialModellingEndpointConfig(
+ name="historical_market_capitalization",
+ path="historical-market-capitalization",
+ primary_keys=["symbol", "date"],
+ fan_out_over_symbols=True,
+ partition_key="date",
+ incremental_fields=_date_incremental_fields(),
+ supports_date_window=True,
+ extra_params={"limit": FINANCIAL_MODELLING_MAX_LIMIT},
+ default_lookback_days=365 * 2,
+ ),
+ # 13F institutional holdings summarized per symbol and quarter: how many institutions hold the
+ # symbol, the share and value changes, and the ownership percentage. Off by default because it
+ # costs one request per symbol per quarter, which a rate-limited key feels immediately.
+ "institutional_positions_summary": FinancialModellingEndpointConfig(
+ name="institutional_positions_summary",
+ path="institutional-ownership/symbol-positions-summary",
+ primary_keys=["symbol", "date"],
+ fan_out_over_symbols=True,
+ partition_key="date",
+ quarters_lookback=FINANCIAL_MODELLING_QUARTERS_LOOKBACK,
+ should_sync_default=False,
+ ),
}
ENDPOINTS = tuple(FINANCIAL_MODELLING_ENDPOINTS.keys())
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.py
index f45555b0b5a0..d46f692d4a06 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
@@ -1,3 +1,4 @@
+from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any
@@ -15,6 +16,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.financial_
_build_url,
_extract_rows,
_fetch_page,
+ _FiscalQuarter,
+ _recent_quarters,
_to_date,
_window_params,
financial_modelling_source,
@@ -147,6 +150,31 @@ class TestWindowParams:
assert params["from"] == "2022-06-16"
+def _quarters(*pairs: tuple[int, int]) -> list[_FiscalQuarter]:
+ return [_FiscalQuarter(year=year, quarter=quarter) for year, quarter in pairs]
+
+
+class TestRecentQuarters:
+ @parameterized.expand(
+ [
+ # The quarter `today` falls in is still open, so the walk starts at the one before it.
+ ("mid_q2", date(2024, 5, 20), ((2024, 1), (2023, 4), (2023, 3))),
+ ("first_day_of_q1_rolls_back_a_year", date(2024, 1, 1), ((2023, 4), (2023, 3), (2023, 2))),
+ ("last_day_of_q4", date(2024, 12, 31), ((2024, 3), (2024, 2), (2024, 1))),
+ ]
+ )
+ def test_walks_back_from_the_last_completed_quarter(
+ self, _name: str, today: date, expected: tuple[tuple[int, int], ...]
+ ) -> None:
+ assert _recent_quarters(3, today) == _quarters(*expected)
+
+ def test_spans_multiple_year_boundaries(self) -> None:
+ quarters = _recent_quarters(8, date(2024, 5, 20))
+ assert quarters[0] == _FiscalQuarter(year=2024, quarter=1)
+ assert quarters[-1] == _FiscalQuarter(year=2022, quarter=2)
+ assert len(set(quarters)) == 8
+
+
class _FakeResumableManager:
def __init__(self, state: FinancialModellingResumeConfig | None = None) -> None:
self._state = state
@@ -163,53 +191,52 @@ class _FakeResumableManager:
def _collect(
- endpoint: str, symbols: list[str], manager: _FakeResumableManager, monkeypatch: Any, by_symbol: dict[str, Any]
+ endpoint: str, symbols: list[str], manager: _FakeResumableManager, by_symbol: dict[str, Any]
) -> list[dict]:
def fake_fetch(session: Any, path: str, params: dict[str, Any], api_key: str, logger: Any) -> Any:
key = params.get("symbol", path)
return by_symbol[key]
- monkeypatch.setattr(financial_modelling, "_fetch_page", fake_fetch)
-
rows: list[dict] = []
- for table in get_rows(
- api_key="k",
- endpoint=endpoint,
- symbols=symbols,
- logger=MagicMock(),
- resumable_source_manager=manager, # type: ignore[arg-type]
- ):
- rows.extend(table.to_pylist())
+ with patch.object(financial_modelling, "_fetch_page", fake_fetch):
+ for table in get_rows(
+ api_key="k",
+ endpoint=endpoint,
+ symbols=symbols,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(table.to_pylist())
return rows
class TestGetRowsFanOut:
- def test_fans_out_over_each_symbol_and_injects_symbol(self, monkeypatch: Any) -> None:
+ def test_fans_out_over_each_symbol_and_injects_symbol(self) -> None:
by_symbol = {
"AAPL": [{"symbol": "AAPL", "companyName": "Apple"}],
"MSFT": [{"symbol": "MSFT", "companyName": "Microsoft"}],
}
- rows = _collect("company_profiles", ["AAPL", "MSFT"], _FakeResumableManager(), monkeypatch, by_symbol)
+ rows = _collect("company_profiles", ["AAPL", "MSFT"], _FakeResumableManager(), by_symbol)
assert {r["symbol"] for r in rows} == {"AAPL", "MSFT"}
- def test_symbol_injected_when_missing_from_row(self, monkeypatch: Any) -> None:
+ def test_symbol_injected_when_missing_from_row(self) -> None:
# historical_prices rows arrive without a symbol; the fan-out injects it.
by_symbol = {"AAPL": {"symbol": "AAPL", "historical": [{"date": "2024-01-02", "close": 10}]}}
- rows = _collect("historical_prices", ["AAPL"], _FakeResumableManager(), monkeypatch, by_symbol)
+ rows = _collect("historical_prices", ["AAPL"], _FakeResumableManager(), by_symbol)
assert rows == [{"date": "2024-01-02", "close": 10, "symbol": "AAPL"}]
- def test_saves_resume_state_advancing_per_symbol(self, monkeypatch: Any) -> None:
+ def test_saves_resume_state_advancing_per_symbol(self) -> None:
manager = _FakeResumableManager()
by_symbol = {
"AAPL": [{"symbol": "AAPL"}],
"MSFT": [{"symbol": "MSFT"}],
"GOOGL": [{"symbol": "GOOGL"}],
}
- _collect("company_profiles", ["AAPL", "MSFT", "GOOGL"], manager, monkeypatch, by_symbol)
+ _collect("company_profiles", ["AAPL", "MSFT", "GOOGL"], manager, by_symbol)
# State is saved after every symbol except the last (no point bookmarking past the end).
assert [s.symbol_index for s in manager.saved] == [1, 2]
- def test_resumes_from_saved_symbol_index(self, monkeypatch: Any) -> None:
+ def test_resumes_from_saved_symbol_index(self) -> None:
manager = _FakeResumableManager(FinancialModellingResumeConfig(symbol_index=1))
fetched: list[str] = []
@@ -217,16 +244,16 @@ class TestGetRowsFanOut:
fetched.append(params["symbol"])
return [{"symbol": params["symbol"]}]
- monkeypatch.setattr(financial_modelling, "_fetch_page", fake_fetch)
- list(
- get_rows(
- api_key="k",
- endpoint="company_profiles",
- symbols=["AAPL", "MSFT", "GOOGL"],
- logger=MagicMock(),
- resumable_source_manager=manager, # type: ignore[arg-type]
+ with patch.object(financial_modelling, "_fetch_page", fake_fetch):
+ list(
+ get_rows(
+ api_key="k",
+ endpoint="company_profiles",
+ symbols=["AAPL", "MSFT", "GOOGL"],
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
)
- )
# AAPL (index 0) is skipped because the bookmark resumes at index 1.
assert fetched == ["MSFT", "GOOGL"]
@@ -252,13 +279,32 @@ class TestGetRowsRequestParams:
)
return captured
- @parameterized.expand([("key_metrics",), ("ratios",), ("dividends",), ("earnings",)])
+ @parameterized.expand(
+ [
+ ("key_metrics",),
+ ("ratios",),
+ ("dividends",),
+ ("earnings",),
+ ("splits",),
+ ("historical_market_capitalization",),
+ ]
+ )
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",)])
+ @parameterized.expand(
+ [
+ ("key_metrics",),
+ ("ratios",),
+ ("dividends",),
+ ("earnings",),
+ ("key_metrics_ttm",),
+ ("splits",),
+ ("market_capitalization",),
+ ]
+ )
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(
@@ -272,14 +318,99 @@ class TestGetRowsRequestParams:
def test_ttm_endpoint_sends_only_the_symbol(self) -> None:
assert self._params_for("key_metrics_ttm") == {"symbol": "AAPL"}
+ def test_market_cap_history_keeps_the_limit_alongside_the_window(self) -> None:
+ # The endpoint's `limit` defaults to 100, so dropping it would truncate the requested window
+ # rather than fail.
+ params = self._params_for(
+ "historical_market_capitalization",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-01-01",
+ )
+ assert params["from"] == "2024-01-01"
+ assert params["limit"] == "1000"
+
+ @parameterized.expand([("company_profiles",), ("splits",), ("market_capitalization",)])
+ def test_non_quarterly_endpoints_send_no_period(self, endpoint: str) -> None:
+ params = self._params_for(endpoint)
+ assert "year" not in params
+ assert "quarter" not in params
+
+
+class TestWindowFitsInsideTheLimit:
+ @parameterized.expand(
+ [
+ (name,)
+ for name, config in FINANCIAL_MODELLING_ENDPOINTS.items()
+ if config.default_lookback_days is not None and "limit" in config.extra_params
+ ]
+ )
+ def test_first_window_cannot_outgrow_the_page(self, endpoint: str) -> None:
+ # These endpoints do not paginate, so a lookback wider than `limit` rows silently drops the
+ # oldest days and the watermark then skips past them for good.
+ config = FINANCIAL_MODELLING_ENDPOINTS[endpoint]
+ assert config.default_lookback_days is not None
+ assert config.default_lookback_days <= int(config.extra_params["limit"])
+
+
+class TestGetRowsQuarterFanOut:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self) -> Iterator[None]:
+ with time_machine.travel("2024-06-15", tick=False):
+ yield
+
+ def _requests_for(self, endpoint: str, symbols: list[str], manager: _FakeResumableManager) -> list[dict[str, Any]]:
+ captured: list[dict[str, Any]] = []
+
+ def fake_fetch(session: Any, path: str, params: dict[str, Any], api_key: str, logger: Any) -> Any:
+ captured.append(dict(params))
+ return []
+
+ with patch.object(financial_modelling, "_fetch_page", fake_fetch):
+ list(
+ get_rows(
+ api_key="k",
+ endpoint=endpoint,
+ symbols=symbols,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+ return captured
+
+ def test_requests_every_quarter_for_every_symbol(self) -> None:
+ # The endpoint answers for one quarter at a time, so a missing quarter is a silent hole in
+ # the series rather than an error.
+ requests_made = self._requests_for("institutional_positions_summary", ["AAPL", "MSFT"], _FakeResumableManager())
+ quarters = FINANCIAL_MODELLING_ENDPOINTS["institutional_positions_summary"].quarters_lookback
+ assert quarters is not None
+ assert len(requests_made) == 2 * quarters
+ assert {(r["symbol"], r["year"], r["quarter"]) for r in requests_made[:2]} == {
+ ("AAPL", "2024", "1"),
+ ("AAPL", "2023", "4"),
+ }
+
+ def test_bookmark_advances_once_per_symbol_not_per_quarter(self) -> None:
+ # Resume state indexes symbols; saving per quarter would skip the rest of a symbol's series
+ # after an interruption.
+ manager = _FakeResumableManager()
+ self._requests_for("institutional_positions_summary", ["AAPL", "MSFT", "GOOGL"], manager)
+ assert [state.symbol_index for state in manager.saved] == [1, 2]
+
class TestGetRowsMarketWide:
- def test_single_request_no_symbol(self, monkeypatch: Any) -> None:
+ @parameterized.expand(
+ [
+ ("earnings_calendar", "earnings-calendar", {"symbol": "AAPL", "date": "2024-01-01"}),
+ ("available_exchanges", "available-exchanges", {"exchange": "AMEX", "name": "NYSE Arca"}),
+ ("available_sectors", "available-sectors", {"sector": "Basic Materials"}),
+ ("available_industries", "available-industries", {"industry": "Steel"}),
+ ]
+ )
+ def test_single_request_no_symbol(self, endpoint: str, path: str, row: dict[str, Any]) -> None:
+ # These endpoints take no symbol, so the row must not gain one and no bookmark is saved.
manager = _FakeResumableManager()
- by_path = {"earnings-calendar": [{"symbol": "AAPL", "date": "2024-01-01"}]}
- rows = _collect("earnings_calendar", [], manager, monkeypatch, by_path)
- assert rows == [{"symbol": "AAPL", "date": "2024-01-01"}]
- # Market-wide endpoints fan out over nothing, so no resume bookmark is saved.
+ rows = _collect(endpoint, [], manager, {path: [row]})
+ assert rows == [row]
assert manager.saved == []
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.py
index 478c71ed2a2c..f84373b25fb7 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
@@ -52,6 +52,13 @@ class TestGetSchemas:
("historical_prices", True),
("earnings_calendar", True),
("dividends_calendar", True),
+ ("available_exchanges", False),
+ ("available_sectors", False),
+ ("available_industries", False),
+ ("splits", False),
+ ("market_capitalization", False),
+ ("historical_market_capitalization", True),
+ ("institutional_positions_summary", False),
]
)
def test_incremental_support_matches_date_window(self, endpoint: str, expected_incremental: bool) -> None:
@@ -60,6 +67,13 @@ class TestGetSchemas:
# supports_append tracks incremental here (date-windowed endpoints can append).
assert schemas[endpoint].supports_append is expected_incremental
+ def test_request_amplifying_table_is_off_by_default(self) -> None:
+ # One request per symbol per quarter would exhaust a small key on the first sync, so the
+ # user opts in rather than out.
+ schemas = {s.name: s for s in FinancialModellingSource().get_schemas(MagicMock(), team_id=1)}
+ assert schemas["institutional_positions_summary"].should_sync_default is False
+ assert schemas["splits"].should_sync_default is True
+
def test_names_filter(self) -> None:
schemas = FinancialModellingSource().get_schemas(MagicMock(), team_id=1, names=["historical_prices"])
assert [s.name for s in schemas] == ["historical_prices"]