Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse_sources): add marketstack lookup tables (#115052)

Tom Owers2e8d57a5d039
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 1ad72c639872..c6bc31471434 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
@@ -5446,12 +5446,13 @@ Today (8): `currencies`, `dividends`, `eod`, `exchanges`, `intraday`, `splits`,
Diffed against: <https://api.swaggerhub.com/apis/apilayer-863/MarketstackAPIv2/2.0.0/swagger.json>
-- [ ] `/tickerinfo` — Company profile/fundamentals per symbol - the lookup table that resolves the tickers we already sync (high)
+- [x] `/tickerinfo` — Company profile/fundamentals per symbol - the lookup table that resolves the tickers we already sync (high). Added as `tickerinfo` (one request per configured symbol, v2 only).
- [ ] `/indexlist and /indexinfo` — Market index reference and metadata; benchmarking EOD prices against indices is a core use case (medium)
-- [ ] `/etfholdings` — Constituent breakdown per ETF, a genuine breakdown dimension (medium)
+- [ ] `/etfholdings` — Constituent breakdown per ETF, a genuine breakdown dimension (medium). Skipped for now: the spec documents `limit`/`offset` and a date range on a single-filing response with no pagination block, holdings carry no documented unique identifier, and each call costs 20x quota, so the row grain can't be pinned down without a live account.
- [ ] `/commodities and /commoditieshistory` — Commodity price time series alongside the equity EOD series (medium)
-- [ ] `/companyratings` — Analyst ratings per ticker, a common join onto price history (medium)
-- [ ] `/company_facts and /submissions` — SEC filing facts and submission history keyed by CIK, for fundamentals analysis (medium)
+- [x] `/companyratings` — Analyst ratings per ticker, a common join onto price history (medium). Added as `companyratings` (one row per analyst rating, one request per configured symbol paced to the endpoint's one-call-per-minute limit, v2 only).
+- [x] `/submissions` — SEC submission history keyed by CIK, for fundamentals analysis (medium). Added as `submissions` (one row per recent filing, one request per configured CIK code, v2 only).
+- [ ] `/company_facts` — SEC XBRL filing facts keyed by CIK, for fundamentals analysis (medium). Skipped for now: facts are nested under dynamic taxonomy/concept/unit keys with no unique fact identifier, and the documented `limit`/`offset` don't say what they page over on a single-company response.
- [ ] `/bondlist and /bond` — Bond reference and pricing data for fixed-income coverage (low)
- [ ] `/etflist` — Lookup table of ETFs that etfholdings rows reference (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/marketstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/marketstack.py
index 9557cef26261..0a0fdbd92830 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/marketstack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/marketstack.py
@@ -8,3 +8,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
class MarketstackSourceConfig(config.Config):
access_key: str
symbols: str | None = None
+ cik_codes: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/canonical_descriptions.py
index 6aa77d36da1e..892905edbdcf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/canonical_descriptions.py
@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
)
_DOCS_URL = "https://marketstack.com/documentation"
+_DOCS_V2_URL = "https://marketstack.com/documentation_v2"
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"eod": {
@@ -66,6 +67,62 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"dividend": "Dividend amount paid per share on this date.",
},
},
+ "tickerinfo": {
+ "description": "Extended company and listing information per ticker, including sector, industry, description, and key identifiers.",
+ "docs_url": _DOCS_V2_URL,
+ "columns": {
+ "ticker": "Ticker symbol.",
+ "name": "Company or instrument name.",
+ "item_type": "Type of item (e.g. equity).",
+ "sector": "Sector of the company.",
+ "industry": "Industry of the company.",
+ "exchange_code": "Exchange code.",
+ "full_time_employees": "Number of full-time employees.",
+ "ipo_date": "IPO date.",
+ "date_founded": "Date founded.",
+ "key_executives": "Key executives with name, function, salary, exercised options, and birth year.",
+ "incorporation": "State or country of incorporation.",
+ "start_fiscal": "Fiscal year start (MM-DD).",
+ "end_fiscal": "Fiscal year end (MM-DD).",
+ "previous_names": "Previous names of the company.",
+ "stock_exchanges": "Exchanges the ticker is listed on.",
+ "reporting_currency": "Reporting currency.",
+ "website": "Company website.",
+ "about": "Company description.",
+ },
+ },
+ "companyratings": {
+ "description": "Individual analyst buy/sell/hold ratings and price targets per ticker.",
+ "docs_url": _DOCS_V2_URL,
+ "columns": {
+ "ticker": "Ticker symbol.",
+ "company_name": "Name of the company.",
+ "analyst_name": "Name of the analyst.",
+ "analyst_firm": "Firm the analyst works for.",
+ "analyst_role": "Role of the analyst.",
+ "date_rating": "Date of the rating.",
+ "target_date": "Date the price target applies to.",
+ "price_target": "Price target set by the analyst.",
+ "rated": "Rating given by the analyst (buy, sell, or hold).",
+ "conclusion": "Conclusion of the rating.",
+ },
+ },
+ "submissions": {
+ "description": "Recent SEC filing submissions per company, one row per filing.",
+ "docs_url": _DOCS_V2_URL,
+ "columns": {
+ "cik_code": "SEC Central Index Key of the filer (zero-padded).",
+ "company_name": "Company name.",
+ "accession_number": "Accession number of the filing.",
+ "filing_date": "Date the filing was made.",
+ "report_date": "Date of the reporting period.",
+ "acceptance_date_time": "Time the SEC accepted the filing.",
+ "form": "Filing form type (e.g. 10-K, 10-Q, 8-K).",
+ "file_number": "SEC file number.",
+ "primary_document": "File name of the primary document.",
+ "primary_doc_description": "Description of the primary document.",
+ },
+ },
"tickers": {
"description": "Reference table of supported stock tickers with name, exchange, and EOD/intraday availability.",
"docs_url": _DOCS_URL,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.mdx
index 3a3dcda120f3..85da28423a48 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.mdx
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.mdx
@@ -14,7 +14,7 @@ import AlphaRelease from '../_snippets/alpha-release.mdx'
<AlphaRelease />
-[Marketstack](https://marketstack.com) (an APILayer product) is a REST API for real-time, intraday, and historical stock market data covering 70+ exchanges and 125,000+ tickers. Linking Marketstack as a source pulls end-of-day, intraday, splits, and dividends data along with market reference tables (tickers, exchanges, currencies, timezones) into your PostHog Data warehouse, where you can join it with your product data.
+[Marketstack](https://marketstack.com) (an APILayer product) is a REST API for real-time, intraday, and historical stock market data covering 70+ exchanges and 125,000+ tickers. Linking Marketstack as a source pulls end-of-day, intraday, splits, and dividends data, company profiles, analyst ratings, and SEC filings along with market reference tables (tickers, exchanges, currencies, timezones) into your PostHog Data warehouse, where you can join it with your product data.
## Prerequisites
@@ -30,7 +30,10 @@ Before connecting Marketstack, you need:
When configuring the source, provide:
- **Access key**: your Marketstack API access key from the [dashboard](https://marketstack.com/dashboard).
-- **Symbols** (optional): a comma-separated list of ticker symbols, e.g. `AAPL,MSFT,TSLA`. Symbols are **required** for the EOD, intraday, splits, and dividends tables — those endpoints return data per symbol. The reference tables (tickers, exchanges, currencies, timezones) don't need symbols.
+- **Symbols** (optional): a comma-separated list of ticker symbols, e.g. `AAPL,MSFT,TSLA`. Symbols are **required** for the EOD, intraday, splits, dividends, ticker info, and company ratings tables — those endpoints return data per symbol. The reference tables (tickers, exchanges, currencies, timezones) don't need symbols.
+- **CIK codes** (optional): a comma-separated list of SEC Central Index Key codes, e.g. `0000320193`. CIK codes are **required** for the submissions table.
+
+The `tickerinfo`, `companyratings`, and `submissions` tables are only available on Marketstack API v2. The `companyratings` endpoint allows one request per minute, so each symbol adds about a minute to its sync.
Marketstack enforces a rate limit of 5 requests per second and a monthly request quota tied to your plan, so keep the number of symbols and the historical range in mind when backfilling.
@@ -38,7 +41,7 @@ Marketstack enforces a rate limit of 5 requests per second and a monthly request
<SyncModes />
-The time-series tables (`eod`, `intraday`, `splits`, `dividends`) support incremental sync — after the first backfill, each run only requests data on or after the latest synced `date`, using Marketstack's `date_from` filter. The reference tables (`tickers`, `exchanges`, `currencies`, `timezones`) are full-refresh snapshots.
+The time-series tables (`eod`, `intraday`, `splits`, `dividends`) support incremental sync — after the first backfill, each run only requests data on or after the latest synced `date`, using Marketstack's `date_from` filter. The reference and lookup tables (`tickers`, `exchanges`, `currencies`, `timezones`, `tickerinfo`, `companyratings`, `submissions`) are full-refresh snapshots.
## Configuration
@@ -50,7 +53,8 @@ The time-series tables (`eod`, `intraday`, `splits`, `dividends`) support increm
## Troubleshooting
-- **`missing_symbols` / no rows for EOD, intraday, splits, or dividends**: these tables require at least one symbol. Add symbols to the source configuration and resync.
+- **`missing_symbols` / no rows for EOD, intraday, splits, dividends, ticker info, or company ratings**: these tables require at least one symbol. Add symbols to the source configuration and resync.
+- **`missing_cik_codes`**: the submissions table requires at least one CIK code. Add CIK codes to the source configuration and resync.
- **`function_access_restricted`**: your Marketstack plan doesn't include this endpoint (intraday requires a paid plan). Upgrade your plan or deselect the restricted table.
- **`usage_limit_reached`**: you've hit your monthly request quota. Upgrade your plan or wait for the quota to reset, then resync.
- **`invalid_access_key`**: the access key is wrong or deactivated. Generate a new key in your Marketstack dashboard and reconnect.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py
index 88d0309b5916..26a04d0551e1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py
@@ -1,19 +1,32 @@
import dataclasses
+from collections.abc import Iterator
from datetime import date
from typing import Any, Optional
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.interruptible_wait import (
+ interruptible_wait,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
+ create_response_hooks,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
OffsetPaginator,
+ SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.settings import MARKETSTACK_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.settings import (
+ MARKETSTACK_ENDPOINTS,
+ MarketstackEndpointConfig,
+)
# Opaque Marketstack version labels (never parsed/ordered). Each version is served under its own
# path segment; the source pin selects the base URL. v1 is deprecated (vendor sunset 2025-06-30);
@@ -57,9 +70,10 @@ _PERMANENT_BODY_CODES = (
)
[email protected](frozen=True)
class MarketstackResumeConfig:
- # Offset of the next page to fetch — Marketstack uses limit/offset pagination.
+ # Offset of the next page to fetch — Marketstack uses limit/offset pagination. Fan-out
+ # endpoints store the index of the next ticker / CIK to request instead.
next_offset: int
@@ -104,6 +118,97 @@ def _response_actions() -> list[ResponseAction]:
return actions
+def _split_values(raw: str | None) -> list[str]:
+ values = (value.strip() for value in (raw or "").split(","))
+ return list(dict.fromkeys(value for value in values if value))
+
+
+def _company_rating_rows(item: dict[str, Any], ticker: str) -> list[dict[str, Any]]:
+ basics = item.get("basics") or {}
+ analysts = (item.get("output") or {}).get("analysts") or []
+ rows = []
+ for analyst in analysts:
+ row = {key: value for key, value in analyst.items() if key != "rating"}
+ row.update(analyst.get("rating") or {})
+ rows.append({"ticker": basics.get("ticker") or ticker, "company_name": basics.get("company_name"), **row})
+ return rows
+
+
+def _filing_rows(item: dict[str, Any]) -> list[dict[str, Any]]:
+ # SEC returns recent filings as parallel arrays, one array per field.
+ recent = (item.get("filings") or {}).get("recent") or {}
+ columns = {key: values for key, values in recent.items() if isinstance(values, list)}
+ count = len(columns.get("accession_number") or [])
+ company = {"cik_code": item.get("cik_code"), "company_name": item.get("company_name")}
+ return [
+ {**company, **{key: values[i] if i < len(values) else None for key, values in columns.items()}}
+ for i in range(count)
+ ]
+
+
+def _shape_rows(endpoint: str, item: dict[str, Any], value: str) -> list[dict[str, Any]]:
+ if endpoint == "companyratings":
+ return _company_rating_rows(item, value)
+ if endpoint == "submissions":
+ return _filing_rows(item)
+ return [{"ticker": value, **item}]
+
+
+def _fan_out_pages(
+ client: RESTClient,
+ config: MarketstackEndpointConfig,
+ values: list[str],
+ resumable_source_manager: ResumableSourceManager[MarketstackResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ assert config.fan_out_param is not None
+ start = 0
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ start = resume.next_offset
+ hooks = create_response_hooks(_response_actions(), resource_name=config.name)
+
+ for index in range(start, len(values)):
+ if index > start and config.request_interval_seconds:
+ interruptible_wait(config.request_interval_seconds, safe_point=resumable_source_manager.safe_point)
+ rows: list[dict[str, Any]] = []
+ for page in client.paginate(
+ path=config.path,
+ params={config.fan_out_param: values[index]},
+ data_selector=config.data_selector,
+ data_selector_required=True,
+ hooks=hooks,
+ ):
+ for item in page:
+ rows.extend(_shape_rows(config.name, item, values[index]))
+ if index + 1 < len(values):
+ resumable_source_manager.save_state(MarketstackResumeConfig(next_offset=index + 1))
+ if rows:
+ yield rows
+ else:
+ resumable_source_manager.safe_point()
+
+
+def _fan_out_source(
+ access_key: str,
+ config: MarketstackEndpointConfig,
+ values: list[str],
+ resumable_source_manager: ResumableSourceManager[MarketstackResumeConfig],
+ api_version: str,
+) -> SourceResponse:
+ client = RESTClient(
+ base_url=marketstack_base_url(api_version),
+ auth=APIKeyAuth(api_key=access_key, name="access_key", location="query"),
+ paginator=SinglePagePaginator(),
+ )
+ return SourceResponse(
+ name=config.name,
+ items=lambda: _fan_out_pages(client, config, values, resumable_source_manager),
+ primary_keys=config.primary_keys,
+ sort_mode="asc",
+ )
+
+
def marketstack_source(
access_key: str,
endpoint: str,
@@ -113,9 +218,20 @@ def marketstack_source(
api_version: str,
symbols: str | None = None,
db_incremental_field_last_value: Optional[Any] = None,
+ cik_codes: str | None = None,
) -> SourceResponse:
config = MARKETSTACK_ENDPOINTS[endpoint]
+ if config.fan_out_over is not None:
+ values = _split_values(symbols if config.fan_out_over == "symbols" else cik_codes)
+ if not values:
+ raise ValueError(
+ f"Marketstack API error [missing_{config.fan_out_over}]: the '{endpoint}' table requires one or "
+ f"more {'symbols' if config.fan_out_over == 'symbols' else 'CIK codes'}. Add them to the source "
+ "configuration, then resync."
+ )
+ return _fan_out_source(access_key, config, values, resumable_source_manager, api_version)
+
if config.requires_symbols and not (symbols and symbols.strip()):
# Selecting a time-series table with no symbols is a permanent misconfiguration; fail loud
# with a fix-it message rather than issuing a request that can never make progress.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/settings.py
index 103b2b784f1b..6f117d102247 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/settings.py
@@ -1,4 +1,5 @@
import dataclasses
+from typing import Literal
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -23,7 +24,7 @@ _DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [
]
[email protected](frozen=True)
class MarketstackEndpointConfig:
name: str
path: str
@@ -36,6 +37,15 @@ class MarketstackEndpointConfig:
# Stable datetime column for datetime partitioning (`date` never changes for a given row).
partition_key: str | None = None
description: str | None = None
+ # Lookup endpoints take one ticker / CIK per request, so they are requested once per value in
+ # the named source config list, with the value passed as `fan_out_param`.
+ fan_out_over: Literal["symbols", "cik_codes"] | None = None
+ fan_out_param: str | None = None
+ data_selector: str = "data"
+ # Only served under v2; hidden from sources still pinned to v1.
+ v2_only: bool = False
+ # Minimum spacing between fan-out requests, for endpoints with their own tighter rate limit.
+ request_interval_seconds: float = 0
MARKETSTACK_ENDPOINTS: dict[str, MarketstackEndpointConfig] = {
@@ -81,6 +91,37 @@ MARKETSTACK_ENDPOINTS: dict[str, MarketstackEndpointConfig] = {
partition_key="date",
description="Historical dividend payouts per symbol. Requires symbols. Incremental on date.",
),
+ "tickerinfo": MarketstackEndpointConfig(
+ name="tickerinfo",
+ path="/tickerinfo",
+ primary_keys=["ticker"],
+ fan_out_over="symbols",
+ fan_out_param="ticker",
+ v2_only=True,
+ description="Company profile per configured symbol: sector, industry, executives, addresses, and listing exchanges. Requires symbols. Full refresh.",
+ ),
+ "companyratings": MarketstackEndpointConfig(
+ name="companyratings",
+ path="/companyratings",
+ # Analyst ids are not exposed; an analyst rates a ticker at most once per day.
+ primary_keys=["ticker", "analyst_firm", "analyst_name", "date_rating"],
+ fan_out_over="symbols",
+ fan_out_param="ticker",
+ data_selector="result",
+ v2_only=True,
+ # The endpoint allows one call per minute.
+ request_interval_seconds=60,
+ description="Individual analyst ratings and price targets per configured symbol. Requires symbols. Rate-limited by Marketstack to one request per minute, so each symbol adds a minute to the sync. Full refresh.",
+ ),
+ "submissions": MarketstackEndpointConfig(
+ name="submissions",
+ path="/submissions",
+ primary_keys=["accession_number"],
+ fan_out_over="cik_codes",
+ fan_out_param="cik_code",
+ v2_only=True,
+ description="Recent SEC filings (10-K, 10-Q, 8-K, and others) per configured CIK code, one row per filing. Requires CIK codes. Full refresh.",
+ ),
"tickers": MarketstackEndpointConfig(
name="tickers",
path="/tickers",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py
index eeda8a24db97..66ddd8bc801f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py
@@ -63,7 +63,8 @@ class MarketstackSource(ResumableSource[MarketstackSourceConfig, MarketstackResu
"Marketstack API error [https_access_restricted]": "Your Marketstack plan does not allow HTTPS access. Upgrade your Marketstack plan, then reconnect.",
# The time-series tables need at least one symbol; without one the sync can never make
# progress, so fail permanently with a fix-it message rather than retrying.
- "Marketstack API error [missing_symbols]": "One or more of the selected tables (EOD, intraday, splits, dividends) requires symbols. Add symbols to the source configuration, then resync.",
+ "Marketstack API error [missing_symbols]": "One or more of the selected tables (EOD, intraday, splits, dividends, ticker info, company ratings) requires symbols. Add symbols to the source configuration, then resync.",
+ "Marketstack API error [missing_cik_codes]": "The submissions table requires one or more SEC CIK codes. Add CIK codes to the source configuration, then resync.",
"Marketstack API error [no_valid_symbols_provided]": "None of the configured symbols are valid Marketstack tickers. Check the symbols in the source configuration, then resync.",
}
@@ -83,8 +84,9 @@ class MarketstackSource(ResumableSource[MarketstackSourceConfig, MarketstackResu
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # The endpoint catalog and incremental fields are identical across v1 and v2 (v2 only adds
- # response columns, absorbed by the auto-inferred schema), so discovery ignores the pin.
+ # v2 adds response columns to the shared endpoints (absorbed by the auto-inferred schema) and
+ # adds lookup endpoints that v1 doesn't serve, so only those depend on the pin.
+ is_v1 = self.resolve_api_version(api_version) == MARKETSTACK_API_VERSION_V1
schemas = [
SourceSchema(
name=endpoint.name,
@@ -96,6 +98,7 @@ class MarketstackSource(ResumableSource[MarketstackSourceConfig, MarketstackResu
description=endpoint.description,
)
for endpoint in MARKETSTACK_ENDPOINTS.values()
+ if not (is_v1 and endpoint.v2_only)
]
if names is not None:
@@ -135,6 +138,7 @@ class MarketstackSource(ResumableSource[MarketstackSourceConfig, MarketstackResu
resumable_source_manager=resumable_source_manager,
api_version=self.resolve_api_version(inputs.api_version),
symbols=config.symbols,
+ cik_codes=config.cik_codes,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
else None,
@@ -151,7 +155,9 @@ class MarketstackSource(ResumableSource[MarketstackSourceConfig, MarketstackResu
You can find your access key in your [Marketstack dashboard](https://marketstack.com/dashboard).
-Add one or more comma-separated **symbols** (e.g. `AAPL,MSFT,TSLA`) to sync the EOD, intraday, splits, and dividends tables — those endpoints require at least one symbol. The reference tables don't need symbols.
+Add one or more comma-separated **symbols** (e.g. `AAPL,MSFT,TSLA`) to sync the EOD, intraday, splits, dividends, ticker info, and company ratings tables — those endpoints require at least one symbol. The reference tables don't need symbols.
+
+Add one or more comma-separated SEC **CIK codes** (e.g. `0000320193`) to sync the submissions table.
Note: Marketstack pricing is a monthly request quota tied to your plan. Some tables (e.g. intraday) require a paid plan.""",
iconPath="/static/services/marketstack.png",
@@ -175,6 +181,14 @@ Note: Marketstack pricing is a monthly request quota tied to your plan. Some tab
placeholder="AAPL,MSFT,TSLA",
secret=False,
),
+ SourceFieldInputConfig(
+ name="cik_codes",
+ label="CIK codes",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="0000320193,0000789019",
+ secret=False,
+ ),
],
),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py
index 5f793b121b9d..555406d0eb7a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py
@@ -12,6 +12,13 @@ from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClientRetryableError,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.marketstack import (
+ MarketstackSourceConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.marketstack import (
MARKETSTACK_API_VERSION_V1,
MARKETSTACK_API_VERSION_V2,
@@ -21,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.marketstac
marketstack_source,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.source import MarketstackSource
# RESTClient builds its session via make_tracked_session in the rest_client module.
CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
@@ -141,12 +149,22 @@ class TestPagination:
class TestRequiresSymbols:
- @parameterized.expand([("eod",), ("intraday",), ("splits",), ("dividends",)])
- def test_time_series_endpoints_require_symbols(self, endpoint: str) -> None:
- # Selecting a time-series table with no symbols is a permanent misconfiguration.
+ @parameterized.expand(
+ [
+ ("eod", "[missing_symbols]"),
+ ("intraday", "[missing_symbols]"),
+ ("splits", "[missing_symbols]"),
+ ("dividends", "[missing_symbols]"),
+ ("tickerinfo", "[missing_symbols]"),
+ ("companyratings", "[missing_symbols]"),
+ ("submissions", "[missing_cik_codes]"),
+ ]
+ )
+ def test_endpoints_require_their_lookup_values(self, endpoint: str, expected_code: str) -> None:
+ # Selecting a table with nothing to look up is a permanent misconfiguration.
with pytest.raises(ValueError) as exc:
_source(endpoint, symbols=None)
- assert "[missing_symbols]" in str(exc.value)
+ assert expected_code in str(exc.value)
def test_blank_symbols_treated_as_missing(self) -> None:
with pytest.raises(ValueError) as exc:
@@ -318,3 +336,147 @@ class TestBaseUrl:
_rows(_source("currencies", symbols=None, api_version=version))
assert sent_urls[0].startswith(f"https://api.marketstack.com/{version}/")
+
+
+def _fan_out_driver(symbols: str | None = "AAPL", cik_codes: str | None = None) -> SourceDriver:
+ return SourceDriver(
+ MarketstackSource(), MarketstackSourceConfig(access_key="supersecret", symbols=symbols, cik_codes=cik_codes)
+ )
+
+
+class TestFanOutEndpoints:
+ @parameterized.expand(
+ [
+ (
+ "tickerinfo_one_row_per_symbol",
+ "tickerinfo",
+ {"data": {"name": "Apple Inc", "sector": "Technology", "key_executives": [{"name": "A"}]}},
+ [{"ticker": "AAPL", "name": "Apple Inc", "sector": "Technology", "key_executives": [{"name": "A"}]}],
+ ),
+ (
+ "companyratings_flattens_rating",
+ "companyratings",
+ {
+ "status": {"code": 200, "message": "ok"},
+ "result": {
+ "basics": {"company_name": "Apple Inc", "ticker": "AAPL"},
+ "output": {
+ "analyst_consensus": {"consensus_conclusion": "Buy"},
+ "analysts": [
+ {
+ "analyst_name": "Jane Doe",
+ "analyst_firm": "Example Securities",
+ "analyst_role": "Analyst",
+ "rating": {"date_rating": "2026-09-01", "price_target": "250", "rated": "buy"},
+ },
+ {"analyst_name": "John Roe", "analyst_firm": "Sample Capital", "rating": None},
+ ],
+ },
+ },
+ },
+ [
+ {
+ "ticker": "AAPL",
+ "company_name": "Apple Inc",
+ "analyst_name": "Jane Doe",
+ "analyst_firm": "Example Securities",
+ "analyst_role": "Analyst",
+ "date_rating": "2026-09-01",
+ "price_target": "250",
+ "rated": "buy",
+ },
+ {
+ "ticker": "AAPL",
+ "company_name": "Apple Inc",
+ "analyst_name": "John Roe",
+ "analyst_firm": "Sample Capital",
+ },
+ ],
+ ),
+ (
+ "companyratings_without_analysts_yields_nothing",
+ "companyratings",
+ {"result": {"basics": {"ticker": "AAPL"}, "output": {"analysts": None}}},
+ [],
+ ),
+ (
+ "submissions_transposes_filing_arrays",
+ "submissions",
+ {
+ "data": {
+ "cik_code": "0000000001",
+ "company_name": "Example Corp",
+ "tickers": ["EXMP"],
+ "filings": {
+ "recent": {
+ "accession_number": ["0000000001-26-000002", "0000000001-26-000001"],
+ "filing_date": ["2026-08-01", "2026-05-01"],
+ "form": ["10-Q"],
+ },
+ "files": [],
+ },
+ }
+ },
+ [
+ {
+ "cik_code": "0000000001",
+ "company_name": "Example Corp",
+ "accession_number": "0000000001-26-000002",
+ "filing_date": "2026-08-01",
+ "form": "10-Q",
+ },
+ {
+ "cik_code": "0000000001",
+ "company_name": "Example Corp",
+ "accession_number": "0000000001-26-000001",
+ "filing_date": "2026-05-01",
+ "form": None,
+ },
+ ],
+ ),
+ ]
+ )
+ def test_row_shaping(self, _name: str, endpoint: str, body: dict[str, Any], expected: list[dict]) -> None:
+ result = _fan_out_driver(cik_codes="0000000001").run(endpoint, [ScriptedResponse(json=body)])
+
+ assert result.raised is None
+ assert result.rows == expected
+ assert result.paths == [f"/v2/{endpoint}"]
+
+ def test_walks_each_distinct_value_and_saves_state_before_yielding(self) -> None:
+ def ratings(ticker: str) -> ScriptedResponse:
+ return ScriptedResponse(
+ json={
+ "result": {
+ "basics": {"ticker": ticker},
+ "output": {"analysts": [{"analyst_name": "Jane Doe", "rating": {"date_rating": "2026-09-01"}}]},
+ }
+ }
+ )
+
+ result = _fan_out_driver(symbols=" AAPL, MSFT,AAPL,").run("companyratings", [ratings("AAPL"), ratings("MSFT")])
+
+ assert result.raised is None
+ assert result.params("ticker") == ["AAPL", "MSFT"]
+ assert [row["ticker"] for row in result.rows] == ["AAPL", "MSFT"]
+ assert result.committed_states == [MarketstackResumeConfig(next_offset=1)]
+
+ def test_resumes_from_the_next_value(self) -> None:
+ result = _fan_out_driver(symbols="AAPL,MSFT").run(
+ "tickerinfo",
+ [ScriptedResponse(json={"data": {"ticker": "MSFT"}})],
+ resume_state=MarketstackResumeConfig(next_offset=1),
+ )
+
+ assert result.raised is None
+ assert result.params("ticker") == ["MSFT"]
+
+ def test_error_envelope_fails_loud(self) -> None:
+ result = _fan_out_driver().run(
+ "tickerinfo",
+ [ScriptedResponse(json={"error": {"code": "function_access_restricted", "message": "Upgrade your plan."}})],
+ )
+
+ assert isinstance(result.raised, ValueError)
+ assert "[function_access_restricted]" in str(result.raised)
+ assert "supersecret" not in str(result.raised)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py
index 4679f193cf41..5fc4027ce615 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py
@@ -23,6 +23,22 @@ class TestMarketstackSource:
schemas = MarketstackSource().get_schemas(_make_config(), team_id=1, names=["eod", "exchanges"])
assert {s.name for s in schemas} == {"eod", "exchanges"}
+ @parameterized.expand(
+ [
+ ("legacy_v1_pin_hides_v2_only_tables", MARKETSTACK_API_VERSION_V1, False),
+ ("v2_pin_lists_v2_only_tables", MARKETSTACK_API_VERSION_V2, True),
+ ("no_pin_resolves_to_v2", None, True),
+ ]
+ )
+ def test_get_schemas_lists_v2_only_tables_by_pin(self, _name: str, pin: str | None, expected: bool) -> None:
+ names = {s.name for s in MarketstackSource().get_schemas(_make_config(), team_id=1, api_version=pin)}
+ assert "eod" in names
+ assert (
+ {"tickerinfo", "companyratings", "submissions"} <= names
+ if expected
+ else not ({"tickerinfo", "companyratings", "submissions"} & names)
+ )
+
@parameterized.expand(
[
("valid", True, True, None),