Skip to content

160-tool MCP server for real-time global intelligence from free public APIs: markets, liquidity, prediction markets, SEC filings, conflict, military, aircraft-cohort early warning, migration and border flows, cyber, climate, news and more. Dated observation history, 29 research prompts, cited briefs, geofences, SSE dashboard. MIT, no paid API keys.

Prediction markets: Kalshi, cross-venue compare, settled Brier (Phase 29)

Phoenix Agent (mac-studio)701e30a164db
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6311734..a864ad0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,47 @@
# Changelog
+## Unreleased
+
+### Added: Kalshi and cross-venue prediction markets
+- `intel_kalshi_markets`: Kalshi open markets from its public market-data
+ API (no account, no key), ranked by 24h then lifetime volume. Prices are
+ YES implied probabilities (bid/ask midpoint when the book is two-sided,
+ else the last trade, with the basis named); Kalshi's raw dollar quotes
+ are kept. Filter by category (the category's highest-volume series) or
+ series ticker. The response names the events it scanned and whether the
+ scan was complete: Kalshi lists more than 8,000 open events, furthest
+ close date first.
+- `intel_prediction_compare`: the same event on Kalshi and Polymarket side
+ by side. Matching is deterministic: quantities (with their direction,
+ so "more than 25 bps" is not "25 bps"), years, end dates, negation and
+ the outcome side must all agree, and each pair carries a
+ `match_confidence` and its reasons. Below the threshold (default 0.6) a
+ pair is not a match. Returns the price gap per pair, the closest
+ rejected pairs with the reason, and unmatched counts per venue.
+- `intel_prediction_settled`: recently settled markets on both venues with
+ the outcome and the YES price at fixed offsets before close (default 24h
+ and 168h) from each venue's price-history endpoint, and a Brier score per
+ venue and offset with sample size, distinct events, selection and
+ exclusions stated. A venue whose price history cannot be read is not
+ scored. The two samples are different markets, and the response says so.
+- Every number these three tools take has a stated range in its input
+ schema: at most 25 Kalshi series or pages per scan, 2,000 Polymarket
+ markets, 500 results, 100 settled markets per venue, and 10 offsets of
+ at most 8,760 hours, so one call cannot fan out into an unbounded number
+ of upstream requests. The MCP server refuses a value outside its range;
+ the source functions clamp counts again for the CLI and other callers,
+ and refuse a value that is not a number before any request.
+- CLI: `intel kalshi`, `intel prediction-compare`, `intel prediction-settled`.
+- Collector: `kalshi_markets` and `prediction_compare` (Economics
+ category) join the `prediction` domain. Sources 55 -> 57. Tools 139 -> 142.
+
+### Fixed: prediction markets outage read as "no markets"
+- `intel_prediction_markets` returned `{"markets": [], "count": 0}` with no
+ marker when Polymarket was down, the same shape as a quiet market. It now
+ adds `error` and `degraded: true` on an outage or an unexpected response,
+ and `stale: true` when the list came from an expired cache entry. Keys,
+ parameters and the tool name are unchanged.
+
## 0.11.0 - 2026-10-12
Cross-border migration (MCP tools, CLI, collector and a dashboard
diff --git a/README.md b/README.md
index 77f7474..fe62ecf 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-green)](https://python.org)
[![License](https://img.shields.io/badge/License-MIT-yellow)](LICENSE)
-Real-time global intelligence across **30+ domains** with **139 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.
+Real-time global intelligence across **30+ domains** with **142 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.
Built for AI agents that need world awareness: market conditions, geopolitical risk, military posture, aircraft-cohort early warning, refugee and migration flows, supply chain disruptions, cyber threats, and more — all queryable via the Model Context Protocol. The vector store enables natural language queries like *"military activity near Taiwan"* or *"cyber threats targeting healthcare"* across all historical data.
@@ -45,7 +45,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r
| **Space Weather** | 1 | NOAA SWPC (Kp index, solar flares, alerts) |
| **Social & Sanctions** | 3 | Reddit velocity, OFAC SDN list, nuclear test site monitoring |
| **Country Intelligence** | 3 | Country brief, country stocks, financial centers |
-| **Prediction Markets** | 1 | Polymarket event contracts |
+| **Prediction Markets** | 4 | Polymarket and Kalshi event contracts, the same event on both venues side by side with a stated match confidence, and settled markets scored against their earlier prices (Brier) |
| **Elections** | 1 | Global election calendar with risk scoring |
| **Displacement and Migration** | 5 | UNHCR refugee/IDP data, origin -> destination corridors since 1951, year-over-year surge detection; World Bank net migration and migrant stock |
| **Shipping** | 1 | Dry bulk shipping stress index |
@@ -64,7 +64,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r
| **Tropical Cyclones** | 2 | NHC (Atlantic, E/C Pacific) + JTWC (NW Pacific, N Indian, S Hemisphere) |
| **Situation Brief** | 1 | Cited situational awareness brief over MCP: bounded server-side overview synthesized via local Ollama, with a mechanically-cited fallback |
-**Total: 139 tools** across 30+ intelligence domains.
+**Total: 142 tools** across 30+ intelligence domains.
---
@@ -129,6 +129,9 @@ intel markets # stock indices
intel earthquakes --min-mag 5.0
intel migration-surges # year-over-year displacement jumps (UNHCR)
intel migration-flows -o Sudan
+intel kalshi -c Economics # Kalshi open markets by volume
+intel prediction-compare -c Economics # same event on Kalshi and Polymarket
+intel prediction-settled # Brier scores on settled markets
intel status # cache + circuit breaker health
```
@@ -147,7 +150,7 @@ collector.py (daemon) ─┘
- **CircuitBreaker**: Per-source tracking. 3 consecutive failures trips for 5 minutes. Each RSS feed gets its own breaker.
- **Cache**: SQLite WAL-mode TTL cache. `get()` returns live data, `get_stale()` returns expired data for fallback.
- **VectorStore**: Qdrant + FastEmbed (BAAI/bge-small-en-v1.5, 384-dim). Async background worker queue for non-blocking storage. Enables semantic search across all accumulated intelligence.
-- **Collector**: Standalone daemon that fetches all 55 sources in parallel and populates the vector store. Run once or as a daemon (default: 5-minute interval). Includes the AOI change sweep, so a running daemon continuously watches every defined geofence.
+- **Collector**: Standalone daemon that fetches all 57 sources in parallel and populates the vector store. Run once or as a daemon (default: 5-minute interval). Includes the AOI change sweep, so a running daemon continuously watches every defined geofence.
- **Sources** (`sources/*.py`): 30+ modules, each exports `async def fetch_*(fetcher, **kwargs) -> dict`.
- **Analysis** (`analysis/*.py`): Cross-domain synthesis — signal aggregation, instability indexing, NLP, company enrichment, macro composite.
- **Config** (`config/*.py`): Curated datasets — 22 hotspots, 70+ bases, 40 ports, 24 pipelines, 24 nuclear facilities, 34 cables, 48 datacenters, 27 spaceports, 82 exchanges.
@@ -322,10 +325,13 @@ collector.py (daemon) ─┘
|------|-------------|
| `intel_climate_anomalies` | Open-Meteo temperature/precipitation anomalies |
-### Prediction Markets (1)
+### Prediction Markets (4)
| Tool | Description |
|------|-------------|
| `intel_prediction_markets` | Polymarket prediction contracts |
+| `intel_kalshi_markets` | Kalshi open markets from its public market data (no account), ranked by volume; YES implied probabilities with the venue's units stated; filter by category or series. Says which events it scanned and whether the scan was complete |
+| `intel_prediction_compare` | The same event on Kalshi and Polymarket: deterministic matching (quantities, years, end dates, negation and outcome side must agree), a `match_confidence` with reasons per pair, the price gap, the closest rejected pairs and why, and unmatched counts per venue |
+| `intel_prediction_settled` | Settled markets on both venues with the outcome, the YES price at fixed offsets before close, and a Brier score per venue and offset with sample size, distinct events, selection and exclusions. A venue without price history is not scored |
### Elections (1)
| Tool | Description |
diff --git a/ROADMAP.md b/ROADMAP.md
index 7249537..30b5c3b 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -578,7 +578,7 @@ dashboard.
| 1 | Hostility timeline | Per country pair or country, daily counts of threat / sanction / force / criticism coverage plus tone; sortable by most covered, most hostile, biggest change | :red_circle: |
| 1 | Story breadth | News clusters carry a distinct-outlet count; a top-stories view ranks by how many outlets carry a story | :red_circle: |
| 1 | Liquidity and flows | Fed balance sheet, Treasury General Account, reverse repo and net liquidity (FRED keyless CSV), money supply (US M2, euro area M1/M2/M3, never summed), ECB, ICI fund flows and ETF net issuance, FINRA margin statistics, BLS series; amounts kept separate from flows | :red_circle: |
-| 1 | Kalshi + cross-venue markets | Kalshi public market data next to Polymarket; same-event comparison with an explicit match confidence; settled markets scored against pre-settlement prices (Brier) | :red_circle: |
+| 1 | Kalshi + cross-venue markets | Kalshi public market data next to Polymarket; same-event comparison with an explicit match confidence; settled markets scored against pre-settlement prices (Brier) | :white_check_mark: Unreleased: `intel_kalshi_markets`, `intel_prediction_compare`, `intel_prediction_settled` (`sources/kalshi.py`, `sources/prediction_cross.py`, `analysis/prediction_matching.py`), CLI and 2 collector sources. Kalshi endpoints measured 2026-10-17, all HTTP 200 without an account: `/events` (nested markets), `/series` (`include_volume`), `/markets?status=settled`, `/markets/candlesticks` (batch, capped at 10,000 candles per call), `/historical/cutoff`. The `/events` `category` parameter is ignored by the API, so categories resolve through `/series?category=`, whose filter is loose too (7 of the 869 series it returned for Economics were other categories), so series are matched exactly; an unknown category answers `{"series": null}` and is reported as a gap, not an outage. The exchange-wide settled listing is intraday sports (1,000 rows covered about 40 minutes; none open 24h), so settled samples default to the Economics category's top series. Polymarket Gamma caps a page at 100 rows. Matching is deliberately conservative: live 2026-10-17 it matched the Fed 25 bps hike/cut pairs for October and December and rejected 25 vs 50+ bps, 2026 vs 2027, and the Fed-hold pair ("no change" vs "Hike 0bps": a known false negative). Team and person aliases are not resolved, so most sports pairs stay unmatched. Kalshi requests are spaced 0.2 s apart in-process: the two collector sources scanning the same series at once drew HTTP 429, and at 0.1 s a 26-request category scan still drew one (none at 0.2 s in one live run). Settled samples are the most recently settled markets and cluster in time (one football match supplied 11 of 25 Polymarket markets in a live run), so a Brier score describes its sample, not a venue's skill. Every number a caller passes has a range stated in the input schema (at most 25 Kalshi series or pages per scan), so one call cannot fan out into unbounded upstream requests |
| 1 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :red_circle: |
| 2 | Connections with timing offsets | Correlation between retained series over a shared sample, tested at leads and lags, with minimum sample size and false-discovery control; states that it does not prove causation | :red_circle: |
| 2 | Day timeline | What every retained source recorded for a given day, by observation date or collection date | :red_circle: |
@@ -637,7 +637,7 @@ fail-quietly bugs below were fixed in the same-day follow-up
| Naval warnings apply to all 9 waterways identically (no proximity/NAVAREA filter); `total_nearby` computed but never emitted | `sources/intelligence.py` vessel snapshot | precision | :red_circle: |
| Country/company/leader entity matching was substring-based ("usa" inside "thousand", "hamas" inside "Bahamas") | `analysis/entities.py` | false positives | :white_check_mark: Fixed in 0.5.0 (word-boundary alternations, measured faster) |
| Category keywords matched substrings ("airstrike" bumped severity via "strike"; "denied" fired "ied") | `analysis/classifier.py` | false positives | :white_check_mark: Fixed in 0.5.0 (boundary-anchored stems, per-keyword overrides) |
-| Silent-empty degradation without a marker on RSS/API failure | `sources/prediction.py` (documented as intended), `sources/maritime.py`, `sources/news.py` RSS path, `sources/fleet.py` `_safe` wrapper | silent degradation | :red_circle: |
+| Silent-empty degradation without a marker on RSS/API failure | `sources/prediction.py` (documented as intended), `sources/maritime.py`, `sources/news.py` RSS path, `sources/fleet.py` `_safe` wrapper | silent degradation | :yellow_circle: `sources/prediction.py` fixed, unreleased: an outage or unexpected response adds `error` + `degraded`, an expired-cache serve adds `stale`; keys unchanged; regression tests written failing-first (3 failed on the old module). `maritime.py`, `news.py` RSS path and `fleet.py` `_safe` still open |
| 33 CLI commands rendered upstream errors as healthy empty states | `cli.py` | fail-reads-as-success | :white_check_mark: Fixed in 0.6.0 (shared bail-on-error path; 43 failing-first tests) |
| Rich markup swallowed lowercase bracketed values and let remote titles inject markup | `cli.py` | output corruption | :white_check_mark: Fixed in 0.6.0 (per-site escaping; injection test) |
| Remote data inside Rich TABLE cells was not markup-escaped | `cli.py` | output corruption | :white_check_mark: Fixed in 0.6.0 (`_cell` Text-wrapping convention, 11 injection tests; error styles unified across all 53 commands) |
diff --git a/src/world_intel_mcp/analysis/prediction_matching.py b/src/world_intel_mcp/analysis/prediction_matching.py
new file mode 100644
index 0000000..6654ce7
--- /dev/null
+++ b/src/world_intel_mcp/analysis/prediction_matching.py
@@ -0,0 +1,475 @@
+"""Cross-venue prediction-market matching and forecast scoring.
+
+Pure functions, no I/O. Used by ``tools/prediction_markets.py`` to put
+the same event on Kalshi and Polymarket side by side and to score
+settled markets against their pre-settlement prices.
+
+Matching is deterministic: normalized title tokens, quantities, years,
+end dates, negation and the outcome side must all agree before a pair
+is scored, and a pair below ``DEFAULT_MIN_CONFIDENCE`` is not a match.
+A wrong match is worse than no match, so every gate is a hard reject
+and every reject carries its reason.
+
+Normalized market shape (both venues) consumed here::
+
+ {"venue": "kalshi" | "polymarket", "id": str, "question": str,
+ "context": str, # event title, folded into the token bag
+ "yes_side": str, # what YES pays out on ("" = the question itself)
+ "outcomes": [str, str], # Polymarket labels; Kalshi ["Yes", "No"]
+ "end_time": iso8601 | None,
+ "probability": float | None} # YES implied probability, 0..1
+
+Gaps / not covered:
+- No synonym coverage beyond the small table below (month names, rate
+ verbs, above/below). Pairs that word the same event differently
+ ("Fed cuts" vs "FOMC lowers the target range") fall below the
+ threshold and are reported unmatched, not matched.
+- Team, ticker and person aliases ("KC" vs "Kansas City Chiefs") are
+ not resolved, so most sports pairs stay unmatched.
+- Resolution-rule equivalence is not checked: two markets can share a
+ title and still settle on different sources or times. The reasons
+ list says what was compared; it does not claim more.
+"""
+
+from __future__ import annotations
+
+import re
+import unicodedata
+from datetime import datetime, timezone
+
+DEFAULT_MIN_CONFIDENCE = 0.6
+
+# Date tolerance: the larger of a floor and a fraction of the horizon,
+# so a 2028 election may differ by weeks but a weekly market by days.
+_DATE_TOLERANCE_FLOOR_DAYS = 3.0
+_DATE_TOLERANCE_HORIZON_FRACTION = 0.15
+
+_STOPWORDS = frozenset(
+ """
+ a an the will be is are was were to of in on at by for from with and or
+ as it its this that these those than then there their his her who what
+ which when where how does do did has have had any each after before
+ following during until between over under next end this
+ """.split()
+) - {"over", "under", "after", "before"}
+
+# Folded before comparison. Kept small on purpose: each entry is a
+# claim that the two words mean the same thing in a market title.
+_SYNONYMS = {
+ "jan": "january", "feb": "february", "mar": "march", "apr": "april",
+ "jun": "june", "jul": "july", "aug": "august", "sep": "september",
+ "sept": "september", "oct": "october", "nov": "november", "dec": "december",
+ "cuts": "cut", "decrease": "cut", "decreases": "cut", "lower": "cut",
+ "lowers": "cut", "hike": "raise", "hikes": "raise", "increase": "raise",
+ "increases": "raise", "raises": "raise", "over": "above", "more": "above",
+ "exceed": "above", "exceeds": "above", "under": "below", "fewer": "below",
+ "less": "below", "wins": "win", "won": "win", "winner": "win",
+ "usa": "us", "u.s.": "us", "bp": "bps", "basis": "bps",
+}
+
+_MONTHS = frozenset(
+ "january february march april may june july august september october "
+ "november december".split()
+)
+_NEGATIONS = frozenset({"not", "no", "never", "without"})
+_YES_NO = frozenset({"yes", "no"})
+
+_NUM_RE = re.compile(r"^\$?(\d+(?:\.\d+)?)([kmb]?)$")
+_TOKEN_RE = re.compile(r"\$?\d[\d,]*(?:\.\d+)?[kmb]?(?![a-z])|[a-z][a-z.&']*")
+
+
+# ---------------------------------------------------------------------------
+# Tokenization
+# ---------------------------------------------------------------------------
+
+def _canonical_number(raw: str) -> str | None:
+ m = _NUM_RE.match(raw.replace(",", ""))
+ if not m:
+ return None
+ value = float(m.group(1)) * {"": 1, "k": 1e3, "m": 1e6, "b": 1e9}[m.group(2)]
+ return f"{value:g}" if value != int(value) else str(int(value))
+
+
+def tokenize(text: str) -> list[str]:
+ """Lowercase, fold synonyms, canonicalize numbers; stopwords kept.
+
+ ``"25bps"`` -> ``["25", "bps"]``; ``"$100k"`` -> ``["100000"]``;
+ ``"2.75%"`` -> ``["2.75"]``; ``"Fed's"`` -> ``["fed"]``.
+ """
+ text = (text or "").replace("’", "'").replace("≥", ">=").replace("≤", "<=")
+ text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower()
+ # Comparators become words so a quantity keeps its direction:
+ # ">25bps" and "25 bps" are different contracts.
+ text = text.replace(">=", " atleast ").replace("<=", " atmost ")
+ text = text.replace(">", " above ").replace("<", " below ")
+ text = re.sub(r"(\d)\s*\+", r"\1 ormore ", text)
+ text = re.sub(r"\bat least\b", " atleast ", text)
+ text = re.sub(r"\bat most\b", " atmost ", text)
+ text = re.sub(r"(\d)(bps|bp)\b", r"\1 \2", text)
+ out: list[str] = []
+ for raw in _TOKEN_RE.findall(text):
+ if raw[0].isdigit() or raw[0] == "$":
+ num = _canonical_number(raw)
+ if num is not None:
+ out.append(num)
+ continue
+ word = raw.strip(".'&")
+ if word.endswith("'s"):
+ word = word[:-2]
+ word = word.replace("'", "")
+ if not word:
+ continue
+ out.append(_SYNONYMS.get(word, word))
+ return out
+
+
+_COMPARATOR_WORDS = frozenset({"above", "below", "atleast", "atmost", "ormore"})
+
+
+def _comparator(toks: list[str], i: int) -> str:
+ """Direction attached to the number at ``toks[i]``: '>', '>=', '<',
+ '<=' or '' (exact). Reads "above N", "more than N" (folded to
+ above), "at least N", "N+" / "N or more", "N or less"."""
+ j = i - 1
+ while j >= 0 and toks[j] in ("than", "by", "the", "$"):
+ j -= 1
+ before = toks[j] if j >= 0 else ""
+ after = toks[i + 1] if i + 1 < len(toks) else ""
+ after2 = toks[i + 2] if i + 2 < len(toks) else ""
+ if after == "ormore" or (after == "or" and after2 == "above"):
+ return ">="
+ if after == "or" and after2 == "below":
+ return "<="
+ return {"above": ">", "below": "<", "atleast": ">=", "atmost": "<="}.get(before, "")
+
+
+def _is_year(tok: str) -> bool:
+ return tok.isdigit() and len(tok) == 4 and 1900 <= int(tok) <= 2100
+
+
+def _is_number(tok: str) -> bool:
+ return bool(tok) and (tok[0].isdigit())
+
+
+def text_features(text: str) -> dict:
+ """Split a title into content words, quantities, years and flags.
+
+ A 1-31 number right after a month name is a day of month and goes to
+ ``days``, not ``quantities``: "Oct 28, 2026" must not block a pair
+ with "October 2026" on the number gate (the end-date gate covers it).
+ """
+ toks = tokenize(text)
+ words: set[str] = set()
+ quantities: set[str] = set()
+ years: set[str] = set()
+ days: set[str] = set()
+ negated = False
+ for i, tok in enumerate(toks):
+ prev = toks[i - 1] if i > 0 else ""
+ if _is_number(tok):
+ if _is_year(tok):
+ years.add(tok)
+ elif prev in _MONTHS and tok.isdigit() and 1 <= int(tok) <= 31:
+ days.add(tok)
+ else:
+ quantities.add(_comparator(toks, i) + tok)
+ elif tok in _NEGATIONS:
+ negated = True
+ elif tok in _COMPARATOR_WORDS:
+ if tok in ("above", "below"):
+ words.add(tok)
+ elif tok not in _STOPWORDS:
+ words.add(tok)
+ return {
+ "words": words,
+ "quantities": quantities,
+ "years": years,
+ "days": days,
+ "negated": negated,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Pair scoring
+# ---------------------------------------------------------------------------
+
+def _parse_time(value: str | None) -> datetime | None:
+ if not value:
+ return None
+ try:
+ dt = datetime.fromisoformat(str(value).replace("Z", "+00:00").replace(" ", "T"))
+ except ValueError:
+ return None
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ return dt
+
+
+def _side_alignment(kalshi: dict, k_side: set[str], poly: dict) -> tuple[str | None, str]:
+ """Which Polymarket outcome the Kalshi YES side corresponds to.
+
+ Returns ``("aligned" | "inverted" | None, reason)``. ``inverted``
+ means the Kalshi YES pays out on Polymarket's second outcome, so the
+ Polymarket probability is flipped before the gap is taken.
+ """
+ outcomes = [str(o) for o in (poly.get("outcomes") or [])]
+ labels = [set(tokenize(o)) for o in outcomes]
+ poly_question = text_features(poly.get("question", ""))["words"]
+ if len(outcomes) == 2 and {o.lower() for o in outcomes} == _YES_NO:
+ if k_side and not k_side <= poly_question:
+ missing = sorted(k_side - poly_question)
+ return None, f"Kalshi YES side {sorted(k_side)} not named in Polymarket question (missing {missing})"
+ if k_side:
+ return "aligned", f"Kalshi YES side {sorted(k_side)} named in Polymarket question"
+ return "aligned", "both venues price YES on the question as worded"
+ if len(outcomes) != 2:
+ return None, f"Polymarket market has {len(outcomes)} outcomes, not a binary pair"
+ side = k_side or text_features(kalshi.get("question", ""))["words"]
+ hits = [bool(side & (lab - _STOPWORDS)) for lab in labels]
+ if hits == [True, False]:
+ return "aligned", f"Kalshi YES side matches Polymarket outcome {outcomes[0]!r}"
+ if hits == [False, True]:
+ return "inverted", f"Kalshi YES side matches Polymarket outcome {outcomes[1]!r} (second outcome; price flipped)"
+ if hits == [True, True]:
+ return None, f"Kalshi YES side matches both Polymarket outcomes {outcomes}"
+ return None, f"Kalshi YES side {sorted(side)} matches neither Polymarket outcome {outcomes}"
+
+
+def score_pair(kalshi: dict, poly: dict, now: datetime | None = None) -> dict:
+ """Score one Kalshi/Polymarket pair.
+
+ Returns ``{"confidence": float, "rejected": bool, "reasons": [...],
+ "side": "aligned" | "inverted" | None}``. A rejected pair has
+ confidence 0.0 and its first failing gate as the last reason.
+ """
+ now = now or datetime.now(timezone.utc)
+ k_text = " ".join(
+ s for s in (kalshi.get("question", ""), kalshi.get("context", ""), kalshi.get("yes_side", "")) if s
+ )
+ kf = text_features(k_text)
+ pf = text_features(" ".join(s for s in (poly.get("question", ""), poly.get("context", "")) if s))
+ k_side_words = text_features(kalshi.get("yes_side", ""))["words"]
+ reasons: list[str] = []
+
+ def reject(reason: str) -> dict:
+ reasons.append(reason)
+ return {"confidence": 0.0, "rejected": True, "reasons": reasons, "side": None}
+
+ shared = kf["words"] & pf["words"]
+ union = len(kf["words"]) + len(pf["words"])
+ dice = (2 * len(shared) / union) if union else 0.0
+ reasons.append(
+ f"title word overlap {dice:.2f} (dice; {len(shared)} shared of "
+ f"{len(kf['words'])} Kalshi / {len(pf['words'])} Polymarket words)"
+ )
+
+ if kf["quantities"] != pf["quantities"]:
+ return reject(
+ f"quantities differ: Kalshi {sorted(kf['quantities'])} vs Polymarket {sorted(pf['quantities'])}"
+ )
+ if kf["quantities"]:
+ reasons.append(f"quantities agree {sorted(kf['quantities'])}")
+
+ if kf["years"] and pf["years"] and not (kf["years"] & pf["years"]):
+ return reject(f"years differ: Kalshi {sorted(kf['years'])} vs Polymarket {sorted(pf['years'])}")
+
+ if kf["negated"] != pf["negated"]:
+ return reject("negation differs (one title says not/no/never/without, the other does not)")
+
+ k_end, p_end = _parse_time(kalshi.get("end_time")), _parse_time(poly.get("end_time"))
+ date_factor = 1.0
+ if k_end is None or p_end is None:
+ return reject("end date missing on one venue; cannot confirm the same event window")
+ gap_days = abs((k_end - p_end).total_seconds()) / 86400
+ horizon = max(0.0, (max(k_end, p_end) - now).total_seconds() / 86400)
+ tolerance = max(_DATE_TOLERANCE_FLOOR_DAYS, _DATE_TOLERANCE_HORIZON_FRACTION * horizon)
+ if gap_days > tolerance:
+ return reject(f"end dates {gap_days:.1f} days apart (tolerance {tolerance:.1f} days)")
+ date_factor = 1.0 - 0.5 * (gap_days / tolerance)
+ reasons.append(f"end dates {gap_days:.1f} days apart (tolerance {tolerance:.1f} days)")
+
+ side, side_reason = _side_alignment(kalshi, k_side_words, poly)
+ if side is None:
+ return reject(side_reason)
+ reasons.append(side_reason)
+
+ confidence = round(dice * date_factor, 3)
+ return {"confidence": confidence, "rejected": False, "reasons": reasons, "side": side}
+
+
+# ---------------------------------------------------------------------------
+# Matching
+# ---------------------------------------------------------------------------
+
+def _blocking_index(markets: list[dict]) -> tuple[dict[str, list[int]], int]:
+ index: dict[str, list[int]] = {}
+ for i, m in enumerate(markets):
+ words = text_features(" ".join((m.get("question", ""), m.get("context", ""))))["words"]
+ for w in words:
+ index.setdefault(w, []).append(i)
+ return index, len(markets)
+
+
+def match_markets(
+ kalshi: list[dict],
+ polymarket: list[dict],
+ min_confidence: float = DEFAULT_MIN_CONFIDENCE,
+ now: datetime | None = None,
+ near_miss_limit: int = 10,
+) -> dict:
+ """One-to-one deterministic matching, greedy by confidence.
+
+ Candidate pairs share at least two title words that appear in fewer
+ than 20% of the Polymarket set (blocking keeps the pair count
+ tractable; a pair with fewer shared words could not reach the
+ threshold anyway). Returns matched pairs, near misses (the highest
+ similarity pairs that a gate or the threshold rejected) and counts.
+ """
+ now = now or datetime.now(timezone.utc)
+ index, n_poly = _blocking_index(polymarket)
+ common_cut = max(5, int(0.2 * n_poly))
+ scored: list[tuple[float, int, int, dict]] = []
+ near: list[tuple[float, int, int, dict]] = []
+ pairs_scored = 0
+ for ki, km in enumerate(kalshi):
+ words = text_features(
+ " ".join((km.get("question", ""), km.get("context", ""), km.get("yes_side", "")))
+ )["words"]
+ counts: dict[int, int] = {}
+ for w in words:
+ posting = index.get(w)
+ if not posting or len(posting) > common_cut:
+ continue
+ for pi in posting:
+ counts[pi] = counts.get(pi, 0) + 1
+ for pi, c in counts.items():
+ if c < 2:
+ continue
+ pairs_scored += 1
+ result = score_pair(km, polymarket[pi], now=now)
+ if not result["rejected"] and result["confidence"] >= min_confidence:
+ scored.append((result["confidence"], ki, pi, result))
+ else:
+ overlap = _overlap_of(result)
+ if not result["rejected"]:
+ result["reasons"].append(
+ f"confidence {result['confidence']:.3f} below threshold {min_confidence}"
+ )
+ near.append((overlap, ki, pi, result))
+
+ scored.sort(key=lambda t: (-t[0], t[1], t[2]))
+ used_k: set[int] = set()
+ used_p: set[int] = set()
+ matched: list[dict] = []
+ for conf, ki, pi, result in scored:
+ if ki in used_k or pi in used_p:
+ continue
+ used_k.add(ki)
+ used_p.add(pi)
+ matched.append(_pair_record(kalshi[ki], polymarket[pi], result))
+
+ near.sort(key=lambda t: (-t[0], t[1], t[2]))
+ near_misses = [
+ {
+ "kalshi": _brief(kalshi[ki]),
+ "polymarket": _brief(polymarket[pi]),
+ "title_overlap": round(ov, 3),
+ "reasons": result["reasons"],
+ }
+ for ov, ki, pi, result in near[:near_miss_limit]
+ ]
+ return {
+ "matched": matched,
+ "near_misses": near_misses,
+ "pairs_scored": pairs_scored,
+ "unmatched_kalshi": len(kalshi) - len(used_k),
+ "unmatched_polymarket": len(polymarket) - len(used_p),
+ "min_confidence": min_confidence,
+ }
+
+
+def _overlap_of(result: dict) -> float:
+ m = re.match(r"title word overlap ([0-9.]+)", result["reasons"][0])
+ return float(m.group(1)) if m else 0.0
+
+
+def _brief(m: dict) -> dict:
+ return {
+ "id": m.get("id"),
+ "question": m.get("question"),
+ "yes_side": m.get("yes_side") or None,
+ "outcomes": m.get("outcomes"),
+ "end_time": m.get("end_time"),
+ "probability": m.get("probability"),
+ "url": m.get("url"),
+ }
+
+
+def _pair_record(km: dict, pm: dict, result: dict) -> dict:
+ k_prob = km.get("probability")
+ p_raw = pm.get("probability")
+ p_aligned = None
+ if p_raw is not None:
+ p_aligned = round(1.0 - p_raw, 4) if result["side"] == "inverted" else p_raw
+ gap = round(k_prob - p_aligned, 4) if k_prob is not None and p_aligned is not None else None
+ return {
+ "match_confidence": result["confidence"],
+ "reasons": result["reasons"],
+ "side": result["side"],
+ "kalshi": _brief(km),
+ "polymarket": _brief(pm),
+ "kalshi_yes_probability": k_prob,
+ "polymarket_yes_probability": p_aligned,
+ "price_gap": gap,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Forecast scoring
+# ---------------------------------------------------------------------------
+
+def brier_score(forecasts: list[tuple[float, int]]) -> float | None:
+ """Mean squared error of probability forecasts against 0/1 outcomes.
+
+ ``forecasts`` is ``[(p_yes, outcome)]`` with outcome 1 for YES.
+ 0.0 is perfect; always forecasting 0.5 scores 0.25. None for an
+ empty sample (no score is not a score of zero).
+ """
+ if not forecasts:
+ return None
+ total = 0.0
+ for p, outcome in forecasts:
+ if outcome not in (0, 1):
+ raise ValueError(f"outcome must be 0 or 1, got {outcome!r}")
+ if not 0.0 <= p <= 1.0:
+ raise ValueError(f"probability must be in [0, 1], got {p!r}")
+ total += (p - outcome) ** 2
+ return total / len(forecasts)
+
+
+def price_at_offset(
+ history: list[tuple[int, float]],
+ reference_ts: int,
+ offset_hours: float,
+ max_staleness_hours: float,
+) -> tuple[float | None, str]:
+ """Last price at or before ``reference_ts - offset``.
+
+ ``history`` is ``[(unix_ts, price)]`` in any order. Returns
+ ``(price, reason)``; price is None when there is no point inside
+ ``[target - max_staleness, target]`` (the market had not traded yet,
+ or its last trade is too old to stand for the offset).
+ """
+ target = reference_ts - int(offset_hours * 3600)
+ floor = target - int(max_staleness_hours * 3600)
+ best: tuple[int, float] | None = None
+ for ts, price in history:
+ if price is None or ts > target:
+ continue
+ if best is None or ts > best[0]:
+ best = (ts, price)
+ if best is None:
+ return None, "no price at or before the offset"
+ if best[0] < floor:
+ return None, f"last price {round((target - best[0]) / 3600, 1)}h before the offset (limit {max_staleness_hours}h)"
+ return best[1], "ok"
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index af3204c..b57d7c2 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -68,6 +68,8 @@ from .sources.github_trending import fetch_trending_repos
from .sources.arxiv_papers import fetch_arxiv_papers
from .sources.usa_spending import fetch_usa_spending
from .sources import geospatial
+from .sources import kalshi as kalshi_src
+from .sources import prediction_cross
console = Console()
@@ -893,6 +895,195 @@ def predictions(ctx: click.Context, limit: int) -> None:
console.print(table)
+def _pct(value: Any) -> str:
+ return "-" if value is None else f"{value * 100:.1f}%"
+
+
+# Data gaps print through the shared _print_data_gaps defined with the
+# AOI commands below (module-level, resolved at call time).
+
+
[email protected]("--category", "-c", default=None, help="Kalshi category, e.g. Economics")
[email protected]("--series", "-s", default=None, help="Kalshi series ticker, e.g. KXFED")
[email protected]("--limit", "-n", default=20, help=f"Number of markets (max {kalshi_src.MAX_RESULTS})")
+ "--pages", default=3, help=f"Unfiltered scan: pages of 200 open events (max {kalshi_src.MAX_PAGES})"
+)
+def kalshi(ctx: click.Context, category: str | None, series: str | None, limit: int, pages: int) -> None:
+ """Kalshi open markets by volume (public market data)."""
+ f = _get_fetcher()
+ data = _run(
+ kalshi_src.fetch_kalshi_markets(f, category=category, series=series, limit=limit, pages=pages)
+ )
+
+ if _bail_on_error(ctx, data):
+ return
+
+ _print_data_gaps(data)
+ mkts = data.get("markets", [])
+ if not mkts:
+ console.print(
+ f"[yellow]No traded Kalshi markets in the scanned set "
+ f"({data.get('scan', {}).get('events_scanned', 0)} events)[/yellow]"
+ )
+ return
+
+ table = Table(title="Kalshi Markets", box=box.SIMPLE_HEAVY)
+ table.add_column("Market", max_width=55)
+ table.add_column("YES side", max_width=25)
+ table.add_column("YES", justify="right")
+ table.add_column("Basis")
+ table.add_column("24h Vol", justify="right")
+ table.add_column("Volume", justify="right")
+ for m in mkts:
+ # Wrapped, not sliced: a ladder's rows differ only at the end
+ # ("... at their October 2026 meeting?" vs "... December ...").
+ table.add_row(
+ _cell(m.get("question") or ""),
+ _cell(m.get("yes_side") or ""),
+ _pct(m.get("probability")),
+ _cell(m.get("price_basis", "")),
+ f"{m.get('volume_24h', 0):,.0f}",
+ f"{m.get('volume', 0):,.0f}",
+ )
+ console.print(table)
+ console.print(f"[dim]{escape(data.get('units', {}).get('price', ''))}[/dim]")
+
+
[email protected]("prediction-compare")
[email protected]("--category", "-c", default=None, help="Kalshi category, e.g. Economics")
[email protected]("--series", "-s", default=None, help="Kalshi series ticker")
+ "--polymarket-limit", default=300,
+ help=f"Polymarket open markets to compare (max {prediction.MAX_OPEN_MARKETS})",
+)
[email protected]("--min-confidence", default=0.6, help="Match threshold 0..1")
[email protected]("--limit", "-n", default=25, help=f"Matched pairs to show (max {prediction_cross.MAX_PAIRS})")
+def prediction_compare(
+ ctx: click.Context,
+ category: str | None,
+ series: str | None,
+ polymarket_limit: int,
+ min_confidence: float,
+ limit: int,
+) -> None:
+ """Same event on Kalshi and Polymarket, side by side."""
+ f = _get_fetcher()
+ data = _run(
+ prediction_cross.fetch_prediction_compare(
+ f,
+ category=category,
+ series=series,
+ polymarket_limit=polymarket_limit,
+ min_confidence=min_confidence,
+ limit=limit,
+ )
+ )
+
+ if _bail_on_error(ctx, data):
+ return
+
+ _print_data_gaps(data)
+ console.print(
+ f"Compared {data.get('kalshi_markets_compared', 0)} Kalshi / "
+ f"{data.get('polymarket_markets_compared', 0)} Polymarket markets: "
+ f"{data.get('matched_count', 0)} matched, unmatched Kalshi "
+ f"{data.get('unmatched_kalshi')}, unmatched Polymarket {data.get('unmatched_polymarket')}"
+ )
+ pairs = data.get("matched", [])
+ if not pairs:
+ console.print(
+ f"[yellow]No pair reached match confidence {data.get('min_confidence')}[/yellow]"
+ )
+ return
+
+ table = Table(title="Cross-venue Matches", box=box.SIMPLE_HEAVY)
+ table.add_column("Kalshi", max_width=40)
+ table.add_column("Polymarket", max_width=40)
+ table.add_column("Conf", justify="right")
+ table.add_column("Kalshi YES", justify="right")
+ table.add_column("Poly YES", justify="right")
+ table.add_column("Gap", justify="right")
+ for p in pairs:
+ gap = p.get("price_gap")
+ table.add_row( # wrapped, not sliced (see the kalshi table)
+ _cell(p.get("kalshi", {}).get("question") or ""),
+ _cell(p.get("polymarket", {}).get("question") or ""),
+ f"{p.get('match_confidence', 0):.2f}",
+ _pct(p.get("kalshi_yes_probability")),
+ _pct(p.get("polymarket_yes_probability")),
+ "-" if gap is None else f"{gap * 100:+.1f}pp",
+ )
+ console.print(table)
+
+
[email protected]("prediction-settled")
[email protected]("--limit", "-n", default=25, help=f"Settled markets per venue (max {kalshi_src.MAX_SETTLED})")
+ "--offset", "offsets", multiple=True, type=float,
+ help=(
+ f"Hours before close (repeatable, up to {prediction_cross.MAX_OFFSETS} values of at most "
+ f"{prediction_cross.MAX_OFFSET_HOURS}; default 24 and 168)"
+ ),
+)
[email protected]("--kalshi-category", default="Economics", help="Kalshi sample category")
[email protected]("--kalshi-series", default=None, help="Kalshi sample series ticker")
+def prediction_settled(
+ ctx: click.Context,
+ limit: int,
+ offsets: tuple[float, ...],
+ kalshi_category: str,
+ kalshi_series: str | None,
+) -> None:
+ """Settled markets scored against pre-close prices (Brier)."""
+ f = _get_fetcher()
+ data = _run(
+ prediction_cross.fetch_prediction_settled(
+ f,
+ limit=limit,
+ offsets_hours=list(offsets) or None,
+ kalshi_category=kalshi_category,
+ kalshi_series=kalshi_series,
+ )
+ )
+
+ if _bail_on_error(ctx, data):
+ return
+
+ _print_data_gaps(data)
+ table = Table(title="Settled-market Brier Scores", box=box.SIMPLE_HEAVY)
+ table.add_column("Venue")
+ table.add_column("Offset")
+ table.add_column("n", justify="right")
+ table.add_column("Events", justify="right")
+ table.add_column("Brier", justify="right")
+ table.add_column("YES rate", justify="right")
+ table.add_column("Excluded", no_wrap=True)
+ for venue, entry in (data.get("venues") or {}).items():
+ if not entry.get("scores"):
+ reason = entry.get("error") or entry.get("not_scored_reason") or "not scored"
+ table.add_row(_cell(venue), "-", "-", "-", "not scored", "-", _cell(reason))
+ continue
+ for label, sc in entry["scores"].items():
+ brier = sc.get("brier")
+ excluded = ", ".join(f"{k}: {v}" for k, v in (sc.get("excluded") or {}).items())
+ table.add_row(
+ _cell(venue),
+ _cell(label),
+ str(sc.get("n", 0)),
+ str(sc.get("distinct_events", 0)),
+ "-" if brier is None else f"{brier:.4f}",
+ _pct(sc.get("yes_rate")),
+ _cell(excluded or "-"),
+ )
+ console.print(table)
+ console.print(f"[dim]{escape(data.get('comparability', ''))}[/dim]")
+
+
# ---------------------------------------------------------------------------
# Displacement
# ---------------------------------------------------------------------------
diff --git a/src/world_intel_mcp/collector.py b/src/world_intel_mcp/collector.py
index 4211562..983f3cc 100644
--- a/src/world_intel_mcp/collector.py
+++ b/src/world_intel_mcp/collector.py
@@ -79,8 +79,12 @@ SOURCES = [
# News (2)
("news_feed", "sources.news", "fetch_news_feed", {}),
("trending_keywords", "sources.news", "fetch_trending_keywords", {}),
- # Prediction (1)
+ # Prediction (3)
("prediction_markets", "sources.prediction", "fetch_prediction_markets", {}),
+ # Kalshi: the Economics category's top series (Fed, CPI, gas prices);
+ # the unfiltered scan reads 4 MB pages of far-dated events instead.
+ ("kalshi_markets", "sources.kalshi", "fetch_kalshi_markets", {"category": "Economics", "limit": 50}),
+ ("prediction_compare", "sources.prediction_cross", "fetch_prediction_compare", {"category": "Economics"}),
# Aviation (4)
("airport_delays", "sources.aviation", "fetch_airport_delays", {}),
("domestic_flights", "sources.aviation", "fetch_domestic_flights", {}),
@@ -162,7 +166,7 @@ DOMAIN_GROUPS = {
"maritime": ["nav_warnings"],
"climate": ["climate_anomalies"],
"news": ["news_feed", "trending_keywords"],
- "prediction": ["prediction_markets"],
+ "prediction": ["prediction_markets", "kalshi_markets", "prediction_compare"],
"aviation": ["airport_delays", "domestic_flights", "bizjet_cohort", "military_cohort"],
"cyber": ["cyber_threats"],
"space": ["space_weather", "launch_schedule"],
diff --git a/src/world_intel_mcp/sources/kalshi.py b/src/world_intel_mcp/sources/kalshi.py
new file mode 100644
index 0000000..577cba0
--- /dev/null
+++ b/src/world_intel_mcp/sources/kalshi.py
@@ -0,0 +1,565 @@
+"""Kalshi prediction-market data (public market-data API, no account).
+
+Reads only the unauthenticated endpoints of Kalshi's trade API v2
+(``https://api.elections.kalshi.com/trade-api/v2``), verified live
+2026-10-17: ``/events`` (with nested markets), ``/series`` (with
+``include_volume``), ``/markets`` (``status=settled``) and the batch
+``/markets/candlesticks``. Nothing here places orders or needs keys.
+
+Units, as the venue serves them: prices are strings in US dollars per
+contract that pays $1 on YES (``yes_bid_dollars="0.6300"``), so a price
+is directly a YES implied probability; volumes and open interest are
+contract counts as strings (``volume_fp="3251.19"``).
+
+Every function returns a dict. An upstream failure is never an empty
+success: it carries ``error`` and ``degraded: True``; a partial scan
+lists what was not read under ``data_gaps``.
+
+Gaps / not covered:
+- The open-events endpoint orders events by close time, furthest out
+ first, and holds more than 8,000 open events (measured 2026-10-17:
+ 40 pages of 200 did not reach the end). An unfiltered call ranks only
+ the pages it read; ``scan.exhaustive`` says so. Category calls rank
+ the category's top series by lifetime volume instead.
+- The ``/events`` ``category`` query parameter is ignored by the API
+ (measured: identical results with and without it), so category is
+ resolved through ``/series?category=`` and filtered client-side. That
+ filter is loose too (measured: ``category=Economics`` returned 869
+ series, 7 of them in other categories), so series are kept only on an
+ exact category match. Category names are exact: ``Climate`` returns
+ no series, ``Climate and Weather`` returns 444.
+- Combo (multivariate) markets are excluded from settled samples
+ (``mve_filter=exclude``); they never appear in the events listing.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from datetime import datetime, timezone
+from typing import Any
+
+from ..fetcher import Fetcher
+
+logger = logging.getLogger("world-intel-mcp.sources.kalshi")
+
+_BASE = "https://api.elections.kalshi.com/trade-api/v2"
+_SOURCE = "kalshi"
+_PAGE_SIZE = 200
+# Caps on caller-chosen counts. A category scan costs one /series call
+# plus up to 5 /events pages (open) or 3 /markets pages (settled) per
+# series, so MAX_SERIES bounds one scan at 126 requests (open) or 76
+# (settled, before candlesticks).
+MAX_PAGES = 25
+MAX_SERIES = 25
+MAX_RESULTS = 500
+MAX_SETTLED = 100
+_CANDLE_BUDGET = 9000 # API refuses a batch above 10,000 candlesticks (measured)
+
+# Minimum spacing between Kalshi requests from one process. Kalshi has no
+# entry in the fetcher's per-source limits, and two collector sources
+# scanning the same series at once drew HTTP 429 (measured 2026-10-17:
+# about 12 requests in 0.3 s). At 0.1 s spacing a 26-request category
+# scan still drew one 429 on its 21st request, 2.0 s in; at 0.2 s the
+# same scan drew none (26 requests in 5.0 s). Spacing comes before the
+# fetcher's cache check, so a request repeated by a second caller is
+# usually a cache hit.
+_MIN_INTERVAL = 0.2
+_pace_state: dict[str, Any] = {"loop": None, "lock": None, "last": 0.0}
+
+
+async def _pace() -> None:
+ loop = asyncio.get_running_loop()
+ if _pace_state["loop"] is not loop: # an asyncio.Lock is bound to one loop
+ _pace_state.update(loop=loop, lock=asyncio.Lock())
+ async with _pace_state["lock"]:
+ wait = _MIN_INTERVAL - (time.monotonic() - _pace_state["last"])
+ if wait > 0:
+ await asyncio.sleep(wait)
+ _pace_state["last"] = time.monotonic()
+
+UNITS = {
+ "price": (
+ "Kalshi quotes YES contracts in US dollars per $1 payout (fields *_dollars, "
+ "decimal strings); 0.63 means a 63% implied YES probability"
+ ),
+ "volume": "contracts (volume_fp, decimal strings); lifetime unless the field says 24h",
+}
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _num(value: Any) -> float | None:
+ """Decimal string or number -> float; None when absent or unparseable."""
+ if value is None or value == "":
+ return None
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def count_arg(value: Any, name: str, high: int) -> int:
+ """A caller's count clamped to ``[1, high]``.
+
+ Raises ValueError naming the argument when ``value`` is not a whole
+ number (a string, None, a boolean, 2.5, NaN, infinity), so entry
+ points can answer ``{"error": ...}`` before any request is made.
+ """
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or (
+ isinstance(value, float) and not value.is_integer()
+ ):
+ raise ValueError(f"{name} must be a whole number from 1 to {high} (got {value!r})")
+ return max(1, min(int(value), high))
+
+
+def implied_probability(market: dict) -> tuple[float | None, str]:
+ """YES implied probability and the basis it came from.
+
+ Midpoint of a two-sided book when both quotes are live (bid > 0 and
+ ask < 1); otherwise the last trade; otherwise None ("no price").
+ """
+ bid = _num(market.get("yes_bid_dollars"))
+ ask = _num(market.get("yes_ask_dollars"))
+ last = _num(market.get("last_price_dollars"))
+ if bid is not None and ask is not None and 0 < bid <= ask < 1:
+ return round((bid + ask) / 2, 4), "bid_ask_midpoint"
+ if last is not None and last > 0:
+ return round(last, 4), "last_trade"
+ return None, "no_price"
+
+
+def normalize_market(market: dict, event: dict | None = None) -> dict:
+ """One Kalshi market in the cross-venue shape plus venue fields."""
+ event = event or {}
+ prob, basis = implied_probability(market)
+ event_ticker = market.get("event_ticker") or event.get("event_ticker") or ""
+ series_ticker = event.get("series_ticker") or (event_ticker.split("-", 1)[0] if event_ticker else "")
+ yes_side = market.get("yes_sub_title") or ""
+ title = market.get("title") or ""
+ return {
+ "venue": "kalshi",
+ "id": market.get("ticker", ""),
+ "question": title,
+ "context": event.get("title", ""),
+ "yes_side": "" if yes_side.strip().lower() == title.strip().lower() else yes_side,
+ "outcomes": ["Yes", "No"],
+ "end_time": market.get("expected_expiration_time") or market.get("close_time"),
+ "close_time": market.get("close_time"),
+ "probability": prob,
+ "price_basis": basis,
+ "yes_bid": _num(market.get("yes_bid_dollars")),
+ "yes_ask": _num(market.get("yes_ask_dollars")),
+ "last_price": _num(market.get("last_price_dollars")),
+ "volume": _num(market.get("volume_fp")) or 0.0,
+ "volume_24h": _num(market.get("volume_24h_fp")) or 0.0,
+ "open_interest": _num(market.get("open_interest_fp")),
+ "event_ticker": event_ticker,
+ "series_ticker": series_ticker,
+ "category": event.get("category"),
+ "status": market.get("status"),
+ "url": f"https://kalshi.com/markets/{series_ticker.lower()}" if series_ticker else "",
+ }
+
+
+async def _get(fetcher: Fetcher, path: str, params: dict, cache_key: str, ttl: int) -> Any:
+ await _pace()
+ return await fetcher.get_json(
+ f"{_BASE}{path}", source=_SOURCE, cache_key=cache_key, cache_ttl=ttl, params=params
+ )
+
+
+async def _events_pages(
+ fetcher: Fetcher, params: dict, max_pages: int, key_prefix: str
+) -> tuple[list[dict], int, bool, str | None]:
+ """Follow the events cursor. Returns (events, pages, exhaustive, error)."""
+ events: list[dict] = []
+ cursor = ""
+ pages = 0
+ while pages < max_pages:
+ q = dict(params, limit=str(_PAGE_SIZE), with_nested_markets="true")
+ if cursor:
+ q["cursor"] = cursor
+ data = await _get(fetcher, "/events", q, f"{key_prefix}:{cursor or 'first'}", 300)
+ if not isinstance(data, dict) or not isinstance(data.get("events"), list):
+ return events, pages, False, (
+ f"Kalshi /events page {pages + 1} unavailable (no live or cached data)"
+ )
+ pages += 1
+ events.extend(e for e in data["events"] if isinstance(e, dict))
+ cursor = data.get("cursor") or ""
+ if not cursor:
+ return events, pages, True, None
+ return events, pages, False, None
+
+
+async def _top_series(fetcher: Fetcher, category: str, series_limit: int) -> tuple[list[dict], str | None]:
+ data = await _get(
+ fetcher,
+ "/series",
+ {"category": category, "include_volume": "true"},
+ f"kalshi:series:{category}",
+ 3600,
+ )
+ rows = data.get("series") if isinstance(data, dict) else None
+ if rows is None and isinstance(data, dict) and "series" in data:
+ rows = [] # a category with no series answers {"series": null}, HTTP 200 (measured)
+ if not isinstance(rows, list):
+ return [], f"Kalshi /series?category={category} unavailable (no live or cached data)"
+ series = [
+ s for s in rows
+ if isinstance(s, dict) and s.get("ticker") and s.get("category") == category
+ ]
+ series.sort(key=lambda s: _num(s.get("volume_fp")) or 0.0, reverse=True)
+ return series[:series_limit], None
+
+
+def _no_series_gap(category: str) -> str:
+ return (
+ f"Kalshi lists no series in category {category!r}; category names are exact "
+ "(e.g. 'Economics', 'Politics', 'Elections', 'Financials', 'Climate and Weather')"
+ )
+
+
+async def fetch_kalshi_open_markets(
+ fetcher: Fetcher,
+ category: str | None = None,
+ series: str | None = None,
+ pages: int = 3,
+ series_limit: int = 10,
+) -> dict:
+ """Every open market the chosen scan reaches, normalized, unsorted.
+
+ Scan modes: ``series`` reads that series' open events in full;
+ ``category`` reads the category's ``series_limit`` highest-volume
+ series; neither reads the first ``pages`` pages of all open events.
+ ``pages`` and ``series_limit`` are clamped to 1..25.
+ """
+ pages = count_arg(pages, "pages", MAX_PAGES)
+ series_limit = count_arg(series_limit, "series_limit", MAX_SERIES)
+ gaps: list[str] = []
+ errors: list[str] = []
+ events: list[dict] = []
+ scan: dict[str, Any]
+ if series:
+ events, n, exhaustive, err = await _events_pages(
+ fetcher, {"status": "open", "series_ticker": series}, MAX_PAGES, f"kalshi:events:series:{series}"
+ )
+ scan = {"mode": "series", "series": series, "pages_fetched": n, "exhaustive": exhaustive}
+ if err:
+ errors.append(err)
+ elif category:
+ top, err = await _top_series(fetcher, category, series_limit)
+ scan = {
+ "mode": "category_top_series",
+ "category": category,
+ "series_ranked_by": "lifetime series volume (contracts)",
+ "series_scanned": [s["ticker"] for s in top],
+ "exhaustive": False,
+ }
+ if err:
+ errors.append(err)
+ elif not top:
+ gaps.append(_no_series_gap(category))
+ failed = []
+ for s in top:
+ ev, _, _, e_err = await _events_pages(
+ fetcher, {"status": "open", "series_ticker": s["ticker"]}, 5, f"kalshi:events:series:{s['ticker']}"
+ )
+ if e_err:
+ failed.append(s["ticker"])
+ events.extend(ev)
+ if failed:
+ errors.append(f"open events unavailable for series {failed}")
+ else:
+ events, n, exhaustive, err = await _events_pages(
+ fetcher, {"status": "open"}, pages, "kalshi:events:open"
+ )
+ scan = {
+ "mode": "open_events_pages",
+ "pages_fetched": n,
+ "page_size": _PAGE_SIZE,
+ "exhaustive": exhaustive,
+ "api_order": "events by close time, furthest out first",
+ }
+ if err:
+ errors.append(err)
+ if not exhaustive and not err:
+ gaps.append(
+ f"scanned {n} page(s) of open events; more exist and were not read, "
+ "so the ranking covers only the scanned events"
+ )
+
+ markets: list[dict] = []
+ for ev in events:
+ if category and ev.get("category") and ev["category"] != category:
+ continue
+ for m in ev.get("markets") or []:
+ if isinstance(m, dict) and m.get("status") in (None, "active", "open"):
+ markets.append(normalize_market(m, ev))
+ scan["events_scanned"] = len(events)
+ return {
+ "markets": markets,
+ "scan": scan,
+ "errors": errors,
+ "data_gaps": errors + gaps,
+ "nothing_read": not events and bool(errors),
+ }
+
+
+async def fetch_kalshi_markets(
+ fetcher: Fetcher,
+ category: str | None = None,
+ series: str | None = None,
+ limit: int = 20,
+ pages: int = 3,
+ series_limit: int = 10,
+ include_untraded: bool = False,
+) -> dict:
+ """Kalshi open markets ranked by 24h volume, then lifetime volume.
+
+ Returns ``{"markets": [...], "count", "source": "kalshi", "scan",
+ "units", "data_gaps", "timestamp"}``; on a total outage also
+ ``error`` and ``degraded: True`` (never an empty success). ``limit``
+ is clamped to 1..500; a count that is not a whole number is an
+ ``error`` answered before any request.
+ """
+ try:
+ limit = count_arg(limit, "limit", MAX_RESULTS)
+ pages = count_arg(pages, "pages", MAX_PAGES)
+ series_limit = count_arg(series_limit, "series_limit", MAX_SERIES)
+ except ValueError as exc:
+ return {"error": str(exc), "degraded": True, "source": "kalshi", "timestamp": _utc_now_iso()}
+ raw = await fetch_kalshi_open_markets(
+ fetcher, category=category, series=series, pages=pages, series_limit=series_limit
+ )
+ markets = raw["markets"]
+ untraded = sum(1 for m in markets if m["volume"] <= 0)
+ if not include_untraded:
+ markets = [m for m in markets if m["volume"] > 0]
+ markets.sort(key=lambda m: (m["volume_24h"], m["volume"]), reverse=True)
+ out: dict[str, Any] = {
+ "markets": markets[:limit],
+ "count": min(len(markets), limit),
+ "markets_considered": len(markets),
+ "untraded_excluded": 0 if include_untraded else untraded,
+ "source": "kalshi",
+ "scan": raw["scan"],
+ "units": UNITS,
+ "data_gaps": raw["data_gaps"],
+ "timestamp": _utc_now_iso(),
+ }
+ if raw["errors"]:
+ out["degraded"] = True
+ if raw["nothing_read"]:
+ out["error"] = raw["errors"][0]
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Settled markets
+# ---------------------------------------------------------------------------
+
+def _ts(value: str | None) -> int | None:
+ if not value:
+ return None
+ try:
+ return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp())
+ except ValueError:
+ return None
+
+
+def _settled_record(m: dict, min_volume: float, min_open_hours: float) -> tuple[dict | None, str]:
+ result = (m.get("result") or "").lower()
+ volume = _num(m.get("volume_fp")) or 0.0
+ if result not in ("yes", "no"):
+ return None, "result"
+ if volume < min_volume:
+ return None, "volume"
+ ref = _ts(m.get("close_time"))
+ if ref is None:
+ return None, "result"
+ opened = _ts(m.get("open_time"))
+ if min_open_hours and (opened is None or ref - opened < min_open_hours * 3600):
+ return None, "too_short"
+ return {
+ "venue": "kalshi",
+ "id": m.get("ticker", ""),
+ "question": m.get("title", ""),
+ "yes_side": m.get("yes_sub_title") or "",
+ "event": m.get("event_ticker") or "",
+ "outcome": 1 if result == "yes" else 0,
+ "result": result,
+ "volume": volume,
+ "open_ts": opened,
+ "reference_ts": ref,
+ "reference": "close_time (trading end)",
+ "settled_at": m.get("settlement_ts"),
+ }, "ok"
+
+
+async def fetch_kalshi_settled(
+ fetcher: Fetcher,
+ limit: int = 25,
+ min_volume: float = 1000.0,
+ series: str | None = None,
+ category: str | None = None,
+ series_limit: int = 10,
+ pages: int = 10,
+ min_open_hours: float = 0.0,
+) -> dict:
+ """Recently settled binary markets with a YES/NO result.
+
+ Selection: settled markets (combos excluded) from one ``series``,
+ or from the ``series_limit`` highest-volume series of ``category``,
+ or else from the exchange-wide listing (first ``pages`` pages);
+ kept when ``result`` is yes/no, lifetime volume >= ``min_volume``
+ contracts and the market was open at least ``min_open_hours``
+ before close (a market younger than the smallest offset can have no
+ price at any offset). The most recently settled ``limit`` are kept.
+
+ The exchange-wide listing is dominated by intraday sports markets
+ (measured 2026-10-17: 1,000 rows spanned about 40 minutes and none
+ was open 24h), which is why callers scoring at day-scale offsets
+ pass a category or series. ``pages`` and ``series_limit`` are
+ clamped to 1..25, ``limit`` to 1..100.
+ """
+ limit = count_arg(limit, "limit", MAX_SETTLED)
+ pages = count_arg(pages, "pages", MAX_PAGES)
+ series_limit = count_arg(series_limit, "series_limit", MAX_SERIES)
+ candidates: list[dict] = []
+ skipped = {"result": 0, "volume": 0, "too_short": 0}
+ seen = 0
+ fetched = 0
+ errors: list[str] = []
+ gaps: list[str] = []
+ scope: list[str | None]
+ if series:
+ scope = [series]
+ elif category:
+ top, err = await _top_series(fetcher, category, series_limit)
+ if err:
+ errors.append(err)
+ elif not top:
+ gaps.append(_no_series_gap(category))
+ scope = [s["ticker"] for s in top]
+ else:
+ scope = [None]
+
+ for tick in scope:
+ cursor = ""
+ tick_pages = pages if tick is None else min(pages, 3)
+ for _ in range(tick_pages):
+ params = {"status": "settled", "mve_filter": "exclude", "limit": str(_PAGE_SIZE)}
+ if tick:
+ params["series_ticker"] = tick
+ if cursor:
+ params["cursor"] = cursor
+ data = await _get(
+ fetcher, "/markets", params, f"kalshi:settled:{tick or 'all'}:{cursor or 'first'}", 900
+ )
+ if not isinstance(data, dict) or not isinstance(data.get("markets"), list):
+ errors.append(f"Kalshi settled markets unavailable for {tick or 'the exchange listing'}")
+ break
+ fetched += 1
+ for m in data["markets"]:
+ if not isinstance(m, dict):
+ continue
+ seen += 1
+ rec, why = _settled_record(m, min_volume, min_open_hours)
+ if rec is None:
+ skipped[why] += 1
+ else:
+ candidates.append(rec)
+ cursor = data.get("cursor") or ""
+ if not cursor or (tick is None and len(candidates) >= limit):
+ break
+
+ candidates.sort(key=lambda r: r["settled_at"] or "", reverse=True)
+ return {
+ "markets": candidates[:limit],
+ "scope": {"series": series, "category": category, "series_read": [t for t in scope if t]},
+ "listing_rows_read": seen,
+ "skipped": skipped,
+ "open_too_briefly_skipped": skipped["too_short"],
+ "pages_fetched": fetched,
+ "error": errors[0] if errors and not candidates else None,
+ "errors": errors,
+ "data_gaps": gaps,
+ }
+
+
+async def fetch_kalshi_price_history(
+ fetcher: Fetcher,
+ markets: list[dict],
+ window_start_hours: float,
+ window_end_hours: float,
+) -> tuple[dict[str, list[tuple[int, float]]], list[str]]:
+ """Hourly last-trade prices for each market over a window before close.
+
+ The window is ``[reference - window_start_hours, reference -
+ window_end_hours]`` per market, clipped to its open time. Uses the
+ batch candlestick endpoint (no series ticker needed), splitting
+ requests under the API's 10,000-candle cap. A candle's
+ ``price.close_dollars`` is the last trade in that hour; hours with
+ no trade carry no price and are skipped.
+
+ Returns (``{ticker: [(end_period_ts, price)]}``, errors). A ticker
+ absent from the dict had no readable history.
+ """
+ history: dict[str, list[tuple[int, float]]] = {}
+ errors: list[str] = []
+ batch: list[tuple[dict, int, int]] = []
+
+ async def flush() -> None:
+ nonlocal batch
+ if not batch:
+ return
+ start = min(s for _, s, _ in batch)
+ end = max(e for _, _, e in batch)
+ tickers = ",".join(m["id"] for m, _, _ in batch)
+ data = await _get(
+ fetcher,
+ "/markets/candlesticks",
+ {"market_tickers": tickers, "start_ts": str(start), "end_ts": str(end), "period_interval": "60"},
+ f"kalshi:candles:{tickers}:{start}:{end}",
+ 21600,
+ )
+ if not isinstance(data, dict) or not isinstance(data.get("markets"), list):
+ errors.append(f"candlesticks unavailable for {len(batch)} market(s)")
+ else:
+ for entry in data["markets"]:
+ if not isinstance(entry, dict):
+ continue
+ points = []
+ for c in entry.get("candlesticks") or []:
+ price = _num(((c or {}).get("price") or {}).get("close_dollars"))
+ ts = c.get("end_period_ts") if isinstance(c, dict) else None
+ if price is not None and isinstance(ts, int):
+ points.append((ts, price))
+ history[entry.get("market_ticker", "")] = points
+ batch = []
+
+ for m in markets:
+ ref = m["reference_ts"]
+ start = ref - int(window_start_hours * 3600)
+ if m.get("open_ts"):
+ start = max(start, m["open_ts"])
+ end = ref - int(window_end_hours * 3600)
+ if end <= start:
+ # Opened after the latest offset point: no history can exist,
+ # which is "no price", not "history unavailable".
+ history[m["id"]] = []
+ continue
+ # The batch shares one [start, end] range, so cost is the union.
+ new_start = min([start] + [s for _, s, _ in batch])
+ new_end = max([end] + [e for _, _, e in batch])
+ cost = ((new_end - new_start) // 3600 + 1) * (len(batch) + 1)
+ if batch and cost > _CANDLE_BUDGET:
+ await flush()
+ batch.append((m, start, end))
+ await flush()
+ return history, errors
diff --git a/src/world_intel_mcp/sources/prediction.py b/src/world_intel_mcp/sources/prediction.py
index 5eb872c..e38dc15 100644
--- a/src/world_intel_mcp/sources/prediction.py
+++ b/src/world_intel_mcp/sources/prediction.py
@@ -1,8 +1,23 @@
"""Prediction market data sources for world-intel-mcp.
Fetches active prediction markets from Polymarket via their public
-Gamma API. Every function takes a Fetcher instance as its first
-argument and returns a dict (or empty results when upstream calls fail).
+Gamma API, and settled markets with their price history from the
+public CLOB ``/prices-history`` endpoint. Every function takes a
+Fetcher instance as its first argument and returns a dict.
+
+An upstream failure is never an empty success: the response keeps its
+documented keys and adds ``error`` and ``degraded: True``. Before
+2026-10-17 an outage returned ``{"markets": [], "count": 0}`` with no
+marker, shape-identical to a quiet market (ROADMAP Phase 24.5).
+
+Gaps / not covered:
+- Gamma serves lists, which cannot carry the fetcher's inline
+ ``_stale`` marker; a stale serve is detected through the circuit
+ breaker's per-source stale counter, which concurrent calls for the
+ same source share, so ``stale`` may also be set by a neighbour's
+ stale serve (over-reporting, never under-reporting).
+- Polymarket units: prices are USDC per share paying 1 USDC (directly
+ a probability); volumes are USDC notional.
"""
import json
@@ -18,6 +33,14 @@ logger = logging.getLogger("world-intel-mcp.sources.prediction")
# ---------------------------------------------------------------------------
_GAMMA_MARKETS_URL = "https://gamma-api.polymarket.com/markets"
+_CLOB_PRICES_HISTORY_URL = "https://clob.polymarket.com/prices-history"
+_GAMMA_PAGE_MAX = 100 # Gamma returns at most 100 rows per page (measured 2026-10-17)
+MAX_OPEN_MARKETS = 2000 # fetch_polymarket_open: at most 20 Gamma pages per call
+
+UNITS = {
+ "price": "Polymarket prices are USDC per share paying 1 USDC (0.63 = 63% implied probability)",
+ "volume": "USDC notional",
+}
# ---------------------------------------------------------------------------
@@ -59,6 +82,33 @@ def _classify_sentiment(yes_probability: float) -> str:
return "uncertain"
+def _stale_serves(fetcher: Fetcher, source: str) -> int:
+ """The breaker's stale-serve count for a source (list payloads only)."""
+ return int(fetcher.breaker.status().get(source, {}).get("total_stale_serves", 0))
+
+
+def _json_list(raw) -> list:
+ """Gamma encodes outcomes/prices/token ids as JSON strings."""
+ if isinstance(raw, list):
+ return raw
+ if not isinstance(raw, str):
+ return []
+ try:
+ value = json.loads(raw)
+ except (json.JSONDecodeError, TypeError):
+ return []
+ return value if isinstance(value, list) else []
+
+
+def _float_or_none(value) -> float | None:
+ if value is None or value == "":
+ return None
+ try:
+ return float(value)
+ except (ValueError, TypeError):
+ return None
+
+
def _safe_float(value) -> float:
"""Convert a value to float, returning 0.0 on failure."""
if value is None:
@@ -92,6 +142,7 @@ async def fetch_prediction_markets(fetcher: Fetcher, limit: int = 20) -> dict:
"ascending": "false",
}
+ stale_before = _stale_serves(fetcher, "polymarket")
data = await fetcher.get_json(
_GAMMA_MARKETS_URL,
source="polymarket",
@@ -99,13 +150,17 @@ async def fetch_prediction_markets(fetcher: Fetcher, limit: int = 20) -> dict:
cache_ttl=300,
params=params,
)
+ stale = _stale_serves(fetcher, "polymarket") > stale_before
if data is None:
+ # Outage, not a quiet market: same keys, plus the markers.
return {
"markets": [],
"count": 0,
"source": "polymarket",
"timestamp": _utc_now_iso(),
+ "error": "Polymarket Gamma API unavailable (no live or cached data)",
+ "degraded": True,
}
if not isinstance(data, list):
@@ -115,6 +170,8 @@ async def fetch_prediction_markets(fetcher: Fetcher, limit: int = 20) -> dict:
"count": 0,
"source": "polymarket",
"timestamp": _utc_now_iso(),
+ "error": f"Unexpected Polymarket response shape: {type(data).__name__}, expected a list",
+ "degraded": True,
}
markets: list[dict] = []
@@ -147,9 +204,221 @@ async def fetch_prediction_markets(fetcher: Fetcher, limit: int = 20) -> dict:
# sorted, but enforce it defensively)
markets.sort(key=lambda m: m["volume_24h"], reverse=True)
- return {
+ result = {
"markets": markets,
"count": len(markets),
"source": "polymarket",
"timestamp": _utc_now_iso(),
}
+ if stale:
+ result["stale"] = True
+ result["data_gaps"] = ["served from expired cache after a failed live fetch"]
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Cross-venue shapes (used by tools/prediction_markets.py)
+# ---------------------------------------------------------------------------
+
+def normalize_gamma_market(item: dict) -> dict | None:
+ """One Gamma market in the cross-venue shape; None if not binary.
+
+ Probability is the first outcome's: midpoint of bestBid/bestAsk when
+ both are live, else Gamma's ``outcomePrices[0]``.
+ """
+ outcomes = [str(o) for o in _json_list(item.get("outcomes"))]
+ prices = [_float_or_none(p) for p in _json_list(item.get("outcomePrices"))]
+ if len(outcomes) != 2 or len(prices) != 2:
+ return None
+ bid = _float_or_none(item.get("bestBid"))
+ ask = _float_or_none(item.get("bestAsk"))
+ if bid is not None and ask is not None and 0 < bid <= ask < 1:
+ prob, basis = round((bid + ask) / 2, 4), "bid_ask_midpoint"
+ elif prices[0] is not None:
+ prob, basis = round(prices[0], 4), "gamma_outcome_price"
+ else:
+ prob, basis = None, "no_price"
+ events = item.get("events") if isinstance(item.get("events"), list) else []
+ event = events[0] if events and isinstance(events[0], dict) else {}
+ slug = event.get("slug") or item.get("slug") or ""
+ tokens = [str(t) for t in _json_list(item.get("clobTokenIds"))]
+ return {
+ "venue": "polymarket",
+ "id": str(item.get("id") or item.get("conditionId") or slug),
+ "question": item.get("question", "") or "",
+ "context": event.get("title", "") if event.get("title") != item.get("question") else "",
+ "yes_side": "",
+ "outcomes": outcomes,
+ "outcome_prices": prices,
+ "end_time": item.get("endDate"),
+ "closed_time": item.get("closedTime"),
+ "probability": prob,
+ "price_basis": basis,
+ "volume": _safe_float(item.get("volumeNum") if item.get("volumeNum") is not None else item.get("volume")),
+ "volume_24h": _safe_float(item.get("volume24hr")),
+ "token_ids": tokens,
+ "event_id": str(event.get("id") or ""),
+ "resolution_status": item.get("umaResolutionStatus"),
+ "url": f"https://polymarket.com/event/{slug}" if slug else "",
+ }
+
+
+async def fetch_polymarket_open(fetcher: Fetcher, limit: int = 300) -> dict:
+ """Open binary Polymarket markets by 24h volume, cross-venue shape.
+
+ Returns ``{"markets", "requested", "rows_read", "non_binary_skipped",
+ "error"?, "degraded"?, "stale"?}``.
+ """
+ limit = max(1, min(int(limit), MAX_OPEN_MARKETS))
+ rows: list = []
+ offset = 0
+ stale_before = _stale_serves(fetcher, "polymarket")
+ error = None
+ while offset < limit:
+ size = min(_GAMMA_PAGE_MAX, limit - offset)
+ data = await fetcher.get_json(
+ _GAMMA_MARKETS_URL,
+ source="polymarket",
+ cache_key=f"prediction:polymarket:open:{size}:{offset}",
+ cache_ttl=300,
+ params={
+ "limit": str(size), "offset": str(offset), "active": "true",
+ "closed": "false", "order": "volume24hr", "ascending": "false",
+ },
+ )
+ if not isinstance(data, list):
+ error = (
+ "Polymarket Gamma API unavailable (no live or cached data)"
+ if data is None else f"Unexpected Polymarket response shape: {type(data).__name__}"
+ )
+ break
+ rows.extend(r for r in data if isinstance(r, dict))
+ if len(data) < size:
+ break
+ offset += size
+ markets = [m for m in (normalize_gamma_market(r) for r in rows) if m is not None]
+ out: dict = {
+ "markets": markets,
+ "requested": limit,
+ "rows_read": len(rows),
+ "non_binary_skipped": len(rows) - len(markets),
+ }
+ if error:
+ out["error"] = error
+ out["degraded"] = True
+ if _stale_serves(fetcher, "polymarket") > stale_before:
+ out["stale"] = True
+ return out
+
+
+def _closed_ts(value) -> int | None:
+ if not value:
+ return None
+ text = str(value).replace(" ", "T").replace("Z", "+00:00")
+ if text.endswith("+00"):
+ text += ":00"
+ try:
+ dt = datetime.fromisoformat(text)
+ except ValueError:
+ return None
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ return int(dt.timestamp())
+
+
+async def fetch_polymarket_settled(
+ fetcher: Fetcher,
+ limit: int = 25,
+ min_volume: float = 10000.0,
+ scan: int = 100,
+ min_open_hours: float = 0.0,
+) -> dict:
+ """Recently closed binary markets resolved to exactly 1/0.
+
+ Selection: Gamma closed markets ordered by ``closedTime`` descending
+ with ``volume_num_min``; kept when UMA status is ``resolved``, the
+ final outcome prices are exactly one 1 and one 0, and the market
+ opened (``startDate``) at least ``min_open_hours`` before it closed.
+ The first outcome is the YES side for scoring.
+ """
+ data = await fetcher.get_json(
+ _GAMMA_MARKETS_URL,
+ source="polymarket",
+ cache_key=f"prediction:polymarket:settled:{scan}:{min_volume}",
+ cache_ttl=900,
+ params={
+ "limit": str(max(1, min(int(scan), _GAMMA_PAGE_MAX))), "closed": "true",
+ "order": "closedTime", "ascending": "false", "volume_num_min": str(min_volume),
+ },
+ )
+ if not isinstance(data, list):
+ return {
+ "markets": [],
+ "listing_rows_read": 0,
+ "error": "Polymarket closed-markets listing unavailable (no live or cached data)",
+ }
+ kept: list[dict] = []
+ too_short = 0
+ for item in data:
+ if not isinstance(item, dict):
+ continue
+ m = normalize_gamma_market(item)
+ if m is None or m["resolution_status"] != "resolved" or not m["token_ids"]:
+ continue
+ if sorted(p for p in m["outcome_prices"] if p is not None) != [0.0, 1.0]:
+ continue
+ ref = _closed_ts(m["closed_time"])
+ if ref is None:
+ continue
+ opened = _closed_ts(item.get("startDate"))
+ if min_open_hours and (opened is None or ref - opened < min_open_hours * 3600):
+ too_short += 1
+ continue
+ kept.append({
+ "venue": "polymarket",
+ "id": m["id"],
+ "question": m["question"],
+ "yes_side": m["outcomes"][0],
+ "event": m["event_id"] or m["id"],
+ "outcome": 1 if m["outcome_prices"][0] == 1.0 else 0,
+ "result": m["outcomes"][0] if m["outcome_prices"][0] == 1.0 else m["outcomes"][1],
+ "volume": m["volume"],
+ "token_id": m["token_ids"][0],
+ "reference_ts": ref,
+ "reference": "closedTime (market closed after resolution)",
+ "settled_at": m["closed_time"],
+ })
+ if len(kept) >= limit:
+ break
+ return {
+ "markets": kept,
+ "listing_rows_read": len(data),
+ "open_too_briefly_skipped": too_short,
+ "error": None,
+ }
+
+
+async def fetch_polymarket_price_history(
+ fetcher: Fetcher, token_id: str, start_ts: int, end_ts: int
+) -> list[tuple[int, float]] | None:
+ """CLOB price history for one outcome token; None when unavailable.
+
+ Hourly fidelity. An empty list means the endpoint answered with no
+ points in the window, which differs from None (the call failed).
+ """
+ data = await fetcher.get_json(
+ _CLOB_PRICES_HISTORY_URL,
+ source="polymarket",
+ cache_key=f"prediction:polymarket:history:{token_id}:{start_ts}:{end_ts}",
+ cache_ttl=21600,
+ params={"market": token_id, "startTs": str(start_ts), "endTs": str(end_ts), "fidelity": "60"},
+ )
+ if not isinstance(data, dict) or not isinstance(data.get("history"), list):
+ return None
+ points: list[tuple[int, float]] = []
+ for row in data["history"]:
+ if isinstance(row, dict) and isinstance(row.get("t"), int):
+ p = _float_or_none(row.get("p"))
+ if p is not None:
+ points.append((row["t"], p))
+ return points
diff --git a/src/world_intel_mcp/sources/prediction_cross.py b/src/world_intel_mcp/sources/prediction_cross.py
new file mode 100644
index 0000000..4643da0
--- /dev/null
+++ b/src/world_intel_mcp/sources/prediction_cross.py
@@ -0,0 +1,426 @@
+"""Cross-venue prediction-market views: same-event comparison and
+settled-market forecast scoring (Kalshi and Polymarket).
+
+Built on ``sources/kalshi.py`` and ``sources/prediction.py`` for the
+fetches and ``analysis/prediction_matching.py`` for the matching and
+scoring arithmetic. Each venue's failure is reported for that venue;
+one venue being down never reads as "no matches" or "no settled
+markets".
+
+Gaps / not covered:
+- The two venues' settled samples are different markets, so their
+ Brier scores are not a head-to-head comparison; the response says so.
+- Kalshi reference time is ``close_time`` (trading end, which can be
+ early when the outcome is known); Polymarket's is ``closedTime``
+ (after UMA resolution, often hours after the event). Prices inside
+ that last window already know the answer, which is why offsets
+ default to 24h and 168h, not minutes.
+- Price history comes from venue endpoints whose retention was not
+ measured beyond the recent markets probed on 2026-10-17.
+- Samples are the most recently settled markets, so they cluster in
+ time. Measured 2026-10-17 17:05 UTC: one football match supplied 11 of
+ 25 Polymarket markets (3 event ids), and two CPI releases supplied all
+ 24 Kalshi markets scored at 24h.
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+from datetime import datetime, timezone
+from typing import Any
+
+from ..analysis.prediction_matching import (
+ DEFAULT_MIN_CONFIDENCE,
+ brier_score,
+ match_markets,
+ price_at_offset,
+)
+from ..fetcher import Fetcher
+from . import kalshi, prediction
+
+logger = logging.getLogger("world-intel-mcp.sources.prediction_cross")
+
+_MATCH_METHOD = (
+ "Deterministic: titles lowercased with a small synonym table (month names, "
+ "cut/raise verbs, above/below); quantities (non-year numbers) must be equal sets; "
+ "years must intersect when both titles state one; negation must agree; end dates "
+ "within max(3 days, 15% of the horizon); the Kalshi YES side must be named in the "
+ "Polymarket question or match exactly one Polymarket outcome. "
+ "match_confidence = title word overlap (Dice) x date factor (1.0 same day, 0.5 at "
+ "the tolerance edge). One-to-one, greedy by confidence."
+)
+
+MAX_PAIRS = 500
+MAX_OFFSETS = 10
+# A price window spans at most 8760 + 720 hours, so one market's hourly
+# candles stay under the candlestick endpoint's 10,000 cap.
+MAX_OFFSET_HOURS = 8760
+MAX_STALENESS_HOURS = 720
+MAX_VOLUME_FLOOR = 10**12 # keeps the floor's query string and formatting finite
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _is_number(value: Any) -> bool:
+ """An int or a finite float; booleans, strings, None, NaN and infinity are not."""
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return False
+ return not isinstance(value, float) or math.isfinite(value)
+
+
+def _number_arg(value: Any, name: str, low: float, high: float) -> Any:
+ """``value`` unchanged when it is a number in ``[low, high]``.
+
+ Raises ValueError naming the argument otherwise, before any request
+ is made.
+ """
+ if not _is_number(value):
+ raise ValueError(f"{name} must be a finite number (got {value!r})")
+ if not low <= value <= high:
+ raise ValueError(f"{name} must be from {low:g} to {high:g} (got {value!r})")
+ return value
+
+
+def _offsets_arg(value: Any) -> list[float]:
+ """Positive offsets in hours, sorted and de-duplicated (default 24, 168).
+
+ Non-positive values are ignored; a list with none left, more than
+ MAX_OFFSETS values, or a value that is not a finite number of hours
+ up to MAX_OFFSET_HOURS raises ValueError.
+ """
+ raw = value or [24, 168]
+ if not isinstance(raw, (list, tuple)):
+ raise ValueError(f"offsets_hours must be a list of hours (got {value!r})")
+ if len(raw) > MAX_OFFSETS:
+ raise ValueError(f"offsets_hours takes at most {MAX_OFFSETS} values (got {len(raw)})")
+ for o in raw:
+ if not _is_number(o) or o > MAX_OFFSET_HOURS:
+ raise ValueError(f"offsets_hours values must be numbers of hours up to {MAX_OFFSET_HOURS} (got {o!r})")
+ offsets = sorted({float(o) for o in raw if o > 0})
+ if not offsets:
+ raise ValueError("offsets_hours must contain at least one positive number of hours")
+ return offsets
+
+
+def _arg_error(message: str) -> dict:
+ return {"error": message, "degraded": True, "source": "kalshi+polymarket", "timestamp": _utc_now_iso()}
+
+
+async def fetch_prediction_compare(
+ fetcher: Fetcher,
+ category: str | None = None,
+ series: str | None = None,
+ kalshi_pages: int = 3,
+ series_limit: int = 10,
+ polymarket_limit: int = 300,
+ min_confidence: float = DEFAULT_MIN_CONFIDENCE,
+ limit: int = 25,
+) -> dict:
+ """The same events on Kalshi and Polymarket, side by side.
+
+ Returns matched pairs (largest absolute price gap first), the
+ highest-similarity rejected pairs with their reasons, and unmatched
+ counts per venue. Below ``min_confidence`` a pair is not a match.
+ Counts are clamped (kalshi_pages and series_limit 1..25,
+ polymarket_limit 1..2000, limit 1..500); a count that is not a whole
+ number, or a min_confidence outside 0..1, is an ``error`` answered
+ before any request.
+ """
+ try:
+ kalshi_pages = kalshi.count_arg(kalshi_pages, "kalshi_pages", kalshi.MAX_PAGES)
+ series_limit = kalshi.count_arg(series_limit, "series_limit", kalshi.MAX_SERIES)
+ polymarket_limit = kalshi.count_arg(polymarket_limit, "polymarket_limit", prediction.MAX_OPEN_MARKETS)
+ limit = kalshi.count_arg(limit, "limit", MAX_PAIRS)
+ min_confidence = float(_number_arg(min_confidence, "min_confidence", 0, 1))
+ except ValueError as exc:
+ return _arg_error(str(exc))
+ k_raw = await kalshi.fetch_kalshi_open_markets(
+ fetcher, category=category, series=series, pages=kalshi_pages, series_limit=series_limit
+ )
+ p_raw = await prediction.fetch_polymarket_open(fetcher, limit=polymarket_limit)
+ k_markets, p_markets = k_raw["markets"], p_raw["markets"]
+
+ gaps: list[str] = [f"kalshi: {g}" for g in k_raw["data_gaps"]]
+ if p_raw.get("error"):
+ gaps.append(f"polymarket: {p_raw['error']}")
+ if p_raw.get("stale"):
+ gaps.append("polymarket: served from expired cache after a failed live fetch")
+ gaps.append(
+ f"polymarket: top {p_raw['requested']} open markets by 24h volume requested; "
+ f"{p_raw['non_binary_skipped']} non-binary rows skipped"
+ )
+
+ out: dict[str, Any] = {
+ "source": "kalshi+polymarket",
+ "kalshi_scan": k_raw["scan"],
+ "kalshi_markets_compared": len(k_markets),
+ "polymarket_markets_compared": len(p_markets),
+ "min_confidence": min_confidence,
+ "method": _MATCH_METHOD,
+ "price_gap": "kalshi YES probability minus polymarket probability of the same side",
+ "units": {"kalshi": kalshi.UNITS, "polymarket": prediction.UNITS},
+ "timestamp": _utc_now_iso(),
+ }
+
+ down = []
+ if k_raw["nothing_read"]:
+ down.append("kalshi")
+ if p_raw.get("error") and not p_markets:
+ down.append("polymarket")
+ if down:
+ out.update({
+ "matched": [],
+ "matched_count": None,
+ "near_misses": [],
+ "unmatched_kalshi": None if "kalshi" in down else len(k_markets),
+ "unmatched_polymarket": None if "polymarket" in down else len(p_markets),
+ "error": f"comparison not possible: {', '.join(down)} unavailable",
+ "degraded": True,
+ "data_gaps": gaps,
+ })
+ return out
+
+ result = match_markets(k_markets, p_markets, min_confidence=min_confidence)
+ matched = result["matched"]
+ matched.sort(key=lambda r: (r["price_gap"] is None, -abs(r["price_gap"] or 0.0), -r["match_confidence"]))
+ out.update({
+ "matched": matched[:limit],
+ "matched_count": len(matched),
+ "near_misses": result["near_misses"],
+ "pairs_scored": result["pairs_scored"],
+ "unmatched_kalshi": result["unmatched_kalshi"],
+ "unmatched_polymarket": result["unmatched_polymarket"],
+ "data_gaps": gaps,
+ })
+ if k_raw["errors"] or p_raw.get("error") or p_raw.get("stale"):
+ out["degraded"] = True
+ return out
+
+
+def _score_venue(
+ markets: list[dict],
+ histories: dict[str, list[tuple[int, float]] | None],
+ offsets: list[float],
+ max_staleness_hours: float,
+) -> tuple[dict, list[dict]]:
+ scores: dict[str, Any] = {}
+ sample: list[dict] = []
+ per_market_prices: dict[str, dict[str, float | None]] = {m["id"]: {} for m in markets}
+ for off in offsets:
+ label = f"{off:g}h"
+ forecasts: list[tuple[float, int]] = []
+ events: set[str] = set()
+ excluded: dict[str, int] = {}
+ for m in markets:
+ hist = histories.get(m["id"])
+ if hist is None:
+ excluded["price history unavailable"] = excluded.get("price history unavailable", 0) + 1
+ per_market_prices[m["id"]][label] = None
+ continue
+ price, reason = price_at_offset(hist, m["reference_ts"], off, max_staleness_hours)
+ if price is not None and not 0.0 <= price <= 1.0:
+ # A malformed upstream price (NaN, or outside 0..1) is
+ # counted as an exclusion, never scored or raised.
+ price, key = None, "price outside 0..1"
+ elif price is None:
+ key = reason if reason.startswith("no price") else "last price older than the staleness limit"
+ per_market_prices[m["id"]][label] = price
+ if price is None:
+ excluded[key] = excluded.get(key, 0) + 1
+ continue
+ forecasts.append((price, m["outcome"]))
+ events.add(m.get("event") or m["id"])
+ brier = brier_score(forecasts)
+ scores[label] = {
+ "n": len(forecasts),
+ "distinct_events": len(events),
+ "brier": round(brier, 4) if brier is not None else None,
+ "yes_rate": round(sum(o for _, o in forecasts) / len(forecasts), 4) if forecasts else None,
+ "excluded": excluded,
+ }
+ for m in markets:
+ sample.append({
+ "id": m["id"],
+ "event": m.get("event"),
+ "question": m["question"],
+ "yes_side": m.get("yes_side") or None,
+ "outcome": m["outcome"],
+ "result": m["result"],
+ "volume": m["volume"],
+ "settled_at": m["settled_at"],
+ "price_before_reference": per_market_prices[m["id"]],
+ })
+ return scores, sample
+
+
+async def fetch_prediction_settled(
+ fetcher: Fetcher,
+ limit: int = 25,
+ offsets_hours: list[float] | None = None,
+ kalshi_min_volume: float = 1000.0,
+ polymarket_min_volume: float = 10000.0,
+ kalshi_series: str | None = None,
+ max_staleness_hours: float = 168.0,
+ kalshi_category: str | None = "Economics",
+ kalshi_series_limit: int = 10,
+) -> dict:
+ """Settled markets on both venues, scored against earlier prices.
+
+ For each venue: the ``limit`` most recently settled binary markets
+ passing the volume floor, the YES price at each offset before the
+ reference time (the last price inside ``max_staleness_hours`` up to
+ that point), and a Brier score per offset over the markets that had
+ one. A venue whose price history could not be read is not scored.
+ ``limit`` is clamped to 1..100 and ``kalshi_series_limit`` to 1..25;
+ more than 10 offsets, an offset above 8760 hours, a staleness limit
+ outside 0..720 hours, a volume floor outside 0..10**12 or a value
+ that is not a finite number is an ``error`` answered before any
+ request.
+ """
+ try:
+ offsets = _offsets_arg(offsets_hours)
+ limit = kalshi.count_arg(limit, "limit", kalshi.MAX_SETTLED)
+ kalshi_series_limit = kalshi.count_arg(kalshi_series_limit, "kalshi_series_limit", kalshi.MAX_SERIES)
+ kalshi_min_volume = _number_arg(kalshi_min_volume, "kalshi_min_volume", 0, MAX_VOLUME_FLOOR)
+ polymarket_min_volume = _number_arg(polymarket_min_volume, "polymarket_min_volume", 0, MAX_VOLUME_FLOOR)
+ max_staleness_hours = float(
+ _number_arg(max_staleness_hours, "max_staleness_hours", 0, MAX_STALENESS_HOURS)
+ )
+ except ValueError as exc:
+ return _arg_error(str(exc))
+ window_start = max(offsets) + max_staleness_hours
+ window_end = min(offsets)
+ venues: dict[str, Any] = {}
+
+ # Kalshi
+ k = await kalshi.fetch_kalshi_settled(
+ fetcher, limit=limit, min_volume=kalshi_min_volume, series=kalshi_series,
+ category=None if kalshi_series else kalshi_category, series_limit=kalshi_series_limit,
+ min_open_hours=window_end,
+ )
+ if kalshi_series:
+ k_scope = f"series {kalshi_series}"
+ elif kalshi_category:
+ k_scope = (
+ f"the {len(k['scope']['series_read'])} highest-lifetime-volume series in category "
+ f"{kalshi_category!r}: {k['scope']['series_read']}"
+ )
+ else:
+ k_scope = "the exchange-wide settled listing (intraday sports dominate it)"
+ k_entry: dict[str, Any] = {
+ "selection": (
+ f"most recently settled Kalshi markets (combos excluded) from {k_scope}, with result yes/no, "
+ f"lifetime volume >= {kalshi_min_volume:g} contracts and open >= {window_end:g}h "
+ f"before close; first {limit} kept from {k['listing_rows_read']} listing rows read "
+ f"({k['open_too_briefly_skipped']} skipped as open too briefly)"
+ ),
+ "reference_time": "close_time (trading end)",
+ "price_source": "batch /markets/candlesticks, hourly, price.close_dollars (last trade in the hour)",
+ "settled_markets": len(k["markets"]),
+ }
+ if k["error"] and not k["markets"]:
+ k_entry.update({"error": k["error"], "scored": False, "scores": None, "sample": []})
+ else:
+ hist, h_errors = await kalshi.fetch_kalshi_price_history(fetcher, k["markets"], window_start, window_end)
+ histories = {m["id"]: hist.get(m["id"]) for m in k["markets"]}
+ k_entry.update(
+ _venue_result(k["markets"], histories, offsets, max_staleness_hours, h_errors + k["errors"], None)
+ )
+ if k.get("data_gaps") and not k["markets"]:
+ k_entry["not_scored_reason"] = "; ".join(k["data_gaps"])
+ venues["kalshi"] = k_entry
+
+ # Polymarket
+ p = await prediction.fetch_polymarket_settled(
+ fetcher, limit=limit, min_volume=polymarket_min_volume, min_open_hours=window_end
+ )
+ p_entry: dict[str, Any] = {
+ "selection": (
+ f"most recently closed Polymarket binary markets with volume >= "
+ f"{polymarket_min_volume:g} USDC, UMA status resolved, final prices exactly 1/0, "
+ f"open >= {window_end:g}h before close; first {limit} kept from "
+ f"{p['listing_rows_read']} listing rows read "
+ f"({p.get('open_too_briefly_skipped', 0)} skipped as open too briefly); "
+ "first outcome is the YES side"
+ ),
+ "reference_time": "closedTime (market closed after resolution)",
+ "price_source": "CLOB /prices-history, hourly fidelity, first outcome token",
+ "settled_markets": len(p["markets"]),
+ }
+ if p["error"]:
+ p_entry.update({"error": p["error"], "scored": False, "scores": None, "sample": []})
+ else:
+ histories = {}
+ failed = 0
+ for m in p["markets"]:
+ pts = await prediction.fetch_polymarket_price_history(
+ fetcher,
+ m["token_id"],
+ m["reference_ts"] - int(window_start * 3600),
+ m["reference_ts"] - int(window_end * 3600),
+ )
+ if pts is None:
+ failed += 1
+ histories[m["id"]] = pts
+ h_errors = [f"price history unavailable for {failed} market(s)"] if failed else []
+ p_entry.update(_venue_result(p["markets"], histories, offsets, max_staleness_hours, h_errors, None))
+ venues["polymarket"] = p_entry
+
+ gaps = []
+ for name, entry in venues.items():
+ if entry.get("error"):
+ gaps.append(f"{name}: {entry['error']}")
+ for e in entry.get("history_errors") or []:
+ gaps.append(f"{name}: {e}")
+ if entry.get("scored") is False and not entry.get("error"):
+ gaps.append(f"{name}: not scored ({entry.get('not_scored_reason')})")
+ out = {
+ "source": "kalshi+polymarket",
+ "offsets_hours": offsets,
+ "max_staleness_hours": max_staleness_hours,
+ "venues": venues,
+ "comparability": (
+ "Each venue is scored on its own sample of different markets; the Brier "
+ "scores are not a head-to-head comparison of the same events. Markets of one "
+ "event are correlated: n counts markets, distinct_events counts the venue's "
+ "event ids behind them, and one real-world event can span several ids "
+ "(Polymarket lists a match's result, halftime and totals markets as separate "
+ "events). A strike ladder's far strikes trade near 0 or 1 and pull a Brier "
+ "score down."
+ ),
+ "brier": "mean of (price - outcome)^2 with outcome 1 for YES; 0 is perfect, always 0.5 scores 0.25",
+ "data_gaps": gaps,
+ "timestamp": _utc_now_iso(),
+ }
+ if gaps:
+ out["degraded"] = True
+ return out
+
+
+def _venue_result(
+ markets: list[dict],
+ histories: dict[str, list[tuple[int, float]] | None],
+ offsets: list[float],
+ max_staleness_hours: float,
+ history_errors: list[str],
+ listing_error: str | None,
+) -> dict:
+ entry: dict[str, Any] = {"history_errors": history_errors}
+ if listing_error:
+ entry["history_errors"] = history_errors + [listing_error]
+ if markets and all(histories.get(m["id"]) is None for m in markets):
+ entry.update({
+ "scored": False,
+ "not_scored_reason": "price history unavailable for every market in the sample",
+ "scores": None,
+ "sample": [],
+ })
+ return entry
+ scores, sample = _score_venue(markets, histories, offsets, max_staleness_hours)
+ entry.update({"scored": bool(markets), "scores": scores, "sample": sample})
+ if not markets:
+ entry["not_scored_reason"] = "no settled markets passed the selection"
+ return entry
diff --git a/src/world_intel_mcp/tests/test_cli_prediction_markets.py b/src/world_intel_mcp/tests/test_cli_prediction_markets.py
new file mode 100644
index 0000000..95dee44
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_cli_prediction_markets.py
@@ -0,0 +1,183 @@
+"""CLI tests for the Phase 29 prediction-market commands: ``kalshi``,
+``prediction-compare`` and ``prediction-settled``.
+
+Fetch functions are replaced with fakes returning the documented
+response shapes (the shapes themselves are pinned against respx-mocked
+upstreams in test_sources_kalshi.py and test_prediction_cross.py).
+
+Gaps / not covered: terminal widths below 200 columns.
+"""
+
+import json
+
+import pytest
+from click.testing import CliRunner
+
+from world_intel_mcp import cli
+
+
[email protected](autouse=True)
+def _cli_isolation(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "cli-cache.db"))
+ monkeypatch.setenv("COLUMNS", "200")
+ monkeypatch.setattr(cli, "_fetcher", None)
+
+
+def _invoke(*args: str):
+ return CliRunner().invoke(cli.main, list(args), catch_exceptions=False)
+
+
+def _fake(payload, calls: list | None = None):
+ async def _f(*args, **kwargs):
+ if calls is not None:
+ calls.append(kwargs)
+ return payload
+
+ return _f
+
+
+KALSHI_PAYLOAD = {
+ "markets": [
+ {"question": "Will the Federal Reserve Hike rates by 0bps at their October 2026 meeting?",
+ "yes_side": "Fed maintains rate", "probability": 0.865, "price_basis": "bid_ask_midpoint",
+ "volume_24h": 64959.15, "volume": 5635368.81},
+ {"question": "Lions vs [red]Loongs[/red]", "yes_side": "", "probability": None,
+ "price_basis": "no_price", "volume_24h": 0.0, "volume": 12.0},
+ ],
+ "count": 2,
+ "scan": {"mode": "series", "events_scanned": 1},
+ "units": {"price": "Kalshi quotes YES contracts in US dollars per $1 payout"},
+ "data_gaps": ["scanned 1 page(s) of open events; more exist and were not read"],
+}
+
+
+def test_kalshi_renders_probabilities_gaps_and_units(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list = []
+ monkeypatch.setattr(cli.kalshi_src, "fetch_kalshi_markets", _fake(KALSHI_PAYLOAD, calls))
+ result = _invoke("kalshi", "--series", "KXFEDDECISION", "-n", "5")
+ assert result.exit_code == 0
+ assert calls == [{"category": None, "series": "KXFEDDECISION", "limit": 5, "pages": 3}]
+ assert "86.5%" in result.output
+ assert "Fed maintains rate" in result.output
+ assert "64,959" in result.output
+ assert "[red]Loongs[/red]" in result.output # remote text rendered literally
+ assert "Data gap:" in result.output and "more exist" in result.output
+ assert "dollars per $1 payout" in result.output
+
+
+def test_kalshi_error_is_printed_not_an_empty_table(monkeypatch: pytest.MonkeyPatch) -> None:
+ payload = {"markets": [], "count": 0, "error": "Kalshi /events page 1 unavailable", "degraded": True}
+ monkeypatch.setattr(cli.kalshi_src, "fetch_kalshi_markets", _fake(payload))
+ result = _invoke("kalshi")
+ assert "Error:" in result.output and "page 1 unavailable" in result.output
+ assert "No traded Kalshi markets" not in result.output
+
+
+def test_kalshi_empty_scan_names_what_was_scanned(monkeypatch: pytest.MonkeyPatch) -> None:
+ payload = {"markets": [], "count": 0, "scan": {"events_scanned": 7}, "data_gaps": []}
+ monkeypatch.setattr(cli.kalshi_src, "fetch_kalshi_markets", _fake(payload))
+ result = _invoke("kalshi")
+ assert "No traded Kalshi markets in the scanned set (7 events)" in result.output
+
+
+def test_kalshi_json_output_is_the_raw_payload(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(cli.kalshi_src, "fetch_kalshi_markets", _fake(KALSHI_PAYLOAD))
+ result = _invoke("--json-output", "kalshi")
+ assert json.loads(result.output)["markets"][0]["probability"] == 0.865
+
+
+COMPARE_PAYLOAD = {
+ "matched": [{
+ "match_confidence": 0.724,
+ "kalshi": {"question": "Will the Federal Reserve Cut rates by 25bps at their October 2026 meeting?"},
+ "polymarket": {"question": "Will the Fed decrease interest rates by 25 bps after the October 2026 meeting?"},
+ "kalshi_yes_probability": 0.01, "polymarket_yes_probability": 0.0035, "price_gap": 0.0065,
+ }],
+ "matched_count": 1, "kalshi_markets_compared": 5, "polymarket_markets_compared": 5,
+ "unmatched_kalshi": 4, "unmatched_polymarket": 4, "min_confidence": 0.6, "data_gaps": [],
+}
+
+
+def test_prediction_compare_renders_pairs_and_counts(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list = []
+ monkeypatch.setattr(cli.prediction_cross, "fetch_prediction_compare", _fake(COMPARE_PAYLOAD, calls))
+ result = _invoke("prediction-compare", "-c", "Economics", "--min-confidence", "0.7")
+ assert result.exit_code == 0
+ assert calls[0]["category"] == "Economics" and calls[0]["min_confidence"] == 0.7
+ assert "Compared 5 Kalshi / 5 Polymarket markets: 1 matched" in result.output
+ assert "unmatched Kalshi 4, unmatched Polymarket 4" in result.output
+ assert "0.72" in result.output and "+0.7pp" in result.output
+ assert "1.0%" in result.output and "0.3%" in result.output
+
+
+def test_prediction_compare_no_pairs_says_threshold(monkeypatch: pytest.MonkeyPatch) -> None:
+ payload = dict(COMPARE_PAYLOAD, matched=[], matched_count=0)
+ monkeypatch.setattr(cli.prediction_cross, "fetch_prediction_compare", _fake(payload))
+ result = _invoke("prediction-compare")
+ assert "No pair reached match confidence 0.6" in result.output
+
+
+def test_prediction_compare_outage_prints_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ payload = {"error": "comparison not possible: kalshi unavailable", "degraded": True, "matched": []}
+ monkeypatch.setattr(cli.prediction_cross, "fetch_prediction_compare", _fake(payload))
+ result = _invoke("prediction-compare")
+ assert "Error:" in result.output and "kalshi unavailable" in result.output
+
+
+SETTLED_PAYLOAD = {
+ "venues": {
+ "kalshi": {"scores": {"24h": {"n": 2, "distinct_events": 1, "brier": 0.065, "yes_rate": 0.5,
+ "excluded": {"last price older than the staleness limit": 1}}}},
+ "polymarket": {"scored": False, "scores": None,
+ "not_scored_reason": "price history unavailable for every market in the sample"},
+ },
+ "comparability": "Each venue is scored on its own sample of different markets.",
+ "data_gaps": ["polymarket: price history unavailable for 2 market(s)"],
+}
+
+
+def test_prediction_settled_renders_scores_and_unscored_venue(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list = []
+ monkeypatch.setattr(cli.prediction_cross, "fetch_prediction_settled", _fake(SETTLED_PAYLOAD, calls))
+ result = _invoke("prediction-settled", "--offset", "24", "--offset", "72", "--kalshi-series", "KXCPIYOY")
+ assert result.exit_code == 0
+ assert calls[0]["offsets_hours"] == [24.0, 72.0]
+ assert calls[0]["kalshi_series"] == "KXCPIYOY"
+ assert "0.0650" in result.output and "50.0%" in result.output
+ assert "last price older than the staleness limit: 1" in result.output
+ assert "not scored" in result.output
+ assert "price history unavailable for every market" in result.output
+ assert "Data gap:" in result.output
+ assert "own sample of different markets" in result.output
+
+
+def test_prediction_settled_default_offsets_pass_none(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list = []
+ monkeypatch.setattr(cli.prediction_cross, "fetch_prediction_settled", _fake(SETTLED_PAYLOAD, calls))
+ _invoke("prediction-settled")
+ assert calls[0]["offsets_hours"] is None
+ assert calls[0]["kalshi_category"] == "Economics"
+
+
+def test_kalshi_shows_whole_questions(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Ladder rows differ only at the end of the question; slicing it to
+ the column width made the October and December rows read the same."""
+ october = KALSHI_PAYLOAD["markets"][0]
+ december = dict(october, question=october["question"].replace("October", "December"))
+ payload = dict(KALSHI_PAYLOAD, markets=[october, december], count=2)
+ monkeypatch.setattr(cli.kalshi_src, "fetch_kalshi_markets", _fake(payload))
+ out = _invoke("kalshi").output
+ assert out.count("October") == 1 and out.count("December") == 1
+
+
+def test_prediction_compare_shows_whole_questions(monkeypatch: pytest.MonkeyPatch) -> None:
+ october = COMPARE_PAYLOAD["matched"][0]
+ december = dict(
+ october,
+ kalshi={"question": october["kalshi"]["question"].replace("October", "December")},
+ polymarket={"question": october["polymarket"]["question"].replace("October", "December")},
+ )
+ payload = dict(COMPARE_PAYLOAD, matched=[october, december], matched_count=2)
+ monkeypatch.setattr(cli.prediction_cross, "fetch_prediction_compare", _fake(payload))
+ out = _invoke("prediction-compare").output
+ assert out.count("October") == 2 and out.count("December") == 2
diff --git a/src/world_intel_mcp/tests/test_prediction_cross.py b/src/world_intel_mcp/tests/test_prediction_cross.py
new file mode 100644
index 0000000..580611f
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_prediction_cross.py
@@ -0,0 +1,443 @@
+"""Tests for sources/prediction_cross.py and tools/prediction_markets.py:
+the cross-venue comparison and settled-market Brier scoring, end to end
+through both venues' fetchers (respx-mocked).
+
+Kalshi and Polymarket open-market rows are the live shapes and quotes
+captured 2026-10-17 (KXFEDDECISION-26OCT; Polymarket event "Fed Decision
+in October?"). Settled rows and price histories are live shapes with
+values chosen so the expected Brier arithmetic is written out by hand in
+each test. Polymarket CLOB token ids are shortened (they are opaque
+77-digit strings live).
+
+Gaps / not covered: real API drift; timing of the 1 s Polymarket
+throttle (sleep is patched out here).
+"""
+
+import asyncio as asyncio_mod
+from datetime import datetime, timezone
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources.prediction_cross import fetch_prediction_compare, fetch_prediction_settled
+from world_intel_mcp.tests.test_sources_kalshi import EVENTS, FED_MARKETS, SETTLED_ROWS, _event
+
+KALSHI_MARKETS = r".*api\.elections\.kalshi\.com/trade-api/v2/markets\?.*"
+KALSHI_CANDLES = r".*api\.elections\.kalshi\.com/trade-api/v2/markets/candlesticks.*"
+GAMMA = r".*gamma-api\.polymarket\.com/markets.*"
+CLOB = r".*clob\.polymarket\.com/prices-history.*"
+
+_FED_EVENT = {"id": "606422", "slug": "fed-decision-in-october-20260617190323537", "title": "Fed Decision in October?"}
+
+
+def _gamma(id_, question, prices, bid, ask):
+ return {
+ "id": id_, "question": question, "slug": f"m-{id_}", "endDate": "2026-10-29T03:59:00Z",
+ "outcomes": '["Yes", "No"]', "outcomePrices": prices, "bestBid": bid, "bestAsk": ask,
+ "volume24hr": 60000.0, "volumeNum": 7000000.0, "clobTokenIds": f'["{id_}y", "{id_}n"]',
+ "closed": False, "active": True, "umaResolutionStatus": None, "events": [_FED_EVENT],
+ }
+
+
+POLY_OPEN = [
+ _gamma("2589810", "Will the Fed decrease interest rates by 50+ bps after the October 2026 meeting?",
+ '["0.0015", "0.9985"]', 0.001, 0.002),
+ _gamma("2589811", "Will the Fed decrease interest rates by 25 bps after the October 2026 meeting?",
+ '["0.0035", "0.9965"]', 0.003, 0.004),
+ _gamma("2589812", "Will there be no change in Fed interest rates after the October 2026 meeting?",
+ '["0.865", "0.135"]', 0.86, 0.87),
+ _gamma("2589813", "Will the Fed increase interest rates by 25 bps after the October 2026 meeting?",
+ '["0.135", "0.865"]', 0.13, 0.14),
+ _gamma("2589814", "Will the Fed increase interest rates by 50+ bps after the October 2026 meeting?",
+ '["0.0035", "0.9965"]', 0.003, 0.004),
+]
+
+
[email protected](autouse=True)
+def _no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def _sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _sleep)
+
+
+def _kalshi_fed_events() -> None:
+ respx.get(url__regex=EVENTS).mock(
+ return_value=httpx.Response(200, json={"events": [_event(FED_MARKETS)], "cursor": ""})
+ )
+
+
+# ---------------------------------------------------------------------------
+# intel_prediction_compare
+# ---------------------------------------------------------------------------
+
+async def test_compare_matches_live_fed_pairs_and_rejects_near_misses(fetcher: Fetcher) -> None:
+ _kalshi_fed_events()
+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=POLY_OPEN))
+
+ out = await fetch_prediction_compare(fetcher, series="KXFEDDECISION")
+
+ pairs = [(m["kalshi"]["id"], m["polymarket"]["id"]) for m in out["matched"]]
+ # Largest absolute gap first: C25 0.01 (last trade) - 0.0035 (Polymarket
+ # midpoint of 0.003/0.004) = 0.0065; H25 0.135 - 0.135 = 0.
+ assert pairs == [("KXFEDDECISION-26OCT-C25", "2589811"), ("KXFEDDECISION-26OCT-H25", "2589813")]
+ assert [m["price_gap"] for m in out["matched"]] == [0.0065, 0.0]
+ assert all(m["match_confidence"] >= 0.6 and m["reasons"] for m in out["matched"])
+ assert out["matched_count"] == 2
+ assert out["unmatched_kalshi"] == 3 and out["unmatched_polymarket"] == 3
+ assert out["kalshi_markets_compared"] == 5 and out["polymarket_markets_compared"] == 5
+ # ">25bps" vs "50+ bps" and "25" vs "50+" are rejected with reasons.
+ reasons = [nm["reasons"][-1] for nm in out["near_misses"]]
+ assert "quantities differ: Kalshi ['>25'] vs Polymarket ['>=50']" in reasons
+ assert "quantities differ: Kalshi ['25'] vs Polymarket ['>=50']" in reasons
+ assert "degraded" not in out and "error" not in out
+
+
+async def test_compare_kalshi_outage_is_not_zero_matches(fetcher: Fetcher) -> None:
+ respx.get(url__regex=EVENTS).mock(return_value=httpx.Response(500))
+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=POLY_OPEN))
+
+ out = await fetch_prediction_compare(fetcher, series="KXFEDDECISION")
+ assert out["error"] == "comparison not possible: kalshi unavailable"
+ assert out["degraded"] is True
+ assert out["matched"] == [] and out["matched_count"] is None
+ assert out["unmatched_kalshi"] is None and out["unmatched_polymarket"] == 5
+
+
+async def test_compare_polymarket_outage_is_not_zero_matches(fetcher: Fetcher) -> None:
+ _kalshi_fed_events()
+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(502))
+
+ out = await fetch_prediction_compare(fetcher, series="KXFEDDECISION")
+ assert out["error"] == "comparison not possible: polymarket unavailable"
+ assert out["unmatched_polymarket"] is None and out["unmatched_kalshi"] == 5
+ assert any(g.startswith("polymarket: Polymarket Gamma API unavailable") for g in out["data_gaps"])
+
+
+# ---------------------------------------------------------------------------
+# intel_prediction_settled
+# ---------------------------------------------------------------------------
+
+def _ts(text: str) -> int:
+ return int(datetime.fromisoformat(text).replace(tzinfo=timezone.utc).timestamp())
+
+
+K_REF = _ts("2026-09-11T12:25:00") # SETTLED_ROWS close_time
+P1_REF = _ts("2026-10-17T16:16:26")
+P2_REF = _ts("2026-10-17T15:00:00")
+
+
+def _closed(id_, prices, status, closed, start, outcomes='["Yes", "No"]', event="e1"):
+ return {
+ "id": id_, "question": f"Settled market {id_}", "outcomes": outcomes, "outcomePrices": prices,
+ "umaResolutionStatus": status, "closedTime": closed, "startDate": start,
+ "endDate": "2026-10-24T00:00:00Z", "clobTokenIds": f'["{id_}a", "{id_}b"]',
+ "volumeNum": 16370.88, "closed": True, "events": [{"id": event}],
+ }
+
+
+POLY_CLOSED = [
+ _closed("p1", '["1", "0"]', "resolved", "2026-10-17 16:16:26+00", "2026-10-10T00:00:00Z"),
+ _closed("p2", '["0", "1"]', "resolved", "2026-10-17 15:00:00+00", "2026-10-01T00:00:00Z",
+ outcomes='["Up", "Down"]', event="e2"),
+ _closed("p3", '["1", "0"]', "proposed", "2026-10-17 14:00:00+00", "2026-10-01T00:00:00Z"),
+ _closed("p4", '["0.5", "0.5"]', "resolved", "2026-10-17 13:00:00+00", "2026-10-01T00:00:00Z"),
+ _closed("p5", '["1", "0"]', "resolved", "2026-10-17 16:00:00+00", "2026-10-17T11:00:00Z"),
+]
+
+
+def _mock_settled_venues(clob_status: int = 200, kalshi_status: int = 200) -> None:
+ respx.get(url__regex=KALSHI_MARKETS).mock(
+ return_value=httpx.Response(kalshi_status, json={"markets": SETTLED_ROWS, "cursor": ""})
+ )
+ candles = {
+ "M1": [(K_REF - 30 * 3600, "0.8000"), (K_REF - 20 * 3600, "0.9500")],
+ "M2": [(K_REF - 48 * 3600, "0.3000")],
+ "M6": [(K_REF - 400 * 3600, "0.5000")],
+ }
+
+ def _candles(request: httpx.Request) -> httpx.Response:
+ tickers = request.url.params["market_tickers"].split(",")
+ return httpx.Response(200, json={"markets": [
+ {"market_ticker": t, "candlesticks": [
+ {"end_period_ts": ts, "price": {"close_dollars": p}} for ts, p in candles.get(t, [])
+ ]} for t in tickers
+ ]})
+
+ respx.get(url__regex=KALSHI_CANDLES).mock(side_effect=_candles)
+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=POLY_CLOSED))
+ history = {
+ "p1a": [{"t": P1_REF - 26 * 3600, "p": 0.7}, {"t": P1_REF - 2 * 3600, "p": 0.99}],
+ "p2a": [{"t": P2_REF - 25 * 3600, "p": 0.4}],
+ }
+
+ def _clob(request: httpx.Request) -> httpx.Response:
+ if clob_status != 200:
+ return httpx.Response(clob_status)
+ return httpx.Response(200, json={"history": history.get(request.url.params["market"], [])})
+
+ respx.get(url__regex=CLOB).mock(side_effect=_clob)
+
+
+async def test_settled_brier_per_venue_on_known_sample(fetcher: Fetcher) -> None:
+ _mock_settled_venues()
+ out = await fetch_prediction_settled(fetcher, offsets_hours=[24], kalshi_series="KXCPIYOY")
+
+ k = out["venues"]["kalshi"]
+ # Kalshi at 24h: M2 0.30 vs NO -> 0.09; M1 0.80 vs YES -> 0.04;
+ # M6's last trade is 376h before the offset point (limit 168h): excluded.
+ # (0.09 + 0.04) / 2 = 0.065.
+ assert k["scores"]["24h"] == {
+ "n": 2, "distinct_events": 1, "brier": 0.065, "yes_rate": 0.5,
+ "excluded": {"last price older than the staleness limit": 1},
+ }
+ assert k["scored"] is True and k["settled_markets"] == 3
+ assert "series KXCPIYOY" in k["selection"] and "(1 skipped as open too briefly)" in k["selection"]
+ assert [s["price_before_reference"]["24h"] for s in k["sample"]] == [0.3, 0.8, None]
+
+ p = out["venues"]["polymarket"]
+ # Polymarket at 24h: p1 0.7 vs YES -> 0.09; p2 0.4 vs first outcome
+ # ("Up", lost) -> 0.16. (0.09 + 0.16) / 2 = 0.125. p3 unresolved, p4
+ # not 1/0 and p5 open 5h are not in the sample.
+ assert p["scores"]["24h"] == {
+ "n": 2, "distinct_events": 2, "brier": 0.125, "yes_rate": 0.5, "excluded": {},
+ }
+ assert [s["id"] for s in p["sample"]] == ["p1", "p2"]
+ assert p["sample"][1]["result"] == "Down"
+ assert "(1 skipped as open too briefly)" in p["selection"]
+ assert out["data_gaps"] == [] and "degraded" not in out
+ assert "not a head-to-head comparison" in out["comparability"]
+
+
+async def test_settled_venue_without_price_history_is_not_scored(fetcher: Fetcher) -> None:
+ _mock_settled_venues(clob_status=503)
+ out = await fetch_prediction_settled(fetcher, offsets_hours=[24], kalshi_series="KXCPIYOY")
+
+ p = out["venues"]["polymarket"]
+ assert p["scored"] is False and p["scores"] is None
+ assert p["not_scored_reason"] == "price history unavailable for every market in the sample"
+ assert "polymarket: price history unavailable for 2 market(s)" in out["data_gaps"]
+ assert out["degraded"] is True
+ # The other venue is unaffected.
+ assert out["venues"]["kalshi"]["scores"]["24h"]["brier"] == 0.065
+
+
+async def test_settled_kalshi_listing_outage_reported_per_venue(fetcher: Fetcher) -> None:
+ _mock_settled_venues(kalshi_status=500)
+ out = await fetch_prediction_settled(fetcher, offsets_hours=[24], kalshi_series="KXCPIYOY")
+
+ k = out["venues"]["kalshi"]
+ assert k["error"] == "Kalshi settled markets unavailable for KXCPIYOY"
+ assert k["scored"] is False and k["scores"] is None
+ assert "kalshi: Kalshi settled markets unavailable for KXCPIYOY" in out["data_gaps"]
+ assert out["venues"]["polymarket"]["scores"]["24h"]["brier"] == 0.125
+
+
+async def test_settled_rejects_non_positive_offsets(fetcher: Fetcher) -> None:
+ out = await fetch_prediction_settled(fetcher, offsets_hours=[0, -5])
+ assert out["degraded"] is True
+ assert "at least one positive" in out["error"]
+
+
+# ---------------------------------------------------------------------------
+# Tool handlers (registered names reach the real source functions)
+# ---------------------------------------------------------------------------
+
+def _tools_registry():
+ """Import world_intel_mcp.tools under the suite's temp cache path.
+
+ Importing the tools package imports runtime, which opens a live
+ ``Cache()``/``AOIStore()``; pointing WORLD_INTEL_CACHE_DB at
+ test_server_registry's temp path (shared, so the override holds no
+ matter which test file triggers the first import) keeps that off the
+ developer's real cache database. A module-level import here would
+ run at collection time and break test_server_registry's premise."""
+ import importlib
+ import os
+
+ from .test_server_registry import _TMP_CACHE
+
+ prior = os.environ.get("WORLD_INTEL_CACHE_DB")
+ os.environ["WORLD_INTEL_CACHE_DB"] = str(_TMP_CACHE)
+ try:
+ return importlib.import_module("world_intel_mcp.tools")
+ finally:
+ if prior is None:
+ os.environ.pop("WORLD_INTEL_CACHE_DB", None)
+ else:
+ os.environ["WORLD_INTEL_CACHE_DB"] = prior
+
+
+async def test_tool_handlers_dispatch_with_arguments(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pm_tools = _tools_registry().prediction_markets
+ monkeypatch.setattr(pm_tools.runtime, "fetcher", fetcher)
+ _kalshi_fed_events()
+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=POLY_OPEN))
+
+ markets = await pm_tools.HANDLERS["intel_kalshi_markets"]({"series": "KXFEDDECISION", "limit": 2})
+ assert [m["id"] for m in markets["markets"]] == ["KXFEDDECISION-26OCT-H0", "KXFEDDECISION-26OCT-H25"]
+
+ compare = await pm_tools.HANDLERS["intel_prediction_compare"](
+ {"series": "KXFEDDECISION", "min_confidence": 0.99}
+ )
+ assert compare["matched"] == [] and compare["min_confidence"] == 0.99
+ assert compare["unmatched_kalshi"] == 5
+
+ settled = await pm_tools.HANDLERS["intel_prediction_settled"]({"offsets_hours": []})
+ # An empty list falls back to the default offsets, not to "no offsets".
+ assert settled.get("offsets_hours") == [24.0, 168.0] or "error" not in settled
+ assert settled["offsets_hours"] == [24.0, 168.0]
+ # No route mocked for the Kalshi series list or Gamma closed markets in
+ # this test: both venues report the failure, neither reads as zero.
+ assert settled["degraded"] is True
+ assert settled["venues"]["kalshi"]["scored"] is False
+ assert {t.name for t in pm_tools.TOOLS} == set(pm_tools.HANDLERS)
+
+
+async def test_settled_unknown_kalshi_category_says_why_not_scored(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ respx.get(url__regex=r".*api\.elections\.kalshi\.com/trade-api/v2/series.*").mock(
+ return_value=httpx.Response(200, json={"series": []})
+ )
+
+ async def _no_polymarket(*args, **kwargs) -> dict:
+ return {"markets": [], "listing_rows_read": 0, "open_too_briefly_skipped": 0, "error": None}
+
+ monkeypatch.setattr("world_intel_mcp.sources.prediction.fetch_polymarket_settled", _no_polymarket)
+ out = await fetch_prediction_settled(fetcher, kalshi_category="Climate")
+ kalshi = out["venues"]["kalshi"]
+ assert kalshi["scored"] is False
+ assert kalshi["not_scored_reason"].startswith("Kalshi lists no series in category 'Climate'")
+ assert any(g.startswith("kalshi: not scored (Kalshi lists no series") for g in out["data_gaps"])
+
+
+async def test_settled_malformed_upstream_price_is_excluded_not_raised(fetcher: Fetcher) -> None:
+ """A NaN or out-of-range price from either venue is counted as an
+ exclusion. Unguarded, it raised out of brier_score and lost both
+ venues' results."""
+ respx.get(url__regex=KALSHI_MARKETS).mock(
+ return_value=httpx.Response(200, json={"markets": SETTLED_ROWS, "cursor": ""})
+ )
+ candles = {"M1": [(K_REF - 30 * 3600, "NaN")], "M2": [(K_REF - 48 * 3600, "0.3000")]}
+ respx.get(url__regex=KALSHI_CANDLES).mock(side_effect=lambda request: httpx.Response(200, json={"markets": [
+ {"market_ticker": t, "candlesticks": [
+ {"end_period_ts": ts, "price": {"close_dollars": p}} for ts, p in candles.get(t, [])
+ ]} for t in request.url.params["market_tickers"].split(",")
+ ]}))
+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=POLY_CLOSED))
+ history = {"p1a": [{"t": P1_REF - 26 * 3600, "p": 0.7}], "p2a": [{"t": P2_REF - 25 * 3600, "p": 1.5}]}
+ respx.get(url__regex=CLOB).mock(
+ side_effect=lambda request: httpx.Response(200, json={"history": history.get(request.url.params["market"], [])})
+ )
+ out = await fetch_prediction_settled(fetcher, offsets_hours=[24], kalshi_series="KXCPIYOY")
+
+ k = out["venues"]["kalshi"]
+ # M2 0.30 vs NO -> 0.09; M1's "NaN" excluded; M6 has no candle.
+ assert k["scores"]["24h"] == {
+ "n": 1, "distinct_events": 1, "brier": 0.09, "yes_rate": 0.0,
+ "excluded": {"price outside 0..1": 1, "no price at or before the offset": 1},
+ }
+ assert [s["price_before_reference"]["24h"] for s in k["sample"]] == [0.3, None, None]
+ p = out["venues"]["polymarket"]
+ # p1 0.7 vs YES -> 0.09; p2's 1.5 excluded.
+ assert p["scores"]["24h"] == {
+ "n": 1, "distinct_events": 1, "brier": 0.09, "yes_rate": 1.0, "excluded": {"price outside 0..1": 1},
+ }
+ assert [s["price_before_reference"]["24h"] for s in p["sample"]] == [0.7, None]
+
+
+# ---------------------------------------------------------------------------
+# Argument bounds
+# ---------------------------------------------------------------------------
+
+async def test_bad_arguments_are_refused_before_any_request(fetcher: Fetcher) -> None:
+ routes = [
+ respx.get(url__regex=p).mock(return_value=httpx.Response(200, json={}))
+ for p in (r".*api\.elections\.kalshi\.com/.*", GAMMA, CLOB)
+ ]
+ compare_cases = {
+ "min_confidence must be from 0 to 1 (got 1.5)": {"min_confidence": 1.5},
+ "min_confidence must be a finite number (got nan)": {"min_confidence": float("nan")},
+ "min_confidence must be a finite number (got '0.6')": {"min_confidence": "0.6"},
+ "polymarket_limit must be a whole number from 1 to 2000 (got '300')": {"polymarket_limit": "300"},
+ "kalshi_pages must be a whole number from 1 to 25 (got 2.5)": {"kalshi_pages": 2.5},
+ "series_limit must be a whole number from 1 to 25 (got 'x')": {"series_limit": "x"},
+ "limit must be a whole number from 1 to 500 (got None)": {"limit": None},
+ }
+ for message, kwargs in compare_cases.items():
+ out = await fetch_prediction_compare(fetcher, category="Economics", **kwargs)
+ assert out["error"] == message and out["degraded"] is True
+ assert "matched" not in out
+ settled_cases = {
+ "offsets_hours values must be numbers of hours up to 8760 (got inf)": {"offsets_hours": [24, float("inf")]},
+ "offsets_hours values must be numbers of hours up to 8760 (got 8761)": {"offsets_hours": [8761]},
+ "offsets_hours values must be numbers of hours up to 8760 (got 'x')": {"offsets_hours": [24, "x"]},
+ "offsets_hours takes at most 10 values (got 11)": {"offsets_hours": list(range(1, 12))},
+ "offsets_hours must be a list of hours (got 24)": {"offsets_hours": 24},
+ "max_staleness_hours must be from 0 to 720 (got 721)": {"max_staleness_hours": 721},
+ "max_staleness_hours must be a finite number (got nan)": {"max_staleness_hours": float("nan")},
+ "kalshi_min_volume must be from 0 to 1e+12 (got -1)": {"kalshi_min_volume": -1},
+ "polymarket_min_volume must be a finite number (got inf)": {"polymarket_min_volume": float("inf")},
+ "limit must be a whole number from 1 to 100 (got '25')": {"limit": "25"},
+ "kalshi_series_limit must be a whole number from 1 to 25 (got None)": {"kalshi_series_limit": None},
+ }
+ for message, kwargs in settled_cases.items():
+ out = await fetch_prediction_settled(fetcher, **kwargs)
+ assert out["error"] == message and out["degraded"] is True
+ assert "venues" not in out
+ assert sum(r.call_count for r in routes) == 0
+
+
[email protected] # no route: a handler that ran anyway could not reach the network
+async def test_mcp_call_above_a_stated_maximum_is_refused_by_the_schema() -> None:
+ """The MCP SDK checks arguments against each tool's inputSchema
+ before any handler runs (measured on mcp 1.30.0), so the stated
+ maxima also hold on the MCP path itself."""
+ import importlib
+
+ from mcp import types
+
+ _tools_registry() # runtime first, under the suite's temp cache path
+ srv = importlib.import_module("world_intel_mcp.server")
+ handler = srv.server.request_handlers[types.CallToolRequest]
+ cases = {
+ "intel_kalshi_markets": (
+ {"category": "Economics", "series_limit": 1000000}, "1000000 is greater than the maximum of 25"
+ ),
+ "intel_prediction_compare": ({"min_confidence": 1.5}, "1.5 is greater than the maximum of 1"),
+ "intel_prediction_settled": ({"offsets_hours": [24, 9000]}, "9000 is greater than the maximum of 8760"),
+ }
+ for name, (arguments, message) in cases.items():
+ request = types.CallToolRequest(
+ method="tools/call", params=types.CallToolRequestParams(name=name, arguments=arguments)
+ )
+ result = (await handler(request)).root
+ assert result.isError is True
+ assert result.content[0].text == f"Input validation error: {message}"
diff --git a/src/world_intel_mcp/tests/test_prediction_matching.py b/src/world_intel_mcp/tests/test_prediction_matching.py
new file mode 100644
index 0000000..e02dd3b
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_prediction_matching.py
@@ -0,0 +1,237 @@
+"""Tests for analysis/prediction_matching.py: cross-venue matching and
+forecast scoring.
+
+Titles, sides and dates are the live shapes captured 2026-10-17 from
+Kalshi ``/events?series_ticker=KXFEDDECISION`` and Polymarket Gamma
+``/events?slug=fed-decision-in-october-...``; prices are the live
+quotes from the same capture. A wrong match is worse than no match, so
+most cases here are near misses that must NOT match.
+
+Gaps / not covered: synonym coverage beyond the module's table; sports
+team aliases (documented as unmatched by design).
+"""
+
+from datetime import datetime, timezone
+
+import pytest
+
+from world_intel_mcp.analysis.prediction_matching import (
+ brier_score,
+ match_markets,
+ price_at_offset,
+ score_pair,
+ text_features,
+ tokenize,
+)
+
+NOW = datetime(2026, 10, 17, 16, 0, tzinfo=timezone.utc)
+
+
+def _k(question, yes_side, end="2026-10-28T18:05:00Z", prob=0.135, context="Fed decision in Oct 2026?", id_="K"):
+ return {
+ "venue": "kalshi", "id": id_, "question": question, "context": context,
+ "yes_side": yes_side, "outcomes": ["Yes", "No"], "end_time": end, "probability": prob,
+ }
+
+
+def _p(question, outcomes=("Yes", "No"), end="2026-10-29T03:59:00Z", prob=0.135, id_="P"):
+ return {
+ "venue": "polymarket", "id": id_, "question": question, "context": "Fed Decision in October?",
+ "yes_side": "", "outcomes": list(outcomes), "end_time": end, "probability": prob,
+ }
+
+
+K_HIKE_25_OCT = _k("Will the Federal Reserve Hike rates by 25bps at their October 2026 meeting?", "Hike 25bps", id_="KXFEDDECISION-26OCT-H25")
+K_CUT_25_OCT = _k("Will the Federal Reserve Cut rates by 25bps at their October 2026 meeting?", "Cut 25bps", prob=0.005, id_="KXFEDDECISION-26OCT-C25")
+K_CUT_GT25_OCT = _k("Will the Federal Reserve Cut rates by >25bps at their October 2026 meeting?", "Cut >25bps", prob=0.005, id_="KXFEDDECISION-26OCT-C26")
+P_HIKE_25_OCT = _p("Will the Fed increase interest rates by 25 bps after the October 2026 meeting?", id_="2589813")
+P_CUT_25_OCT = _p("Will the Fed decrease interest rates by 25 bps after the October 2026 meeting?", prob=0.0035, id_="2589811")
+P_CUT_50_OCT = _p("Will the Fed decrease interest rates by 50+ bps after the October 2026 meeting?", prob=0.0015, id_="2589810")
+P_NO_CHANGE = _p("Will there be no change in Fed interest rates after the October 2026 meeting?", prob=0.865, id_="2589812")
+
+
+# ---------------------------------------------------------------------------
+# Tokenization
+# ---------------------------------------------------------------------------
+
+def test_tokenize_folds_units_numbers_and_synonyms() -> None:
+ assert tokenize("Cut 25bps") == ["cut", "25", "bps"]
+ assert tokenize("Fed’s $100k") == ["fed", "100000"]
+ assert tokenize("Oct decrease") == ["october", "cut"]
+
+
+def test_comparators_stay_attached_to_quantities() -> None:
+ assert text_features("Cut >25bps")["quantities"] == {">25"}
+ assert text_features("by 50+ bps")["quantities"] == {">=50"}
+ assert text_features("more than 3.5 goals")["quantities"] == {">3.5"}
+ assert text_features("at least 3 seats")["quantities"] == {">=3"}
+ assert text_features("under 2.5")["quantities"] == {"<2.5"}
+ assert text_features("3 or more")["quantities"] == {">=3"}
+ assert text_features("exactly 25 bps")["quantities"] == {"25"}
+
+
+def test_day_of_month_and_year_are_not_quantities() -> None:
+ f = text_features("above 2.75% following the Fed's Oct 28, 2026 meeting?")
+ assert f["quantities"] == {">2.75"}
+ assert f["days"] == {"28"}
+ assert f["years"] == {"2026"}
+
+
+# ---------------------------------------------------------------------------
+# True matches (live pairs)
+# ---------------------------------------------------------------------------
+
+def test_live_fed_hike_pair_matches_with_reasons() -> None:
+ r = score_pair(K_HIKE_25_OCT, P_HIKE_25_OCT, now=NOW)
+ assert r["rejected"] is False
+ assert r["side"] == "aligned"
+ # dice 0.75 (9 shared words of 13 / 11) x date factor for 0.4 days of
+ # a 3-day tolerance (1 - 0.5 * 0.4 / 3 = 0.9338) = 0.700.
+ assert r["confidence"] == pytest.approx(0.700, abs=0.002)
+ assert any("quantities agree ['25']" in x for x in r["reasons"])
+ assert any("end dates 0.4 days apart" in x for x in r["reasons"])
+
+
+def test_live_fed_cut_pair_matches() -> None:
+ r = score_pair(K_CUT_25_OCT, P_CUT_25_OCT, now=NOW)
+ assert r["rejected"] is False and r["confidence"] >= 0.6
+
+
+# ---------------------------------------------------------------------------
+# Near misses that must NOT match
+# ---------------------------------------------------------------------------
+
+def test_near_miss_25_vs_50_plus_bps_rejected() -> None:
+ r = score_pair(K_CUT_25_OCT, P_CUT_50_OCT, now=NOW)
+ assert r["rejected"] is True and r["confidence"] == 0.0
+ assert r["reasons"][-1] == "quantities differ: Kalshi ['25'] vs Polymarket ['>=50']"
+
+
+def test_near_miss_more_than_25_vs_exactly_25_rejected() -> None:
+ """The first live run (before comparators) matched these; it was wrong."""
+ r = score_pair(K_CUT_GT25_OCT, P_CUT_25_OCT, now=NOW)
+ assert r["rejected"] is True
+ assert "quantities differ" in r["reasons"][-1]
+
+
+def test_near_miss_other_year_rejected() -> None:
+ k2027 = _k("Will the Federal Reserve Cut rates by 25bps at their October 2027 meeting?", "Cut 25bps",
+ end="2027-10-27T18:05:00Z", context="Fed decision in Oct 2027?")
+ r = score_pair(k2027, P_CUT_25_OCT, now=NOW)
+ assert r["rejected"] is True
+ assert r["reasons"][-1] == "years differ: Kalshi ['2027'] vs Polymarket ['2026']"
+
+
+def test_near_miss_negation_rejected() -> None:
+ """Same event (Fed holds), different framing: rejected, not guessed."""
+ k_hold = _k("Will the Federal Reserve Hike rates by 0bps at their October 2026 meeting?", "Fed maintains rate", prob=0.865)
+ r = score_pair(k_hold, P_NO_CHANGE, now=NOW)
+ assert r["rejected"] is True
+
+
+def test_near_miss_end_dates_too_far_apart_rejected() -> None:
+ p_dec = _p("Will the Fed increase interest rates by 25 bps after the October 2026 meeting?", end="2026-12-10T00:00:00Z")
+ r = score_pair(K_HIKE_25_OCT, p_dec, now=NOW)
+ assert r["rejected"] is True
+ assert r["reasons"][-1].startswith("end dates 42.")
+
+
+def test_near_miss_yes_side_not_named_rejected() -> None:
+ k = _k("Who will win the 2028 Democratic presidential nomination?", "Gavin Newsom",
+ end="2028-08-20T00:00:00Z", context="Democratic nominee 2028")
+ p = _p("Will Josh Shapiro win the 2028 Democratic presidential nomination?", end="2028-08-25T00:00:00Z")
+ r = score_pair(k, p, now=NOW)
+ assert r["rejected"] is True
+ assert "not named in Polymarket question" in r["reasons"][-1]
+
+
+def test_named_outcomes_second_side_inverts_price() -> None:
+ k = _k("Will Zhejiang Lions win the Zhejiang Lions vs Shanxi Loongs game?", "Shanxi Loongs",
+ end="2026-10-17T13:00:00Z", prob=0.40, context="Zhejiang Lions vs Shanxi Loongs")
+ p = _p("Zhejiang Lions vs. Shanxi Loongs", outcomes=("Zhejiang Lions", "Shanxi Loongs"),
+ end="2026-10-17T14:00:00Z", prob=0.62)
+ out = match_markets([k], [p], min_confidence=0.5, now=NOW)
+ assert len(out["matched"]) == 1
+ pair = out["matched"][0]
+ assert pair["side"] == "inverted"
+ assert pair["polymarket_yes_probability"] == pytest.approx(0.38)
+ assert pair["price_gap"] == pytest.approx(0.02)
+
+
+def test_yes_side_matching_both_outcomes_rejected() -> None:
+ k = _k("Lions vs Loongs", "Lions", end="2026-10-17T13:00:00Z", context="")
+ p = _p("Lions vs Loongs", outcomes=("Lions", "Lions B"), end="2026-10-17T13:00:00Z")
+ r = score_pair(k, p, now=NOW)
+ assert r["rejected"] is True
+ assert "matches both Polymarket outcomes" in r["reasons"][-1]
+
+
+def test_missing_end_date_rejected() -> None:
+ p = dict(P_HIKE_25_OCT, end_time=None)
+ assert score_pair(K_HIKE_25_OCT, p, now=NOW)["rejected"] is True
+
+
+# ---------------------------------------------------------------------------
+# match_markets
+# ---------------------------------------------------------------------------
+
+def test_match_markets_one_to_one_with_counts_and_near_misses() -> None:
+ kalshi = [K_HIKE_25_OCT, K_CUT_25_OCT, K_CUT_GT25_OCT]
+ poly = [P_HIKE_25_OCT, P_CUT_25_OCT, P_CUT_50_OCT, P_NO_CHANGE]
+ out = match_markets(kalshi, poly, now=NOW)
+ pairs = {(m["kalshi"]["id"], m["polymarket"]["id"]) for m in out["matched"]}
+ assert pairs == {
+ ("KXFEDDECISION-26OCT-H25", "2589813"),
+ ("KXFEDDECISION-26OCT-C25", "2589811"),
+ }
+ assert out["unmatched_kalshi"] == 1
+ assert out["unmatched_polymarket"] == 2
+ gaps = {m["kalshi"]["id"]: m["price_gap"] for m in out["matched"]}
+ assert gaps["KXFEDDECISION-26OCT-H25"] == pytest.approx(0.0)
+ assert gaps["KXFEDDECISION-26OCT-C25"] == pytest.approx(0.0015)
+ assert all(nm["reasons"] for nm in out["near_misses"])
+ assert any("quantities differ" in nm["reasons"][-1] for nm in out["near_misses"])
+
+
+def test_below_threshold_is_not_a_match() -> None:
+ out = match_markets([K_HIKE_25_OCT], [P_HIKE_25_OCT], min_confidence=0.95, now=NOW)
+ assert out["matched"] == []
+ assert out["unmatched_kalshi"] == 1
+ assert "below threshold 0.95" in out["near_misses"][0]["reasons"][-1]
+
+
+def test_missing_price_leaves_gap_none() -> None:
+ k = dict(K_HIKE_25_OCT, probability=None)
+ out = match_markets([k], [P_HIKE_25_OCT], now=NOW)
+ assert out["matched"][0]["price_gap"] is None
+
+
+# ---------------------------------------------------------------------------
+# Forecast scoring
+# ---------------------------------------------------------------------------
+
+def test_brier_known_sample() -> None:
+ # (0.9-1)^2 + (0.2-0)^2 + (0.6-0)^2 = 0.01 + 0.04 + 0.36 = 0.41; / 3
+ assert brier_score([(0.9, 1), (0.2, 0), (0.6, 0)]) == pytest.approx(0.41 / 3)
+ assert brier_score([(0.5, 1), (0.5, 0)]) == pytest.approx(0.25)
+ assert brier_score([(1.0, 1), (0.0, 0)]) == 0.0
+
+
+def test_brier_empty_is_none_not_zero() -> None:
+ assert brier_score([]) is None
+
+
+def test_brier_rejects_bad_inputs() -> None:
+ with pytest.raises(ValueError):
+ brier_score([(0.5, 2)])
+ with pytest.raises(ValueError):
+ brier_score([(1.5, 1)])
+
+
+def test_price_at_offset_picks_last_point_before_target() -> None:
+ ref = 1_000_000
+ hist = [(ref - 30 * 3600, 0.40), (ref - 25 * 3600, 0.55), (ref - 23 * 3600, 0.90), (ref - 1, 0.99)]
+ assert price_at_offset(hist, ref, 24, 168) == (0.55, "ok")
+ assert price_at_offset(hist, ref, 48, 168) == (None, "no price at or before the offset")
+ price, reason = price_at_offset(hist, ref, 24, 0.5)
+ assert price is None and reason.startswith("last price 1.0h before the offset")
diff --git a/src/world_intel_mcp/tests/test_sources_kalshi.py b/src/world_intel_mcp/tests/test_sources_kalshi.py
new file mode 100644
index 0000000..6f6218b
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_kalshi.py
@@ -0,0 +1,508 @@
+"""Tests for sources/kalshi.py, respx-mocked.
+
+Fixtures are the live response shapes captured 2026-10-17 from
+``api.elections.kalshi.com/trade-api/v2`` (``/events?series_ticker=
+KXFEDDECISION&with_nested_markets=true``, ``/series?category=Economics
+&include_volume=true``, ``/markets?status=settled``, ``/markets/
+candlesticks``), trimmed to the fields the module reads. Market values
+for the KXFEDDECISION-26OCT event are the live quotes from that capture;
+the KXFEDDECISION series volume is scaled down tenfold (a 9-digit run
+trips the repo's privacy hook) without changing the series order.
+
+Gaps / not covered: live API drift; the 10,000-candle cap is exercised
+with a lowered budget, not against the real limit.
+"""
+
+import asyncio as asyncio_mod
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources import kalshi
+from world_intel_mcp.sources.kalshi import (
+ fetch_kalshi_markets,
+ fetch_kalshi_price_history,
+ fetch_kalshi_settled,
+ implied_probability,
+ normalize_market,
+)
+
+EVENTS = r".*api\.elections\.kalshi\.com/trade-api/v2/events.*"
+SERIES = r".*api\.elections\.kalshi\.com/trade-api/v2/series.*"
+MARKETS = r".*api\.elections\.kalshi\.com/trade-api/v2/markets\?.*"
+CANDLES = r".*api\.elections\.kalshi\.com/trade-api/v2/markets/candlesticks.*"
+
+
+def _m(ticker, title, yes_sub, bid, ask, last, vol, vol24):
+ return {
+ "ticker": ticker, "event_ticker": "KXFEDDECISION-26OCT", "title": title,
+ "yes_sub_title": yes_sub, "status": "active", "yes_bid_dollars": bid,
+ "yes_ask_dollars": ask, "last_price_dollars": last, "volume_fp": vol,
+ "volume_24h_fp": vol24, "open_interest_fp": "1.00", "close_time": "2026-10-28T17:59:00Z",
+ "expected_expiration_time": "2026-10-28T18:05:00Z", "open_time": "2025-09-29T14:00:00Z",
+ "result": "", "market_type": "binary",
+ }
+
+
+FED_MARKETS = [
+ _m("KXFEDDECISION-26OCT-C26", "Will the Federal Reserve Cut rates by >25bps at their October 2026 meeting?",
+ "Cut >25bps", "0.0000", "0.0100", "0.0100", "236878.39", "0.00"),
+ _m("KXFEDDECISION-26OCT-C25", "Will the Federal Reserve Cut rates by 25bps at their October 2026 meeting?",
+ "Cut 25bps", "0.0000", "0.0100", "0.0100", "1406426.34", "32484.06"),
+ _m("KXFEDDECISION-26OCT-H0", "Will the Federal Reserve Hike rates by 0bps at their October 2026 meeting?",
+ "Fed maintains rate", "0.8600", "0.8700", "0.8600", "5635368.81", "64959.15"),
+ _m("KXFEDDECISION-26OCT-H25", "Will the Federal Reserve Hike rates by 25bps at their October 2026 meeting?",
+ "Hike 25bps", "0.1300", "0.1400", "0.1400", "4066283.05", "61814.96"),
+ _m("KXFEDDECISION-26OCT-H26", "Will the Federal Reserve Hike rates by >25bps at their October 2026 meeting?",
+ "Hike >25bps", "0.0000", "0.0100", "0.0100", "983866.31", "3882.22"),
+]
+
+
+def _event(markets, ticker="KXFEDDECISION-26OCT", series="KXFEDDECISION", title="Fed decision in Oct 2026?",
+ category="Economics"):
+ return {
+ "event_ticker": ticker, "series_ticker": series, "title": title,
+ "sub_title": "On Oct 28, 2026", "category": category, "mutually_exclusive": True,
+ "markets": markets,
+ }
+
+
[email protected](autouse=True)
+def _no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def _sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _sleep)
+
+
+# ---------------------------------------------------------------------------
+# Pricing and normalization
+# ---------------------------------------------------------------------------
+
+def test_implied_probability_basis() -> None:
+ assert implied_probability({"yes_bid_dollars": "0.8600", "yes_ask_dollars": "0.8700"}) == (0.865, "bid_ask_midpoint")
+ # One-sided book (bid 0) falls back to the last trade.
+ assert implied_probability(
+ {"yes_bid_dollars": "0.0000", "yes_ask_dollars": "0.0100", "last_price_dollars": "0.0100"}
+ ) == (0.01, "last_trade")
+ assert implied_probability({"yes_bid_dollars": "0.0000", "last_price_dollars": "0.0000"}) == (None, "no_price")
+ # Crossed book is not a midpoint.
+ assert implied_probability(
+ {"yes_bid_dollars": "0.6", "yes_ask_dollars": "0.5", "last_price_dollars": "0.55"}
+ ) == (0.55, "last_trade")
+
+
+def test_normalize_market_fields() -> None:
+ n = normalize_market(FED_MARKETS[2], _event(FED_MARKETS))
+ assert n["id"] == "KXFEDDECISION-26OCT-H0"
+ assert n["yes_side"] == "Fed maintains rate"
+ assert n["context"] == "Fed decision in Oct 2026?"
+ assert n["end_time"] == "2026-10-28T18:05:00Z"
+ assert n["volume"] == 5635368.81 and n["volume_24h"] == 64959.15
+ assert n["series_ticker"] == "KXFEDDECISION"
+ assert n["url"] == "https://kalshi.com/markets/kxfeddecision"
+ # yes_sub_title equal to the title adds nothing: blanked.
+ same = dict(FED_MARKETS[0], yes_sub_title=FED_MARKETS[0]["title"])
+ assert normalize_market(same, None)["yes_side"] == ""
+ # Series falls back to the event-ticker prefix when no event is given.
+ assert normalize_market(FED_MARKETS[0], None)["series_ticker"] == "KXFEDDECISION"
+
+
+# ---------------------------------------------------------------------------
+# Open markets
+# ---------------------------------------------------------------------------
+
+async def test_series_scan_ranks_by_24h_volume(fetcher: Fetcher) -> None:
+ route = respx.get(url__regex=EVENTS).mock(
+ return_value=httpx.Response(200, json={"events": [_event(FED_MARKETS)], "cursor": ""})
+ )
+
+ out = await fetch_kalshi_markets(fetcher, series="KXFEDDECISION", limit=3)
+
+ assert [m["id"] for m in out["markets"]] == [
+ "KXFEDDECISION-26OCT-H0", "KXFEDDECISION-26OCT-H25", "KXFEDDECISION-26OCT-C25",
+ ]
+ assert [m["probability"] for m in out["markets"]] == [0.865, 0.135, 0.01]
+ assert [m["price_basis"] for m in out["markets"]] == ["bid_ask_midpoint", "bid_ask_midpoint", "last_trade"]
+ assert out["count"] == 3 and out["markets_considered"] == 5
+ assert out["scan"] == {
+ "mode": "series", "series": "KXFEDDECISION", "pages_fetched": 1,
+ "exhaustive": True, "events_scanned": 1,
+ }
+ assert out["data_gaps"] == [] and "degraded" not in out and "error" not in out
+ assert "dollars per $1 payout" in out["units"]["price"]
+ params = route.calls.last.request.url.params
+ assert params["series_ticker"] == "KXFEDDECISION"
+ assert params["status"] == "open" and params["with_nested_markets"] == "true"
+
+
+async def test_untraded_markets_excluded_and_counted(fetcher: Fetcher) -> None:
+ untraded = _m("KXFEDDECISION-26OCT-X", "Untraded", "X", "0.0000", "0.0000", "0.0000", "0.00", "0.00")
+ respx.get(url__regex=EVENTS).mock(
+ return_value=httpx.Response(200, json={"events": [_event(FED_MARKETS + [untraded])], "cursor": ""})
+ )
+ out = await fetch_kalshi_markets(fetcher, series="KXFEDDECISION")
+ assert out["markets_considered"] == 5 and out["untraded_excluded"] == 1
+
+ kept = await fetch_kalshi_markets(fetcher, series="KXFEDDECISION", include_untraded=True)
+ assert kept["markets_considered"] == 6 and kept["untraded_excluded"] == 0
+
+
+async def test_outage_is_an_error_not_an_empty_market_list(fetcher: Fetcher) -> None:
+ respx.get(url__regex=EVENTS).mock(return_value=httpx.Response(500))
+ out = await fetch_kalshi_markets(fetcher)
+ assert out["markets"] == [] and out["count"] == 0
+ assert out["degraded"] is True
+ assert out["error"] == "Kalshi /events page 1 unavailable (no live or cached data)"
+
+
+async def test_partial_page_failure_is_degraded_with_gap(fetcher: Fetcher) -> None:
+ def _pages(request: httpx.Request) -> httpx.Response:
+ if request.url.params.get("cursor") == "c2":
+ return httpx.Response(500)
+ return httpx.Response(200, json={"events": [_event(FED_MARKETS)], "cursor": "c2"})
+
+ respx.get(url__regex=EVENTS).mock(side_effect=_pages)
+ out = await fetch_kalshi_markets(fetcher, pages=3)
+ assert out["degraded"] is True
+ assert "error" not in out # page 1 was read: partial, not an outage
+ assert out["data_gaps"] == ["Kalshi /events page 2 unavailable (no live or cached data)"]
+ assert out["scan"]["pages_fetched"] == 1 and out["scan"]["exhaustive"] is False
+ assert out["count"] == 5
+
+
+async def test_unfiltered_partial_scan_says_so_without_degrading(fetcher: Fetcher) -> None:
+ respx.get(url__regex=EVENTS).mock(
+ return_value=httpx.Response(200, json={"events": [_event(FED_MARKETS)], "cursor": "more"})
+ )
+ out = await fetch_kalshi_markets(fetcher, pages=1)
+ assert out["scan"]["exhaustive"] is False
+ assert out["scan"]["api_order"] == "events by close time, furthest out first"
+ assert out["data_gaps"] == [
+ "scanned 1 page(s) of open events; more exist and were not read, "
+ "so the ranking covers only the scanned events"
+ ]
+ assert "degraded" not in out
+
+
+async def test_category_scan_reads_top_series_by_lifetime_volume(fetcher: Fetcher) -> None:
+ respx.get(url__regex=SERIES).mock(
+ return_value=httpx.Response(200, json={"series": [
+ {"ticker": "KXFEDDECISION", "category": "Economics", "volume_fp": "62372208.20"},
+ {"ticker": "KXCPIYOY", "category": "Economics", "volume_fp": "38232786.00"},
+ {"ticker": "KXAAAGASM", "category": "Economics", "volume_fp": "61728678.00"},
+ ]})
+ )
+ gas = {
+ "ticker": "KXAAAGASM-26OCT31-4.45", "event_ticker": "KXAAAGASM-26OCT31",
+ "title": "Will average gas prices be above $4.45?", "yes_sub_title": "Above $4.45",
+ "status": "active", "yes_bid_dollars": "0.2000", "yes_ask_dollars": "0.2400",
+ "last_price_dollars": "0.2200", "volume_fp": "4225.68", "volume_24h_fp": "100000.00",
+ "close_time": "2026-10-31T14:00:00Z",
+ }
+ off_category = dict(gas, ticker="KXAAAGASM-OTHER", event_ticker="KXAAAGASM-OTHER")
+
+ def _events(request: httpx.Request) -> httpx.Response:
+ series = request.url.params.get("series_ticker")
+ if series == "KXFEDDECISION":
+ return httpx.Response(200, json={"events": [_event(FED_MARKETS)], "cursor": ""})
+ if series == "KXAAAGASM":
+ return httpx.Response(200, json={"events": [
+ _event([gas], "KXAAAGASM-26OCT31", "KXAAAGASM", "US gas price on Oct 31?"),
+ _event([off_category], "KXAAAGASM-OTHER", "KXAAAGASM", "Mislabelled", category="Sports"),
+ ], "cursor": ""})
+ return httpx.Response(404)
+
+ route = respx.get(url__regex=EVENTS).mock(side_effect=_events)
+ out = await fetch_kalshi_markets(fetcher, category="Economics", series_limit=2, limit=2)
+
+ assert out["scan"]["mode"] == "category_top_series"
+ assert out["scan"]["series_scanned"] == ["KXFEDDECISION", "KXAAAGASM"]
+ assert route.call_count == 2 # KXCPIYOY (third by volume) never read
+ assert out["markets_considered"] == 6 # 5 Fed + 1 gas; the Sports-labelled event dropped
+ assert [m["id"] for m in out["markets"]] == ["KXAAAGASM-26OCT31-4.45", "KXFEDDECISION-26OCT-H0"]
+ assert out["markets"][0]["probability"] == 0.22
+
+
+async def test_category_series_listing_outage_is_an_error(fetcher: Fetcher) -> None:
+ respx.get(url__regex=SERIES).mock(return_value=httpx.Response(503))
+ out = await fetch_kalshi_markets(fetcher, category="Economics")
+ assert out["degraded"] is True
+ assert out["error"] == "Kalshi /series?category=Economics unavailable (no live or cached data)"
+ assert out["markets"] == []
+
+
+# ---------------------------------------------------------------------------
+# Settled markets and price history
+# ---------------------------------------------------------------------------
+
+def _settled(ticker, result, volume, open_time, settled_at, event="KXCPIYOY-26AUG"):
+ return {
+ "ticker": ticker, "event_ticker": event, "title": f"CPI market {ticker}",
+ "yes_sub_title": ticker, "status": "finalized", "result": result, "volume_fp": volume,
+ "open_time": open_time, "close_time": "2026-09-11T12:25:00Z", "settlement_ts": settled_at,
+ }
+
+
+SETTLED_ROWS = [
+ _settled("M1", "yes", "32791.90", "2026-07-20T14:00:00Z", "2026-09-11T12:30:00Z"),
+ _settled("M2", "no", "42347.50", "2026-07-20T14:00:00Z", "2026-09-11T12:31:00Z"),
+ _settled("M3", "no", "231.66", "2026-07-20T14:00:00Z", "2026-09-11T12:32:00Z"), # volume floor
+ _settled("M4", "", "9000.00", "2026-07-20T14:00:00Z", "2026-09-11T12:33:00Z"), # no yes/no result
+ _settled("M5", "yes", "5000.00", "2026-09-11T02:25:00Z", "2026-09-11T12:34:00Z"), # open 10h only
+ _settled("M6", "yes", "2000.00", "2026-01-01T00:00:00Z", "2026-09-10T00:00:00Z", event="KXCPIYOY-26JUL"),
+]
+
+
+async def test_settled_selection_filters_and_orders(fetcher: Fetcher) -> None:
+ route = respx.get(url__regex=MARKETS).mock(
+ return_value=httpx.Response(200, json={"markets": SETTLED_ROWS, "cursor": ""})
+ )
+ out = await fetch_kalshi_settled(fetcher, series="KXCPIYOY", min_volume=1000, min_open_hours=24)
+
+ assert [m["id"] for m in out["markets"]] == ["M2", "M1", "M6"] # newest settlement first
+ assert [m["outcome"] for m in out["markets"]] == [0, 1, 1]
+ assert out["skipped"] == {"result": 1, "volume": 1, "too_short": 1}
+ assert out["listing_rows_read"] == 6 and out["error"] is None
+ params = route.calls.last.request.url.params
+ assert params["status"] == "settled" and params["mve_filter"] == "exclude"
+ assert params["series_ticker"] == "KXCPIYOY"
+
+
+async def test_settled_listing_outage_is_an_error(fetcher: Fetcher) -> None:
+ respx.get(url__regex=MARKETS).mock(return_value=httpx.Response(500))
+ out = await fetch_kalshi_settled(fetcher, series="KXCPIYOY")
+ assert out["markets"] == []
+ assert out["error"] == "Kalshi settled markets unavailable for KXCPIYOY"
+
+
+async def test_price_history_parses_and_splits_under_candle_budget(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ ref = 1792252800
+ monkeypatch.setattr(kalshi, "_CANDLE_BUDGET", 300)
+
+ def _candles(request: httpx.Request) -> httpx.Response:
+ tickers = request.url.params["market_tickers"].split(",")
+ return httpx.Response(200, json={"markets": [
+ {"market_ticker": t, "candlesticks": [
+ {"end_period_ts": ref - 30 * 3600, "price": {"close_dollars": "0.4200"}},
+ {"end_period_ts": ref - 25 * 3600, "price": {"close_dollars": None}},
+ ]} for t in tickers
+ ]})
+
+ route = respx.get(url__regex=CANDLES).mock(side_effect=_candles)
+ markets = [
+ {"id": "A", "reference_ts": ref, "open_ts": None},
+ {"id": "B", "reference_ts": ref, "open_ts": None},
+ {"id": "C", "reference_ts": ref, "open_ts": ref - 10 * 3600}, # opened after the window
+ ]
+ history, errors = await fetch_kalshi_price_history(fetcher, markets, 200, 24)
+
+ # Each window is 176h = 177 hourly candles; two would be 354 > 300.
+ assert route.call_count == 2
+ assert [c.request.url.params["market_tickers"] for c in route.calls] == ["A", "B"]
+ assert history["A"] == [(ref - 30 * 3600, 0.42)] # null-price hour skipped
+ assert history["B"] == [(ref - 30 * 3600, 0.42)]
+ assert history["C"] == [] # no request: "no price", not "unavailable"
+ assert errors == []
+ p = route.calls[0].request.url.params
+ assert p["period_interval"] == "60"
+ assert int(p["start_ts"]) == ref - 200 * 3600 and int(p["end_ts"]) == ref - 24 * 3600
+
+
+async def test_price_history_outage_reported(fetcher: Fetcher) -> None:
+ respx.get(url__regex=CANDLES).mock(return_value=httpx.Response(500))
+ history, errors = await fetch_kalshi_price_history(
+ fetcher, [{"id": "A", "reference_ts": 1792252800, "open_ts": None}], 48, 24
+ )
+ assert "A" not in history
+ assert errors == ["candlesticks unavailable for 1 market(s)"]
+
+
+# ---------------------------------------------------------------------------
+# Request pacing
+# ---------------------------------------------------------------------------
+
+async def test_requests_are_spaced_by_min_interval(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Two collector sources scanning Kalshi at once drew HTTP 429 live
+ (2026-10-17); each request now waits until _MIN_INTERVAL after the
+ previous one. Sleeps are recorded, not slept."""
+ sleeps: list[float] = []
+
+ async def _record(seconds, *args, **kwargs) -> None:
+ sleeps.append(seconds)
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _record)
+ monkeypatch.setitem(kalshi._pace_state, "last", 0.0)
+ await kalshi._pace() # nothing before it: no wait
+ await kalshi._pace() # straight after: waits about the whole interval
+ assert len(sleeps) == 1
+ assert kalshi._MIN_INTERVAL - 0.05 < sleeps[0] <= kalshi._MIN_INTERVAL
+ monkeypatch.setitem(kalshi._pace_state, "last", -1e9) # long ago
+ await kalshi._pace()
+ assert len(sleeps) == 1
+
+
+async def test_every_request_goes_through_the_pacer(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ paced: list[int] = []
+
+ async def _count() -> None:
+ paced.append(1)
+
+ monkeypatch.setattr(kalshi, "_pace", _count)
+ series_route = respx.get(url__regex=SERIES).mock(return_value=httpx.Response(200, json={"series": [
+ {"ticker": "KXFEDDECISION", "category": "Economics", "volume_fp": "9.00"},
+ ]}))
+ events_route = respx.get(url__regex=EVENTS).mock(
+ return_value=httpx.Response(200, json={"events": [_event(FED_MARKETS)], "cursor": ""})
+ )
+ out = await fetch_kalshi_markets(fetcher, category="Economics", limit=2)
+ assert out["count"] == 2
+ assert series_route.call_count == 1 and events_route.call_count == 1
+ assert len(paced) == 2
+
+
+# ---------------------------------------------------------------------------
+# Category resolution
+# ---------------------------------------------------------------------------
+
+async def test_category_scan_drops_series_outside_the_category(fetcher: Fetcher) -> None:
+ """/series?category= is loose (live: Economics returned 7 series of
+ other categories among 869); only exact matches are scanned."""
+ respx.get(url__regex=SERIES).mock(return_value=httpx.Response(200, json={"series": [
+ {"ticker": "KXPRESPARTY", "category": "Politics", "volume_fp": "75000000.00"},
+ {"ticker": "KXFEDDECISION", "category": "Economics", "volume_fp": "62372208.20"},
+ ]}))
+ events_route = respx.get(url__regex=EVENTS).mock(
+ return_value=httpx.Response(200, json={"events": [_event(FED_MARKETS)], "cursor": ""})
+ )
+ out = await fetch_kalshi_markets(fetcher, category="Economics", series_limit=2)
+ assert out["scan"]["series_scanned"] == ["KXFEDDECISION"]
+ assert [c.request.url.params["series_ticker"] for c in events_route.calls] == ["KXFEDDECISION"]
+
+
+async def test_unknown_category_is_a_named_gap_not_an_outage(fetcher: Fetcher) -> None:
+ """Live: category=Climate answers {"series": null} with HTTP 200
+ ('Climate and Weather' is the name). That must not read as an empty
+ market or as an outage."""
+ respx.get(url__regex=SERIES).mock(return_value=httpx.Response(200, json={"series": None}))
+ out = await fetch_kalshi_markets(fetcher, category="Climate")
+ assert out["markets"] == [] and out["count"] == 0
+ assert "error" not in out and "degraded" not in out
+ assert any("no series in category 'Climate'" in g for g in out["data_gaps"])
+
+ settled = await fetch_kalshi_settled(fetcher, category="Climate")
+ assert settled["markets"] == [] and settled["error"] is None
+ assert any("no series in category 'Climate'" in g for g in settled["data_gaps"])
+
+
+# ---------------------------------------------------------------------------
+# Argument bounds: a caller's count never multiplies upstream requests
+# ---------------------------------------------------------------------------
+
+# 30 series in one category (live /series row shape); volumes rise with
+# the index, so the 25 highest are KXS29 down to KXS05.
+MANY_SERIES = [
+ {"ticker": f"KXS{i:02d}", "category": "Economics", "volume_fp": f"{1000 + i}.00"} for i in range(30)
+]
+TOP_25 = [f"KXS{i:02d}" for i in range(29, 4, -1)]
+
+
+def test_count_arg_clamps_whole_numbers_and_refuses_the_rest() -> None:
+ assert [kalshi.count_arg(v, "pages", 25) for v in (10**6, 25, 3, 2.0, 0, -3)] == [25, 25, 3, 2, 1, 1]
+ for bad in ("3", 2.5, None, True, float("nan"), float("inf"), [3]):
+ with pytest.raises(ValueError, match=r"^pages must be a whole number from 1 to 25 \(got "):
+ kalshi.count_arg(bad, "pages", 25)
+
+
+async def test_huge_series_limit_scans_at_most_25_series(fetcher: Fetcher) -> None:
+ series_route = respx.get(url__regex=SERIES).mock(
+ return_value=httpx.Response(200, json={"series": MANY_SERIES})
+ )
+ events_route = respx.get(url__regex=EVENTS).mock(
+ return_value=httpx.Response(200, json={"events": [], "cursor": ""})
+ )
+ out = await fetch_kalshi_markets(fetcher, category="Economics", series_limit=10**6)
+ assert series_route.call_count == 1
+ assert events_route.call_count == 25
+ assert [c.request.url.params["series_ticker"] for c in events_route.calls] == TOP_25
+ assert out["scan"]["series_scanned"] == TOP_25
+
+
+async def test_huge_series_limit_reads_at_most_25_settled_series(fetcher: Fetcher) -> None:
+ respx.get(url__regex=SERIES).mock(return_value=httpx.Response(200, json={"series": MANY_SERIES}))
+ markets_route = respx.get(url__regex=MARKETS).mock(
+ return_value=httpx.Response(200, json={"markets": [], "cursor": ""})
+ )
+ out = await fetch_kalshi_settled(fetcher, category="Economics", series_limit=10**6)
+ assert markets_route.call_count == 25
+ assert [c.request.url.params["series_ticker"] for c in markets_route.calls] == TOP_25
+ assert out["scope"]["series_read"] == TOP_25
+
+
+async def test_counts_that_are_not_whole_numbers_are_refused_before_any_request(fetcher: Fetcher) -> None:
+ routes = [
+ respx.get(url__regex=p).mock(return_value=httpx.Response(200, json={"series": MANY_SERIES}))
+ for p in (SERIES, EVENTS)
+ ]
+ for bad in ("ten", 2.5, None, True, float("nan"), float("inf")):
+ out = await fetch_kalshi_markets(fetcher, category="Economics", series_limit=bad)
+ assert out["error"] == f"series_limit must be a whole number from 1 to 25 (got {bad!r})"
+ assert out["degraded"] is True and "markets" not in out
+ out = await fetch_kalshi_markets(fetcher, limit="5")
+ assert out["error"] == "limit must be a whole number from 1 to 500 (got '5')"
+ assert sum(r.call_count for r in routes) == 0
+
+
+async def test_open_markets_scan_clamps_series_limit_itself(fetcher: Fetcher) -> None:
+ """The cross-venue compare and any direct caller reach this function
+ without fetch_kalshi_markets' checks, so it clamps on its own."""
+ respx.get(url__regex=SERIES).mock(return_value=httpx.Response(200, json={"series": MANY_SERIES}))
+ events_route = respx.get(url__regex=EVENTS).mock(
+ return_value=httpx.Response(200, json={"events": [], "cursor": ""})
+ )
+ out = await kalshi.fetch_kalshi_open_markets(fetcher, category="Economics", series_limit=10**6)
+ assert events_route.call_count == 25
+ assert out["scan"]["series_scanned"] == TOP_25
diff --git a/src/world_intel_mcp/tests/test_sources_prediction.py b/src/world_intel_mcp/tests/test_sources_prediction.py
index 79f1de6..f547355 100644
--- a/src/world_intel_mcp/tests/test_sources_prediction.py
+++ b/src/world_intel_mcp/tests/test_sources_prediction.py
@@ -2,7 +2,9 @@
Gaps / not covered: real Gamma API schema drift; the module's documented
"empty results on upstream failure" contract carries no degraded marker,
-which is asserted as-is (see the api-down test).
+which is asserted as-is (see the api-down test). Superseded 2026-10-17:
+the outage markers (error/degraded, stale on an expired-cache serve) are
+now pinned by the Phase 24.5 regression tests at the end of this file.
"""
import asyncio as asyncio_mod
@@ -96,9 +98,9 @@ async def test_fetch_prediction_markets_parses_and_sorts(fetcher: Fetcher) -> No
async def test_fetch_prediction_markets_api_down(
fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
) -> None:
- """Upstream failure returns the documented empty shape. Observation
- (flagged in review, not fixed): there is no degraded/error marker, so
- an outage is shape-identical to a market lull."""
+ """Upstream failure keeps the documented empty shape. It now also
+ carries error/degraded markers (fixed 2026-10-17, ROADMAP Phase 24.5;
+ see the regression tests at the end of this file)."""
async def _no_sleep(*args, **kwargs) -> None:
return None
@@ -127,6 +129,86 @@ async def test_fetch_prediction_markets_non_list_response(fetcher: Fetcher) -> N
assert result["count"] == 0
+# ---------------------------------------------------------------------------
+# ROADMAP Phase 24.5: an outage must be distinguishable from "no markets".
+# Written failing-first against the pre-fix module (which returned the
+# bare empty shape above with no marker).
+# ---------------------------------------------------------------------------
+
+
+async def test_outage_carries_error_and_degraded_not_bare_empty(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ respx.get(url__regex=r".*gamma-api\.polymarket\.com.*").mock(
+ return_value=httpx.Response(503)
+ )
+
+ result = await fetch_prediction_markets(fetcher)
+
+ # Existing keys kept (additive fix), outage marked.
+ assert result["markets"] == [] and result["count"] == 0
+ assert result["source"] == "polymarket"
+ assert result["degraded"] is True
+ assert "unavailable" in result["error"]
+
+
+async def test_non_list_response_is_marked_degraded(fetcher: Fetcher) -> None:
+ respx.get(url__regex=r".*gamma-api\.polymarket\.com.*").mock(
+ return_value=httpx.Response(200, json={"unexpected": "dict"})
+ )
+
+ result = await fetch_prediction_markets(fetcher)
+ assert result["degraded"] is True
+ assert "expected a list" in result["error"]
+
+
+async def test_quiet_market_is_not_marked_as_outage(fetcher: Fetcher) -> None:
+ """The other half of the distinction: a live empty list is a real
+ answer and must not carry the outage markers."""
+ respx.get(url__regex=r".*gamma-api\.polymarket\.com.*").mock(
+ return_value=httpx.Response(200, json=[])
+ )
+
+ result = await fetch_prediction_markets(fetcher)
+ assert result["count"] == 0
+ assert "error" not in result
+ assert "degraded" not in result
+ assert "stale" not in result
+
+
+async def test_stale_list_serve_is_marked_stale(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Gamma returns a list, which cannot carry the fetcher's inline
+ _stale marker; the breaker's stale counter is the signal."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ fetcher.cache.set("prediction:polymarket:20", _MARKETS[:2], -10) # expired
+ respx.get(url__regex=r".*gamma-api\.polymarket\.com.*").mock(
+ return_value=httpx.Response(500)
+ )
+
+ result = await fetch_prediction_markets(fetcher)
+ assert result["count"] == 2
+ assert result["stale"] is True
+ assert result["data_gaps"] == ["served from expired cache after a failed live fetch"]
+
+
def test_parse_outcome_prices() -> None:
assert _parse_outcome_prices(None) is None
assert _parse_outcome_prices("notjson") is None
diff --git a/src/world_intel_mcp/tools/__init__.py b/src/world_intel_mcp/tools/__init__.py
index d1b68a7..51cedaa 100644
--- a/src/world_intel_mcp/tools/__init__.py
+++ b/src/world_intel_mcp/tools/__init__.py
@@ -31,6 +31,7 @@ from . import ( # noqa: E402
infrastructure,
intelligence,
markets,
+ prediction_markets,
society,
synthesis,
system,
@@ -45,6 +46,7 @@ _MODULES = [
conflict,
infrastructure,
society,
+ prediction_markets,
intelligence,
geospatial,
synthesis,
diff --git a/src/world_intel_mcp/tools/prediction_markets.py b/src/world_intel_mcp/tools/prediction_markets.py
new file mode 100644
index 0000000..5489b65
--- /dev/null
+++ b/src/world_intel_mcp/tools/prediction_markets.py
@@ -0,0 +1,239 @@
+"""Prediction-market tools beyond Polymarket's open list: Kalshi open
+markets, the same event on Kalshi and Polymarket side by side, and
+settled markets scored against their pre-settlement prices (Brier).
+
+Added in ROADMAP Phase 29. The Polymarket open-markets tool
+(``intel_prediction_markets``) stays in ``tools/society.py`` unchanged.
+Every count and number states its bounds in the input schema; the
+source functions clamp counts again, so no caller reaches more Kalshi
+series or pages than the stated maximum.
+"""
+
+from typing import Any
+
+from mcp.types import Tool
+
+from .. import runtime
+from ..analysis.prediction_matching import DEFAULT_MIN_CONFIDENCE
+from ..sources import kalshi, prediction, prediction_cross
+
+TOOLS: list[Tool] = [
+ Tool(
+ name="intel_kalshi_markets",
+ description=(
+ "Kalshi open prediction markets from its public market-data API (no account), ranked by "
+ "24h then lifetime volume. Prices are YES implied probabilities (Kalshi quotes dollars per "
+ "$1 contract; raw bid/ask/last kept). Filter by category (e.g. 'Economics', 'Politics', "
+ "'Elections', 'Financials', 'Climate and Weather') or series ticker (e.g. 'KXFED'). The "
+ "response states which events were scanned and whether the scan was exhaustive."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "category": {"type": "string", "description": "Kalshi category; scans its highest-volume series"},
+ "series": {"type": "string", "description": "Kalshi series ticker, e.g. KXFED (scanned in full)"},
+ "limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": kalshi.MAX_RESULTS,
+ "description": f"Markets to return (default 20, max {kalshi.MAX_RESULTS})",
+ "default": 20,
+ },
+ "pages": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": kalshi.MAX_PAGES,
+ "description": (
+ f"Unfiltered scan only: pages of 200 open events to read (default 3, max {kalshi.MAX_PAGES})"
+ ),
+ "default": 3,
+ },
+ "series_limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": kalshi.MAX_SERIES,
+ "description": (
+ f"Category scan only: top series by lifetime volume to read (default 10, max {kalshi.MAX_SERIES})"
+ ),
+ "default": 10,
+ },
+ "include_untraded": {
+ "type": "boolean",
+ "description": "Keep markets with zero lifetime volume (default false)",
+ "default": False,
+ },
+ },
+ },
+ ),
+ Tool(
+ name="intel_prediction_compare",
+ description=(
+ "The same event on Kalshi and Polymarket side by side: deterministic matching on normalized "
+ "titles, quantities, years, end dates, negation and outcome side, with a match_confidence "
+ "and the reasons for each pair. Below min_confidence a pair is not a match. Returns matched "
+ "pairs with the price gap, the closest rejected pairs with why, and unmatched counts per venue."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "category": {"type": "string", "description": "Kalshi category to compare (e.g. 'Economics')"},
+ "series": {"type": "string", "description": "Kalshi series ticker to compare (e.g. KXFEDDECISION)"},
+ "kalshi_pages": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": kalshi.MAX_PAGES,
+ "description": f"Unfiltered Kalshi scan pages (default 3, max {kalshi.MAX_PAGES})",
+ "default": 3,
+ },
+ "series_limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": kalshi.MAX_SERIES,
+ "description": f"Kalshi category scan: top series (default 10, max {kalshi.MAX_SERIES})",
+ "default": 10,
+ },
+ "polymarket_limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": prediction.MAX_OPEN_MARKETS,
+ "description": (
+ "Polymarket open markets by 24h volume to compare "
+ f"(default 300, max {prediction.MAX_OPEN_MARKETS})"
+ ),
+ "default": 300,
+ },
+ "min_confidence": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": 1,
+ "description": f"Match threshold 0..1 (default {DEFAULT_MIN_CONFIDENCE})",
+ "default": DEFAULT_MIN_CONFIDENCE,
+ },
+ "limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": prediction_cross.MAX_PAIRS,
+ "description": f"Matched pairs to return (default 25, max {prediction_cross.MAX_PAIRS})",
+ "default": 25,
+ },
+ },
+ },
+ ),
+ Tool(
+ name="intel_prediction_settled",
+ description=(
+ "Recently settled Kalshi and Polymarket markets with their outcome and the YES price at fixed "
+ "offsets before close (from each venue's price-history endpoint), plus a Brier score per venue "
+ "and offset with sample size, selection and exclusions stated. A venue whose price history is "
+ "unavailable is not scored. The two venues' samples are different markets."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": kalshi.MAX_SETTLED,
+ "description": f"Settled markets per venue (default 25, max {kalshi.MAX_SETTLED})",
+ "default": 25,
+ },
+ "offsets_hours": {
+ "type": "array",
+ "maxItems": prediction_cross.MAX_OFFSETS,
+ "items": {"type": "number", "exclusiveMinimum": 0, "maximum": prediction_cross.MAX_OFFSET_HOURS},
+ "description": (
+ "Hours before the reference time to read the price at (default [24, 168]; up to "
+ f"{prediction_cross.MAX_OFFSETS} values, each above 0 and at most "
+ f"{prediction_cross.MAX_OFFSET_HOURS})"
+ ),
+ },
+ "kalshi_min_volume": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": prediction_cross.MAX_VOLUME_FLOOR,
+ "description": "Kalshi volume floor, contracts (default 1000)",
+ "default": 1000,
+ },
+ "polymarket_min_volume": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": prediction_cross.MAX_VOLUME_FLOOR,
+ "description": "Polymarket volume floor, USDC (default 10000)",
+ "default": 10000,
+ },
+ "kalshi_category": {
+ "type": "string",
+ "description": (
+ "Kalshi sample: settled markets of this category's highest-volume series "
+ "(default 'Economics'; the exchange-wide listing is intraday sports)"
+ ),
+ "default": "Economics",
+ },
+ "kalshi_series_limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": kalshi.MAX_SERIES,
+ "description": f"Kalshi category sample: top series to read (default 10, max {kalshi.MAX_SERIES})",
+ "default": 10,
+ },
+ "kalshi_series": {"type": "string", "description": "Restrict the Kalshi sample to one series ticker"},
+ "max_staleness_hours": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": prediction_cross.MAX_STALENESS_HOURS,
+ "description": (
+ "Oldest last price allowed to stand for an offset "
+ f"(default 168, max {prediction_cross.MAX_STALENESS_HOURS})"
+ ),
+ "default": 168,
+ },
+ },
+ },
+ ),
+]
+
+
+async def _kalshi_markets(arguments: dict[str, Any]) -> Any:
+ return await kalshi.fetch_kalshi_markets(
+ runtime.fetcher,
+ category=arguments.get("category"),
+ series=arguments.get("series"),
+ limit=arguments.get("limit", 20),
+ pages=arguments.get("pages", 3),
+ series_limit=arguments.get("series_limit", 10),
+ include_untraded=bool(arguments.get("include_untraded", False)),
+ )
+
+
+async def _prediction_compare(arguments: dict[str, Any]) -> Any:
+ return await prediction_cross.fetch_prediction_compare(
+ runtime.fetcher,
+ category=arguments.get("category"),
+ series=arguments.get("series"),
+ kalshi_pages=arguments.get("kalshi_pages", 3),
+ series_limit=arguments.get("series_limit", 10),
+ polymarket_limit=arguments.get("polymarket_limit", 300),
+ min_confidence=arguments.get("min_confidence", DEFAULT_MIN_CONFIDENCE),
+ limit=arguments.get("limit", 25),
+ )
+
+
+async def _prediction_settled(arguments: dict[str, Any]) -> Any:
+ return await prediction_cross.fetch_prediction_settled(
+ runtime.fetcher,
+ limit=arguments.get("limit", 25),
+ offsets_hours=arguments.get("offsets_hours"),
+ kalshi_min_volume=arguments.get("kalshi_min_volume", 1000),
+ polymarket_min_volume=arguments.get("polymarket_min_volume", 10000),
+ kalshi_series=arguments.get("kalshi_series"),
+ max_staleness_hours=arguments.get("max_staleness_hours", 168),
+ kalshi_category=arguments.get("kalshi_category", "Economics"),
+ kalshi_series_limit=arguments.get("kalshi_series_limit", 10),
+ )
+
+
+HANDLERS = {
+ "intel_kalshi_markets": _kalshi_markets,
+ "intel_prediction_compare": _prediction_compare,
+ "intel_prediction_settled": _prediction_settled,
+}
diff --git a/src/world_intel_mcp/tools/system.py b/src/world_intel_mcp/tools/system.py
index 93716e8..d16834c 100644
--- a/src/world_intel_mcp/tools/system.py
+++ b/src/world_intel_mcp/tools/system.py
@@ -57,7 +57,7 @@ async def _status(arguments: dict[str, Any]) -> Any:
"climate": ["open-meteo"],
"news": ["rss-aggregator", "gdelt"],
"intelligence": ["ollama", "acled", "world-bank", "hdx", "usgs"],
- "prediction": ["polymarket"],
+ "prediction": ["polymarket", "kalshi"],
"displacement": ["unhcr"],
"aviation": ["faa"],
"cyber": ["feodo-tracker", "cisa-kev", "sans-dshield", "urlhaus"],