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(finage): sync dividend, split and financial statement tables (#107412)

Tom Owersef8eea24e9fc
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 0c139a7305de..0ed113d59448 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
@@ -3065,17 +3065,17 @@ Note: Very small API. The full published reference is 8 endpoints: get forms, ge
## Finage — **thin**
-Today (3): `aggregates`, `last_quote`, `last_trade`
+Today (9): `aggregates`, `balance_sheet_statements`, `cash_flow_statement`, `dividend_calendar`, `historical_dividends`, `historical_stock_splits`, `last_quote`, `last_trade`, `stock_split_calendar`
Diffed against: <https://finage.co.uk/docs/api>
- [ ] `/symbol-list/{market} (Full Symbol List API)` — lookup table of tradeable symbols per market - resolves the symbol keys every other table is built on (high)
- [ ] `/fnd/detail/stock/{symbol} (Stock Market Details)` — company profile: name, exchange, sector, industry - the dimension table for all price data (high)
- [ ] `/fnd/income-statement/{symbol}` — core fundamentals; currently no financial statement data is exposed at all (high)
-- [ ] `/fnd/balance-sheet-statements/{symbol}` — core fundamentals alongside income statements (high)
-- [ ] `/fnd/cash-flow-statement/{symbol}` — completes the three-statement set (high)
-- [ ] `/fnd/historical-dividends/{symbol} and /fnd/dividend-calendar` — dividend events needed for total-return calculations on the aggregates already synced (high)
-- [ ] `/fnd/historical-stock-splits/{symbol} and /fnd/stock-split-calendar` — split events are required to make historical aggregates comparable across time (high)
+- [x] `/fnd/balance-sheet-statements/{symbol}` — core fundamentals alongside income statements (high)
+- [x] `/fnd/cash-flow-statement/{symbol}` — completes the three-statement set (high)
+- [x] `/fnd/historical-dividends/{symbol} and /fnd/dividend-calendar` — dividend events needed for total-return calculations on the aggregates already synced (high)
+- [x] `/fnd/historical-stock-splits/{symbol} and /fnd/stock-split-calendar` — split events are required to make historical aggregates comparable across time (high)
- [ ] `/fnd/financial-ratios/{symbol}` — precomputed valuation and profitability ratios (medium)
- [ ] `/agg/stock/prev-close/{symbol}` — previous close reference price for daily change calculations (medium)
- [ ] `/snapshot/stock (also /snapshot/forex, /snapshot/crypto)` — whole-market snapshot in one call rather than per-symbol quote fetches (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/canonical_descriptions.py
index 897c2d650668..168495e52b2c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/canonical_descriptions.py
@@ -46,4 +46,124 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"t": "Unix epoch (milliseconds) at the start of the bar.",
},
},
+ "historical_dividends": {
+ "description": "Past dividends for each tracked stock symbol, one row per ex-dividend date.",
+ "docs_url": "https://finage.co.uk/docs/api",
+ "columns": {
+ "symbol": "Ticker symbol the dividend is for (e.g. AAPL). Pinned from the requested symbol.",
+ "date": "Ex-dividend date. Used as the partition key.",
+ "label": "Human-readable form of the ex-dividend date.",
+ "dividend": "Dividend amount per share as declared.",
+ "adj_dividend": "Dividend amount per share adjusted for later stock splits.",
+ "record_date": "Date on which a holder must be on the register to receive the dividend.",
+ "payment_date": "Date the dividend is paid out.",
+ "declaration_date": "Date the company announced the dividend.",
+ },
+ },
+ "historical_stock_splits": {
+ "description": "Past stock splits for each tracked stock symbol, one row per split date.",
+ "docs_url": "https://finage.co.uk/docs/api",
+ "columns": {
+ "symbol": "Ticker symbol the split is for (e.g. AAPL). Pinned from the requested symbol.",
+ "date": "Date the split took effect. Used as the partition key.",
+ "label": "Human-readable form of the split date.",
+ "numerator_factor": "Number of new shares issued for every `denominator_factor` held.",
+ "denominator_factor": "Number of shares held that `numerator_factor` new shares replace.",
+ },
+ },
+ "balance_sheet_statements": {
+ "description": "Reported balance sheets for each tracked stock symbol, annual and quarterly.",
+ "docs_url": "https://finage.co.uk/docs/api",
+ "columns": {
+ "symbol": "Ticker symbol the statement is for (e.g. AAPL).",
+ "date": "End date of the fiscal period the statement covers. Used as the partition key.",
+ "period": "Fiscal period the statement covers, such as FY or Q3.",
+ "fillingDate": "Date the statement was filed with the regulator.",
+ "acceptedDate": "Date and time the regulator accepted the filing.",
+ "cashAndCashEquivalents": "Cash and holdings that convert to cash almost immediately.",
+ "shortTermInvestments": "Investments expected to be sold within a year.",
+ "cashAndShortTermInvestments": "Cash, cash equivalents and short term investments combined.",
+ "netReceivables": "Money owed by customers, after expected bad debt.",
+ "inventory": "Value of goods held for sale or production.",
+ "totalCurrentAssets": "Assets expected to convert to cash within a year.",
+ "propertyPlantEquipmentNet": "Book value of property, plant and equipment after depreciation.",
+ "goodwill": "Premium paid over fair value in past acquisitions.",
+ "intangibleAssets": "Book value of non-physical assets such as patents and trademarks.",
+ "totalNonCurrentAssets": "Assets not expected to convert to cash within a year.",
+ "totalAssets": "Total book value of everything the company owns.",
+ "accountPayables": "Money owed to suppliers.",
+ "shortTermDebt": "Borrowings due within a year.",
+ "taxPayables": "Tax owed and not yet paid.",
+ "deferredRevenue": "Payments received for goods or services not yet delivered.",
+ "totalCurrentLiabilities": "Obligations due within a year.",
+ "totalNonCurrentLiabilities": "Obligations due after more than a year.",
+ "totalLiabilities": "Total book value of everything the company owes.",
+ "commonStock": "Par value of issued common shares.",
+ "retainedEarnings": "Cumulative profit kept in the business rather than paid out.",
+ "totalStockholdersEquity": "Total assets minus total liabilities.",
+ "totalLiabilitiesAndStockholdersEquity": "Total liabilities plus stockholders equity, which equals total assets.",
+ "totalInvestments": "Short and long term investments combined.",
+ "totalDebt": "Short term debt plus long term debt.",
+ "netDebt": "Total debt minus cash and cash equivalents.",
+ "link": "Link to the filing index page at the regulator.",
+ "finalLink": "Link to the filing document itself.",
+ },
+ },
+ "cash_flow_statement": {
+ "description": "Reported cash flow statements for each tracked stock symbol, annual and quarterly.",
+ "docs_url": "https://finage.co.uk/docs/api",
+ "columns": {
+ "symbol": "Ticker symbol the statement is for (e.g. AAPL).",
+ "date": "End date of the fiscal period the statement covers. Used as the partition key.",
+ "period": "Fiscal period the statement covers, such as FY or Q3.",
+ "fillingDate": "Date the statement was filed with the regulator.",
+ "acceptedDate": "Date and time the regulator accepted the filing.",
+ "netIncome": "Profit for the period, the starting point of the cash flow statement.",
+ "depreciationAndAmortization": "Non-cash charge for the wear and expiry of assets.",
+ "deferredIncomeTax": "Change in tax owed in future periods rather than this one.",
+ "stockBasedCompensation": "Non-cash cost of shares and options granted to employees.",
+ "changeInWorkingCapital": "Net cash effect of movements in receivables, inventory and payables.",
+ "netCashProvidedByOperatingActivities": "Cash generated by running the business.",
+ "investmentsInPropertyPlantAndEquipment": "Cash spent on property, plant and equipment.",
+ "acquisitionsNet": "Cash spent acquiring other businesses, net of cash acquired.",
+ "purchasesOfInvestments": "Cash spent buying investments.",
+ "salesMaturitiesOfInvestments": "Cash received from selling or maturing investments.",
+ "netCashUsedForInvestingActivites": "Net cash effect of all investing activity.",
+ "debtRepayment": "Cash used to repay borrowings.",
+ "commonStockIssued": "Cash raised by issuing shares.",
+ "commonStockRepurchased": "Cash used to buy back shares.",
+ "dividendsPaid": "Cash paid out to shareholders as dividends.",
+ "netCashUsedProvidedByFinancingActivities": "Net cash effect of all financing activity.",
+ "effectOfForexChangesOnCash": "Change in cash caused by exchange rate movements.",
+ "netChangeInCash": "Total change in cash over the period.",
+ "cashAtBeginningOfPeriod": "Cash held at the start of the period.",
+ "cashAtEndOfPeriod": "Cash held at the end of the period.",
+ "operatingCashFlow": "Cash generated by operations, repeated as a headline figure.",
+ "capitalExpenditure": "Cash spent on long-lived assets.",
+ "freeCashFlow": "Operating cash flow minus capital expenditure.",
+ "link": "Link to the filing index page at the regulator.",
+ "finalLink": "Link to the filing document itself.",
+ },
+ },
+ "dividend_calendar": {
+ "description": "Declared dividends across the whole market, not limited to the tracked symbols.",
+ "docs_url": "https://finage.co.uk/docs/api",
+ "columns": {
+ "symbol": "Ticker symbol the dividend is for.",
+ "date": "Ex-dividend date. Used as the partition key.",
+ "label": "Human-readable form of the ex-dividend date.",
+ "adj_dividend": "Dividend amount per share adjusted for later stock splits.",
+ },
+ },
+ "stock_split_calendar": {
+ "description": "Declared stock splits across the whole market, not limited to the tracked symbols.",
+ "docs_url": "https://finage.co.uk/docs/api",
+ "columns": {
+ "symbol": "Ticker symbol the split is for.",
+ "date": "Date the split takes effect. Used as the partition key.",
+ "label": "Human-readable form of the split date.",
+ "numerator_factor": "Number of new shares issued for every `denominator_factor` held.",
+ "denominator_factor": "Number of shares held that `numerator_factor` new shares replace.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/finage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/finage.py
index b1771596313f..adefe626f807 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/finage.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/finage.py
@@ -1,6 +1,6 @@
import re
from collections.abc import Iterator
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Any, Optional
import requests
@@ -8,13 +8,20 @@ from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from urllib3.util.retry import Retry
+from posthog.dataclasses import frozen
+
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.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.finage.settings import (
FINAGE_ENDPOINTS,
FinageEndpointConfig,
+ FinageEndpointKind,
)
+# Finage returns a wrapper object for the quote and aggregate endpoints and a bare array for the
+# fundamentals ones, so every caller narrows the body before reading it.
+JsonBody = dict[str, Any] | list[Any]
+
FINAGE_BASE_URL = "https://api.finage.co.uk"
# Daily OHLCV bars are the canonical historical-price grain. Finer intervals (minute/hour) explode row
@@ -26,6 +33,18 @@ AGG_TIMESPAN = "day"
AGG_LIMIT = 50000
DEFAULT_START_DATE = "2020-01-01"
+# Statement endpoints return the most recent filings first and cap the response with `limit`. 100
+# filings reaches back further than any statement stays comparable, for annual and quarterly alike.
+STATEMENT_LIMIT = 100
+
+# The calendar endpoints require `from` and `to` on every request and cover every listed company
+# rather than the configured symbols, so the backfill window is walked in slices. The slice length
+# bounds how many rows one response has to hold in memory.
+CALENDAR_WINDOW_DAYS = 30
+# Both calendars publish events once they are declared, which is weeks before they take effect. The
+# window runs past today so a sync picks up the events that are already scheduled.
+CALENDAR_FORWARD_DAYS = 90
+
REQUEST_TIMEOUT_SECONDS = 60
# Each symbol costs one request per point-in-time sync and one 50k-row fetch per aggregate sync, so the
@@ -101,6 +120,20 @@ def _today() -> str:
return datetime.now(UTC).date().isoformat()
+def _is_iso_date(value: Any) -> bool:
+ """True only for a canonical `YYYY-MM-DD` string.
+
+ `strptime` accepts a date with the leading zeros left off, so "2021-1-8" parses. Left alone it
+ would key the same day two ways and merge as two rows, hence the round-trip comparison.
+ """
+ if not isinstance(value, str):
+ return False
+ try:
+ return datetime.strptime(value, "%Y-%m-%d").date().isoformat() == value
+ except ValueError:
+ return False
+
+
@retry(
retry=retry_if_exception_type((FinageRetryableError, requests.ReadTimeout, requests.ConnectionError)),
stop=stop_after_attempt(5),
@@ -113,7 +146,7 @@ def _fetch_json(
api_key: str,
logger: FilteringBoundLogger,
params: Optional[dict[str, Any]] = None,
-) -> dict[str, Any]:
+) -> JsonBody:
request_params: dict[str, Any] = {"apikey": api_key, **(params or {})}
url = f"{FINAGE_BASE_URL}{path}"
response = session.get(url, params=request_params, timeout=REQUEST_TIMEOUT_SECONDS)
@@ -216,7 +249,9 @@ def _iter_aggregate_rows(
_handle_symbol_http_error(exc, logger, f"aggregates request for {symbol}")
continue
- results = data.get("results") if isinstance(data, dict) else None
+ if not isinstance(data, dict):
+ continue
+ results = data.get("results")
if not results:
continue
@@ -238,6 +273,139 @@ def _iter_aggregate_rows(
yield rows
+def _records(data: JsonBody, what: str, logger: FilteringBoundLogger) -> list[dict[str, Any]]:
+ """Narrow a fundamentals response to its record list.
+
+ These endpoints answer with a bare JSON array. Finage reports a symbol it has no data for with an
+ object instead, so a non-list body means there is nothing to sync for this request.
+ """
+ if not isinstance(data, list):
+ logger.warning(f"Finage: {what} returned no records, skipping")
+ return []
+ if not all(isinstance(record, dict) for record in data):
+ raise ValueError(f"Finage {what} returned an array element that is not a record")
+ return data
+
+
+def _keyed_row(
+ record: dict[str, Any], config: FinageEndpointConfig, *, pinned_symbol: str | None, what: str
+) -> dict[str, Any]:
+ """Return the record with `symbol` and `date` pinned, rejecting records that can't supply them.
+
+ Both columns are part of the primary key on every fundamentals endpoint, and `date` is also the
+ partition key. A missing symbol merges unrelated companies onto one key, and a missing or
+ malformed date buckets the row into the fallback 1970-01 partition, so either fails the sync
+ rather than corrupting the table.
+
+ A per-symbol request passes `pinned_symbol` so the row is keyed by the symbol we asked for. The
+ response cannot then relabel one company's history under another company's key, and the four
+ per-symbol tables key the same way whether or not the response repeats the symbol. A calendar
+ request passes `None`, because only the record says which company it is about.
+ """
+ symbol = pinned_symbol if pinned_symbol is not None else record.get("symbol")
+ symbol = symbol.strip() if isinstance(symbol, str) else ""
+ if not symbol:
+ raise ValueError(f"Finage {config.name} for {what} returned a record with no symbol")
+
+ date = record.get("date")
+ if not _is_iso_date(date):
+ raise ValueError(f"Finage {config.name} for {what} returned a record with an invalid date: {date!r}")
+
+ return {**record, "symbol": symbol, "date": date}
+
+
+def _symbol_history_params(config: FinageEndpointConfig) -> list[Optional[dict[str, Any]]]:
+ """One request's params per fiscal period, or a single unparameterized request."""
+ if not config.periods:
+ return [None]
+ return [{"limit": STATEMENT_LIMIT, "period": period} for period in config.periods]
+
+
+def _iter_symbol_history_rows(
+ session: requests.Session,
+ api_key: str,
+ symbols: list[str],
+ config: FinageEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield one company's historical dividends, splits or financial statements, per symbol.
+
+ Full refresh: Finage exposes no time filter on these paths, so the whole history is re-fetched
+ every sync and de-duplicated on the endpoint's primary key at merge time. A per-symbol error
+ (unknown ticker, no fundamentals for that company) is logged and skipped; auth and plan failures
+ (401/403) propagate from `_fetch_json` and stop the sync.
+ """
+ for symbol in symbols:
+ path = config.path.format(symbol=symbol)
+ for params in _symbol_history_params(config):
+ try:
+ data = _fetch_json(session, path, api_key, logger, params=params)
+ except requests.HTTPError as exc:
+ _handle_symbol_http_error(exc, logger, f"{config.name} request for {symbol}")
+ continue
+
+ records = _records(data, f"{config.name} for {symbol}", logger)
+ if not records:
+ continue
+
+ yield [_keyed_row(record, config, pinned_symbol=symbol, what=symbol) for record in records]
+
+
+@frozen
+class _CalendarWindow:
+ """One inclusive `from` / `to` pair for a calendar request."""
+
+ start: str
+ end: str
+
+ def __post_init__(self) -> None:
+ if self.start > self.end:
+ raise ValueError(f"Finage calendar window starts after it ends: {self.start} to {self.end}")
+
+
+def _calendar_windows(start_date: str) -> Iterator[_CalendarWindow]:
+ """Walk [start_date, today + CALENDAR_FORWARD_DAYS] as contiguous, non-overlapping date windows.
+
+ Finage treats `from` and `to` as inclusive, so each window starts the day after the previous one
+ ends. Overlapping windows would re-fetch rows the merge then has to de-duplicate, and a gap would
+ lose every event in it.
+ """
+ window_start = datetime.strptime(start_date, "%Y-%m-%d").date()
+ last_day = datetime.now(UTC).date() + timedelta(days=CALENDAR_FORWARD_DAYS)
+ while window_start <= last_day:
+ window_end = min(window_start + timedelta(days=CALENDAR_WINDOW_DAYS - 1), last_day)
+ yield _CalendarWindow(start=window_start.isoformat(), end=window_end.isoformat())
+ window_start = window_end + timedelta(days=1)
+
+
+def _iter_calendar_rows(
+ session: requests.Session,
+ api_key: str,
+ config: FinageEndpointConfig,
+ start_date: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield market-wide dividend or split events one date window at a time.
+
+ These endpoints list every listed company, not the configured symbols, so each row carries its own
+ symbol. A window that fails is logged and skipped so one bad request doesn't lose the rest of the
+ backfill; auth and plan failures (401/403) still stop the sync.
+ """
+ for window in _calendar_windows(start_date):
+ what = f"{config.name} between {window.start} and {window.end}"
+ try:
+ data = _fetch_json(session, config.path, api_key, logger, params={"from": window.start, "to": window.end})
+ except requests.HTTPError as exc:
+ _handle_symbol_http_error(exc, logger, what)
+ continue
+
+ records = _records(data, what, logger)
+ if not records:
+ continue
+
+ yield [_keyed_row(record, config, pinned_symbol=None, what=what) for record in records]
+
+
def get_rows(
api_key: str,
endpoint: str,
@@ -252,10 +420,15 @@ def get_rows(
# second urllib3 retry layer would multiply backoff and let long `Retry-After` waits bypass its cap.
session = make_tracked_session(redact_values=(api_key,), retry=Retry(total=0))
- if config.is_aggregate:
- yield from _iter_aggregate_rows(session, api_key, symbols, config, start_date, logger)
- else:
- yield from _iter_point_in_time_rows(session, api_key, symbols, config, logger)
+ match config.kind:
+ case FinageEndpointKind.AGGREGATE:
+ yield from _iter_aggregate_rows(session, api_key, symbols, config, start_date, logger)
+ case FinageEndpointKind.SYMBOL_HISTORY:
+ yield from _iter_symbol_history_rows(session, api_key, symbols, config, logger)
+ case FinageEndpointKind.CALENDAR:
+ yield from _iter_calendar_rows(session, api_key, config, start_date, logger)
+ case FinageEndpointKind.POINT_IN_TIME:
+ yield from _iter_point_in_time_rows(session, api_key, symbols, config, logger)
def finage_source(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/settings.py
index ab9746775040..d20984d9e50d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/settings.py
@@ -1,21 +1,39 @@
-from dataclasses import dataclass, field
+from dataclasses import field
+from enum import StrEnum
+
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.types import IncrementalField
-@dataclass
+class FinageEndpointKind(StrEnum):
+ # A single current object per symbol.
+ POINT_IN_TIME = "point_in_time"
+ # A `results` array of OHLCV bars per symbol, windowed by a date range in the path.
+ AGGREGATE = "aggregate"
+ # A bare JSON array of one company's historical records, addressed by symbol.
+ SYMBOL_HISTORY = "symbol_history"
+ # A bare JSON array of market-wide events, windowed by required `from` / `to` query params.
+ CALENDAR = "calendar"
+
+
+# Statement endpoints report one row per fiscal period and default to annual, so both periods are
+# requested to give the table the full filing history rather than only the yearly summary.
+STATEMENT_PERIODS = ("annual", "quarter")
+
+
+@frozen
class FinageEndpointConfig:
name: str
# Finage path template. `{symbol}` is filled per symbol; aggregate paths additionally fill
# `{multiplier}` / `{timespan}` / `{from_date}` / `{to_date}`.
path: str
+ kind: FinageEndpointKind
primary_keys: list[str] = field(default_factory=lambda: ["symbol"])
- # Stable datetime column to partition on (only the aggregate bars have one). Never a value that
- # changes after a row is first written.
+ # Stable datetime column to partition on. Never a value that changes after a row is first written.
partition_key: str | None = None
- # True for the historical OHLCV aggregate endpoint: returns a `results` array of bars windowed by
- # a date range in the path, rather than a single point-in-time object.
- is_aggregate: bool = False
+ # Fiscal periods to request separately. Empty for endpoints that take no `period` param.
+ periods: tuple[str, ...] = ()
should_sync_default: bool = True
@@ -31,28 +49,86 @@ FINAGE_ENDPOINTS: dict[str, FinageEndpointConfig] = {
"last_quote": FinageEndpointConfig(
name="last_quote",
path="/last/stock/{symbol}",
+ kind=FinageEndpointKind.POINT_IN_TIME,
primary_keys=["symbol"],
),
"last_trade": FinageEndpointConfig(
name="last_trade",
path="/last/trade/stock/{symbol}",
+ kind=FinageEndpointKind.POINT_IN_TIME,
primary_keys=["symbol"],
),
"aggregates": FinageEndpointConfig(
name="aggregates",
path="/agg/stock/{symbol}/{multiplier}/{timespan}/{from_date}/{to_date}",
+ kind=FinageEndpointKind.AGGREGATE,
# The bar timestamp `t` is only unique within a symbol, so the symbol is part of the key —
# otherwise fan-out rows from different symbols collide and every merge multi-matches them.
primary_keys=["symbol", "t"],
partition_key="date",
- is_aggregate=True,
+ ),
+ "historical_dividends": FinageEndpointConfig(
+ name="historical_dividends",
+ path="/fnd/historical-dividends/{symbol}",
+ kind=FinageEndpointKind.SYMBOL_HISTORY,
+ # The response carries no symbol, so the requested symbol is pinned onto every row and is
+ # part of the key. `date` is the ex-dividend date, which is unique within a symbol.
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ ),
+ "historical_stock_splits": FinageEndpointConfig(
+ name="historical_stock_splits",
+ path="/fnd/historical-stock-splits/{symbol}",
+ kind=FinageEndpointKind.SYMBOL_HISTORY,
+ # Same shape as historical dividends: no symbol in the response, one event per date.
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ ),
+ "balance_sheet_statements": FinageEndpointConfig(
+ name="balance_sheet_statements",
+ path="/fnd/balance-sheet-statements/{symbol}",
+ kind=FinageEndpointKind.SYMBOL_HISTORY,
+ # A fiscal year ends on the same date as its closing quarter, so both statements carry the
+ # same `date` for a symbol and only `period` separates them.
+ primary_keys=["symbol", "date", "period"],
+ partition_key="date",
+ periods=STATEMENT_PERIODS,
+ ),
+ "cash_flow_statement": FinageEndpointConfig(
+ name="cash_flow_statement",
+ path="/fnd/cash-flow-statement/{symbol}",
+ kind=FinageEndpointKind.SYMBOL_HISTORY,
+ primary_keys=["symbol", "date", "period"],
+ partition_key="date",
+ periods=STATEMENT_PERIODS,
+ ),
+ # The two calendars cover every listed company rather than the configured symbols, so they are a
+ # much larger table than the rest of the source and are left off by default.
+ "dividend_calendar": FinageEndpointConfig(
+ name="dividend_calendar",
+ path="/fnd/dividend-calendar",
+ kind=FinageEndpointKind.CALENDAR,
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ should_sync_default=False,
+ ),
+ "stock_split_calendar": FinageEndpointConfig(
+ name="stock_split_calendar",
+ path="/fnd/stock-split-calendar",
+ kind=FinageEndpointKind.CALENDAR,
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ should_sync_default=False,
),
}
ENDPOINTS = tuple(FINAGE_ENDPOINTS.keys())
# Finage has no cross-resource `updated_after` cursor. Quote/trade endpoints are point-in-time, and
-# the aggregate endpoint fans out per symbol — concatenating per-symbol bar streams isn't globally
-# ascending, so a single watermark can't be checkpointed safely. Every endpoint therefore ships full
-# refresh, and there are no advertised incremental fields.
+# the aggregate and fundamentals endpoints fan out per symbol, so concatenating the per-symbol streams
+# isn't globally ascending and a single watermark can't be checkpointed safely. The two calendars filter
+# on the event date, but they also list events that have been declared and not yet happened, so a
+# watermark taken from the newest row lands in the future and skips events declared afterwards for an
+# earlier date. Every endpoint therefore ships full refresh, and there are no advertised incremental
+# fields.
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in FINAGE_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/source.py
index c63b8d9ccad5..face0fe09e6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/source.py
@@ -30,6 +30,12 @@ _ENDPOINT_DESCRIPTIONS = {
"last_quote": "Latest bid/ask quote per symbol. Point-in-time snapshot, full refresh.",
"last_trade": "Latest trade (price and size) per symbol. Point-in-time snapshot, full refresh.",
"aggregates": "Historical daily OHLCV bars per symbol from the backfill start date. Full refresh.",
+ "historical_dividends": "Past dividends per symbol, with the declaration, record and payment dates. Full refresh.",
+ "historical_stock_splits": "Past stock splits per symbol, with the split ratio and the date it took effect. Full refresh.",
+ "balance_sheet_statements": "Annual and quarterly balance sheet filings per symbol. Full refresh.",
+ "cash_flow_statement": "Annual and quarterly cash flow filings per symbol. Full refresh.",
+ "dividend_calendar": "Declared dividends across the whole market, not only your symbols. Full refresh.",
+ "stock_split_calendar": "Declared stock splits across the whole market, not only your symbols. Full refresh.",
}
@@ -53,7 +59,7 @@ class FinageSource(SimpleSource[FinageSourceConfig]):
releaseStatus=ReleaseStatus.ALPHA,
caption="""Enter your Finage API key and the symbols you want to sync to pull market data into the PostHog Data warehouse.
-You can find your API key in the [Finage dashboard](https://finage.co.uk/dashboard) after subscribing to a plan. The key needs access to the **US stocks** endpoints.""",
+You can find your API key in the [Finage dashboard](https://finage.co.uk/dashboard) after subscribing to a plan. The key needs access to the **US stocks** endpoints, plus **fundamentals** for the dividend, split and financial statement tables.""",
iconPath="/static/services/finage.png",
docsUrl="https://posthog.com/docs/cdp/sources/finage",
keywords=["stocks", "market data", "ohlcv", "finance"],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage.py
index f304ac1d6962..c1dd846bae91 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage.py
@@ -1,6 +1,8 @@
+from datetime import date, timedelta
from typing import Any
import pytest
+import time_machine
from unittest import mock
import requests
@@ -9,8 +11,11 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.finage import finage
from products.warehouse_sources.backend.temporal.data_imports.sources.finage.finage import (
AGG_LIMIT,
+ CALENDAR_FORWARD_DAYS,
+ CALENDAR_WINDOW_DAYS,
MAX_SYMBOLS,
MIN_START_DATE,
+ STATEMENT_LIMIT,
FinageConfigError,
FinageRetryableError,
finage_source,
@@ -290,6 +295,156 @@ class TestGetRows:
assert kwargs["retry"].total == 0
+class TestCalendarWindows:
+ @time_machine.travel("2024-03-01", tick=False)
+ def test_windows_are_contiguous_and_cover_the_declared_range(self) -> None:
+ # A gap between windows loses every event inside it, and an overlap re-fetches rows the merge
+ # then has to de-duplicate. Both are invisible in the synced table until someone counts.
+ windows = list(finage._calendar_windows("2024-01-01"))
+
+ assert windows[0].start == "2024-01-01"
+ # `from`/`to` are inclusive, so the forward horizon is the last day a window may end on.
+ assert windows[-1].end == (date(2024, 3, 1) + timedelta(days=CALENDAR_FORWARD_DAYS)).isoformat()
+ for window, following in zip(windows, windows[1:]):
+ assert date.fromisoformat(following.start) == date.fromisoformat(window.end) + timedelta(days=1)
+ for window in windows:
+ span = date.fromisoformat(window.end) - date.fromisoformat(window.start)
+ assert timedelta(0) <= span <= timedelta(days=CALENDAR_WINDOW_DAYS - 1)
+
+ @time_machine.travel("2024-03-01", tick=False)
+ def test_start_date_inside_the_forward_horizon_still_yields_one_window(self) -> None:
+ # A source created today must not produce an empty walk, which would sync nothing silently.
+ windows = list(finage._calendar_windows("2024-03-01"))
+ assert windows[0].start == "2024-03-01"
+ assert len(windows) >= 1
+
+
+class TestFundamentalsRows:
+ @parameterized.expand(
+ [
+ ("dividends", "historical_dividends", [None]),
+ ("splits", "historical_stock_splits", [None]),
+ (
+ "cash_flow",
+ "cash_flow_statement",
+ [{"limit": STATEMENT_LIMIT, "period": "annual"}, {"limit": STATEMENT_LIMIT, "period": "quarter"}],
+ ),
+ (
+ "balance_sheet",
+ "balance_sheet_statements",
+ [{"limit": STATEMENT_LIMIT, "period": "annual"}, {"limit": STATEMENT_LIMIT, "period": "quarter"}],
+ ),
+ ]
+ )
+ def test_requests_one_call_per_fiscal_period(
+ self, _name: str, endpoint: str, expected_params: list[dict | None]
+ ) -> None:
+ # Statements default to annual, so dropping the quarter request would silently halve the table
+ # while leaving it looking healthy. The dividend and split paths take no period at all.
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", return_value=[]) as fetch,
+ ):
+ list(get_rows("k", endpoint, ["AAPL"], "2020-01-01", mock.Mock()))
+
+ assert [call.kwargs["params"] for call in fetch.call_args_list] == expected_params
+
+ @parameterized.expand(
+ [
+ ("response_omits_symbol", {}),
+ ("response_reports_another_symbol", {"symbol": "MSFT"}),
+ ]
+ )
+ def test_pins_the_requested_symbol_onto_every_row(self, _name: str, response_symbol: dict) -> None:
+ # The split and dividend responses carry no symbol, so without pinning the rows lose half
+ # their primary key. A response that names a different company must not write its history
+ # under that company's key either.
+ record = {"numerator_factor": 4, "denominator_factor": 1, "label": "August 31, 20", "date": "2020-08-31"}
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", return_value=[{**record, **response_symbol}]),
+ ):
+ batches = list(get_rows("k", "historical_stock_splits", ["AAPL"], "2020-01-01", mock.Mock()))
+
+ assert batches == [[{**record, "symbol": "AAPL"}]]
+
+ def test_calendar_keeps_the_symbol_each_row_reports(self) -> None:
+ # The calendars cover the whole market, so the row's own symbol is the only one available.
+ records = [
+ {"symbol": "GORO", "label": "January 08, 21", "adj_dividend": 0.003, "date": "2021-01-08"},
+ {"symbol": "BLSR.TA", "label": "January 10, 21", "adj_dividend": 517.912, "date": "2021-01-10"},
+ ]
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", return_value=records) as fetch,
+ ):
+ batches = list(get_rows("k", "dividend_calendar", ["AAPL"], "2021-01-01", mock.Mock()))
+
+ assert [row["symbol"] for row in batches[0]] == ["GORO", "BLSR.TA"]
+ # Both bounds are required by the endpoint; omitting either is a 4xx for every window.
+ assert set(fetch.call_args_list[0].kwargs["params"]) == {"from", "to"}
+
+ @parameterized.expand(
+ [
+ ("missing_date", "historical_dividends", {"adj_dividend": 0.22}),
+ ("malformed_date", "historical_dividends", {"date": "November 05, 21", "adj_dividend": 0.22}),
+ ("calendar_without_symbol", "dividend_calendar", {"date": "2021-01-08", "adj_dividend": 0.003}),
+ ("calendar_blank_symbol", "dividend_calendar", {"symbol": " ", "date": "2021-01-08"}),
+ # `strptime` parses "2021-1-8", which would key the same day two ways.
+ ("noncanonical_date", "historical_dividends", {"date": "2021-1-8", "adj_dividend": 0.22}),
+ ]
+ )
+ def test_rejects_records_that_cannot_be_keyed(self, _name: str, endpoint: str, bad_record: dict) -> None:
+ # `symbol` and `date` are the primary key, and `date` is also the partition key. A bad value
+ # merges unrelated rows together or buckets them into the fallback 1970-01 partition.
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", return_value=[bad_record]),
+ ):
+ with pytest.raises(ValueError):
+ list(get_rows("k", endpoint, ["AAPL"], "2021-01-01", mock.Mock()))
+
+ def test_rejects_an_array_holding_something_that_is_not_a_record(self) -> None:
+ # Dropping the element would let the sync finish with an incomplete table, which is the
+ # outcome the key checks above exist to prevent.
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", return_value=[{"date": "2020-08-31"}, "not-a-record"]),
+ ):
+ with pytest.raises(ValueError):
+ list(get_rows("k", "historical_stock_splits", ["AAPL"], "2020-01-01", mock.Mock()))
+
+ def test_skips_a_symbol_whose_body_is_not_a_record_list(self) -> None:
+ # Finage answers a symbol it has no fundamentals for with an object rather than an array.
+ # Indexing that as a list would fail the whole sync over one company with no filings.
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(
+ finage,
+ "_fetch_json",
+ side_effect=[{"error": "no data"}, [{"symbol": "MSFT", "date": "2020-08-31"}]],
+ ),
+ ):
+ batches = list(get_rows("k", "historical_stock_splits", ["BAD", "MSFT"], "2020-01-01", mock.Mock()))
+
+ assert [row["symbol"] for batch in batches for row in batch] == ["MSFT"]
+
+ @parameterized.expand([("symbol_history", "historical_dividends"), ("calendar", "dividend_calendar")])
+ def test_404_is_skipped_but_401_stops_the_sync(self, _name: str, endpoint: str) -> None:
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", side_effect=_http_error(404)),
+ ):
+ assert list(get_rows("k", endpoint, ["BAD"], "2021-01-01", mock.Mock())) == []
+
+ with (
+ mock.patch.object(finage, "make_tracked_session"),
+ mock.patch.object(finage, "_fetch_json", side_effect=_http_error(401)),
+ ):
+ with pytest.raises(requests.HTTPError):
+ list(get_rows("k", endpoint, ["AAPL"], "2021-01-01", mock.Mock()))
+
+
class TestFinageSourceResponse:
@parameterized.expand(
[