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(finnhub): add candle, filing, insider and financials tables (#107411)

Tom Owerse539c8734005
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 fe36e67dfda8..2e3d4ea358cc 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
@@ -3108,14 +3108,14 @@ Note: The stable docs page lists ~230 endpoints; PostHog exposes 14. None of the
## Finnhub — **thin**
-Today (11): `basic_financials`, `company_news`, `company_profile`, `country`, `earnings_calendar`, `earnings_surprises`, `ipo_calendar`, `market_news`, `quote`, `recommendation_trends`, `stock_symbols`
+Today (15): `basic_financials`, `company_news`, `company_profile`, `country`, `earnings_calendar`, `earnings_surprises`, `financials_reported`, `insider_transactions`, `ipo_calendar`, `market_news`, `quote`, `recommendation_trends`, `sec_filings`, `stock_candles`, `stock_symbols`
Diffed against: <https://finnhub.io/static/swagger.json>
-- [ ] `/stock/financials-reported` — full as-reported income statement, balance sheet and cash flow per filing; basic_financials only gives ratios (high)
-- [ ] `/stock/candle` — historical OHLCV bars, the backbone of any price time-series analysis (quote is a point-in-time snapshot only) (high)
-- [ ] `/stock/filings` — SEC filing index per symbol, the join key from company to disclosure documents (high)
-- [ ] `/stock/insider-transactions` — insider buy/sell transaction rows, a headline alt-data signal (high)
+- [x] `/stock/financials-reported` — full as-reported income statement, balance sheet and cash flow per filing; basic_financials only gives ratios (high)
+- [x] `/stock/candle` — historical OHLCV bars, the backbone of any price time-series analysis (quote is a point-in-time snapshot only) (high)
+- [x] `/stock/filings` — SEC filing index per symbol, the join key from company to disclosure documents (high)
+- [x] `/stock/insider-transactions` — insider buy/sell transaction rows, a headline alt-data signal (high)
- [ ] `/stock/dividend` — dividend history transactions; nothing in the current table set carries payouts (high)
- [ ] `/stock/peers` — lookup table resolving each synced symbol to its comparable set for benchmarking (high)
- [ ] `/stock/price-target` — analyst price targets, a natural companion to recommendation_trends which is already synced (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/canonical_descriptions.py
index 7d4e66829e7d..d9939ba1c5be 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/canonical_descriptions.py
@@ -161,4 +161,62 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"year": "Fiscal year.",
},
},
+ "financials_reported": {
+ "description": "Financial statements exactly as reported in a company's annual SEC filing.",
+ "docs_url": "https://finnhub.io/docs/api/financials-reported",
+ "columns": {
+ "symbol": "Company ticker.",
+ "cik": "SEC Central Index Key of the filer.",
+ "accessNumber": "SEC accession number of the filing the report comes from.",
+ "year": "Fiscal year the report covers.",
+ "quarter": "Fiscal quarter the report covers.",
+ "form": "Filing form type (e.g. 10-K).",
+ "startDate": "Start of the reporting period.",
+ "endDate": "End of the reporting period.",
+ "filedDate": "Date the filing was submitted to the SEC.",
+ "acceptedDate": "Date the SEC accepted the filing.",
+ "report": "Object holding the as-reported balance sheet (bs), cash flow (cf) and income statement (ic) line items.",
+ },
+ },
+ "stock_candles": {
+ "description": "Daily open/high/low/close/volume candles for a company, adjusted for splits.",
+ "docs_url": "https://finnhub.io/docs/api/stock-candles",
+ "columns": {
+ "symbol": "Requested ticker the candles were fetched for.",
+ "t": "Start of the candle as a Unix timestamp (seconds).",
+ "o": "Open price.",
+ "h": "High price.",
+ "l": "Low price.",
+ "c": "Close price.",
+ "v": "Volume traded.",
+ },
+ },
+ "sec_filings": {
+ "description": "Index of a company's SEC filings, with links to each document.",
+ "docs_url": "https://finnhub.io/docs/api/filings",
+ "columns": {
+ "symbol": "Company ticker.",
+ "cik": "SEC Central Index Key of the filer.",
+ "accessNumber": "SEC accession number identifying the filing.",
+ "form": "Filing form type (e.g. 10-K, 8-K).",
+ "filedDate": "Date the filing was submitted to the SEC.",
+ "acceptedDate": "Date the SEC accepted the filing.",
+ "reportUrl": "URL of the rendered report.",
+ "filingUrl": "URL of the filing on EDGAR.",
+ },
+ },
+ "insider_transactions": {
+ "description": "Insider buy and sell transactions reported on Form 3, 4 and 5.",
+ "docs_url": "https://finnhub.io/docs/api/insider-transactions",
+ "columns": {
+ "symbol": "Company ticker.",
+ "name": "Name of the insider.",
+ "share": "Number of shares the insider held after the transaction.",
+ "change": "Change in shares. Positive is a buy, negative is a sell.",
+ "filingDate": "Date the transaction was filed.",
+ "transactionDate": "Date the transaction took place.",
+ "transactionPrice": "Average price per share of the transaction.",
+ "transactionCode": "SEC Form 4 transaction code (e.g. P for purchase, S for sale).",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py
index bb8ef648cdce..36e55e1b722a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py
@@ -29,6 +29,16 @@ class FinnhubRetryableError(Exception):
"""Raised for 429 / 5xx responses so tenacity backs off and retries."""
+class FinnhubRowCapExceededError(Exception):
+ """Raised when a windowed response hits Finnhub's documented per-request row cap.
+
+ These endpoints (sec_filings, insider_transactions) have no pagination, so a response at
+ the cap means the API silently dropped the rest of the window. Continuing would let the
+ incremental cursor advance past the missing rows and permanently skip them, so the sync
+ fails loudly here instead of checkpointing incomplete data.
+ """
+
+
def _headers(api_key: str) -> dict[str, str]:
return {"X-Finnhub-Token": api_key, "Accept": "application/json"}
@@ -105,8 +115,23 @@ def _fetch(session: requests.Session, path: str, params: dict[str, Any], logger:
return response.json()
+def _expand_columnar(data: Any) -> list[dict[str, Any]]:
+ """Zip Finnhub's parallel candle arrays (o/h/l/c/v/t) back into one row per bar."""
+ if not isinstance(data, dict) or data.get("s") != "ok":
+ # `s` is "no_data" when the symbol has no bars in the window.
+ return []
+ columns = {key: value for key, value in data.items() if isinstance(value, list)}
+ if not columns:
+ return []
+ # Defend against a short array leaving a row half-populated.
+ length = min(len(values) for values in columns.values())
+ return [{key: values[index] for key, values in columns.items()} for index in range(length)]
+
+
def _extract_rows(data: Any, config: FinnhubEndpointConfig) -> list[dict[str, Any]]:
"""Normalize a Finnhub response into a list of row dicts per the endpoint's shape."""
+ if config.columnar:
+ return _expand_columnar(data)
if config.single_object:
# Snapshot endpoints (quote/profile/metric) return a single object. Finnhub returns an
# empty object for an unknown symbol, which we skip.
@@ -127,6 +152,10 @@ def _window(config: FinnhubEndpointConfig, last_value: Any) -> SyncWindow[str]:
return SyncWindow(start=start.isoformat(), end=end.isoformat())
+def _to_epoch(iso_date: str) -> int:
+ return int(datetime.fromisoformat(iso_date).replace(tzinfo=UTC).timestamp())
+
+
def _request_params(
config: FinnhubEndpointConfig,
symbol: str | None,
@@ -145,8 +174,15 @@ def _request_params(
# endpoints (calendars) always sweep the full rolling window.
last_value = db_incremental_field_last_value if should_use_incremental_field else None
window = _window(config, last_value)
- params["from"] = window.start
- params["to"] = window.end
+ if config.epoch_window:
+ # Candles take UNIX seconds. Rounding the watermark down to midnight also re-fetches
+ # the day it fell in, so a bar captured before the session closed is replaced by the
+ # settled one rather than kept at its intraday value.
+ params["from"] = _to_epoch(window.start)
+ params["to"] = _to_epoch(window.end)
+ else:
+ params["from"] = window.start
+ params["to"] = window.end
return params
@@ -166,6 +202,21 @@ def _emit(rows: list[dict[str, Any]], symbol: str | None, config: FinnhubEndpoin
return rows
+def _check_row_cap(
+ rows: list[dict[str, Any]], config: FinnhubEndpointConfig, symbol: str | None, logger: FilteringBoundLogger
+) -> None:
+ if config.max_rows_per_request is None or len(rows) < config.max_rows_per_request:
+ return
+ message = (
+ f"Finnhub: endpoint '{config.name}' returned its per-request cap of {config.max_rows_per_request} rows"
+ f"{f' for {symbol}' if symbol else ''}; the API silently dropped anything else in this window. Failing "
+ "the sync rather than checkpointing past the missing rows — narrow the sync window (e.g. sync more "
+ "often, or split a large Symbols list across sources) so each request stays under the cap."
+ )
+ logger.error(message)
+ raise FinnhubRowCapExceededError(message)
+
+
def get_rows(
api_key: str,
endpoint: str,
@@ -191,12 +242,14 @@ def get_rows(
config, ticker, exchange, should_use_incremental_field, db_incremental_field_last_value
)
rows = _extract_rows(_fetch(session, config.path, params, logger), config)
+ _check_row_cap(rows, config, ticker, logger)
if rows:
yield _emit(rows, ticker, config)
return
params = _request_params(config, None, exchange, should_use_incremental_field, db_incremental_field_last_value)
rows = _extract_rows(_fetch(session, config.path, params, logger), config)
+ _check_row_cap(rows, config, None, logger)
if rows:
yield _emit(rows, None, config)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/settings.py
index 69b1ed21f850..c89758c81aef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/settings.py
@@ -1,10 +1,12 @@
-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
-@dataclass
+@frozen
class FinnhubEndpointConfig:
name: str
path: str
@@ -14,11 +16,13 @@ class FinnhubEndpointConfig:
# The response is a single JSON object yielded as one row (quote, profile, basic
# financials) rather than a list.
single_object: bool = False
+ # The response is parallel arrays keyed by field name (Finnhub's candle shape) that are
+ # zipped back into one row per index.
+ columnar: bool = False
primary_keys: list[str] = field(default_factory=lambda: ["symbol"])
incremental_fields: list[IncrementalField] = field(default_factory=list)
- # Stable field used to partition the Delta table. Must be a "YYYY-MM-DD" date string
- # (Finnhub's epoch-second timestamps aren't parsed by the datetime partitioner), and
- # must never change for a given row — so never an `updated`/`lastSeen` style field.
+ # Stable field used to partition the Delta table. Either a date string or epoch seconds,
+ # and it must never change for a given row — so never an `updated`/`lastSeen` style field.
partition_key: Optional[str] = None
# Per-symbol fan-out: the endpoint needs a `symbol` query param and is queried once per
# configured ticker, with the requested symbol injected into each emitted row.
@@ -32,8 +36,13 @@ class FinnhubEndpointConfig:
# bounds how far back the initial/full window reaches; `forward_days` extends it into
# the future for forward-looking calendars (scheduled IPOs / earnings).
windowed: bool = False
+ # The window params are UNIX seconds rather than "YYYY-MM-DD".
+ epoch_window: bool = False
lookback_days: int = 365
forward_days: int = 0
+ # Documented hard cap on rows one call can return. Finnhub gives these endpoints no
+ # pagination, so a response at the cap means the window was silently truncated.
+ max_rows_per_request: Optional[int] = None
should_sync_default: bool = True
description: Optional[str] = None
@@ -157,6 +166,117 @@ FINNHUB_ENDPOINTS: dict[str, FinnhubEndpointConfig] = {
should_sync_default=False,
description="Historical EPS estimate vs actual surprises per configured symbol. Full refresh.",
),
+ "financials_reported": FinnhubEndpointConfig(
+ name="financials_reported",
+ path="/stock/financials-reported",
+ data_key="data",
+ requires_symbol=True,
+ # `accessNumber` is the SEC accession number of the filing the report was taken from.
+ primary_keys=["symbol", "accessNumber"],
+ partition_key="endDate",
+ fixed_params={"freq": "annual"},
+ windowed=True,
+ # Financial statements are only worth having with several years of history behind them.
+ lookback_days=1825,
+ should_sync_default=False,
+ # Known limitation: a report re-filed after a newer period has already synced (its
+ # endDate older than the saved cursor) won't be picked up by this from/to window. Fixing
+ # that needs a periodic full rescan, since a restatement can reference an arbitrarily old
+ # period; left as a documented gap rather than expanding this source's sync strategy.
+ incremental_fields=[
+ {
+ "label": "endDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "endDate",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ description="As-reported income statement, balance sheet and cash flow per annual filing, for each configured symbol. Supports incremental sync on the period end date.",
+ ),
+ "stock_candles": FinnhubEndpointConfig(
+ name="stock_candles",
+ path="/stock/candle",
+ columnar=True,
+ requires_symbol=True,
+ primary_keys=["symbol", "t"],
+ partition_key="t",
+ # Daily bars are adjusted for splits; intraday resolutions are not, and Finnhub caps
+ # them at a month per call.
+ fixed_params={"resolution": "D"},
+ windowed=True,
+ epoch_window=True,
+ # `to` lands on midnight, so reach a day past it to take in today's bar.
+ forward_days=1,
+ lookback_days=730,
+ should_sync_default=False,
+ # Known limitation: Finnhub adjusts daily candles for splits, so a split can change bars
+ # older than the saved cursor. Incremental requests only start at the cursor day, so
+ # those stored bars go stale. Fixing that needs a periodic full-history refresh; left as
+ # a documented gap rather than expanding this source's sync strategy.
+ incremental_fields=[
+ {
+ "label": "t",
+ "type": IncrementalFieldType.DateTime,
+ "field": "t",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ description="Daily OHLCV candles for each configured symbol. Supports incremental sync on the candle timestamp.",
+ ),
+ "sec_filings": FinnhubEndpointConfig(
+ name="sec_filings",
+ path="/stock/filings",
+ requires_symbol=True,
+ primary_keys=["symbol", "accessNumber"],
+ partition_key="filedDate",
+ windowed=True,
+ max_rows_per_request=250,
+ should_sync_default=False,
+ incremental_fields=[
+ {
+ "label": "filedDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "filedDate",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ description="Index of a company's SEC filings, for each configured symbol. Supports incremental sync on the filed date.",
+ ),
+ "insider_transactions": FinnhubEndpointConfig(
+ name="insider_transactions",
+ path="/stock/insider-transactions",
+ data_key="data",
+ requires_symbol=True,
+ # Form 4 rows carry no id, and one insider can report several lines on the same day —
+ # commonly a sale filled at different prices. Key on everything that identifies a line
+ # except `share`, which is the running holding rather than part of the transaction.
+ primary_keys=[
+ "symbol",
+ "name",
+ "transactionDate",
+ "filingDate",
+ "transactionCode",
+ "change",
+ "transactionPrice",
+ ],
+ partition_key="transactionDate",
+ windowed=True,
+ max_rows_per_request=100,
+ should_sync_default=False,
+ incremental_fields=[
+ # Finnhub documents `from`/`to` without saying which date they filter. A filing
+ # date is never earlier than the transaction it reports, so watermarking on
+ # `transactionDate` asks for a superset either way — watermarking on `filingDate`
+ # would skip transactions under the other reading.
+ {
+ "label": "transactionDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "transactionDate",
+ "field_type": IncrementalFieldType.Date,
+ },
+ ],
+ description="Insider buy and sell transactions reported on Form 3/4/5, for each configured symbol. Supports incremental sync on the transaction date.",
+ ),
}
ENDPOINTS = tuple(FINNHUB_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/source.py
index b7e836968dd7..48dc8a5c2417 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/source.py
@@ -116,7 +116,7 @@ class FinnhubSource(SimpleSource[FinnhubSourceConfig]):
Create a free API key in your [Finnhub dashboard](https://finnhub.io/dashboard).
-Per-company tables (company profile, quote, company news, basic financials, recommendation trends, earnings surprises) are synced for each ticker you list in **Symbols**. Market-wide tables (stock symbols, market news, IPO calendar, earnings calendar, countries) sync without any symbols.
+Per-company tables (company profile, quote, company news, basic financials, recommendation trends, earnings surprises, stock candles, as-reported financials, SEC filings, insider transactions) are synced for each ticker you list in **Symbols**. Market-wide tables (stock symbols, market news, IPO calendar, earnings calendar, countries) sync without any symbols.
Note: the free tier is rate limited to 60 requests/minute, and some endpoints require a paid plan.""",
iconPath="/static/services/finnhub.png",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
index 9088055bc94f..45db578ef85c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
@@ -11,6 +11,8 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub import finnhub
from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub.finnhub import (
FINNHUB_BASE_URL,
+ FinnhubRowCapExceededError,
+ _expand_columnar,
_extract_rows,
_fetch,
_parse_symbols,
@@ -93,6 +95,37 @@ class TestExtractRows:
def test_bare_array_non_list_returns_empty(self) -> None:
assert _extract_rows({"error": "boom"}, FINNHUB_ENDPOINTS["stock_symbols"]) == []
+ def test_columnar_candles_zipped_into_rows(self) -> None:
+ payload = {
+ "s": "ok",
+ "t": [100, 200],
+ "o": [1.0, 2.0],
+ "h": [1.5, 2.5],
+ "l": [0.5, 1.5],
+ "c": [1.2, 2.2],
+ "v": [10, 20],
+ }
+ assert _extract_rows(payload, FINNHUB_ENDPOINTS["stock_candles"]) == [
+ {"t": 100, "o": 1.0, "h": 1.5, "l": 0.5, "c": 1.2, "v": 10},
+ {"t": 200, "o": 2.0, "h": 2.5, "l": 1.5, "c": 2.2, "v": 20},
+ ]
+
+ @parameterized.expand(
+ [
+ ("no_data_status", {"s": "no_data", "t": [], "c": []}),
+ ("missing_status", {"t": [100], "c": [1.0]}),
+ ("no_arrays", {"s": "ok"}),
+ ("not_a_dict", []),
+ ]
+ )
+ def test_columnar_non_ok_returns_empty(self, _name: str, payload: Any) -> None:
+ assert _expand_columnar(payload) == []
+
+ def test_columnar_truncates_to_shortest_array(self) -> None:
+ # A short array would otherwise leave a half-populated final row.
+ payload = {"s": "ok", "t": [100, 200], "c": [1.0]}
+ assert _expand_columnar(payload) == [{"t": 100, "c": 1.0}]
+
class TestRequestParams:
def test_stock_symbols_defaults_exchange(self) -> None:
@@ -127,6 +160,34 @@ class TestRequestParams:
params = _request_params(FINNHUB_ENDPOINTS["company_news"], "AAPL", "US", True, None)
assert params == {"symbol": "AAPL", "from": "2023-06-16", "to": "2024-06-15"}
+ @time_machine.travel("2024-06-15", tick=False)
+ def test_candles_window_uses_epoch_seconds(self) -> None:
+ params = _request_params(FINNHUB_ENDPOINTS["stock_candles"], "AAPL", "US", False, None)
+ assert params == {"symbol": "AAPL", "resolution": "D", "from": 1655337600, "to": 1718496000}
+
+ @time_machine.travel("2024-06-15", tick=False)
+ def test_candles_window_starts_at_midnight_of_the_watermark_day(self) -> None:
+ # The stored cursor is a candle timestamp mid-window; rounding down re-fetches that day.
+ params = _request_params(FINNHUB_ENDPOINTS["stock_candles"], "AAPL", "US", True, 1717000000)
+ assert params["from"] == 1716940800 # 2024-05-29T00:00:00Z
+ assert params["to"] == 1718496000
+
+ @time_machine.travel("2024-06-15", tick=False)
+ def test_financials_reported_window_uses_long_lookback_and_freq(self) -> None:
+ params = _request_params(FINNHUB_ENDPOINTS["financials_reported"], "AAPL", "US", False, None)
+ assert params == {"symbol": "AAPL", "freq": "annual", "from": "2019-06-17", "to": "2024-06-15"}
+
+ @time_machine.travel("2024-06-15", tick=False)
+ def test_insider_transactions_window_uses_incremental_cursor(self) -> None:
+ params = _request_params(FINNHUB_ENDPOINTS["insider_transactions"], "AAPL", "US", True, "2024-05-01")
+ assert params == {"symbol": "AAPL", "from": "2024-05-01", "to": "2024-06-15"}
+
+ @time_machine.travel("2024-06-15", tick=False)
+ def test_full_refresh_omits_the_watermark(self) -> None:
+ # A full refresh must sweep the whole lookback even when a cursor is stored.
+ params = _request_params(FINNHUB_ENDPOINTS["sec_filings"], "AAPL", "US", False, "2024-05-01")
+ assert params == {"symbol": "AAPL", "from": "2023-06-16", "to": "2024-06-15"}
+
class TestWindow:
@time_machine.travel("2024-06-15", tick=False)
@@ -205,6 +266,35 @@ class TestGetRows:
with pytest.raises(KeyError):
list(get_rows(api_key="k", endpoint="company_news", symbols="AAPL", exchange="US", logger=MagicMock()))
+ def test_candles_emitted_as_rows_with_symbol(self, monkeypatch: Any) -> None:
+ self._patch_fetch(
+ monkeypatch,
+ {"AAPL": {"s": "ok", "t": [200, 100], "c": [2.0, 1.0]}},
+ )
+ batches = list(
+ get_rows(api_key="k", endpoint="stock_candles", symbols="AAPL", exchange="US", logger=MagicMock())
+ )
+ # Sorted ascending on the declared `t` watermark, with the requested ticker injected.
+ assert batches == [[{"t": 100, "c": 1.0, "symbol": "AAPL"}, {"t": 200, "c": 2.0, "symbol": "AAPL"}]]
+
+ def test_raises_when_a_response_hits_the_documented_cap(self, monkeypatch: Any) -> None:
+ # Insider transactions cap at 100 rows per call with no pagination — a full page means
+ # the API silently dropped the rest of the window. Emitting that subset would let the
+ # cursor advance past the missing rows, so the sync must fail instead of checkpointing.
+ rows = [{"symbol": "AAPL", "transactionDate": f"2024-01-{i % 28 + 1:02d}"} for i in range(100)]
+ self._patch_fetch(monkeypatch, {"AAPL": {"data": rows}})
+ logger = MagicMock()
+ with pytest.raises(FinnhubRowCapExceededError):
+ list(get_rows(api_key="k", endpoint="insider_transactions", symbols="AAPL", exchange="US", logger=logger))
+ logger.error.assert_called_once()
+
+ def test_no_cap_error_below_the_cap(self, monkeypatch: Any) -> None:
+ rows = [{"symbol": "AAPL", "transactionDate": "2024-01-01"}]
+ self._patch_fetch(monkeypatch, {"AAPL": {"data": rows}})
+ logger = MagicMock()
+ list(get_rows(api_key="k", endpoint="insider_transactions", symbols="AAPL", exchange="US", logger=logger))
+ logger.error.assert_not_called()
+
def test_calendar_unwraps_data_key(self, monkeypatch: Any) -> None:
self._patch_fetch(
monkeypatch,
@@ -230,6 +320,23 @@ class TestFinnhubSource:
("company_news", ["id", "symbol"], None, "asc"),
("recommendation_trends", ["symbol", "period"], "period", None),
("earnings_surprises", ["symbol", "period"], "period", None),
+ ("financials_reported", ["symbol", "accessNumber"], "endDate", "asc"),
+ ("stock_candles", ["symbol", "t"], "t", "asc"),
+ ("sec_filings", ["symbol", "accessNumber"], "filedDate", "asc"),
+ (
+ "insider_transactions",
+ [
+ "symbol",
+ "name",
+ "transactionDate",
+ "filingDate",
+ "transactionCode",
+ "change",
+ "transactionPrice",
+ ],
+ "transactionDate",
+ "asc",
+ ),
]
)
def test_source_response_keys_and_partitioning(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub_source.py
index c761ce13e7ae..30a896739c05 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub_source.py
@@ -45,13 +45,23 @@ class TestGetSchemas:
"basic_financials",
"recommendation_trends",
"earnings_surprises",
+ "financials_reported",
+ "stock_candles",
+ "sec_filings",
+ "insider_transactions",
}
- def test_only_company_news_is_incremental(self) -> None:
+ def test_incremental_endpoints_advertise_their_cursor(self) -> None:
+ # Only endpoints Finnhub lets us filter server-side may advertise incremental sync.
schemas = {s.name: s for s in FinnhubSource().get_schemas(_config(), team_id=1)}
- incremental = {name for name, s in schemas.items() if s.supports_incremental}
- assert incremental == {"company_news"}
- assert schemas["company_news"].incremental_fields[0]["field"] == "datetime"
+ incremental = {name: s.incremental_fields[0]["field"] for name, s in schemas.items() if s.supports_incremental}
+ assert incremental == {
+ "company_news": "datetime",
+ "financials_reported": "endDate",
+ "stock_candles": "t",
+ "sec_filings": "filedDate",
+ "insider_transactions": "transactionDate",
+ }
@parameterized.expand(
[
@@ -66,6 +76,10 @@ class TestGetSchemas:
("basic_financials", False),
("recommendation_trends", False),
("earnings_surprises", False),
+ ("financials_reported", False),
+ ("stock_candles", False),
+ ("sec_filings", False),
+ ("insider_transactions", False),
]
)
def test_should_sync_default(self, endpoint: str, expected_default: bool) -> None:
@@ -91,7 +105,7 @@ class TestDocumentedTables:
def test_lists_tables_without_credentials(self) -> None:
assert FinnhubSource.lists_tables_without_credentials is True
tables = FinnhubSource().get_documented_tables()
- assert len(tables) == 11
+ assert len(tables) == 15
class TestSourceForPipeline: