: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(warehouse): add kalshi weather index table (#119246)
Tom Owers9defb20572bf
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 900437b9bef8..7f173dc456f1 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@@ -6722,6 +6722,7 @@ Diffed against: <https://docs.kalshi.com/openapi.yaml>- [ ] `Orders (GET /trade-api/v2/portfolio/orders; GET /trade-api/v2/historical/orders)` — compare submitted, executed, and canceled orders across current and archived history (medium)- [ ] `Market orderbook (GET /trade-api/v2/markets/{ticker}/orderbook)` — measure market depth and available liquidity at each price level (medium)- [ ] `Series fee changes (GET /trade-api/v2/series/fee_changes)` — explain trading cost changes across series and time (medium)+- [x] `Weather index (GET /trade-api/v2/live_data/weather/{city})` — analyze the minute-resolution city temperature index behind hourly temperature markets (medium)Note: Parsed every GET operation in the official Trade API OpenAPI specification. Historical endpoints contain archived records absent from current collections. Portfolio tables require authenticated requests; the current source only reads public market data. Order book history requires periodic snapshots; API keys, exchange status, and trading actions were excluded.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/canonical_descriptions.pyindex ed782ecf2bc9..bebb36daee6b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/canonical_descriptions.py@@ -132,4 +132,16 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"open_interest_fp": "Contracts outstanding at the end of the period.",},},+ "weather_index": {+ "description": "Kalshi-computed temperature index for each city, one row per minute. This is the series behind Kalshi's hourly temperature markets.",+ "docs_url": "https://docs.kalshi.com/api-reference/live-data/get-weather-index",+ "columns": {+ "city": "Index city ID, for example miami.",+ "t": "Event minute, as a Unix timestamp in milliseconds (UTC).",+ "v": "Published index value in Fahrenheit, rounded to 0.01.",+ "status": "normal when every member station contributed its primary observation, degraded when a member was absent, fell back, or was replaced by quality control. Both are settlement-eligible.",+ "contributors": "Number of accepted member stations that back the point.",+ "receipt_basis": "Set only on points from the historical backfill for the period before a city went live. These points are not settlement-eligible.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/kalshi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/kalshi.pyindex 6b004d631dd1..7b1566c78639 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/kalshi.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/kalshi.py@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.soufrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.kalshi.settings import (KALSHI_ENDPOINTS,+ WEATHER_INDEX_CITIES,KalshiEndpointConfig,)@@ -32,6 +33,11 @@ _CANDLESTICK_PERIOD_SECONDS = CANDLESTICK_PERIOD_MINUTES * 60_MAX_TICKERS_PER_REQUEST = 100_MAX_CANDLESTICKS_PER_REQUEST = 10_000+# `from=0` reads as unset and falls back to the trailing 24 hours, so a full read starts at 1 ms.+_WEATHER_INDEX_EARLIEST_MS = 1+# Re-read the last hour so a minute published after the previous run's watermark is not skipped.+_WEATHER_INDEX_OVERLAP_MS = 60 * 60 * 1000+@frozenclass KalshiResumeConfig:@@ -192,6 +198,58 @@ def _candlestick_source()+def _weather_index_rows(+ client: RESTClient,+ resumable_source_manager: ResumableSourceManager[KalshiResumeConfig],+ from_ms: int,+ to_ms: int,+) -> Iterator[list[dict[str, Any]]]:+ cities = list(WEATHER_INDEX_CITIES)+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.cursor in cities:+ cities = cities[cities.index(resume.cursor) :]++ for position, city in enumerate(cities):+ rows: list[dict[str, Any]] = []+ for page in client.paginate(+ path=f"/live_data/weather/{city}",+ params={"from": from_ms, "to": to_ms},+ paginator=SinglePagePaginator(),+ data_selector="timeseries",+ data_selector_required=True,+ ):+ rows.extend({"city": city, **point} for point in page)+ if position + 1 < len(cities):+ # The cursor names the next city to read, so a resume skips the cities already yielded.+ resumable_source_manager.save_state(KalshiResumeConfig(cursor=cities[position + 1]))+ if rows:+ yield rows+ else:+ resumable_source_manager.safe_point()+++def _weather_index_source(+ config: KalshiEndpointConfig,+ resumable_source_manager: ResumableSourceManager[KalshiResumeConfig],+ last_value: Optional[Any],+) -> SourceResponse:+ client = RESTClient(base_url=KALSHI_BASE_URL, headers={"Accept": "application/json"})+ from_ms = _WEATHER_INDEX_EARLIEST_MS+ if last_value is not None:+ from_ms = max(int(last_value) - _WEATHER_INDEX_OVERLAP_MS, _WEATHER_INDEX_EARLIEST_MS)+ to_ms = int(datetime.now(UTC).timestamp() * 1000)++ return SourceResponse(+ name=config.name,+ items=lambda: _weather_index_rows(client, resumable_source_manager, from_ms, to_ms),+ primary_keys=config.primary_keys,+ # Rows arrive grouped by city, not by time, so the watermark can only advance once the+ # walk completes.+ sort_mode="desc",+ )++def _build_endpoint(config: KalshiEndpointConfig, should_use_incremental_field: bool) -> Endpoint:endpoint: Endpoint = {"path": config.path,@@ -232,6 +290,9 @@ def kalshi_source(if config.market_fan_out:return _candlestick_source(config, resumable_source_manager, last_value)+ if config.city_fan_out:+ return _weather_index_source(config, resumable_source_manager, last_value)+# Kalshi's market-data endpoints are public and take no credential, so no `auth` is configured.rest_config: RESTAPIConfig = {"client": {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/settings.pyindex c89a2727f53c..a28309d2bb43 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/settings.py@@ -24,6 +24,8 @@ class KalshiEndpointConfig:paginated: bool = True# Candlesticks are fetched per batch of markets, so rows arrive in no global time order.market_fan_out: bool = False+ # The weather index is served one city at a time, with no listing endpoint for the cities.+ city_fan_out: bool = Falsepage_size: int = 200@@ -49,6 +51,35 @@ def _end_period_ts_field() -> list[IncrementalField]:]+def _weather_index_minute_field() -> list[IncrementalField]:+ return [+ {+ "label": "t",+ "type": IncrementalFieldType.Integer,+ "field": "t",+ "field_type": IncrementalFieldType.Integer,+ }+ ]+++# Kalshi lists the configured index cities only in the 400 response for an unknown city.+WEATHER_INDEX_CITIES: tuple[str, ...] = (+ "miami",+ "dfw",+ "houston",+ "phl-delaware-valley",+ "puget-sound",+ "sf-bay",+ "greater-boston",+ "southeast-michigan",+ "kansas-city",+ "minneapolis-st-paul",+ "nyc",+ "chicago",+ "la-coastal",+)++KALSHI_ENDPOINTS: dict[str, KalshiEndpointConfig] = {# Every market ever listed, one row per contract. `updated_time` moves but there is no filter# for it, so this is a full refresh; partition on the stable `created_time`.@@ -132,6 +163,18 @@ KALSHI_ENDPOINTS: dict[str, KalshiEndpointConfig] = {market_fan_out=True,page_size=1000,),+ # Minute-resolution temperature index per city, filtered server-side with `from`/`to` (unix ms).+ # The API keeps only recent history, so incremental merge is what retains older minutes.+ "weather_index": KalshiEndpointConfig(+ name="weather_index",+ path="/live_data/weather/{city}",+ data_key="timeseries",+ primary_keys=["city", "t"],+ incremental_fields=_weather_index_minute_field(),+ supports_incremental=True,+ paginated=False,+ city_fan_out=True,+ ),}ENDPOINTS = tuple(KALSHI_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/source.pyindex 97f466063e31..5334cc4b6f40 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/source.py@@ -56,7 +56,7 @@ class KalshiSource(ResumableSource[KalshiSourceConfig, KalshiResumeConfig]):releaseStatus=ReleaseStatus.ALPHA,caption="""Kalshi's market data endpoints are public, so this source needs no API key.-It syncs markets, events, series, trades, milestones, and daily market candlesticks. It also syncs the historical archive of markets and trades. Portfolio data (your own orders, fills, and positions) needs a signed API key and is not supported yet.""",+It syncs markets, events, series, trades, milestones, daily market candlesticks, and the per-minute weather index for each city. It also syncs the historical archive of markets and trades. Portfolio data (your own orders, fills, and positions) needs a signed API key and is not supported yet.""",iconPath="/static/services/kalshi.png",docsUrl="https://posthog.com/docs/cdp/sources/kalshi",keywords=["prediction market", "event contracts", "trading"],@@ -86,9 +86,10 @@ It syncs markets, events, series, trades, milestones, and daily market candlestiforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # Only the trade and candlestick endpoints carry incremental fields, so build_endpoint_schemas+ # Only the trade, candlestick, and weather index endpoints carry incremental fields, so build_endpoint_schemas# marks them incremental and leaves the rest full-refresh.- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ # Append would duplicate the hour each weather index run re-reads; merge dedupes it.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=("weather_index",))def validate_credentials(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi.pyindex 028b7d950321..99d2825f6ebb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi.py@@ -19,7 +19,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.kalshi.kal_to_epoch_seconds,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.kalshi.settings import KALSHI_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.kalshi.settings import (+ KALSHI_ENDPOINTS,+ WEATHER_INDEX_CITIES,+)from products.warehouse_sources.backend.temporal.data_imports.sources.kalshi.source import KalshiSource@@ -367,3 +370,47 @@ class TestKalshiCandlesticks:markets = [_CandlestickMarket(ticker=str(i), start_ts=0, end_ts=days * 86400) for i in range(count)]assert [len(batch) for batch in _batch_markets(markets)] == expected_sizes+++class TestKalshiWeatherIndex:+ @parameterized.expand(+ [+ # `from=0` would silently fall back to the trailing 24 hours.+ ("full_refresh", {"should_use_incremental_field": False}, "1"),+ (+ "incremental_rereads_the_last_hour",+ {"incremental_field": "t", "db_incremental_field_last_value": 1_790_000_000_000},+ str(1_790_000_000_000 - 3_600_000),+ ),+ ]+ )+ def test_reads_every_city_from_the_window_start(+ self, _name: str, inputs: dict[str, Any], expected_from: str+ ) -> None:+ point = {"t": 1_790_000_060_000, "v": 79.16, "status": "normal", "contributors": 5}+ result = _driver().run(+ "weather_index",+ always(ScriptedResponse(json={"city": "any", "units": "fahrenheit", "timeseries": [point]})),+ **inputs,+ )++ assert result.raised is None+ assert result.paths == [f"/trade-api/v2/live_data/weather/{city}" for city in WEATHER_INDEX_CITIES]+ assert set(result.params("from")) == {expected_from}+ assert all(to is not None for to in result.params("to"))+ # The city is half of the primary key; without it every city's minute collides.+ assert result.rows == [{"city": city, **point} for city in WEATHER_INDEX_CITIES]+ assert result.response is not None+ assert result.response.sort_mode == "desc"++ def test_resumes_from_the_saved_city_and_stages_the_next_one(self) -> None:+ result = _driver().run(+ "weather_index",+ always(ScriptedResponse(json={"city": "any", "units": "fahrenheit", "timeseries": [{"t": 1, "v": 1.0}]})),+ resume_state=KalshiResumeConfig(cursor=WEATHER_INDEX_CITIES[-2]),+ should_use_incremental_field=False,+ )++ assert result.raised is None+ assert result.paths == [f"/trade-api/v2/live_data/weather/{city}" for city in WEATHER_INDEX_CITIES[-2:]]+ assert result.saved_states[-1] == KalshiResumeConfig(cursor=WEATHER_INDEX_CITIES[-1])diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi_source.pyindex de010ce49849..9a9a7baebea1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi_source.py@@ -15,6 +15,7 @@ class TestKalshiSource:("trades_is_incremental", "trades", True),("historical_trades_is_incremental", "historical_trades", True),("market_candlesticks_is_incremental", "market_candlesticks", True),+ ("weather_index_is_incremental", "weather_index", True),("markets_is_not", "markets", False),("historical_markets_is_not", "historical_markets", False),("events_is_not", "events", False),