: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): implement twelve_data import source (#72623)
Tom Owersa6002161646f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b5b995b5e958..974c4465c08d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -544,6 +544,7 @@ the row lists both.| trello | HTTP | requests | ✅ || tremendous | HTTP | requests | ✅ || trigger_dev | HTTP | requests | ✅ |+| twelve_data | HTTP | requests | ✅ || twelve_labs | HTTP | requests | ✅ || twilio | HTTP | requests | ✅ || tyntec_sms | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -975,7 +976,6 @@ doesn't conflict with concurrent PRs.- trustpilot- turso- tvmaze-- twelve_data- twenty- twitter_adsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twelvedata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twelvedata.pyindex fc919139428e..cf7d5c8a01b4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twelvedata.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twelvedata.py@@ -1,9 +1,16 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass TwelveDataSourceConfig(config.Config):- pass+ api_key: str+ symbols: str+ interval: Literal["1min", "5min", "15min", "30min", "45min", "1h", "2h", "4h", "1day", "1week", "1month"] = (+ config.value(default="1day")+ )+ start_date: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/canonical_descriptions.pynew file mode 100644index 000000000000..eccf82c079f5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/canonical_descriptions.py@@ -0,0 +1,147 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "stocks": {+ "description": "Catalog of every stock listing Twelve Data covers, one row per symbol per exchange listing.",+ "docs_url": "https://twelvedata.com/docs#stocks-list",+ "columns": {+ "symbol": "Ticker symbol of the instrument.",+ "name": "Full name of the company.",+ "currency": "Currency the instrument trades in, in ISO 4217 format.",+ "exchange": "Name of the exchange the listing trades on.",+ "mic_code": "Market identifier code of the exchange, per ISO 10383.",+ "country": "Country where the exchange is located.",+ "type": "Instrument type, e.g. Common Stock.",+ "figi_code": "Financial Instrument Global Identifier (OpenFIGI) of the listing.",+ },+ },+ "etfs": {+ "description": "Catalog of every ETF Twelve Data covers, one row per symbol per exchange listing.",+ "docs_url": "https://twelvedata.com/docs#etfs-list",+ "columns": {+ "symbol": "Ticker symbol of the ETF.",+ "name": "Full name of the ETF.",+ "currency": "Currency the ETF trades in, in ISO 4217 format.",+ "exchange": "Name of the exchange the listing trades on.",+ "mic_code": "Market identifier code of the exchange, per ISO 10383.",+ "country": "Country where the exchange is located.",+ },+ },+ "indices": {+ "description": "Catalog of market indices Twelve Data covers.",+ "docs_url": "https://twelvedata.com/docs#indices-list",+ "columns": {+ "symbol": "Symbol of the index.",+ "name": "Full name of the index.",+ "country": "Country the index belongs to.",+ "currency": "Currency of the index, in ISO 4217 format.",+ "exchange": "Name of the exchange the index is calculated on.",+ "mic_code": "Market identifier code of the exchange, per ISO 10383.",+ },+ },+ "forex_pairs": {+ "description": "Catalog of foreign exchange currency pairs available at Twelve Data.",+ "docs_url": "https://twelvedata.com/docs#forex-pairs-list",+ "columns": {+ "symbol": "Currency pair symbol, e.g. EUR/USD.",+ "currency_group": "Group the pair belongs to: Major, Minor, Exotic, or Exotic-Cross.",+ "currency_base": "Base currency of the pair.",+ "currency_quote": "Quote currency of the pair.",+ },+ },+ "cryptocurrencies": {+ "description": "Catalog of cryptocurrency pairs available at Twelve Data.",+ "docs_url": "https://twelvedata.com/docs#cryptocurrencies-list",+ "columns": {+ "symbol": "Cryptocurrency pair symbol, e.g. BTC/USD.",+ "available_exchanges": "Exchanges the pair is available on.",+ "currency_base": "Base currency of the pair.",+ "currency_quote": "Quote currency of the pair.",+ },+ },+ "exchanges": {+ "description": "Catalog of stock exchanges available at Twelve Data.",+ "docs_url": "https://twelvedata.com/docs#exchanges",+ "columns": {+ "title": "Full name of the exchange.",+ "name": "Short name of the exchange.",+ "code": "Market identifier code of the exchange, per ISO 10383.",+ "country": "Country where the exchange is located.",+ "timezone": "Time zone the exchange operates in.",+ },+ },+ "time_series": {+ "description": "Historical OHLCV bars for each configured symbol at the configured interval.",+ "docs_url": "https://twelvedata.com/docs#time-series",+ "columns": {+ "symbol": "Symbol the bar belongs to.",+ "interval": "Bar interval the row was synced at, e.g. 1day.",+ "datetime": "Start of the bar, in the exchange's local time.",+ "open": "Price at the open of the bar.",+ "high": "Highest price during the bar.",+ "low": "Lowest price during the bar.",+ "close": "Price at the close of the bar.",+ "volume": "Trading volume during the bar.",+ },+ },+ "quotes": {+ "description": "Latest quote snapshot for each configured symbol at sync time.",+ "docs_url": "https://twelvedata.com/docs#quote",+ "columns": {+ "symbol": "Symbol the quote belongs to.",+ "name": "Full name of the instrument.",+ "exchange": "Name of the exchange the instrument trades on.",+ "mic_code": "Market identifier code of the exchange, per ISO 10383.",+ "currency": "Currency the instrument trades in.",+ "datetime": "Date of the quote.",+ "timestamp": "Unix timestamp of the quote.",+ "open": "Price at the open of the current period.",+ "high": "Highest price of the current period.",+ "low": "Lowest price of the current period.",+ "close": "Latest price.",+ "volume": "Trading volume of the current period.",+ "previous_close": "Closing price of the previous period.",+ "change": "Absolute price change versus the previous close.",+ "percent_change": "Percentage price change versus the previous close.",+ "average_volume": "Average trading volume.",+ "is_market_open": "Whether the instrument's market is currently open.",+ "fifty_two_week": "52-week price statistics for the instrument.",+ },+ },+ "dividends": {+ "description": "Full dividend payout history for each configured symbol.",+ "docs_url": "https://twelvedata.com/docs#dividends",+ "columns": {+ "symbol": "Symbol the dividend belongs to.",+ "ex_date": "Ex-dividend date of the payout.",+ "amount": "Dividend amount per share.",+ },+ },+ "splits": {+ "description": "Full stock split history for each configured symbol.",+ "docs_url": "https://twelvedata.com/docs#splits",+ "columns": {+ "symbol": "Symbol the split belongs to.",+ "date": "Date the split took effect.",+ "description": "Human-readable split description, e.g. 4-for-1 split.",+ "ratio": "Split ratio as a decimal.",+ "from_factor": "Number of shares before the split.",+ "to_factor": "Number of shares after the split.",+ },+ },+ "earnings": {+ "description": "Earnings report history for each configured symbol, with EPS estimates and actuals.",+ "docs_url": "https://twelvedata.com/docs#earnings",+ "columns": {+ "symbol": "Symbol the earnings report belongs to.",+ "date": "Date of the earnings report.",+ "time": "Time of day the report is released, e.g. Before Market Open.",+ "eps_estimate": "Analyst consensus earnings-per-share estimate.",+ "eps_actual": "Reported earnings per share.",+ "difference": "Difference between actual and estimated EPS.",+ "surprise_prc": "EPS surprise as a percentage of the estimate.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/settings.pynew file mode 100644index 000000000000..14b120aa411b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/settings.py@@ -0,0 +1,126 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++TWELVE_DATA_BASE_URL = "https://api.twelvedata.com"++# Hard cap the API enforces on /time_series `outputsize`.+TIME_SERIES_PAGE_SIZE = 5000++# Bounds on import fan-out: every per-symbol table issues one request per configured symbol, and+# /time_series pages further toward the start date, so both dimensions need a ceiling. Enforced at+# config validation AND at sync time, so a previously stored config can't bypass them.+MAX_SYMBOLS = 100+MAX_TIME_SERIES_PAGES_PER_SYMBOL = 50++TIME_SERIES_ENDPOINT = "time_series"++TIME_SERIES_INTERVALS = (+ "1min",+ "5min",+ "15min",+ "30min",+ "45min",+ "1h",+ "2h",+ "4h",+ "1day",+ "1week",+ "1month",+)++DEFAULT_TIME_SERIES_INTERVAL = "1day"+++@dataclass(frozen=True)+class TwelveDataEndpointConfig:+ path: str+ primary_keys: list[str]+ # JSON key holding the row list in the response body. None means the body itself is one row.+ data_key: str | None = None+ # Whether the endpoint is fetched once per configured symbol (vs one catalog-wide call).+ per_symbol: bool = False+ # Static query params sent on every request to the endpoint.+ params: dict[str, str] = field(default_factory=dict)+ partition_key: str | None = None+++ENDPOINTS: dict[str, TwelveDataEndpointConfig] = {+ # Reference catalogs — one request each, full refresh.+ "stocks": TwelveDataEndpointConfig(+ path="/stocks",+ data_key="data",+ # The same ticker is listed on many exchanges; the MIC code disambiguates the listing.+ primary_keys=["symbol", "mic_code"],+ ),+ "etfs": TwelveDataEndpointConfig(+ path="/etfs",+ data_key="data",+ primary_keys=["symbol", "mic_code"],+ ),+ "indices": TwelveDataEndpointConfig(+ path="/indices",+ data_key="data",+ primary_keys=["symbol", "mic_code"],+ ),+ "forex_pairs": TwelveDataEndpointConfig(+ path="/forex_pairs",+ data_key="data",+ primary_keys=["symbol"],+ ),+ "cryptocurrencies": TwelveDataEndpointConfig(+ path="/cryptocurrencies",+ data_key="data",+ primary_keys=["symbol"],+ ),+ "exchanges": TwelveDataEndpointConfig(+ path="/exchanges",+ data_key="data",+ primary_keys=["code"],+ ),+ # Per-symbol market data.+ TIME_SERIES_ENDPOINT: TwelveDataEndpointConfig(+ path="/time_series",+ data_key="values",+ per_symbol=True,+ primary_keys=["symbol", "datetime"],+ partition_key="datetime",+ ),+ "quotes": TwelveDataEndpointConfig(+ path="/quote",+ data_key=None,+ per_symbol=True,+ primary_keys=["symbol"],+ ),+ "dividends": TwelveDataEndpointConfig(+ path="/dividends",+ data_key="dividends",+ per_symbol=True,+ # Default `range` is only the most recent payout; `full` returns the whole history.+ params={"range": "full"},+ primary_keys=["symbol", "ex_date"],+ ),+ "splits": TwelveDataEndpointConfig(+ path="/splits",+ data_key="splits",+ per_symbol=True,+ params={"range": "full"},+ primary_keys=["symbol", "date"],+ ),+ "earnings": TwelveDataEndpointConfig(+ path="/earnings",+ data_key="earnings",+ per_symbol=True,+ # Default `outputsize` is only the most recent reports; 1000 is the documented maximum.+ params={"outputsize": "1000"},+ primary_keys=["symbol", "date"],+ ),+}++# Only /time_series exposes a genuine server-side timestamp filter (start_date); the catalog and+# fundamentals endpoints are full refresh.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ **{endpoint: [] for endpoint in ENDPOINTS},+ TIME_SERIES_ENDPOINT: [incremental_field("datetime")],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/source.pyindex 5437016aee0c..6528f92727a8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/source.py@@ -1,32 +1,172 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.twelvedata import (TwelveDataSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_data.settings import (+ DEFAULT_TIME_SERIES_INTERVAL,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ MAX_SYMBOLS,+ TIME_SERIES_INTERVALS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_data.twelve_data import (+ TwelveDataResumeConfig,+ parse_symbols,+ twelve_data_source,+ validate_credentials as validate_twelve_data_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TwelveDataSource(SimpleSource[TwelveDataSourceConfig]):+class TwelveDataSource(ResumableSource[TwelveDataSourceConfig, TwelveDataResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://twelvedata.com/docs"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TWELVEDATA+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "Twelve Data API error 401": "Your Twelve Data API key is invalid or missing. Check the key and reconnect the source.",+ "Twelve Data API error 403": "Your Twelve Data plan does not include access to this data. Upgrade your plan or deselect the table.",+ "Twelve Data API error 404": "Twelve Data could not find one of the configured symbols. Check the symbols list in the source settings.",+ "Twelve Data symbol limit exceeded": f"Too many symbols configured for the Twelve Data source. Reduce the list to at most {MAX_SYMBOLS} symbols.",+ }++ def get_retryable_errors(self) -> set[str]:+ # Credit-based rate limiting — the per-minute quota restores itself, so the sync recovers+ # on the next Temporal attempt.+ return {"Twelve Data API error 429"}++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_data.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: TwelveDataSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: TwelveDataSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ symbols = parse_symbols(config.symbols)+ if not symbols:+ return False, "Enter at least one symbol to sync"+ if len(symbols) > MAX_SYMBOLS:+ return False, f"Too many symbols — the maximum is {MAX_SYMBOLS}"++ return validate_twelve_data_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TwelveDataResumeConfig]:+ return ResumableSourceManager[TwelveDataResumeConfig](inputs, TwelveDataResumeConfig)++ def source_for_pipeline(+ self,+ config: TwelveDataSourceConfig,+ resumable_source_manager: ResumableSourceManager[TwelveDataResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return twelve_data_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ symbols=parse_symbols(config.symbols),+ interval=config.interval,+ config_start_date=(config.start_date or "").strip() or None,+ resumable_source_manager=resumable_source_manager,+ logger=inputs.logger,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TWELVE_DATA,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Twelve Data",+ caption="Import market data from Twelve Data: instrument catalogs, historical prices, quotes, dividends, splits, and earnings.",+ docsUrl="https://posthog.com/docs/cdp/sources/twelve-data",iconPath="/static/services/twelve_data.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["stocks", "forex", "crypto", "market data", "twelvedata"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="symbols",+ label="Symbols",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="AAPL, MSFT, EUR/USD",+ secret=False,+ caption=f"Comma-separated list of up to {MAX_SYMBOLS} symbols to sync in the time series, quotes, dividends, splits, and earnings tables. Each Twelve Data request is charged per symbol, so a longer list uses more of your plan's API credits.",+ ),+ SourceFieldSelectConfig(+ name="interval",+ label="Time series interval",+ required=True,+ defaultValue=DEFAULT_TIME_SERIES_INTERVAL,+ options=[+ SourceFieldSelectConfigOption(label=interval, value=interval)+ for interval in TIME_SERIES_INTERVALS+ ],+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Time series start date",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="2020-01-01",+ secret=False,+ caption="Backfill time series history from this date. Leave empty to sync only the most recent 5,000 bars per symbol.",+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/tests/test_twelve_data.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/tests/test_twelve_data.pynew file mode 100644index 000000000000..133d601da4e5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/tests/test_twelve_data.py@@ -0,0 +1,358 @@+import json+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++import structlog+from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_data import twelve_data+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_data.twelve_data import (+ TwelveDataError,+ TwelveDataResumeConfig,+ _format_time_bound,+ parse_symbols,+ twelve_data_rows,+ twelve_data_source,+ validate_credentials,+)++SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.twelve_data.twelve_data.make_tracked_session"+)++LOGGER = structlog.get_logger()+++def _response(body: Any, status: int = 200) -> Response:+ resp = Response()+ resp.status_code = status+ resp.url = "https://api.twelvedata.com/mock"+ resp.reason = "Error" if status >= 400 else "OK"+ resp._content = json.dumps(body).encode()+ return resp+++def _error_body(code: int, message: str) -> dict[str, Any]:+ return {"code": code, "message": message, "status": "error"}+++def _make_manager(resume_state: TwelveDataResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _time_series_body(symbol: str, datetimes: list[str]) -> dict[str, Any]:+ return {+ "meta": {"symbol": symbol, "interval": "1day"},+ "values": [+ {"datetime": dt, "open": "1", "high": "2", "low": "0.5", "close": "1.5", "volume": "100"}+ for dt in datetimes+ ],+ "status": "ok",+ }+++def _run(+ endpoint: str,+ responses: list[Response],+ symbols: list[str] | None = None,+ manager: mock.MagicMock | None = None,+ **kwargs: Any,+) -> tuple[list[list[dict]], mock.MagicMock, mock.MagicMock]:+ manager = manager if manager is not None else _make_manager()+ session = mock.MagicMock()+ session.get.side_effect = responses+ with mock.patch(SESSION_PATCH, return_value=session):+ batches = list(+ twelve_data_rows(+ api_key="key",+ endpoint=endpoint,+ symbols=symbols if symbols is not None else ["AAPL"],+ interval="1day",+ config_start_date=kwargs.pop("config_start_date", None),+ resumable_source_manager=manager,+ logger=LOGGER,+ **kwargs,+ )+ )+ return batches, session, manager+++def _params(session: mock.MagicMock, call_index: int) -> dict[str, Any]:+ return session.get.call_args_list[call_index].kwargs["params"]+++class TestParseSymbols:+ @parameterized.expand(+ [+ ("simple", "AAPL,MSFT", ["AAPL", "MSFT"]),+ ("whitespace", " AAPL , MSFT ", ["AAPL", "MSFT"]),+ ("blank_entries", "AAPL,,MSFT,", ["AAPL", "MSFT"]),+ ("duplicates", "AAPL,MSFT,AAPL", ["AAPL", "MSFT"]),+ ("forex_pair", "EUR/USD", ["EUR/USD"]),+ ("empty", " ", []),+ ]+ )+ def test_parse_symbols(self, _name: str, raw: str, expected: list[str]) -> None:+ assert parse_symbols(raw) == expected+++class TestFormatTimeBound:+ @parameterized.expand(+ [+ ("datetime", datetime(2026, 7, 1, 15, 30, 0, tzinfo=UTC), "2026-07-01 15:30:00"),+ ("date", date(2026, 7, 1), "2026-07-01"),+ ("string", "2026-07-01", "2026-07-01"),+ ]+ )+ def test_formats_watermark_for_start_date_param(self, _name: str, value: Any, expected: str) -> None:+ assert _format_time_bound(value) == expected+++class TestErrorEnvelope:+ @parameterized.expand(+ [+ ("unauthorized", 401, "**apikey** parameter is incorrect"),+ ("forbidden", 403, "available starting with the Grow plan"),+ ("rate_limited", 429, "You have run out of API credits"),+ ]+ )+ def test_error_envelope_raises_with_code(self, _name: str, code: int, message: str) -> None:+ # The API wraps errors in a JSON envelope (sometimes on HTTP 200) — the raised message must+ # carry the vendor code so get_non_retryable_errors / get_retryable_errors can match it.+ responses = [_response(_error_body(code, message))]+ with pytest.raises(TwelveDataError, match=f"Twelve Data API error {code}"):+ _run("quotes", responses)++ def test_no_data_in_window_is_empty_not_error(self) -> None:+ # An incremental sync with no new bars gets a code-400 "error" — it must complete cleanly,+ # not fail the job.+ responses = [+ _response(_error_body(400, "No data is available on the specified dates."), status=400),+ ]+ batches, _session, _manager = _run(+ "time_series", responses, should_use_incremental_field=True, db_incremental_field_last_value="2026-07-21"+ )+ assert batches == []+++class TestCatalogEndpoints:+ def test_catalog_rows_unwrapped_from_data_key(self) -> None:+ rows = [{"symbol": "AAPL", "mic_code": "XNGS"}, {"symbol": "AAPL", "mic_code": "XWBO"}]+ batches, session, _ = _run("stocks", [_response({"data": rows, "status": "ok"})])+ assert batches == [rows]+ assert session.get.call_count == 1++ def test_large_catalog_yields_in_chunks(self) -> None:+ rows = [{"symbol": f"S{i}", "mic_code": "X"} for i in range(twelve_data.CATALOG_CHUNK_SIZE + 1)]+ batches, _session, _ = _run("stocks", [_response({"data": rows, "status": "ok"})])+ assert [len(b) for b in batches] == [twelve_data.CATALOG_CHUNK_SIZE, 1]++ def test_catalog_does_not_touch_resume_state(self) -> None:+ _batches, _session, manager = _run("exchanges", [_response({"data": [{"code": "XNGS"}], "status": "ok"})])+ manager.save_state.assert_not_called()+++class TestPerSymbolEndpoints:+ def test_rows_carry_symbol_from_meta(self) -> None:+ body = {+ "meta": {"symbol": "AAPL"},+ "dividends": [{"ex_date": "2026-05-11", "amount": 0.27}],+ }+ batches, session, _ = _run("dividends", [_response(body)])+ assert batches == [[{"symbol": "AAPL", "ex_date": "2026-05-11", "amount": 0.27}]]+ assert _params(session, 0)["symbol"] == "AAPL"++ def test_quote_single_object_row_drops_status(self) -> None:+ body = {"symbol": "AAPL", "close": "326.47", "status": "ok"}+ batches, _session, _ = _run("quotes", [_response(body)])+ assert batches == [[{"symbol": "AAPL", "close": "326.47"}]]++ def test_iterates_each_symbol_and_bookmarks_completion(self) -> None:+ responses = [+ _response({"meta": {"symbol": "AAPL"}, "splits": [{"date": "2020-08-31", "ratio": 0.25}]}),+ _response({"meta": {"symbol": "MSFT"}, "splits": []}),+ ]+ batches, session, manager = _run("splits", responses, symbols=["AAPL", "MSFT"])+ assert [_params(session, i)["symbol"] for i in range(2)] == ["AAPL", "MSFT"]+ assert len(batches) == 1+ # A crash between symbols must resume at MSFT, not refetch AAPL.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved[0].completed_symbols == ["AAPL"]+ assert saved[-1].completed_symbols == ["AAPL", "MSFT"]++ def test_sync_rejects_too_many_symbols(self) -> None:+ # The cap must hold at sync time too, so a stored config can't bypass validation.+ symbols = [f"S{i}" for i in range(twelve_data.MAX_SYMBOLS + 1)]+ with pytest.raises(TwelveDataError, match="Twelve Data symbol limit exceeded"):+ _run("quotes", [], symbols=symbols)++ def test_resume_skips_completed_symbols(self) -> None:+ resume = TwelveDataResumeConfig(completed_symbols=["AAPL"])+ responses = [_response({"meta": {"symbol": "MSFT"}, "splits": [{"date": "2003-02-18", "ratio": 0.5}]})]+ batches, session, _ = _run("splits", responses, symbols=["AAPL", "MSFT"], manager=_make_manager(resume))+ assert session.get.call_count == 1+ assert _params(session, 0)["symbol"] == "MSFT"+ assert batches[0][0]["symbol"] == "MSFT"+++class TestTimeSeries:+ def test_first_sync_without_start_date_fetches_single_page(self) -> None:+ # Without a lower bound there is nothing to back-walk toward — even a full page must not+ # trigger endless history paging on high-frequency intervals.+ with mock.patch.object(twelve_data, "TIME_SERIES_PAGE_SIZE", 2):+ responses = [_response(_time_series_body("AAPL", ["2026-07-21", "2026-07-20"]))]+ batches, session, _ = _run("time_series", responses)+ assert session.get.call_count == 1+ assert "start_date" not in _params(session, 0)+ assert batches[0][0] == {+ "symbol": "AAPL",+ "interval": "1day",+ "datetime": "2026-07-21",+ "open": "1",+ "high": "2",+ "low": "0.5",+ "close": "1.5",+ "volume": "100",+ }++ def test_incremental_walks_back_to_watermark(self) -> None:+ with mock.patch.object(twelve_data, "TIME_SERIES_PAGE_SIZE", 3):+ responses = [+ _response(_time_series_body("AAPL", ["2026-07-21", "2026-07-20", "2026-07-19"])),+ # end_date is inclusive, so the boundary bar (07-19) comes back and must be deduped;+ # the short page ends the walk.+ _response(_time_series_body("AAPL", ["2026-07-19", "2026-07-18"])),+ ]+ batches, session, manager = _run(+ "time_series",+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 7, 18),+ )++ assert _params(session, 0)["start_date"] == "2026-07-18"+ assert "end_date" not in _params(session, 0)+ assert _params(session, 1)["start_date"] == "2026-07-18"+ assert _params(session, 1)["end_date"] == "2026-07-19"++ yielded = [(row["datetime"]) for batch in batches for row in batch]+ assert yielded == ["2026-07-21", "2026-07-20", "2026-07-19", "2026-07-18"]++ # Mid-walk checkpoint points at the next page; the final checkpoint completes the symbol.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved[0] == TwelveDataResumeConfig(+ completed_symbols=[], current_symbol="AAPL", next_end_date="2026-07-19"+ )+ assert saved[-1] == TwelveDataResumeConfig(completed_symbols=["AAPL"])++ def test_config_start_date_used_when_not_incremental(self) -> None:+ with mock.patch.object(twelve_data, "TIME_SERIES_PAGE_SIZE", 2):+ responses = [_response(_time_series_body("AAPL", ["2020-01-03", "2020-01-02"]))]+ # Short page → no further requests.+ responses[0]._content = json.dumps(_time_series_body("AAPL", ["2020-01-02"])).encode()+ _batches, session, _ = _run("time_series", responses, config_start_date="2020-01-01")+ assert _params(session, 0)["start_date"] == "2020-01-01"++ def test_page_cap_stops_history_walk(self) -> None:+ # An arbitrarily old start date on a minute interval must not walk history unbounded.+ with (+ mock.patch.object(twelve_data, "TIME_SERIES_PAGE_SIZE", 2),+ mock.patch.object(twelve_data, "MAX_TIME_SERIES_PAGES_PER_SYMBOL", 2),+ ):+ responses = [+ _response(_time_series_body("AAPL", ["2026-07-21", "2026-07-20"])),+ _response(_time_series_body("AAPL", ["2026-07-20", "2026-07-19"])),+ # Would be page 3 — must never be requested.+ _response(_time_series_body("AAPL", ["2026-07-19", "2026-07-18"])),+ ]+ batches, session, _ = _run("time_series", responses, config_start_date="2000-01-01")+ assert session.get.call_count == 2+ assert [row["datetime"] for batch in batches for row in batch] == ["2026-07-21", "2026-07-20", "2026-07-19"]++ def test_resume_mid_symbol_seeds_end_date_and_dedupes_boundary(self) -> None:+ resume = TwelveDataResumeConfig(completed_symbols=[], current_symbol="AAPL", next_end_date="2026-07-20")+ with mock.patch.object(twelve_data, "TIME_SERIES_PAGE_SIZE", 3):+ responses = [_response(_time_series_body("AAPL", ["2026-07-20", "2026-07-19"]))]+ batches, session, _ = _run(+ "time_series",+ responses,+ manager=_make_manager(resume),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-01",+ )+ assert _params(session, 0)["end_date"] == "2026-07-20"+ # The 07-20 bar was already yielded by the crashed attempt.+ assert [row["datetime"] for batch in batches for row in batch] == ["2026-07-19"]+++class TestSourceResponse:+ def test_time_series_response_shape(self) -> None:+ response = twelve_data_source(+ api_key="key",+ endpoint="time_series",+ symbols=["AAPL"],+ interval="1day",+ config_start_date=None,+ resumable_source_manager=_make_manager(),+ logger=LOGGER,+ )+ assert response.primary_keys == ["symbol", "datetime"]+ # History is walked newest → oldest, so the watermark must only persist at job end.+ assert response.sort_mode == "desc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["datetime"]++ @parameterized.expand(+ [+ ("stocks", ["symbol", "mic_code"]),+ ("exchanges", ["code"]),+ ("quotes", ["symbol"]),+ ("dividends", ["symbol", "ex_date"]),+ ("splits", ["symbol", "date"]),+ ("earnings", ["symbol", "date"]),+ ]+ )+ def test_primary_keys_and_full_refresh_shape(self, endpoint: str, primary_keys: list[str]) -> None:+ response = twelve_data_source(+ api_key="key",+ endpoint=endpoint,+ symbols=["AAPL"],+ interval="1day",+ config_start_date=None,+ resumable_source_manager=_make_manager(),+ logger=LOGGER,+ )+ assert response.primary_keys == primary_keys+ assert response.sort_mode == "asc"+ assert response.partition_mode is None+++class TestValidateCredentials:+ def test_valid_key(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response({"current_usage": 0, "plan_limit": 800})+ with mock.patch(SESSION_PATCH, return_value=session):+ assert validate_credentials("key") == (True, None)++ def test_invalid_key_surfaces_vendor_message(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(_error_body(401, "**apikey** parameter is incorrect"), status=401)+ with mock.patch(SESSION_PATCH, return_value=session):+ ok, error = validate_credentials("bad")+ assert ok is False+ assert error is not None and "401" in error++ def test_network_error_is_not_reported_as_bad_key(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = ConnectionError("boom")+ with mock.patch(SESSION_PATCH, return_value=session):+ ok, error = validate_credentials("key")+ assert ok is False+ assert error == "Could not connect to Twelve Data"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/tests/test_twelve_data_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/tests/test_twelve_data_source.pynew file mode 100644index 000000000000..d1dc82dc5e5a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/tests/test_twelve_data_source.py@@ -0,0 +1,175 @@+from typing import Any++from unittest import mock++import structlog+from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.twelvedata import (+ TwelveDataSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_data import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_data.source import TwelveDataSource+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_data.twelve_data import (+ TwelveDataResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(**overrides: Any) -> TwelveDataSourceConfig:+ values: dict[str, Any] = {"api_key": "key", "symbols": "AAPL, MSFT"}+ values.update(overrides)+ return TwelveDataSourceConfig(**values)+++def _inputs(+ schema_name: str,+ should_use_incremental: bool = False,+ last_value: Any = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=should_use_incremental,+ db_incremental_field_last_value=last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="datetime",+ incremental_field_type=None,+ job_id="job-1",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestTwelveDataSource:+ def setup_method(self) -> None:+ self.source = TwelveDataSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.TWELVEDATA++ def test_source_is_released_as_alpha(self) -> None:+ # unreleasedSource hides the connector from every user — a finished source must not carry it.+ config = self.source.get_source_config+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_fields(self) -> None:+ fields = {field.name: field for field in self.source.get_source_config.fields}+ assert set(fields) == {"api_key", "symbols", "interval", "start_date"}++ api_key = fields["api_key"]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.required is True+ assert api_key.secret is True++ symbols = fields["symbols"]+ assert isinstance(symbols, SourceFieldInputConfig)+ assert symbols.required is True++ interval = fields["interval"]+ assert isinstance(interval, SourceFieldSelectConfig)+ assert interval.defaultValue == "1day"+ assert any(option.value == "1min" for option in interval.options)++ start_date = fields["start_date"]+ assert isinstance(start_date, SourceFieldInputConfig)+ assert start_date.required is False++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — required so the public docs render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_only_time_series_is_incremental(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=1)+ incremental = [schema.name for schema in schemas if schema.supports_incremental]+ assert incremental == ["time_series"]++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=1, names=["quotes", "time_series"])+ assert {schema.name for schema in schemas} == {"quotes", "time_series"}++ @parameterized.expand(+ [+ ("valid", "AAPL", (True, None), True, None),+ (+ "bad_key",+ "AAPL",+ (False, "Twelve Data API error 401: bad key"),+ False,+ "Twelve Data API error 401: bad key",+ ),+ ]+ )+ def test_validate_credentials_delegates_to_probe(+ self,+ _name: str,+ symbols: str,+ probe_result: tuple[bool, str | None],+ expected_ok: bool,+ expected_error: str | None,+ ) -> None:+ with mock.patch.object(source_module, "validate_twelve_data_credentials", return_value=probe_result):+ ok, error = self.source.validate_credentials(_config(symbols=symbols), team_id=1)+ assert ok is expected_ok+ assert error == expected_error++ def test_validate_credentials_requires_a_symbol(self) -> None:+ with mock.patch.object(source_module, "validate_twelve_data_credentials") as probe:+ ok, error = self.source.validate_credentials(_config(symbols=" , "), team_id=1)+ assert ok is False+ assert error == "Enter at least one symbol to sync"+ probe.assert_not_called()++ def test_validate_credentials_rejects_too_many_symbols(self) -> None:+ # Guards the fan-out cap: every per-symbol table issues one request per symbol.+ symbols = ",".join(f"S{i}" for i in range(source_module.MAX_SYMBOLS + 1))+ with mock.patch.object(source_module, "validate_twelve_data_credentials") as probe:+ ok, error = self.source.validate_credentials(_config(symbols=symbols), team_id=1)+ assert ok is False+ assert error == f"Too many symbols — the maximum is {source_module.MAX_SYMBOLS}"+ probe.assert_not_called()++ def test_resumable_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_inputs("time_series"))+ assert manager._data_class is TwelveDataResumeConfig++ def test_source_for_pipeline_plumbs_config(self) -> None:+ inputs = _inputs("time_series", should_use_incremental=True, last_value="2026-07-01")+ manager = mock.MagicMock()+ with mock.patch.object(source_module, "twelve_data_source") as transport:+ self.source.source_for_pipeline(_config(start_date=" 2020-01-01 "), manager, inputs)++ transport.assert_called_once_with(+ api_key="key",+ endpoint="time_series",+ symbols=["AAPL", "MSFT"],+ interval="1day",+ config_start_date="2020-01-01",+ resumable_source_manager=manager,+ logger=inputs.logger,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-01",+ )++ def test_source_for_pipeline_drops_watermark_on_full_refresh(self) -> None:+ # A stale watermark from a previous incremental setup must not bound a full refresh.+ inputs = _inputs("time_series", should_use_incremental=False, last_value="2026-07-01")+ with mock.patch.object(source_module, "twelve_data_source") as transport:+ self.source.source_for_pipeline(_config(), mock.MagicMock(), inputs)+ assert transport.call_args.kwargs["db_incremental_field_last_value"] is None+ assert transport.call_args.kwargs["config_start_date"] is None++ def test_auth_and_symbol_errors_are_non_retryable(self) -> None:+ # Without these, a revoked key or a typoed symbol retries forever.+ non_retryable = self.source.get_non_retryable_errors()+ for code in (401, 403, 404):+ assert any(f"Twelve Data API error {code}" in key for key in non_retryable)++ def test_rate_limit_errors_are_retryable(self) -> None:+ assert any("429" in key for key in self.source.get_retryable_errors())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/twelve_data.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/twelve_data.pynew file mode 100644index 000000000000..835152d107ff--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/twelve_data.py@@ -0,0 +1,302 @@+import dataclasses+from collections.abc import Iterator+from datetime import date, datetime+from typing import Any, Optional++from requests import Session+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.twelve_data.settings import (+ ENDPOINTS,+ MAX_SYMBOLS,+ MAX_TIME_SERIES_PAGES_PER_SYMBOL,+ TIME_SERIES_ENDPOINT,+ TIME_SERIES_PAGE_SIZE,+ TWELVE_DATA_BASE_URL,+ TwelveDataEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60++# Rows per yielded batch for the large reference catalogs (the full /stocks dump is >100k rows).+CATALOG_CHUNK_SIZE = 5000+++class TwelveDataError(Exception):+ pass+++class TwelveDataResumeConfig:+ # Symbols whose rows were fully yielded this job; a resumed attempt skips them.+ completed_symbols: list[str] = dataclasses.field(default_factory=list)+ # Symbol mid-way through its time series back-walk, and the end_date the next page should use.+ current_symbol: str | None = None+ next_end_date: str | None = None+++def parse_symbols(symbols: str) -> list[str]:+ """Split the user's comma-separated symbol list, dropping blanks and duplicates."""+ parsed = []+ for raw in symbols.split(","):+ symbol = raw.strip()+ if symbol and symbol not in parsed:+ parsed.append(symbol)+ return parsed+++def _make_session(api_key: str) -> Session:+ return make_tracked_session(+ headers={"Authorization": f"apikey {api_key}"},+ redact_values=(api_key,),+ )+++def _fetch(session: Session, path: str, params: dict[str, Any]) -> Any:+ """GET a Twelve Data endpoint, unwrapping the API's JSON error envelope.++ The API reports errors as ``{"code": ..., "message": ..., "status": "error"}`` — sometimes with a+ matching HTTP status, sometimes on HTTP 200 — so the body is inspected before the status code.+ Returns ``None`` when the requested date window simply has no rows (the API reports that as a+ code-400 error rather than an empty list).+ """+ response = session.get(f"{TWELVE_DATA_BASE_URL}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ try:+ body = response.json()+ except ValueError:+ body = None++ if isinstance(body, dict) and body.get("status") == "error":+ code = body.get("code")+ message = body.get("message", "")+ if code == 400 and "No data is available" in message:+ return None+ raise TwelveDataError(f"Twelve Data API error {code}: {message}")++ response.raise_for_status()+ return body+++def _format_time_bound(value: Any) -> str:+ if isinstance(value, datetime):+ return value.strftime("%Y-%m-%d %H:%M:%S")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%d")+ return str(value)+++def _catalog_rows(session: Session, endpoint_config: TwelveDataEndpointConfig) -> Iterator[list[dict]]:+ body = _fetch(session, endpoint_config.path, dict(endpoint_config.params))+ rows = (body or {}).get(endpoint_config.data_key) or []+ for chunk_start in range(0, len(rows), CATALOG_CHUNK_SIZE):+ yield rows[chunk_start : chunk_start + CATALOG_CHUNK_SIZE]+++def _symbol_rows(session: Session, endpoint_config: TwelveDataEndpointConfig, symbol: str) -> list[dict]:+ """One-shot per-symbol endpoints (quote, dividends, splits, earnings)."""+ params = {"symbol": symbol, **endpoint_config.params}+ body = _fetch(session, endpoint_config.path, params)+ if not body:+ return []++ if endpoint_config.data_key is None:+ row = {key: value for key, value in body.items() if key != "status"}+ return [row] if row else []++ meta = body.get("meta") or {}+ rows = body.get(endpoint_config.data_key) or []+ return [{"symbol": meta.get("symbol", symbol), **row} for row in rows]+++def _time_series_pages(+ session: Session,+ symbol: str,+ interval: str,+ start_date: str | None,+ seeded_end_date: str | None,+ logger: FilteringBoundLogger,+) -> Iterator[tuple[list[dict], str | None]]:+ """Walk a symbol's bars from newest to oldest, yielding ``(rows, next_end_date)`` per page.++ ``outputsize`` always selects the most recent rows inside the date window regardless of the+ requested order (verified against the live API), so history deeper than one page is reached by+ moving ``end_date`` back to the oldest bar received. Without a lower bound (no ``start_date``)+ only the most recent page is fetched, keeping first syncs bounded on high-frequency intervals.+ The walk is additionally capped at ``MAX_TIME_SERIES_PAGES_PER_SYMBOL`` pages per run so an+ arbitrarily old start date on a minute interval can't occupy a worker with unbounded requests.+ """+ end_date = seeded_end_date+ # Oldest datetime already yielded — end_date is inclusive, so the boundary bar comes back on+ # the next page and must be dropped to avoid duplicate rows within one sync.+ boundary = seeded_end_date+ pages_fetched = 0++ while True:+ if pages_fetched >= MAX_TIME_SERIES_PAGES_PER_SYMBOL:+ logger.warning(+ "Twelve Data: time_series page cap reached, stopping history walk",+ symbol=symbol,+ interval=interval,+ start_date=start_date,+ pages_fetched=pages_fetched,+ )+ return+ params: dict[str, Any] = {+ "symbol": symbol,+ "interval": interval,+ "outputsize": TIME_SERIES_PAGE_SIZE,+ "order": "DESC",+ }+ if start_date:+ params["start_date"] = start_date+ if end_date:+ params["end_date"] = end_date++ body = _fetch(session, "/time_series", params)+ pages_fetched += 1+ if body is None:+ return++ meta = body.get("meta") or {}+ values = body.get("values") or []+ full_page = len(values) >= TIME_SERIES_PAGE_SIZE+ # Bar datetimes are unique per symbol+interval and lexicographically ordered in the API's+ # own string format, so a string comparison is safe here.+ if boundary is not None:+ values = [value for value in values if value.get("datetime", "") < boundary]+ if not values:+ return++ oldest = values[-1].get("datetime")+ rows = [{"symbol": meta.get("symbol", symbol), "interval": interval, **value} for value in values]++ has_more = full_page and start_date is not None and oldest is not None+ yield rows, (oldest if has_more else None)++ if not has_more:+ return+ boundary = oldest+ end_date = oldest+++def twelve_data_rows(+ api_key: str,+ endpoint: str,+ symbols: list[str],+ interval: str,+ config_start_date: str | None,+ resumable_source_manager: ResumableSourceManager[TwelveDataResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> Iterator[list[dict]]:+ endpoint_config = ENDPOINTS[endpoint]+ session = _make_session(api_key)++ if not endpoint_config.per_symbol:+ yield from _catalog_rows(session, endpoint_config)+ return++ # Re-checked at sync time (not just config validation) so a previously stored config can't+ # bypass the fan-out cap.+ if len(symbols) > MAX_SYMBOLS:+ raise TwelveDataError(+ f"Twelve Data symbol limit exceeded: {len(symbols)} symbols configured, maximum is {MAX_SYMBOLS}"+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ completed = [s for s in (resume.completed_symbols if resume else []) if s in symbols]+ resume_symbol = resume.current_symbol if resume else None+ resume_end_date = resume.next_end_date if resume else None+ if resume is not None:+ logger.debug(+ f"Twelve Data: resuming {endpoint} — {len(completed)} symbols done, "+ f"current_symbol={resume_symbol}, next_end_date={resume_end_date}"+ )++ start_date: str | None+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ start_date = _format_time_bound(db_incremental_field_last_value)+ else:+ start_date = config_start_date or None++ for symbol in symbols:+ if symbol in completed:+ continue++ if endpoint == TIME_SERIES_ENDPOINT:+ seeded_end_date = resume_end_date if symbol == resume_symbol else None+ for rows, next_end_date in _time_series_pages(+ session, symbol, interval, start_date, seeded_end_date, logger+ ):+ yield rows+ # Save AFTER yielding so a crash re-yields the last page instead of skipping it;+ # merge dedupes the overlap on the primary key.+ if next_end_date is not None:+ resumable_source_manager.save_state(+ TwelveDataResumeConfig(+ completed_symbols=completed, current_symbol=symbol, next_end_date=next_end_date+ )+ )+ else:+ rows = _symbol_rows(session, endpoint_config, symbol)+ if rows:+ yield rows++ completed = [*completed, symbol]+ resumable_source_manager.save_state(TwelveDataResumeConfig(completed_symbols=completed))+++def twelve_data_source(+ api_key: str,+ endpoint: str,+ symbols: list[str],+ interval: str,+ config_start_date: str | None,+ resumable_source_manager: ResumableSourceManager[TwelveDataResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = ENDPOINTS[endpoint]+ is_time_series = endpoint == TIME_SERIES_ENDPOINT++ return SourceResponse(+ name=endpoint,+ items=lambda: twelve_data_rows(+ api_key=api_key,+ endpoint=endpoint,+ symbols=symbols,+ interval=interval,+ config_start_date=config_start_date,+ resumable_source_manager=resumable_source_manager,+ logger=logger,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Time series history is walked newest → oldest, so the incremental watermark must only+ # persist once the whole run completes (desc semantics), like Stripe.+ sort_mode="desc" if is_time_series else "asc",+ partition_count=1 if endpoint_config.partition_key else None,+ partition_size=1 if endpoint_config.partition_key else None,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ """Cheap token probe — /api_usage responds for every plan and costs no API credits."""+ session = _make_session(api_key)+ try:+ _fetch(session, "/api_usage", {})+ except TwelveDataError as e:+ return False, str(e)+ except Exception:+ return False, "Could not connect to Twelve Data"+ return True, None