:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add the missing Finage endpoint tables (#107699)
Tom Owers5f7c31372f3e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex bde2c3dffb65..c8182546a303 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@@ -3066,13 +3066,13 @@ Note: Very small API. The full published reference is 8 endpoints: get forms, ge## Finage — **thin**-Today (9): `aggregates`, `balance_sheet_statements`, `cash_flow_statement`, `dividend_calendar`, `historical_dividends`, `historical_stock_splits`, `last_quote`, `last_trade`, `stock_split_calendar`+Today (16): `aggregates`, `balance_sheet_statements`, `cash_flow_statement`, `crypto_aggregates`, `crypto_last_trade`, `dividend_calendar`, `forex_aggregates`, `forex_last_quote`, `historical_dividends`, `historical_stock_splits`, `income_statement`, `last_quote`, `last_trade`, `stock_details`, `stock_split_calendar`, `symbol_list`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)+- [x] `/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). Added as `symbol_list`, page-walked for the three markets this source syncs data for (us-stock, forex, crypto) and keyed on `[market, symbol]`.+- [x] `/fnd/detail/stock/{symbol} (Stock Market Details)` — company profile: name, exchange, sector, industry - the dimension table for all price data (high). Added as `stock_details`, one current undated row per symbol.+- [x] `/fnd/income-statement/{symbol}` — core fundamentals; currently no financial statement data is exposed at all (high). Added as `income_statement`, annual and quarterly. The rationale over-claims: balance sheet and cash flow statements were already synced.- [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)@@ -3081,9 +3081,9 @@ Diffed against: <https://finage.co.uk/docs/api>- [ ] `/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)- [ ] `/fnd/earning-calendar and /fnd/ipo-calendar` — scheduled corporate events to join against price moves (medium)-- [ ] `/last/crypto, /last/forex, /agg/crypto, /agg/forex (non-equity asset classes)` — same quote/trade/aggregate shapes for FX, crypto, ETF and index, none of which are reachable today (medium)+- [x] `/last/crypto, /last/forex, /agg/crypto, /agg/forex (non-equity asset classes)` — same quote/trade/aggregate shapes for FX, crypto, ETF and index, none of which are reachable today (medium). Added as `forex_last_quote`, `forex_aggregates`, `crypto_last_trade` and `crypto_aggregates`, each fanning out over its own optional symbol field. ETF and index are left out: they need their own symbol fields and were not part of the named endpoints.-Note: The docs are a client-rendered playground, but the full endpoint catalog is embedded in the /docs/api HTML (126 distinct api.finage.co.uk paths, ~72 titled endpoints across US/UK/CA/IN/RU equities, forex, crypto, ETF, index, fundamentals, news and technical indicators). PostHog exposes 3 static endpoints. get_schemas uses a fixed FINAGE_ENDPOINTS map - no dynamic discovery.+Note: The docs are a client-rendered playground, but the full endpoint catalog is embedded in the /docs/api HTML (126 distinct api.finage.co.uk paths, ~72 titled endpoints across US/UK/CA/IN/RU equities, forex, crypto, ETF, index, fundamentals, news and technical indicators). get_schemas uses a fixed FINAGE_ENDPOINTS map - no dynamic discovery. None of the endpoints above take a server-side `updated_after` filter, so they all sync full refresh like the rest of the source.## FinancialModelling — **thin**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.pyindex 168495e52b2c..9e4cf5a56bce 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@@ -145,6 +145,64 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"finalLink": "Link to the filing document itself.",},},+ "income_statement": {+ "description": "Annual and quarterly income statement filings for each tracked stock symbol.",+ "docs_url": "https://finage.co.uk/docs/api",+ "columns": {+ "symbol": "Ticker symbol the filing is for (e.g. AAPL). Pinned from the requested symbol.",+ "date": "Last day of the fiscal period the filing covers. Used as the partition key.",+ "period": "Fiscal period the filing covers, e.g. FY or Q4.",+ "filingDate": "Date the filing was submitted to the regulator.",+ "acceptedDate": "Date and time the regulator accepted the filing.",+ "revenue": "Total revenue recognised in the period.",+ "costOfRevenue": "Direct cost of producing the goods and services sold.",+ "grossProfit": "Revenue minus the cost of revenue.",+ "grossProfitRatio": "Gross profit as a fraction of revenue.",+ "researchAndDevelopmentExpenses": "Spend on research and development.",+ "generalAndAdministrativeExpenses": "Overhead not tied to producing or selling.",+ "sellingAndMarketingExpenses": "Spend on selling and marketing.",+ "otherExpenses": "Expenses that do not fit the named categories.",+ "operatingExpenses": "Total expenses of running the business, excluding cost of revenue.",+ "costAndExpenses": "Cost of revenue plus operating expenses.",+ "interestExpense": "Cost of servicing borrowings.",+ "depreciationAndAmortization": "Non-cash charge spreading asset cost over its life.",+ "ebitda": "Earnings before interest, tax, depreciation and amortisation.",+ "ebitdaRatio": "EBITDA as a fraction of revenue.",+ "operatingIncome": "Profit from operations, before interest and tax.",+ "operatingIncomeRatio": "Operating income as a fraction of revenue.",+ "totalOtherIncomeExpensesNet": "Net of income and expenses outside operations.",+ "incomeBeforeTax": "Profit before income tax is deducted.",+ "incomeBeforeTaxRatio": "Pre-tax income as a fraction of revenue.",+ "incomeTaxExpense": "Income tax charged for the period.",+ "netIncome": "Profit left after every cost and tax.",+ "netIncomeRatio": "Net income as a fraction of revenue.",+ "eps": "Earnings per share, undiluted.",+ "epsDiluted": "Earnings per share, assuming every convertible instrument converts.",+ "weightedAverageShsOut": "Average shares outstanding over the period.",+ "weightedAverageShsOutDil": "Average shares outstanding on a diluted basis.",+ "link": "Link to the filing index page at the regulator.",+ "finalLink": "Link to the filing document itself.",+ },+ },+ "stock_details": {+ "description": "Company profile for each tracked stock symbol. One current row per symbol, not a history.",+ "docs_url": "https://finage.co.uk/docs/api",+ "columns": {+ "symbol": "Ticker symbol the profile is for (e.g. AAPL). Pinned from the requested symbol.",+ "logo": "URL of the company logo image.",+ "name": "Registered company name.",+ "url": "Company website.",+ "description": "Short description of what the company does.",+ "exchange": "Exchange the symbol trades on.",+ "ceo": "Name of the chief executive.",+ "industry": "Industry the company is classified under.",+ "state": "State or region of the registered address.",+ "address": "Registered address of the company.",+ "employees": "Number of people the company employs.",+ "sector": "Sector the company is classified under.",+ "marketcap": "Market capitalisation in the listing currency.",+ },+ },"dividend_calendar": {"description": "Declared dividends across the whole market, not limited to the tracked symbols.","docs_url": "https://finage.co.uk/docs/api",@@ -166,4 +224,60 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"denominator_factor": "Number of shares held that `numerator_factor` new shares replace.",},},+ "symbol_list": {+ "description": "Every tradeable symbol in the US stock, forex and crypto markets, with its name.",+ "docs_url": "https://finage.co.uk/docs/api",+ "columns": {+ "market": "Finage market the symbol belongs to: us-stock, forex or crypto. Part of the key, because a symbol is only unique within its market.",+ "symbol": "Symbol as Finage addresses it in every other endpoint.",+ "name": "Human-readable name of the instrument.",+ },+ },+ "forex_last_quote": {+ "description": "The latest bid/ask quote for each tracked forex pair.",+ "docs_url": "https://finage.co.uk/docs/api",+ "columns": {+ "symbol": "Currency pair the quote is for (e.g. GBPUSD).",+ "ask": "Most recent ask price.",+ "bid": "Most recent bid price.",+ "timestamp": "Unix epoch (milliseconds) at which the quote was last updated.",+ },+ },+ "forex_aggregates": {+ "description": "Historical daily OHLCV bars for each tracked forex pair.",+ "docs_url": "https://finage.co.uk/docs/api",+ "columns": {+ "symbol": "Currency pair the bar is for (e.g. GBPUSD).",+ "date": "ISO date (YYYY-MM-DD) of the bar, derived from `t`. Used as the partition key.",+ "o": "Open price for the bar.",+ "h": "Highest price during the bar.",+ "l": "Lowest price during the bar.",+ "c": "Close price for the bar.",+ "v": "Trading volume during the bar.",+ "t": "Unix epoch (milliseconds) at the start of the bar.",+ },+ },+ "crypto_last_trade": {+ "description": "The latest executed trade for each tracked crypto pair.",+ "docs_url": "https://finage.co.uk/docs/api",+ "columns": {+ "symbol": "Crypto pair the trade is for (e.g. BTCUSD).",+ "price": "Price the last trade executed at.",+ "timestamp": "Unix epoch (milliseconds) at which the trade occurred.",+ },+ },+ "crypto_aggregates": {+ "description": "Historical daily OHLCV bars for each tracked crypto pair.",+ "docs_url": "https://finage.co.uk/docs/api",+ "columns": {+ "symbol": "Crypto pair the bar is for (e.g. BTCUSD).",+ "date": "ISO date (YYYY-MM-DD) of the bar, derived from `t`. Used as the partition key.",+ "o": "Open price for the bar.",+ "h": "Highest price during the bar.",+ "l": "Lowest price during the bar.",+ "c": "Close price for the bar.",+ "v": "Trading volume during the bar.",+ "t": "Unix epoch (milliseconds) at the start of the bar.",+ },+ },}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.pyindex adefe626f807..4dcd8e85bdd1 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@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.httfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.finage.settings import (FINAGE_ENDPOINTS,+ FinageAssetClass,FinageEndpointConfig,FinageEndpointKind,)@@ -45,6 +46,10 @@ CALENDAR_WINDOW_DAYS = 30# window runs past today so a sync picks up the events that are already scheduled.CALENDAR_FORWARD_DAYS = 90+# The symbol list is page-numbered with no total count, so the walk stops on an empty page. The cap+# bounds it anyway: an API that ignores `page` would otherwise re-serve page one for ever.+SYMBOL_LIST_MAX_PAGES = 500+REQUEST_TIMEOUT_SECONDS = 60# Each symbol costs one request per point-in-time sync and one 50k-row fetch per aggregate sync, so the@@ -52,6 +57,8 @@ REQUEST_TIMEOUT_SECONDS = 60MAX_SYMBOLS = 100# US tickers are short and alphanumeric; dots/hyphens cover class shares (e.g. BRK.B, BF-B).SYMBOL_PATTERN = re.compile(r"^[A-Z0-9][A-Z0-9.\-]{0,11}$")+# Forex and crypto symbols are concatenated currency pairs (GBPUSD, BTCUSD, MATICUSDT) — no separators.+PAIR_SYMBOL_PATTERN = re.compile(r"^[A-Z0-9]{4,20}$")# Finage's US stock history doesn't meaningfully predate this; a floor rejects typos and unbounded ranges.MIN_START_DATE = "2000-01-01"@@ -76,23 +83,46 @@ def parse_symbols(symbols: str) -> list[str]:return parsed-def validate_source_config(symbols: list[str], start_date: str) -> None:- """Reject oversized symbol lists, malformed tickers, and out-of-range start dates before a sync runs.-- Each symbol fans out into its own Finage request (and, for aggregates, up to a 50k-row fetch), so an- unbounded symbol list or a start date in the distant past is a resource-exhaustion vector. Raises- `FinageConfigError` with a user-facing message on the first problem found.- """+def _validate_symbol_list(+ symbols: list[str], pattern: re.Pattern[str], *, label: str, example: str, allow_empty: bool+) -> None:+ """Reject an oversized or malformed symbol list for one asset class."""if not symbols:- raise FinageConfigError("Enter at least one stock symbol to sync.")+ if allow_empty:+ return+ raise FinageConfigError(f"Enter at least one {label} symbol to sync.")if len(symbols) > MAX_SYMBOLS:raise FinageConfigError(- f"Too many symbols ({len(symbols)}). Enter at most {MAX_SYMBOLS} comma-separated stock symbols."+ f"Too many {label} symbols ({len(symbols)}). Enter at most {MAX_SYMBOLS} comma-separated symbols.")- invalid = [s for s in symbols if not SYMBOL_PATTERN.match(s)]+ invalid = [s for s in symbols if not pattern.match(s)]if invalid:preview = ", ".join(invalid[:5])- raise FinageConfigError(f"Invalid stock symbol(s): {preview}. Use US tickers like AAPL, MSFT, BRK.B.")+ raise FinageConfigError(f"Invalid {label} symbol(s): {preview}. Use symbols like {example}.")+++def validate_source_config(+ symbols: list[str],+ start_date: str,+ forex_symbols: list[str] | None = None,+ crypto_symbols: list[str] | None = None,+) -> None:+ """Reject oversized symbol lists, malformed tickers, and out-of-range start dates before a sync runs.++ Each symbol fans out into its own Finage request (and, for aggregates, up to a 50k-row fetch), so an+ unbounded symbol list or a start date in the distant past is a resource-exhaustion vector. Raises+ `FinageConfigError` with a user-facing message on the first problem found.++ Only the stock list is required; forex and crypto are opt-in, and their tables sync nothing when+ the matching list is empty.+ """+ _validate_symbol_list(symbols, SYMBOL_PATTERN, label="stock", example="AAPL, MSFT, BRK.B", allow_empty=False)+ _validate_symbol_list(+ forex_symbols or [], PAIR_SYMBOL_PATTERN, label="forex", example="GBPUSD, EURUSD", allow_empty=True+ )+ _validate_symbol_list(+ crypto_symbols or [], PAIR_SYMBOL_PATTERN, label="crypto", example="BTCUSD, ETHUSD", allow_empty=True+ )try:parsed_start = datetime.strptime(start_date, "%Y-%m-%d").replace(tzinfo=UTC).date()@@ -244,7 +274,8 @@ def _iter_aggregate_rows(to_date=to_date,)try:- data = _fetch_json(session, path, api_key, logger, params={"limit": AGG_LIMIT, "sort": "asc"})+ params: dict[str, Any] = {"limit": AGG_LIMIT, "sort": "asc", **config.extra_params}+ data = _fetch_json(session, path, api_key, logger, params=params)except requests.HTTPError as exc:_handle_symbol_http_error(exc, logger, f"aggregates request for {symbol}")continue@@ -287,18 +318,16 @@ def _records(data: JsonBody, what: str, logger: FilteringBoundLogger) -> list[direturn data-def _keyed_row(+def _symbol_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.+ """Return the record with `symbol` pinned, rejecting records that can't supply one.- 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.+ `symbol` is part of the primary key on every fundamentals endpoint, and a missing one merges+ unrelated companies onto the same key.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+ response cannot then relabel one company's history under another company's key, and theper-symbol tables key the same way whether or not the response repeats the symbol. A calendarrequest passes `None`, because only the record says which company it is about."""@@ -307,11 +336,24 @@ def _keyed_row(if not symbol:raise ValueError(f"Finage {config.name} for {what} returned a record with no symbol")+ return {**record, "symbol": symbol}+++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.++ `date` completes the primary key and is also the partition key, so a missing or malformed one+ buckets the row into the fallback 1970-01 partition. Fail the sync rather than corrupt the table.+ """+ row = _symbol_keyed_row(record, config, pinned_symbol=pinned_symbol, what=what)+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}+ return {**row, "date": date}def _symbol_history_params(config: FinageEndpointConfig) -> list[Optional[dict[str, Any]]]:@@ -351,6 +393,73 @@ def _iter_symbol_history_rows(yield [_keyed_row(record, config, pinned_symbol=symbol, what=symbol) for record in records]+def _iter_symbol_profile_rows(+ session: requests.Session,+ api_key: str,+ symbols: list[str],+ config: FinageEndpointConfig,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Yield one company profile row per symbol.++ Finage wraps the single profile object in an array. The row carries no date, so `symbol` alone+ is the key and the table holds the current profile rather than a history.+ """+ for symbol in symbols:+ path = config.path.format(symbol=symbol)+ try:+ data = _fetch_json(session, path, api_key, logger)+ 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 [_symbol_keyed_row(record, config, pinned_symbol=symbol, what=symbol) for record in records]+++def _iter_symbol_list_rows(+ session: requests.Session,+ api_key: str,+ config: FinageEndpointConfig,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Yield the tradeable symbols of each configured market, one page at a time.++ A symbol is only unique within its market, so the requested market is pinned onto every row and+ is part of the key. The response reports no total, so the walk ends on the first empty page.+ """+ for market in config.markets:+ path = config.path.format(market=market)+ for page in range(1, SYMBOL_LIST_MAX_PAGES + 1):+ what = f"{config.name} for {market} page {page}"+ try:+ data = _fetch_json(session, path, api_key, logger, params={"page": page})+ except requests.HTTPError as exc:+ _handle_symbol_http_error(exc, logger, what)+ break++ if not isinstance(data, dict):+ logger.warning(f"Finage: {what} returned no symbols, skipping")+ break+ symbols = data.get("symbols")+ if not symbols:+ break+ if not all(isinstance(record, dict) for record in symbols):+ raise ValueError(f"Finage {what} returned a symbol entry that is not a record")++ yield [+ {**_symbol_keyed_row(record, config, pinned_symbol=None, what=what), "market": market}+ for record in symbols+ ]+ else:+ logger.warning(+ f"Finage: {config.name} for {market} hit the {SYMBOL_LIST_MAX_PAGES}-page cap; later symbols skipped"+ )++@frozenclass _CalendarWindow:"""One inclusive `from` / `to` pair for a calendar request."""@@ -412,8 +521,20 @@ def get_rows(symbols: list[str],start_date: str,logger: FilteringBoundLogger,+ forex_symbols: list[str] | None = None,+ crypto_symbols: list[str] | None = None,) -> Iterator[list[dict[str, Any]]]:config = FINAGE_ENDPOINTS[endpoint]+ endpoint_symbols = {+ FinageAssetClass.STOCK: symbols,+ FinageAssetClass.FOREX: forex_symbols or [],+ FinageAssetClass.CRYPTO: crypto_symbols or [],+ }[config.asset_class]+ if config.asset_class is not FinageAssetClass.STOCK and not endpoint_symbols:+ # Nothing to fan out over. Say so, otherwise the table just syncs empty with no explanation.+ logger.warning(f"Finage: no {config.asset_class} symbols configured, so {endpoint} has nothing to sync")+ return+# One session reused across every symbol so urllib3 keeps the connection alive. Redact the key# so the `apikey` query value is never persisted raw in tracked logs / sample capture. Disable the# adapter's default retry policy: `_fetch_json` already retries 429/5xx with tenacity, and stacking a@@ -422,13 +543,17 @@ def get_rows(match config.kind:case FinageEndpointKind.AGGREGATE:- yield from _iter_aggregate_rows(session, api_key, symbols, config, start_date, logger)+ yield from _iter_aggregate_rows(session, api_key, endpoint_symbols, config, start_date, logger)case FinageEndpointKind.SYMBOL_HISTORY:- yield from _iter_symbol_history_rows(session, api_key, symbols, config, logger)+ yield from _iter_symbol_history_rows(session, api_key, endpoint_symbols, config, logger)+ case FinageEndpointKind.SYMBOL_PROFILE:+ yield from _iter_symbol_profile_rows(session, api_key, endpoint_symbols, config, logger)case FinageEndpointKind.CALENDAR:yield from _iter_calendar_rows(session, api_key, config, start_date, logger)+ case FinageEndpointKind.SYMBOL_LIST:+ yield from _iter_symbol_list_rows(session, api_key, config, logger)case FinageEndpointKind.POINT_IN_TIME:- yield from _iter_point_in_time_rows(session, api_key, symbols, config, logger)+ yield from _iter_point_in_time_rows(session, api_key, endpoint_symbols, config, logger)def finage_source(@@ -437,6 +562,8 @@ def finage_source(symbols: list[str],start_date: str,logger: FilteringBoundLogger,+ forex_symbols: list[str] | None = None,+ crypto_symbols: list[str] | None = None,) -> SourceResponse:config = FINAGE_ENDPOINTS[endpoint]@@ -448,6 +575,8 @@ def finage_source(symbols=symbols,start_date=start_date,logger=logger,+ forex_symbols=forex_symbols,+ crypto_symbols=crypto_symbols,),primary_keys=config.primary_keys,partition_count=1,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.pyindex d20984d9e50d..a4712941dcc1 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@@ -13,14 +13,30 @@ class FinageEndpointKind(StrEnum):AGGREGATE = "aggregate"# A bare JSON array of one company's historical records, addressed by symbol.SYMBOL_HISTORY = "symbol_history"+ # A bare JSON array holding one company's current, undated profile.+ SYMBOL_PROFILE = "symbol_profile"# A bare JSON array of market-wide events, windowed by required `from` / `to` query params.CALENDAR = "calendar"+ # A page-numbered `{page, symbols}` listing of every tradeable symbol in a market.+ SYMBOL_LIST = "symbol_list"+++class FinageAssetClass(StrEnum):+ """Which configured symbol list an endpoint fans out over."""++ STOCK = "stock"+ FOREX = "forex"+ CRYPTO = "crypto"# 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")+# Markets the symbol list is pulled for. Finage also lists ca-stock / in-stock / ru-stock / index,+# but this source syncs no data for those, so their symbols would resolve nothing.+SYMBOL_LIST_MARKETS = ("us-stock", "forex", "crypto")+@frozenclass FinageEndpointConfig:@@ -30,16 +46,22 @@ class FinageEndpointConfig:path: strkind: FinageEndpointKindprimary_keys: list[str] = field(default_factory=lambda: ["symbol"])+ # Which configured symbol list the endpoint fans out over.+ asset_class: FinageAssetClass = FinageAssetClass.STOCK# Stable datetime column to partition on. Never a value that changes after a row is first written.partition_key: str | None = None# Fiscal periods to request separately. Empty for endpoints that take no `period` param.periods: tuple[str, ...] = ()+ # Markets to request separately, each filled into `{market}`. Only used by SYMBOL_LIST.+ markets: tuple[str, ...] = ()+ # Query params sent on top of the ones the endpoint kind already builds.+ extra_params: dict[str, str] = field(default_factory=dict)should_sync_default: bool = True-# US-stock scope for the initial release. Finage exposes the same path shapes for forex/crypto/indices-# (e.g. `/last/forex/{symbol}`, `/agg/crypto/{symbol}/...`), so adding other asset classes later is a-# matter of parameterizing the market segment.+# Finage exposes the same quote and aggregate path shapes per asset class, so the forex and crypto+# tables reuse the stock kinds and only differ in which configured symbol list they fan out over.+# Indices and ETFs are reachable the same way but have no configured symbol list yet.## Paths and response shapes are taken from the public Finage docs (https://finage.co.uk/docs); they# could not be curl-verified against the live API because that requires a paid key. The aggregate and@@ -102,6 +124,21 @@ FINAGE_ENDPOINTS: dict[str, FinageEndpointConfig] = {partition_key="date",periods=STATEMENT_PERIODS,),+ "income_statement": FinageEndpointConfig(+ name="income_statement",+ path="/fnd/income-statement/{symbol}",+ kind=FinageEndpointKind.SYMBOL_HISTORY,+ primary_keys=["symbol", "date", "period"],+ partition_key="date",+ periods=STATEMENT_PERIODS,+ ),+ # One current, undated profile row per symbol — the dimension table the price tables join to.+ "stock_details": FinageEndpointConfig(+ name="stock_details",+ path="/fnd/detail/stock/{symbol}",+ kind=FinageEndpointKind.SYMBOL_PROFILE,+ primary_keys=["symbol"],+ ),# 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(@@ -120,6 +157,54 @@ FINAGE_ENDPOINTS: dict[str, FinageEndpointConfig] = {partition_key="date",should_sync_default=False,),+ # Like the calendars, this lists whole markets rather than the configured symbols, so it is off+ # by default. A symbol is only unique within its market, so the market is part of the key.+ "symbol_list": FinageEndpointConfig(+ name="symbol_list",+ path="/symbol-list/{market}",+ kind=FinageEndpointKind.SYMBOL_LIST,+ primary_keys=["market", "symbol"],+ markets=SYMBOL_LIST_MARKETS,+ should_sync_default=False,+ ),+ # Forex and crypto need their own symbol fields, which are optional, so these are off by default.+ "forex_last_quote": FinageEndpointConfig(+ name="forex_last_quote",+ path="/last/forex/{symbol}",+ kind=FinageEndpointKind.POINT_IN_TIME,+ primary_keys=["symbol"],+ asset_class=FinageAssetClass.FOREX,+ should_sync_default=False,+ ),+ "forex_aggregates": FinageEndpointConfig(+ name="forex_aggregates",+ path="/agg/forex/{symbol}/{multiplier}/{timespan}/{from_date}/{to_date}",+ kind=FinageEndpointKind.AGGREGATE,+ primary_keys=["symbol", "t"],+ asset_class=FinageAssetClass.FOREX,+ partition_key="date",+ # The stock and forex docs disagree on whether `date_format` defaults to a timestamp or a+ # datetime string. `t` is the partition key, so pin the timestamp rather than guess.+ extra_params={"date_format": "ts"},+ should_sync_default=False,+ ),+ "crypto_last_trade": FinageEndpointConfig(+ name="crypto_last_trade",+ path="/last/crypto/{symbol}",+ kind=FinageEndpointKind.POINT_IN_TIME,+ primary_keys=["symbol"],+ asset_class=FinageAssetClass.CRYPTO,+ should_sync_default=False,+ ),+ "crypto_aggregates": FinageEndpointConfig(+ name="crypto_aggregates",+ path="/agg/crypto/{symbol}/{multiplier}/{timespan}/{from_date}/{to_date}",+ kind=FinageEndpointKind.AGGREGATE,+ primary_keys=["symbol", "t"],+ asset_class=FinageAssetClass.CRYPTO,+ partition_key="date",+ should_sync_default=False,+ ),}ENDPOINTS = tuple(FINAGE_ENDPOINTS.keys())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.pyindex face0fe09e6f..f145134b273f 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,12 +30,19 @@ _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.",+ "stock_details": "Company profile per symbol: name, exchange, sector, industry, CEO and market cap. One current row per symbol, 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.",+ "income_statement": "Annual and quarterly income statement 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.",+ "symbol_list": "Every tradeable symbol in the US stock, forex and crypto markets, with its name. Full refresh.",+ "forex_last_quote": "Latest bid/ask quote per forex pair. Needs forex symbols. Point-in-time snapshot, full refresh.",+ "forex_aggregates": "Historical daily OHLCV bars per forex pair from the backfill start date. Needs forex symbols. Full refresh.",+ "crypto_last_trade": "Latest trade price per crypto pair. Needs crypto symbols. Point-in-time snapshot, full refresh.",+ "crypto_aggregates": "Historical daily OHLCV bars per crypto pair from the backfill start date. Needs crypto symbols. Full refresh.",}@@ -59,7 +66,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, plus **fundamentals** for the dividend, split and financial statement tables.""",+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, profile and financial statement tables, and **forex** or **crypto** if you sync those tables.""",iconPath="/static/services/finage.png",docsUrl="https://posthog.com/docs/cdp/sources/finage",keywords=["stocks", "market data", "ohlcv", "finance"],@@ -83,6 +90,24 @@ You can find your API key in the [Finage dashboard](https://finage.co.uk/dashboasecret=False,caption="Comma-separated list of US stock symbols to sync, e.g. `AAPL,MSFT,TSLA`.",),+ SourceFieldInputConfig(+ name="forex_symbols",+ label="Forex symbols",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="GBPUSD,EURUSD",+ secret=False,+ caption="Comma-separated list of forex pairs to sync, e.g. `GBPUSD,EURUSD`. Leave blank to skip the forex tables.",+ ),+ SourceFieldInputConfig(+ name="crypto_symbols",+ label="Crypto symbols",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="BTCUSD,ETHUSD",+ secret=False,+ caption="Comma-separated list of crypto pairs to sync, e.g. `BTCUSD,ETHUSD`. Leave blank to skip the crypto tables.",+ ),SourceFieldInputConfig(name="start_date",label="Backfill start date",@@ -144,7 +169,12 @@ You can find your API key in the [Finage dashboard](https://finage.co.uk/dashboaapi_version: str | None = None,) -> tuple[bool, str | None]:try:- validate_source_config(parse_symbols(config.symbols), config.start_date or DEFAULT_START_DATE)+ validate_source_config(+ parse_symbols(config.symbols),+ config.start_date or DEFAULT_START_DATE,+ forex_symbols=parse_symbols(config.forex_symbols or ""),+ crypto_symbols=parse_symbols(config.crypto_symbols or ""),+ )except FinageConfigError as exc:return False, str(exc)@@ -165,13 +195,17 @@ You can find your API key in the [Finage dashboard](https://finage.co.uk/dashboadef source_for_pipeline(self, config: FinageSourceConfig, inputs: SourceInputs) -> SourceResponse:symbols = parse_symbols(config.symbols)+ forex_symbols = parse_symbols(config.forex_symbols or "")+ crypto_symbols = parse_symbols(config.crypto_symbols or "")start_date = config.start_date or DEFAULT_START_DATE# Re-validate here so a source saved before these guards existed can't fan out a runaway sync.- validate_source_config(symbols, start_date)+ validate_source_config(symbols, start_date, forex_symbols=forex_symbols, crypto_symbols=crypto_symbols)return finage_source(api_key=config.api_key,endpoint=inputs.schema_name,symbols=symbols,start_date=start_date,logger=inputs.logger,+ forex_symbols=forex_symbols,+ crypto_symbols=crypto_symbols,)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.pyindex c1dd846bae91..abda7ad0a338 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@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.finage.finMAX_SYMBOLS,MIN_START_DATE,STATEMENT_LIMIT,+ SYMBOL_LIST_MAX_PAGES,FinageConfigError,FinageRetryableError,finage_source,@@ -78,10 +79,15 @@ class TestValidateSourceConfig:# Class-share tickers with dots/hyphens are valid; a start date inside the window is fine.validate_source_config(["AAPL", "BRK.B", "BF-B"], "2021-06-01")+ def test_accepts_pair_symbols_and_treats_them_as_optional(self) -> None:+ # Forex and crypto are opt-in, so an empty list must pass rather than block the whole source.+ validate_source_config(["AAPL"], "2021-06-01", forex_symbols=[], crypto_symbols=[])+ validate_source_config(["AAPL"], "2021-06-01", forex_symbols=["GBPUSD"], crypto_symbols=["MATICUSDT"])+@parameterized.expand([("no_symbols", [], "2021-01-01", "at least one"),- ("too_many", [f"SYM{i}" for i in range(MAX_SYMBOLS + 1)], "2021-01-01", "Too many symbols"),+ ("too_many", [f"SYM{i}" for i in range(MAX_SYMBOLS + 1)], "2021-01-01", "Too many stock symbols"),("bad_ticker", ["AAPL", "not a ticker"], "2021-01-01", "Invalid stock symbol"),("malformed_date", ["AAPL"], "06/01/2021", "YYYY-MM-DD"),("date_before_floor", ["AAPL"], "1990-01-01", MIN_START_DATE),@@ -93,6 +99,26 @@ class TestValidateSourceConfig:validate_source_config(symbols, start_date)assert expected in str(exc.value)+ @parameterized.expand(+ [+ # Pair symbols carry no separators, so a stock-style ticker in the forex field is a typo+ # that would otherwise 404 every symbol at sync time.+ ("forex_ticker_shaped", {"forex_symbols": ["BRK.B"]}, "Invalid forex symbol"),+ ("forex_too_short", {"forex_symbols": ["GBP"]}, "Invalid forex symbol"),+ ("crypto_ticker_shaped", {"crypto_symbols": ["BTC-USD"]}, "Invalid crypto symbol"),+ ("forex_too_many", {"forex_symbols": [f"AAA{i:03d}" for i in range(MAX_SYMBOLS + 1)]}, "Too many forex"),+ (+ "crypto_too_many",+ {"crypto_symbols": [f"BBB{i:03d}" for i in range(MAX_SYMBOLS + 1)]},+ "Too many crypto",+ ),+ ]+ )+ def test_rejects_invalid_pair_symbols(self, _name: str, kwargs: dict, expected: str) -> None:+ with pytest.raises(FinageConfigError) as exc:+ validate_source_config(["AAPL"], "2021-01-01", **kwargs)+ assert expected in str(exc.value)+class TestMsToDate:@parameterized.expand(@@ -334,6 +360,11 @@ class TestFundamentalsRows:"balance_sheet_statements",[{"limit": STATEMENT_LIMIT, "period": "annual"}, {"limit": STATEMENT_LIMIT, "period": "quarter"}],),+ (+ "income_statement",+ "income_statement",+ [{"limit": STATEMENT_LIMIT, "period": "annual"}, {"limit": STATEMENT_LIMIT, "period": "quarter"}],+ ),])def test_requests_one_call_per_fiscal_period(@@ -445,12 +476,187 @@ class TestFundamentalsRows:list(get_rows("k", endpoint, ["AAPL"], "2021-01-01", mock.Mock()))+class TestSymbolProfileRows:+ def test_unwraps_the_single_profile_object_and_pins_the_requested_symbol(self) -> None:+ # Finage wraps the one profile in an array, and the row has no date at all — routing it+ # through the dated fundamentals path would reject every company profile.+ profile = {"symbol": "AAPL", "name": "Apple Inc.", "sector": "Technology", "employees": 123000}+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(finage, "_fetch_json", return_value=[profile]),+ ):+ batches = list(get_rows("k", "stock_details", ["AAPL"], "2020-01-01", mock.Mock()))++ assert batches == [[profile]]++ def test_pins_the_requested_symbol_over_the_reported_one(self) -> None:+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(finage, "_fetch_json", return_value=[{"symbol": "MSFT", "name": "Wrong Inc."}]),+ ):+ batches = list(get_rows("k", "stock_details", ["AAPL"], "2020-01-01", mock.Mock()))++ assert batches[0][0]["symbol"] == "AAPL"++ def test_skips_a_symbol_with_no_profile_but_keeps_going(self) -> None:+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(+ finage, "_fetch_json", side_effect=[{"error": "no data"}, [{"symbol": "MSFT", "name": "Microsoft"}]]+ ),+ ):+ batches = list(get_rows("k", "stock_details", ["BAD", "MSFT"], "2020-01-01", mock.Mock()))++ assert [row["symbol"] for batch in batches for row in batch] == ["MSFT"]+++class TestSymbolListRows:+ def _page(self, *symbols: str) -> dict[str, Any]:+ return {"page": 1, "symbols": [{"symbol": s, "name": f"{s} name"} for s in symbols]}++ def test_walks_every_market_and_stops_on_the_first_empty_page(self) -> None:+ # A symbol is only unique within its market, so dropping `market` collides US tickers with+ # forex pairs on the same key. Termination is the empty page — there is no total to compare.+ pages = [self._page("AAPL"), self._page("MSFT"), {"page": 3, "symbols": []}]+ pages += [self._page("GBPUSD"), {"symbols": []}]+ pages += [self._page("BTCUSD"), {"symbols": []}]+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(finage, "_fetch_json", side_effect=pages) as fetch,+ ):+ batches = list(get_rows("k", "symbol_list", ["AAPL"], "2020-01-01", mock.Mock()))++ rows = [row for batch in batches for row in batch]+ assert [(row["market"], row["symbol"]) for row in rows] == [+ ("us-stock", "AAPL"),+ ("us-stock", "MSFT"),+ ("forex", "GBPUSD"),+ ("crypto", "BTCUSD"),+ ]+ assert [call.args[1] for call in fetch.call_args_list][:3] == ["/symbol-list/us-stock"] * 3+ assert [call.kwargs["params"] for call in fetch.call_args_list][:3] == [{"page": 1}, {"page": 2}, {"page": 3}]++ def test_stops_at_the_page_cap_when_the_api_never_returns_an_empty_page(self) -> None:+ # An API that ignores `page` would otherwise re-serve page one for ever and never finish.+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(finage, "_fetch_json", return_value=self._page("AAPL")) as fetch,+ ):+ batches = list(get_rows("k", "symbol_list", ["AAPL"], "2020-01-01", mock.Mock()))++ assert len(batches) == SYMBOL_LIST_MAX_PAGES * 3+ assert fetch.call_count == SYMBOL_LIST_MAX_PAGES * 3++ def test_rejects_an_entry_that_cannot_be_keyed(self) -> None:+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(finage, "_fetch_json", return_value={"symbols": [{"name": "no symbol here"}]}),+ ):+ with pytest.raises(ValueError):+ list(get_rows("k", "symbol_list", ["AAPL"], "2020-01-01", mock.Mock()))++ def test_404_on_one_market_skips_it_but_401_stops_the_sync(self) -> None:+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(+ finage,+ "_fetch_json",+ side_effect=[_http_error(404), self._page("GBPUSD"), {"symbols": []}, {"symbols": []}],+ ),+ ):+ batches = list(get_rows("k", "symbol_list", ["AAPL"], "2020-01-01", mock.Mock()))+ assert [row["market"] for batch in batches for row in batch] == ["forex"]++ 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", "symbol_list", ["AAPL"], "2020-01-01", mock.Mock()))+++class TestNonEquityAssetClasses:+ @parameterized.expand(+ [+ ("forex_quote", "forex_last_quote", "/last/forex/GBPUSD"),+ ("crypto_trade", "crypto_last_trade", "/last/crypto/BTCUSD"),+ ]+ )+ def test_point_in_time_fans_out_over_its_own_symbol_list(self, _name: str, endpoint: str, path: str) -> None:+ # Fanning the stock tickers into a forex or crypto path would 404 every symbol, so the+ # endpoint must read the list that matches its asset class.+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(finage, "_fetch_json", return_value={"symbol": "X", "price": 1.0}) as fetch,+ ):+ list(+ get_rows(+ "k",+ endpoint,+ ["AAPL"],+ "2020-01-01",+ mock.Mock(),+ forex_symbols=["GBPUSD"],+ crypto_symbols=["BTCUSD"],+ )+ )++ assert [call.args[1] for call in fetch.call_args_list] == [path]++ @parameterized.expand(+ [+ ("forex_quote", "forex_last_quote"),+ ("forex_aggregates", "forex_aggregates"),+ ("crypto_trade", "crypto_last_trade"),+ ("crypto_aggregates", "crypto_aggregates"),+ ]+ )+ def test_no_configured_symbols_yields_nothing_without_calling_the_api(self, _name: str, endpoint: str) -> None:+ # The pair fields are optional, so an enabled table with an empty list must sync empty+ # rather than fall back to the stock tickers.+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(finage, "_fetch_json") as fetch,+ ):+ assert list(get_rows("k", endpoint, ["AAPL"], "2020-01-01", mock.Mock())) == []+ fetch.assert_not_called()++ def test_forex_aggregates_pin_the_timestamp_date_format(self) -> None:+ # The stock and forex docs disagree on the `date_format` default. `t` is the partition key,+ # so a datetime string there would fail every bar.+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(finage, "_fetch_json", return_value={"results": []}) as fetch,+ ):+ list(get_rows("k", "forex_aggregates", [], "2020-01-01", mock.Mock(), forex_symbols=["GBPUSD"]))++ assert fetch.call_args.kwargs["params"] == {"limit": AGG_LIMIT, "sort": "asc", "date_format": "ts"}++ def test_crypto_aggregates_window_the_path_and_key_on_the_pair(self) -> None:+ payload = {"symbol": "BTCUSD", "results": [{"o": 1, "c": 2, "t": 1580860800000}]}+ with (+ mock.patch.object(finage, "make_tracked_session"),+ mock.patch.object(finage, "_fetch_json", return_value=payload) as fetch,+ ):+ batches = list(get_rows("k", "crypto_aggregates", [], "2020-02-05", mock.Mock(), crypto_symbols=["BTCUSD"]))++ assert fetch.call_args.args[1].startswith("/agg/crypto/BTCUSD/1/day/2020-02-05/")+ assert batches[0][0]["symbol"] == "BTCUSD"+ assert batches[0][0]["date"] == "2020-02-05"++class TestFinageSourceResponse:@parameterized.expand([("last_quote", ["symbol"], None, None),("last_trade", ["symbol"], None, None),("aggregates", ["symbol", "t"], "datetime", ["date"]),+ ("stock_details", ["symbol"], None, None),+ ("symbol_list", ["market", "symbol"], None, None),+ ("forex_last_quote", ["symbol"], None, None),+ ("forex_aggregates", ["symbol", "t"], "datetime", ["date"]),+ ("crypto_last_trade", ["symbol"], None, None),+ ("crypto_aggregates", ["symbol", "t"], "datetime", ["date"]),])def test_source_response_shape(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage_source.pyindex 8d4d388d4258..e6cf57ec5cd3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finage/tests/test_finage_source.py@@ -65,10 +65,18 @@ class TestFinageSource:if not expected_valid:assert message- def test_validate_credentials_rejects_bad_config_before_probing(self):+ @pytest.mark.parametrize(+ "overrides",+ [+ {"symbols": "not a ticker"},+ {"forex_symbols": "BRK.B"},+ {"crypto_symbols": "BTC-USD"},+ ],+ )+ def test_validate_credentials_rejects_bad_config_before_probing(self, overrides):# A malformed symbol list must be rejected without ever calling the Finage API.with mock.patch.object(finage_source_module, "validate_finage_credentials") as probe:- valid, message = self.source.validate_credentials(self._config(symbols="not a ticker"), self.team_id)+ valid, message = self.source.validate_credentials(self._config(**overrides), self.team_id)assert valid is Falseassert messageprobe.assert_not_called()@@ -85,6 +93,27 @@ class TestFinageSource:assert kwargs["start_date"] == "2021-06-01"assert kwargs["api_key"] == "secret"+ def test_source_for_pipeline_passes_each_asset_class_symbol_list(self):+ # Forex and crypto tables read their own list; dropping either here syncs them empty.+ config = self._config(forex_symbols=" gbpusd , eurusd ", crypto_symbols="btcusd")+ inputs = mock.Mock(schema_name="forex_aggregates")+ with mock.patch.object(finage_source_module, "finage_source") as build:+ self.source.source_for_pipeline(config, inputs)++ _args, kwargs = build.call_args+ assert kwargs["forex_symbols"] == ["GBPUSD", "EURUSD"]+ assert kwargs["crypto_symbols"] == ["BTCUSD"]++ def test_source_for_pipeline_treats_unset_pair_fields_as_empty(self):+ # The fields are optional, so they arrive as None and must not blow up `parse_symbols`.+ inputs = mock.Mock(schema_name="last_quote")+ with mock.patch.object(finage_source_module, "finage_source") as build:+ self.source.source_for_pipeline(self._config(), inputs)++ _args, kwargs = build.call_args+ assert kwargs["forex_symbols"] == []+ assert kwargs["crypto_symbols"] == []+def test_source_for_pipeline_defaults_start_date(self):config = self._config(start_date="")inputs = mock.Mock(schema_name="last_quote")@@ -94,5 +123,17 @@ class TestFinageSource:_args, kwargs = build.call_argsassert kwargs["start_date"] == finage_source_module.DEFAULT_START_DATE- def _config(self, symbols: str = "AAPL", start_date: str | None = None) -> FinageSourceConfig:- return FinageSourceConfig(api_key="secret", symbols=symbols, start_date=start_date)+ def _config(+ self,+ symbols: str = "AAPL",+ start_date: str | None = None,+ forex_symbols: str | None = None,+ crypto_symbols: str | None = None,+ ) -> FinageSourceConfig:+ return FinageSourceConfig(+ api_key="secret",+ symbols=symbols,+ start_date=start_date,+ forex_symbols=forex_symbols,+ crypto_symbols=crypto_symbols,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/finage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/finage.pyindex 335c03fb74db..f24e66dde187 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/finage.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/finage.py@@ -8,4 +8,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common impclass FinageSourceConfig(config.Config):api_key: strsymbols: str+ forex_symbols: str | None = None+ crypto_symbols: str | None = Nonestart_date: str | None = None