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.

Add intel_news_market_reaction: same-session moves of what the news names

Phoenix Agent (mac-studio)38cd62d3dca9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6311734..f675f0c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,34 @@
# Changelog
+## Unreleased
+
+### Added: news vs market reaction
+- `intel_news_market_reaction` (CLI: `intel news-reaction`): the companies and
+ countries named in recent story clusters, mapped to a listing (the entity
+ table's ticker, confirmed against SEC's company_tickers.json for US
+ listings) or to the country's primary index (the table `intel_country_stocks`
+ uses), with the move on the story's market session from Yahoo daily bars.
+ Company rows give the stock's close-to-close return (adjusted closes), the
+ benchmark's return over the same two dates (SPY for US listings, the
+ exchange country's index otherwise) and the excess return; country rows
+ give the index return and a z-score against its previous up-to-20 sessions.
+- Session rule, stated in every response: the story time (earliest
+ `published` in the cluster) is converted to the exchange's timezone; before
+ the regular close on a trading day it is that session, at or after the close
+ the next one, and a weekend or holiday (read from the listing's own bars)
+ maps to the next trading day. A session that has not closed is `pending`.
+- Honest gaps: a failed quote, a missing benchmark bar, a stock series missing
+ a day its benchmark traded, a story timestamp later than the collection time
+ and a story older than the bar range are each a `data_gap` row with the
+ reason and no number, never a 0% move. Unmapped names (private companies,
+ countries without an index) are listed, not dropped. Company names that are
+ also common words (apple, amazon, meta, shell, bp, alphabet, chevron,
+ samsung) are excluded with a stated reason unless the headlines carry a
+ corroborating term or an article comes from a feed category where the
+ company sense dominates (a hyphen-joined use such as "meta-analysis" does
+ not count). Responses say they describe same-session co-movement, not
+ causation, and are not a trading signal. Tools 139 -> 140.
+
## 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..e285433 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 **140 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.
@@ -22,6 +22,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r
| **Earnings** | 2 | Yahoo Finance (mega-cap calendar, surprise history) |
| **SEC Filings** | 3 | SEC EDGAR (full-text search, company filings, 8-K material events) |
| **Company Enrichment** | 1 | Yahoo Finance + GDELT + SEC + GitHub (composite profile) |
+| **News vs Market Reaction** | 1 | RSS story clusters + Yahoo Finance daily bars + SEC ticker file (same-session move of named companies and country indices) |
| **Macro Composite** | 1 | Weighted 6-signal market verdict (Fear&Greed, VIX, sectors, DXY, BTC, yields) |
| **Economic Indicators** | 6 | AAA fuel prices, EIA energy, FRED macro, World Bank |
| **Central Banks** | 1 | 15 central bank policy rates |
@@ -64,7 +65,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: 140 tools** across 30+ intelligence domains.
---
@@ -129,6 +130,7 @@ 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 news-reaction -c finance # same-session moves of companies in the news
intel status # cache + circuit breaker health
```
@@ -198,6 +200,11 @@ collector.py (daemon) ─┘
|------|-------------|
| `intel_company_profile` | Composite profile: stock quote + financials + news + SEC + GitHub |
+### News vs Market Reaction (1)
+| Tool | Description |
+|------|-------------|
+| `intel_news_market_reaction` | Companies and countries named in recent story clusters, mapped to tickers (SEC-confirmed for US listings) and country indices; the move on the story's market session (stock, benchmark, excess return; index return with a trailing z-score). After-close stories map to the next session, weekends and holidays to the next trading day, in the exchange's timezone. Unmapped and ambiguous names are listed with reasons; a failed quote is a data gap, never 0%. Co-movement, not causation; not a trading signal |
+
### Macro Composite (1)
| Tool | Description |
|------|-------------|
diff --git a/ROADMAP.md b/ROADMAP.md
index 7249537..43cca17 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -2,7 +2,7 @@
**Benchmark**: [koala73/worldmonitor](https://github.com/koala73/worldmonitor)
**Updated**: 2026-10-12 (0.11.0: aircraft-cohort early warning, cross-border migration)
-**Current tools**: 139 (138 intel + 1 status)
+**Current tools**: 140 (139 intel + 1 status)
---
@@ -579,7 +579,7 @@ dashboard.
| 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 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :red_circle: |
+| 1 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :white_check_mark: Built 2026-10-17, unreleased: `intel_news_market_reaction` and `intel news-reaction`. Company rows: stock, benchmark (SPY, or the exchange country's index) and excess return on the story's session; country rows: index return with a trailing z-score. Session rule in the exchange's timezone (after close = next session; weekends and holidays read from the listing's own bars). Open: `^TASI` and `^TA125` (Saudi and Israel in the country-index table) return 404 on Yahoo, so those benchmarks are data gaps; story times inherit `sources/news.py`'s RSS timestamp offset until that is fixed |
| 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: |
| 3 | Dashboard views | Liquidity board, situations, top stories, collection health panels | :red_circle: |
@@ -671,8 +671,8 @@ suite, and a live MCP stdio session.
| Category | Current | Notes |
|----------|---------|-------|
-| Total MCP tools | 139 | 138 intelligence tools + `intel_status` |
-| Tool parity | 139 / 139 | `TOOLS` and handlers are aligned at import time; README's per-tool reference is pinned to the registry by `test_readme_documents_every_registered_tool` |
+| Total MCP tools | 140 | 139 intelligence tools + `intel_status` |
+| Tool parity | 140 / 140 | `TOOLS` and handlers are aligned at import time; README's per-tool reference is pinned to the registry by `test_readme_documents_every_registered_tool` |
| Static datasets | 18 | Bases, ports, pipelines, nuclear, cables, datacenters, spaceports, minerals, exchanges, trade routes, cloud regions, financial centers |
| RSS feeds | 119 | 24 categories |
| Tests in repo | 991 | 973 non-smoke tests + 18 live smoke tests (measured 2026-10-12: `pytest -m 'not smoke'` -> 973 passed, 18 deselected); full suite requires `.[dev]` |
diff --git a/src/world_intel_mcp/analysis/news_market.py b/src/world_intel_mcp/analysis/news_market.py
new file mode 100644
index 0000000..d1f29c4
--- /dev/null
+++ b/src/world_intel_mcp/analysis/news_market.py
@@ -0,0 +1,782 @@
+"""News vs market reaction: same-session moves of what the news names.
+
+For recent story clusters (the RSS feed of ``sources/news.py`` grouped by
+``analysis/clustering.cluster_articles``), the companies and countries
+their headlines name (``analysis/entities.extract_entities``) are mapped
+to a listing: a company to the ticker in the entity table, confirmed
+against SEC's ``company_tickers.json`` for US listings; a country to its
+primary index (``config/exchanges.COUNTRY_INDEX_TICKERS``, the table
+``intel_country_stocks`` uses). The move on the story's market session is
+then read from Yahoo v8 daily bars.
+
+Company rows: the stock's close-to-close return on the assigned session,
+the benchmark's return over the same two dates (SPY for US listings, the
+exchange country's primary index otherwise) and the excess return
+(simple difference, not beta-adjusted). Country rows: the index's return
+on the session and a z-score against its own preceding session returns.
+
+Session assignment: the story time is the earliest ``published`` among
+the cluster's articles, converted to the listing's exchange timezone.
+Before that exchange's regular close on a trading day -> that session;
+at or after the close -> the next session; on a day with no session
+(weekend or holiday, read from the listing's own daily bars) -> the next
+session. A session that has not closed yet is ``pending``, never a move.
+
+This describes co-movement on the same session, not causation, and is
+not a trading signal. A failed quote is a data gap, never a 0% move.
+
+Gaps / not covered:
+- One close time of day per listing, from Yahoo's current trading period,
+ is applied to every day: past early-close days count as full days, and
+ on an early-close day its shortened close is applied to every day.
+- Excess return is a simple difference, not beta- or sector-adjusted.
+- Admitting an ambiguous company name by its feed category is a stated
+ heuristic; a corroborating term in the headline is the stronger signal.
+- A weekday missing from a country index's bars is read as a holiday;
+ for companies a day the benchmark traded but the stock did not is a
+ data gap instead, but country rows have no such cross-check.
+- Story times are only as good as the feeds' timestamps and their parsing
+ in ``sources/news.py``; one later than the collection time is reported
+ as a data gap, but a wrong time in the past cannot be detected here.
+- Headlines only (titles, not summaries) are matched; the entity table
+ covers a curated set of companies, not every listed name.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import html
+import logging
+import re
+import statistics
+from datetime import date, datetime, time, timedelta, timezone
+from email.utils import parsedate_to_datetime
+from typing import Any
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+
+from ..config.exchanges import COUNTRY_INDEX_TICKERS
+from ..fetcher import Fetcher
+from ..sources import news
+from ..sources.markets import _YAHOO_CHART_URL
+from ..sources.sec_edgar import _SEC_HEADERS, _TICKERS_URL
+from . import clustering, entities
+
+logger = logging.getLogger("world-intel-mcp.analysis.news_market")
+
+US_BENCHMARK = "SPY"
+BARS_RANGE = "3mo"
+BARS_TTL = 900
+ZSCORE_WINDOW = 20
+ZSCORE_MIN = 10
+# A story stamped more than this far past the collection time has a bad
+# feed timestamp, not a scoop.
+FUTURE_TOLERANCE = timedelta(minutes=5)
+
+# Yahoo exchange suffix -> ISO-3 of the exchange's country, so a foreign
+# listing is benchmarked against the index intel_country_stocks maps.
+SUFFIX_COUNTRY: dict[str, str] = {
+ "L": "GBR", "DE": "DEU", "F": "DEU", "AS": "NLD", "SW": "CHE",
+ "MI": "ITA", "MC": "ESP", "ST": "SWE", "SR": "SAU", "KS": "KOR",
+ "KQ": "KOR", "T": "JPN", "HK": "HKG", "SS": "CHN", "SZ": "CHN",
+ "TW": "TWN", "NS": "IND", "BO": "IND", "TO": "CAN", "AX": "AUS",
+ "SA": "BRA", "JO": "ZAF", "MX": "MEX", "SI": "SGP", "TA": "ISR",
+}
+
+# Entity-table company keywords that are also ordinary words or name more
+# than one listed company: (reason, corroborating terms, feed categories).
+# Each is kept only when the story's headlines carry a corroborating term
+# or one of its articles comes from a feed category where the company
+# sense dominates (and the name is not only hyphen-joined); otherwise it
+# is excluded with the reason.
+AMBIGUOUS_COMPANIES: dict[str, tuple[str, tuple[str, ...], tuple[str, ...]]] = {
+ "apple": (
+ "'apple' is also the fruit",
+ ("iphone", "ipad", "macbook", "app store", "tim cook", "apple inc", "airpods", "ios"),
+ ("technology", "finance"),
+ ),
+ "amazon": (
+ "'amazon' is also the river and rainforest",
+ ("aws", "amazon web services", "bezos", "jassy", "amazon.com", "alexa", "prime video"),
+ ("technology", "finance"),
+ ),
+ "meta": (
+ "'meta' is also a common word and prefix",
+ ("facebook", "instagram", "whatsapp", "zuckerberg", "meta platforms"),
+ ("technology", "finance"),
+ ),
+ "shell": (
+ "'shell' is also an artillery round, a casing and a shell company",
+ ("shell plc", "royal dutch shell", "shell oil", "sawan"),
+ ("energy",),
+ ),
+ "bp": (
+ # Finance feeds are not context here: they quote basis points.
+ "'bp' is also basis points and blood pressure",
+ ("bp plc", "british petroleum", "bp's"),
+ ("energy",),
+ ),
+ "alphabet": (
+ "'alphabet' is also a common word",
+ ("google", "waymo", "pichai", "alphabet inc"),
+ ("technology", "finance"),
+ ),
+ "chevron": (
+ "'chevron' is also an insignia and a US legal doctrine",
+ ("chevron corp", "chevron's", "oil", "refinery", "crude", "wirth"),
+ ("energy",),
+ ),
+ "samsung": (
+ "'samsung' names several separately listed companies",
+ ("samsung electronics", "galaxy", "exynos", "hbm", "chip", "semiconductor"),
+ (),
+ ),
+}
+
+# A corroborating term may carry a plural "s" ("foldable iPhones").
+_CORROBORATOR_RE: dict[str, re.Pattern[str]] = {
+ kw: re.compile(r"\b(?:" + "|".join(re.escape(t) for t in terms) + r")s?\b")
+ for kw, (_reason, terms, _cats) in AMBIGUOUS_COMPANIES.items()
+}
+
+METHOD = {
+ "story_time": (
+ "Earliest `published` timestamp among the cluster's articles (UTC, as "
+ "the RSS feeds state it)."
+ ),
+ "session_rule": (
+ "The story time is converted to the listing's exchange timezone "
+ "(Yahoo exchangeTimezoneName). Published before that exchange's "
+ "regular close on a trading day: that day's session. Published at or "
+ "after the close: the next session. Published on a day with no session "
+ "(weekend or holiday, read from the listing's own daily bars): the next "
+ "session. The close time of day is Yahoo's currentTradingPeriod.regular.end "
+ "applied to every day, so early-close days are not modelled."
+ ),
+ "return": (
+ "Close-to-close: adjusted close of the assigned session over the adjusted "
+ "close of the prior session in the listing's own daily bars, minus 1. A "
+ "story that landed mid-session shares the window with trading before it."
+ ),
+ "benchmark": (
+ f"US listings (no exchange suffix): {US_BENCHMARK}. Other listings: the "
+ "primary index of the exchange's country in the table intel_country_stocks "
+ "uses. The benchmark is measured over the same two dates; excess = stock "
+ "return - benchmark return, a simple difference, not beta-adjusted."
+ ),
+ "countries": (
+ "Country rows measure the country's primary index on the assigned session, "
+ f"with a z-score against the index's previous up-to-{ZSCORE_WINDOW} session "
+ f"returns (null with fewer than {ZSCORE_MIN})."
+ ),
+ "entities": (
+ "Companies and countries named in the cluster's headlines (titles only) by "
+ "analysis/entities.py. Company names that are also common words "
+ "(apple, amazon, meta, shell, bp, alphabet, chevron, samsung) are excluded "
+ "unless the headlines carry a corroborating term, or an article comes from a "
+ "feed category where the company sense dominates and the name stands on its "
+ "own (a hyphen-joined use such as 'meta-analysis' does not count); each kept "
+ "one says which."
+ ),
+}
+
+INTERPRETATION = (
+ "Same-session co-movement only. A move on the story's session does not show "
+ "that the story caused it: other news, sector moves and market-wide events "
+ "share the session. This is not a trading signal."
+)
+
+
+def _utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+# ---------------------------------------------------------------------------
+# Story time
+# ---------------------------------------------------------------------------
+
+
+def parse_published(value: Any) -> datetime | None:
+ """Parse a feed item's ``published`` (ISO 8601 or RFC 822) to aware UTC."""
+ if not isinstance(value, str) or not value.strip():
+ return None
+ text = value.strip()
+ try:
+ dt = datetime.fromisoformat(text.replace("Z", "+00:00"))
+ except ValueError:
+ try:
+ dt = parsedate_to_datetime(text)
+ except (TypeError, ValueError, IndexError):
+ return None
+ if dt.tzinfo is None:
+ # A naive timestamp has no stated zone; reading it as UTC would be
+ # a guess, so the story time is unknown.
+ return None
+ return dt.astimezone(timezone.utc)
+
+
+# ---------------------------------------------------------------------------
+# Daily bars
+# ---------------------------------------------------------------------------
+
+
+class Bars:
+ """One listing's daily bars keyed by session date in its exchange zone."""
+
+ def __init__(self, symbol: str, tz: ZoneInfo, close_time: time, closes: dict[date, float]):
+ self.symbol = symbol
+ self.tz = tz
+ self.close_time = close_time
+ self.closes = closes
+ self.dates = sorted(closes)
+
+ @property
+ def tz_name(self) -> str:
+ return self.tz.key
+
+
+def parse_bars(symbol: str, data: Any) -> tuple[Bars | None, str | None]:
+ """Build ``Bars`` from a Yahoo v8 chart payload, or say why not."""
+ if not isinstance(data, dict):
+ return None, f"{symbol}: Yahoo chart returned no data (request failed or symbol unknown)"
+ chart = data.get("chart") or {}
+ results = chart.get("result")
+ if not results:
+ err = chart.get("error") or {}
+ detail = err.get("description") or err.get("code") or "empty result"
+ return None, f"{symbol}: Yahoo chart error ({detail})"
+ try:
+ result = results[0]
+ meta = result.get("meta") or {}
+ tz = ZoneInfo(meta["exchangeTimezoneName"])
+ end = meta["currentTradingPeriod"]["regular"]["end"]
+ close_time = datetime.fromtimestamp(end, tz).time()
+ stamps = result.get("timestamp") or []
+ indicators = result.get("indicators") or {}
+ adj = (indicators.get("adjclose") or [{}])[0].get("adjclose")
+ raw = (indicators.get("quote") or [{}])[0].get("close")
+ except (KeyError, IndexError, TypeError, AttributeError, ZoneInfoNotFoundError) as exc:
+ return None, f"{symbol}: unexpected Yahoo chart structure ({type(exc).__name__}: {exc})"
+ values = adj if isinstance(adj, list) and len(adj) == len(stamps) else raw
+ if not isinstance(values, list) or len(values) != len(stamps):
+ return None, f"{symbol}: Yahoo chart has no close series matching its timestamps"
+ closes: dict[date, float] = {}
+ for ts, value in zip(stamps, values):
+ # A null close is a missing bar, never a zero price.
+ if ts is None or value is None:
+ continue
+ # A later bar on the same local date (Yahoo's live bar) replaces it.
+ closes[datetime.fromtimestamp(ts, tz).date()] = float(value)
+ if not closes:
+ return None, f"{symbol}: Yahoo chart has no usable closes"
+ return Bars(symbol, tz, close_time, closes), None
+
+
+async def fetch_bars(fetcher: Fetcher, symbol: str) -> tuple[Bars | None, str | None]:
+ data = await fetcher.get_json(
+ _YAHOO_CHART_URL.format(symbol=symbol),
+ source="yahoo-finance",
+ cache_key=f"news_market:bars:{symbol}",
+ cache_ttl=BARS_TTL,
+ params={"range": BARS_RANGE, "interval": "1d"},
+ yahoo_rate_limit=True,
+ )
+ return parse_bars(symbol, data)
+
+
+# ---------------------------------------------------------------------------
+# Session assignment and returns
+# ---------------------------------------------------------------------------
+
+
+def assign_session(story_utc: datetime, bars: Bars, now_utc: datetime) -> dict:
+ """Map a story time to the listing's session under the stated rule.
+
+ Returns a dict with ``status`` ("assigned" or "pending"), and when
+ assigned: ``session_date``, ``basis``, ``published_local``.
+ """
+ local = story_utc.astimezone(bars.tz)
+ after_close = local.time() >= bars.close_time
+ candidate = local.date() + timedelta(days=1) if after_close else local.date()
+ out: dict[str, Any] = {
+ "published_local": local.isoformat(),
+ "after_close": after_close,
+ "candidate_date": candidate.isoformat(),
+ }
+ if candidate < bars.dates[0]:
+ out["status"] = "out_of_range"
+ out["reason"] = (
+ f"story session {candidate.isoformat()} predates the first {bars.symbol} "
+ f"bar in range ({bars.dates[0].isoformat()})"
+ )
+ return out
+ session = next((d for d in bars.dates if d >= candidate), None)
+ if session is None:
+ out["status"] = "pending"
+ out["reason"] = (
+ f"no {bars.symbol} session on or after {candidate.isoformat()} yet "
+ f"(last bar {bars.dates[-1].isoformat()})"
+ )
+ return out
+ now_local = now_utc.astimezone(bars.tz)
+ if session == now_local.date() and now_local.time() < bars.close_time:
+ out["status"] = "pending"
+ out["session_date"] = session.isoformat()
+ out["reason"] = f"the {session.isoformat()} session has not closed yet; its move is not final"
+ return out
+ if session > candidate:
+ basis = "next_session_non_trading_day"
+ elif after_close:
+ basis = "next_session_after_close"
+ else:
+ basis = "same_session"
+ out.update({"status": "assigned", "session_date": session.isoformat(), "basis": basis})
+ return out
+
+
+# assign_session status -> row status when no session was assigned.
+_UNASSIGNED = {"pending": "pending", "out_of_range": "data_gap"}
+
+
+def session_return(bars: Bars, session: date) -> tuple[date | None, float | None]:
+ """Close-to-close return of ``session`` against the prior bar."""
+ idx = bars.dates.index(session)
+ if idx == 0:
+ return None, None
+ prior = bars.dates[idx - 1]
+ return prior, bars.closes[session] / bars.closes[prior] - 1.0
+
+
+def window_return(bars: Bars, start: date, end: date) -> float | None:
+ """Return over two exact dates, or None when either bar is missing."""
+ if start not in bars.closes or end not in bars.closes:
+ return None
+ return bars.closes[end] / bars.closes[start] - 1.0
+
+
+def trailing_zscore(bars: Bars, session: date, value: float) -> tuple[float | None, int]:
+ """Z-score of ``value`` against the series' preceding session returns."""
+ idx = bars.dates.index(session)
+ rets = [
+ bars.closes[bars.dates[i]] / bars.closes[bars.dates[i - 1]] - 1.0
+ for i in range(max(1, idx - ZSCORE_WINDOW), idx)
+ ]
+ if len(rets) < ZSCORE_MIN:
+ return None, len(rets)
+ sd = statistics.stdev(rets)
+ if sd == 0:
+ return None, len(rets)
+ return round((value - statistics.fmean(rets)) / sd, 2), len(rets)
+
+
+def _pct(x: float) -> float:
+ return round(x * 100.0, 4)
+
+
+def benchmark_for(symbol: str) -> tuple[str | None, str | None]:
+ """Benchmark symbol for a listing, or the reason there is none."""
+ if "." not in symbol:
+ return US_BENCHMARK, None
+ suffix = symbol.rsplit(".", 1)[1].upper()
+ iso3 = SUFFIX_COUNTRY.get(suffix)
+ if iso3 is None:
+ return None, f"no benchmark mapped for exchange suffix .{suffix}"
+ index = COUNTRY_INDEX_TICKERS.get(iso3)
+ if index is None:
+ return None, f"no primary index mapped for {iso3} (exchange suffix .{suffix})"
+ return index, None
+
+
+def measure_company(story_utc: datetime, bars: Bars, bench: Bars, now_utc: datetime) -> dict:
+ """Stock, benchmark and excess return on the story's session."""
+ if bench.tz_name != bars.tz_name:
+ return {
+ "status": "data_gap",
+ "gap": (
+ f"benchmark {bench.symbol} trades in {bench.tz_name}, "
+ f"{bars.symbol} in {bars.tz_name}; session dates do not align"
+ ),
+ }
+ sess = assign_session(story_utc, bars, now_utc)
+ out: dict[str, Any] = {k: sess[k] for k in ("published_local", "session_date") if k in sess}
+ if sess["status"] != "assigned":
+ out.update({"status": _UNASSIGNED[sess["status"]], "gap": sess["reason"]})
+ return out
+ session = date.fromisoformat(sess["session_date"])
+ candidate = date.fromisoformat(sess["candidate_date"])
+ # A day the benchmark traded but the stock series lacks is missing
+ # data in the stock series, not a holiday: the session would be wrong.
+ skipped = [d for d in bench.dates if candidate <= d < session]
+ if skipped:
+ out.update({
+ "status": "data_gap",
+ "gap": (
+ f"{bench.symbol} traded on {skipped[0].isoformat()} but the {bars.symbol} "
+ "series has no bar for it; the session cannot be assigned"
+ ),
+ })
+ return out
+ out["session_basis"] = sess["basis"]
+ prior, stock_ret = session_return(bars, session)
+ if prior is None or stock_ret is None:
+ out.update({"status": "data_gap", "gap": f"no {bars.symbol} bar before {session.isoformat()} in range"})
+ return out
+ out["prior_session_date"] = prior.isoformat()
+ bench_ret = window_return(bench, prior, session)
+ if bench_ret is None:
+ out.update({
+ "status": "data_gap",
+ "stock_return_pct": _pct(stock_ret),
+ "gap": (
+ f"benchmark {bench.symbol} has no bar for {prior.isoformat()} or "
+ f"{session.isoformat()}"
+ ),
+ })
+ return out
+ out.update({
+ "status": "measured",
+ "stock_return_pct": _pct(stock_ret),
+ "benchmark_return_pct": _pct(bench_ret),
+ "excess_return_pct": _pct(stock_ret - bench_ret),
+ })
+ return out
+
+
+def measure_country(story_utc: datetime, bars: Bars, now_utc: datetime) -> dict:
+ """Index return on the story's session and its trailing z-score."""
+ sess = assign_session(story_utc, bars, now_utc)
+ out: dict[str, Any] = {k: sess[k] for k in ("published_local", "session_date") if k in sess}
+ if sess["status"] != "assigned":
+ out.update({"status": _UNASSIGNED[sess["status"]], "gap": sess["reason"]})
+ return out
+ session = date.fromisoformat(sess["session_date"])
+ out["session_basis"] = sess["basis"]
+ prior, ret = session_return(bars, session)
+ if prior is None or ret is None:
+ out.update({"status": "data_gap", "gap": f"no {bars.symbol} bar before {session.isoformat()} in range"})
+ return out
+ z, n = trailing_zscore(bars, session, ret)
+ out.update({
+ "status": "measured",
+ "prior_session_date": prior.isoformat(),
+ "index_return_pct": _pct(ret),
+ "zscore": z,
+ "trailing_sessions": n,
+ })
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Entities
+# ---------------------------------------------------------------------------
+
+
+def _a(phrase: str) -> str:
+ """Phrase with its indefinite article ("an energy", "a technology")."""
+ return ("an " if phrase[:1] in "aeiou" else "a ") + phrase
+
+
+def classify_companies(
+ text: str, categories: frozenset[str] | set[str] = frozenset()
+) -> tuple[list[dict], list[dict], list[dict]]:
+ """Split the companies a text names into (mapped, unmapped, excluded).
+
+ Uses ``entities.extract_entities`` and keeps one row per ticker.
+ ``categories`` are the feed categories of the story's articles.
+ """
+ lowered = text.lower()
+ mapped: list[dict] = []
+ unmapped: list[dict] = []
+ excluded: list[dict] = []
+ seen: set[str] = set()
+ for comp in entities.extract_entities(text)["entities"]["companies"]:
+ keyword = str(comp.get("name", "")).lower()
+ entity: dict[str, Any] = {"type": "company", "name": comp.get("name"), "sector": comp.get("sector")}
+ ambiguous = AMBIGUOUS_COMPANIES.get(keyword)
+ if ambiguous:
+ reason, terms, context = ambiguous
+ term = _CORROBORATOR_RE[keyword].search(lowered)
+ feed_cats = sorted(set(context) & set(categories))
+ # "meta-analysis", "apple-picking": a hyphen-joined use is the
+ # common word, so a feed category alone does not admit it.
+ standalone = any(
+ m.group(1) is None
+ for m in re.finditer(r"\b" + re.escape(keyword) + r"\b(-)?", lowered)
+ )
+ if term:
+ entity["admitted_by"] = f"corroborating term '{term.group(0)}'"
+ elif feed_cats and standalone:
+ entity["admitted_by"] = f"article from {_a(feed_cats[0])} feed"
+ else:
+ if feed_cats:
+ where = (
+ f"; the {feed_cats[0]} feed does not count because '{keyword}' "
+ "only appears hyphen-joined"
+ )
+ elif context:
+ where = f" and no article from {_a(' or '.join(context))} feed"
+ else:
+ where = ""
+ excluded.append({
+ "entity": entity,
+ "reason": (
+ f"{reason}; no corroborating term ({', '.join(terms)}) in the "
+ f"headlines{where}"
+ ),
+ })
+ continue
+ ticker = comp.get("ticker")
+ if not ticker:
+ unmapped.append({
+ "entity": entity,
+ "reason": "no public listing in the entity table (private or unlisted)",
+ })
+ continue
+ if ticker in seen:
+ continue
+ seen.add(ticker)
+ mapped.append({**entity, "ticker": ticker})
+ return mapped, unmapped, excluded
+
+
+def classify_countries(text: str) -> tuple[list[dict], list[dict]]:
+ """Split the countries a text names into (mapped to an index, unmapped)."""
+ mapped: list[dict] = []
+ unmapped: list[dict] = []
+ for c in entities.extract_entities(text)["entities"]["countries"]:
+ entity = {"type": "country", "iso3": c["iso3"], "name": c["name"]}
+ index = COUNTRY_INDEX_TICKERS.get(c["iso3"])
+ if index is None:
+ unmapped.append({
+ "entity": entity,
+ "reason": (
+ f"no primary index mapped for {c['iso3']} in the table "
+ "intel_country_stocks uses (it covers mega and major exchanges)"
+ ),
+ })
+ continue
+ mapped.append({**entity, "index": index})
+ return mapped, unmapped
+
+
+# ---------------------------------------------------------------------------
+# SEC registrant confirmation
+# ---------------------------------------------------------------------------
+
+
+async def _sec_registrants(fetcher: Fetcher) -> dict[str, dict] | None:
+ """Ticker -> {cik, name} from SEC's company_tickers.json, or None."""
+ data = await fetcher.get_json(
+ _TICKERS_URL,
+ source="sec-edgar",
+ cache_key="sec:company_tickers",
+ cache_ttl=86400,
+ headers=_SEC_HEADERS,
+ )
+ if not isinstance(data, dict):
+ return None
+ out: dict[str, dict] = {}
+ for entry in data.values():
+ if not isinstance(entry, dict) or not entry.get("ticker"):
+ continue
+ try:
+ cik = str(int(entry["cik_str"])).zfill(10)
+ except (KeyError, TypeError, ValueError):
+ continue
+ out.setdefault(str(entry["ticker"]).upper(), {"cik": cik, "name": entry.get("title", "")})
+ return out or None
+
+
+# ---------------------------------------------------------------------------
+# Composite
+# ---------------------------------------------------------------------------
+
+
+def _clean_title(title: Any) -> str:
+ # Feeds leave HTML entities in titles ("Apple&#8217;s"); curly
+ # apostrophes become straight so "BP’s" matches "bp's".
+ return html.unescape(str(title or "")).replace("’", "'")
+
+
+def _story(items: list[dict], indices: list[int]) -> dict:
+ members = [items[i] for i in indices]
+ stamps = [t for t in (parse_published(m.get("published")) for m in members) if t is not None]
+ first = min(stamps) if stamps else None
+ rep = members[0]
+ return {
+ "headline": _clean_title(rep.get("title")),
+ "link": rep.get("link", ""),
+ "articles": len(members),
+ "outlets": len({m.get("feed_name") for m in members if m.get("feed_name")}),
+ "first_published": first.strftime("%Y-%m-%dT%H:%M:%SZ") if first else None,
+ "_time": first,
+ "_text": " ".join(_clean_title(m.get("title")) for m in members),
+ "_categories": frozenset(m["category"] for m in members if m.get("category")),
+ }
+
+
+def _public(story: dict) -> dict:
+ return {k: v for k, v in story.items() if not k.startswith("_")}
+
+
+async def fetch_news_market_reaction(
+ fetcher: Fetcher,
+ category: str | None = None,
+ limit: int = 150,
+ threshold: float = 0.25,
+ min_cluster_size: int = 2,
+ include_countries: bool = True,
+ max_symbols: int = 40,
+ now: datetime | None = None,
+) -> dict:
+ """Same-session market moves of the companies and countries in the news."""
+ now_utc = (now or _utc_now()).astimezone(timezone.utc)
+ limit = max(1, min(int(limit), 300))
+ min_cluster_size = max(1, int(min_cluster_size))
+ max_symbols = max(1, min(int(max_symbols), 60))
+
+ feed = await news.fetch_news_feed(fetcher, category=category, limit=limit)
+ base = {
+ "category": category,
+ "method": dict(METHOD),
+ "interpretation": INTERPRETATION,
+ "source": "rss-aggregator + yahoo-finance + sec-edgar",
+ "timestamp": now_utc.isoformat(),
+ }
+ if feed.get("error"):
+ return {**base, "error": feed["error"]}
+ items = feed.get("items") or []
+ if not items:
+ return {**base, "error": "news feed returned no items; nothing to measure (feeds down or empty)"}
+
+ clusters = [
+ c for c in clustering.cluster_articles(items, similarity_threshold=threshold)
+ if c["member_count"] >= min_cluster_size
+ ]
+
+ data_gaps: list[str] = []
+ unmapped: list[dict] = []
+ excluded: list[dict] = []
+ # (story, entity, symbol, kind)
+ pending_rows: list[tuple[dict, dict, str, str]] = []
+ stories_with_entities = 0
+ for c in clusters:
+ story = _story(items, c["member_indices"])
+ companies, c_unmapped, c_excluded = classify_companies(story["_text"], story["_categories"])
+ countries, k_unmapped = classify_countries(story["_text"]) if include_countries else ([], [])
+ if companies or countries or c_unmapped or c_excluded or k_unmapped:
+ stories_with_entities += 1
+ for row in c_unmapped + k_unmapped:
+ unmapped.append({"story": story["headline"], **row})
+ for row in c_excluded:
+ excluded.append({"story": story["headline"], **row})
+ for comp in companies:
+ pending_rows.append((story, comp, comp["ticker"], "company"))
+ for ctry in countries:
+ pending_rows.append((story, ctry, ctry["index"], "country"))
+
+ # Symbols in first-seen order (largest clusters first), benchmarks
+ # alongside their stocks, capped so one call stays bounded.
+ wanted: list[str] = []
+ bench_of: dict[str, tuple[str | None, str | None]] = {}
+ for _story_, _entity, symbol, kind in pending_rows:
+ needed = [symbol]
+ if kind == "company":
+ bench_of[symbol] = benchmark_for(symbol)
+ if bench_of[symbol][0]:
+ needed.append(bench_of[symbol][0])
+ for s in needed:
+ if s not in wanted:
+ wanted.append(s)
+ fetch_list = wanted[:max_symbols]
+ over_budget = set(wanted[max_symbols:])
+ if over_budget:
+ data_gaps.append(
+ f"symbol budget {max_symbols} reached; not fetched: {', '.join(sorted(over_budget))}"
+ )
+
+ fetched = await asyncio.gather(*(fetch_bars(fetcher, s) for s in fetch_list))
+ bars: dict[str, Bars] = {}
+ for symbol, (b, err) in zip(fetch_list, fetched):
+ if b is not None:
+ bars[symbol] = b
+ elif err:
+ data_gaps.append(err)
+
+ registrants: dict[str, dict] | None = None
+ us_tickers = [s for s, (bench, _r) in bench_of.items() if bench == US_BENCHMARK]
+ if us_tickers:
+ registrants = await _sec_registrants(fetcher)
+ if registrants is None:
+ data_gaps.append("SEC company_tickers.json unavailable; US registrants not confirmed")
+
+ company_rows: list[dict] = []
+ country_rows: list[dict] = []
+ for story, entity, symbol, kind in pending_rows:
+ row: dict[str, Any] = {"story": _public(story), "entity": entity, "symbol": symbol}
+ if kind == "company":
+ bench_sym, bench_reason = bench_of[symbol]
+ row["benchmark"] = bench_sym
+ if bench_sym == US_BENCHMARK and registrants is not None:
+ row["registrant"] = registrants.get(symbol.upper())
+ if row["registrant"] is None:
+ row["registrant_note"] = "ticker not found in SEC company_tickers.json"
+ b = bars.get(symbol)
+ if story["_time"] is None:
+ row.update({"status": "data_gap", "gap": "no parseable published time in the cluster"})
+ elif story["_time"] > now_utc + FUTURE_TOLERANCE:
+ row.update({
+ "status": "data_gap",
+ "gap": (
+ f"story timestamp {story['first_published']} is later than the collection "
+ f"time {now_utc.strftime('%Y-%m-%dT%H:%M:%SZ')} (a timestamp error in the "
+ "feed or in its parsing)"
+ ),
+ })
+ elif b is None:
+ row.update({
+ "status": "data_gap",
+ "gap": f"no daily bars for {symbol}" + (" (symbol budget)" if symbol in over_budget else ""),
+ })
+ elif kind == "country":
+ row["exchange_timezone"] = b.tz_name
+ row.update(measure_country(story["_time"], b, now_utc))
+ else:
+ row["exchange_timezone"] = b.tz_name
+ if bench_sym is None:
+ row.update({"status": "data_gap", "gap": bench_reason})
+ elif bench_sym not in bars:
+ row.update({
+ "status": "data_gap",
+ "gap": f"no daily bars for benchmark {bench_sym}"
+ + (" (symbol budget)" if bench_sym in over_budget else ""),
+ })
+ else:
+ row.update(measure_company(story["_time"], b, bars[bench_sym], now_utc))
+ (company_rows if kind == "company" else country_rows).append(row)
+
+ def _count(rows: list[dict], status: str) -> int:
+ return sum(1 for r in rows if r.get("status") == status)
+
+ return {
+ **base,
+ "company_reactions": company_rows,
+ "country_reactions": country_rows,
+ "unmapped": unmapped,
+ "excluded": excluded,
+ "summary": {
+ "news_items": len(items),
+ "stories_considered": len(clusters),
+ "stories_with_entities": stories_with_entities,
+ "min_cluster_size": min_cluster_size,
+ "companies_measured": _count(company_rows, "measured"),
+ "companies_pending": _count(company_rows, "pending"),
+ "companies_data_gap": _count(company_rows, "data_gap"),
+ "countries_measured": _count(country_rows, "measured"),
+ "countries_pending": _count(country_rows, "pending"),
+ "countries_data_gap": _count(country_rows, "data_gap"),
+ "unmapped": len(unmapped),
+ "excluded": len(excluded),
+ "symbols_fetched": len(bars),
+ },
+ "data_gaps": data_gaps,
+ }
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index af3204c..c6f60e9 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -1605,6 +1605,108 @@ def shipping_cmd(ctx: click.Context) -> None:
console.print(table)
+def _signed_pct(value: Any) -> str:
+ """A measured percent, coloured; a missing one says so, never 0%."""
+ if value is None:
+ return "[dim]n/a[/dim]"
+ style = "green" if value >= 0 else "red"
+ return f"[{style}]{value:+.2f}%[/{style}]"
+
+
[email protected](name="news-reaction")
[email protected]("--category", "-c", default=None, help="RSS category (finance, technology, energy, ...)")
[email protected]("--limit", "-n", default=150, type=int, help="News items to cluster (max 300)")
[email protected]("--min-size", default=2, type=int, help="Minimum articles per story (1 includes single-article stories)")
[email protected]("--no-countries", is_flag=True, help="Skip the country-index rows")
+def news_reaction(
+ ctx: click.Context, category: str | None, limit: int, min_size: int, no_countries: bool
+) -> None:
+ """Market move on the session of each story naming a company or country."""
+ from .analysis.news_market import fetch_news_market_reaction
+
+ data = _run(
+ fetch_news_market_reaction(
+ _get_fetcher(),
+ category=category,
+ limit=limit,
+ min_cluster_size=min_size,
+ include_countries=not no_countries,
+ )
+ )
+ if _bail_on_error(ctx, data):
+ return
+
+ s = data.get("summary", {})
+ console.print(
+ f"[bold]News vs market reaction[/bold]: {s.get('stories_considered', 0)} stories, "
+ f"{s.get('stories_with_entities', 0)} naming a company or country; "
+ f"{s.get('unmapped', 0)} unmapped, {s.get('excluded', 0)} excluded as ambiguous"
+ )
+ console.print(f"[dim]{escape(str(data.get('interpretation', '')))}[/dim]\n")
+
+ table = Table(title="Companies", box=box.SIMPLE_HEAVY)
+ table.add_column("Story", max_width=48)
+ table.add_column("Company", style="bold")
+ table.add_column("Ticker")
+ table.add_column("Session")
+ table.add_column("Stock", justify="right")
+ table.add_column("Benchmark", justify="right")
+ table.add_column("Excess", justify="right")
+ table.add_column("Status")
+ for r in data.get("company_reactions", []):
+ status = r.get("status", "")
+ table.add_row(
+ _cell(r.get("story", {}).get("headline", "")),
+ _cell(r.get("entity", {}).get("name", "")),
+ _cell(f"{r.get('symbol', '')} vs {r.get('benchmark') or 'none'}"),
+ _cell(r.get("session_date") or "-"),
+ _signed_pct(r.get("stock_return_pct")),
+ _signed_pct(r.get("benchmark_return_pct")),
+ _signed_pct(r.get("excess_return_pct")),
+ _cell(status if status == "measured" else f"{status}: {r.get('gap', '')}"),
+ )
+ console.print(table)
+
+ if not no_countries:
+ table = Table(title="Countries", box=box.SIMPLE_HEAVY)
+ table.add_column("Story", max_width=48)
+ table.add_column("Country", style="bold")
+ table.add_column("Index")
+ table.add_column("Session")
+ table.add_column("Index move", justify="right")
+ table.add_column("z", justify="right")
+ table.add_column("Status")
+ for r in data.get("country_reactions", []):
+ status = r.get("status", "")
+ z = r.get("zscore")
+ table.add_row(
+ _cell(r.get("story", {}).get("headline", "")),
+ _cell(r.get("entity", {}).get("name", "")),
+ _cell(r.get("symbol", "")),
+ _cell(r.get("session_date") or "-"),
+ _signed_pct(r.get("index_return_pct")),
+ "[dim]n/a[/dim]" if z is None else f"{z:+.2f}",
+ _cell(status if status == "measured" else f"{status}: {r.get('gap', '')}"),
+ )
+ console.print(table)
+
+ # Unmapped names are listed, not dropped; one line per name and reason.
+ unmapped: dict[tuple[str, str], int] = {}
+ for row in data.get("unmapped", []):
+ key = (str(row.get("entity", {}).get("name", "")), str(row.get("reason", "")))
+ unmapped[key] = unmapped.get(key, 0) + 1
+ for (name, reason), count in unmapped.items():
+ stories = f" ({count} stories)" if count > 1 else ""
+ console.print(f"[dim]Unmapped:[/dim] {escape(name)}{stories}: {escape(reason)}")
+ for row in data.get("excluded", []):
+ console.print(
+ f"[yellow]Excluded:[/yellow] {escape(str(row.get('entity', {}).get('name', '')))}"
+ f" in \"{escape(str(row.get('story', '')))}\": {escape(str(row.get('reason', '')))}"
+ )
+ _print_data_gaps(data)
+
+
# ---------------------------------------------------------------------------
# Social & Health
# ---------------------------------------------------------------------------
diff --git a/src/world_intel_mcp/tests/test_cli.py b/src/world_intel_mcp/tests/test_cli.py
index 5fdbb1b..0406b2f 100644
--- a/src/world_intel_mcp/tests/test_cli.py
+++ b/src/world_intel_mcp/tests/test_cli.py
@@ -2688,3 +2688,137 @@ def test_aoi_changes_error_dict_json_mode_passes_raw_dict(
assert result.exit_code == 0
assert '"error"' in result.output
assert "store exploded" in result.output
+
+
+# ---------------------------------------------------------------------------
+# News vs market reaction
+# ---------------------------------------------------------------------------
+
+# Rows trimmed from a live run on 2026-10-17 (technology and energy feeds).
+_NEWS_REACTION = {
+ "company_reactions": [
+ {
+ "story": {"headline": "British watchdog seeks tougher terms around Microsoft's dominance"},
+ "entity": {"type": "company", "name": "Microsoft"},
+ "symbol": "MSFT",
+ "benchmark": "SPY",
+ "session_date": "2026-10-16",
+ "status": "measured",
+ "stock_return_pct": -1.9261,
+ "benchmark_return_pct": -1.1065,
+ "excess_return_pct": -0.8196,
+ },
+ {
+ "story": {"headline": "Aramco CEO Warns Oil Squeeze is [red]Serious[/red]"},
+ "entity": {"type": "company", "name": "Aramco"},
+ "symbol": "2222.SR",
+ "benchmark": "^TASI",
+ "status": "data_gap",
+ "gap": "no daily bars for benchmark ^TASI",
+ },
+ ],
+ "country_reactions": [
+ {
+ "story": {"headline": "China Adjusts VAT Exemption For Exported Vehicles"},
+ "entity": {"type": "country", "iso3": "CHN", "name": "China"},
+ "symbol": "000001.SS",
+ "session_date": "2026-10-16",
+ "status": "measured",
+ "index_return_pct": 0.2376,
+ "zscore": 0.73,
+ },
+ {
+ "story": {"headline": "India becomes the latest country to report rogue AI agent activity"},
+ "entity": {"type": "country", "iso3": "IND", "name": "India"},
+ "symbol": "^NSEI",
+ "status": "pending",
+ "gap": "no ^NSEI session on or after 2026-10-17 yet (last bar 2026-10-16)",
+ },
+ ],
+ "unmapped": [{"story": "x", "entity": {"name": "Openai"}, "reason": "no public listing"}],
+ "excluded": [
+ {
+ "story": "Shell fire hits border town",
+ "entity": {"type": "company", "name": "Shell"},
+ "reason": "'shell' is also an artillery round",
+ }
+ ],
+ "summary": {"stories_considered": 146, "stories_with_entities": 22, "unmapped": 1, "excluded": 1},
+ "data_gaps": ["^TASI: Yahoo chart returned no data (request failed or symbol unknown)"],
+ "interpretation": "Same-session co-movement only. This is not a trading signal.",
+}
+
+
+def test_news_reaction_renders_rows_gaps_and_options(monkeypatch: pytest.MonkeyPatch) -> None:
+ import world_intel_mcp.analysis.news_market as news_market
+
+ calls: list = []
+ monkeypatch.setattr(news_market, "fetch_news_market_reaction", _fake(_NEWS_REACTION, calls))
+ result = _invoke("news-reaction", "-c", "finance", "--limit", "80", "--min-size", "1")
+ assert result.exit_code == 0
+ assert calls == [{"category": "finance", "limit": 80, "min_cluster_size": 1, "include_countries": True}]
+ out = result.output
+ assert "146 stories, 22 naming a company or country; 1 unmapped, 1 excluded as ambiguous" in out
+ assert "not a trading signal" in out
+ assert "MSFT vs SPY" in out
+ assert "-1.93%" in out and "-1.11%" in out and "-0.82%" in out
+ assert "+0.24%" in out and "+0.73" in out
+ # A gap renders n/a and its reason, never a 0% move
+ assert "data_gap: no daily bars for benchmark ^TASI" in out
+ assert "pending: no ^NSEI session on or after 2026-10-17" in out
+ assert "+0.00%" not in out and "-0.00%" not in out
+ assert "n/a" in out
+ # Remote headline markup renders literally
+ assert "[red]Serious[/red]" in out
+ assert "Excluded: Shell" in out
+ assert "Gap: ^TASI: Yahoo chart returned no data" in out
+
+
+def test_news_reaction_lists_unmapped_names(monkeypatch: pytest.MonkeyPatch) -> None:
+ import world_intel_mcp.analysis.news_market as news_market
+
+ no_listing = "no public listing in the entity table (private or unlisted)"
+ no_index = "no primary index mapped for RUS in the table intel_country_stocks uses"
+ data = {
+ **_NEWS_REACTION,
+ "unmapped": [
+ {"story": "a", "entity": {"type": "company", "name": "Openai"}, "reason": no_listing},
+ {"story": "b", "entity": {"type": "company", "name": "Openai"}, "reason": no_listing},
+ {"story": "c", "entity": {"type": "country", "name": "Russia"}, "reason": no_index},
+ ],
+ }
+ monkeypatch.setattr(news_market, "fetch_news_market_reaction", _fake(data))
+ result = _invoke("news-reaction")
+ assert result.exit_code == 0
+ out = " ".join(result.output.split())
+ assert f"Unmapped: Openai (2 stories): {no_listing}" in out
+ assert f"Unmapped: Russia: {no_index}" in out
+
+
+def test_news_reaction_no_countries_skips_country_table(monkeypatch: pytest.MonkeyPatch) -> None:
+ import world_intel_mcp.analysis.news_market as news_market
+
+ calls: list = []
+ monkeypatch.setattr(news_market, "fetch_news_market_reaction", _fake(_NEWS_REACTION, calls))
+ result = _invoke("news-reaction", "--no-countries")
+ assert result.exit_code == 0
+ assert calls[0]["include_countries"] is False
+ assert "Countries" not in result.output
+ assert "China Adjusts VAT" not in result.output
+
+
+def test_news_reaction_error_dict_and_json_mode(monkeypatch: pytest.MonkeyPatch) -> None:
+ import world_intel_mcp.analysis.news_market as news_market
+
+ err = {"error": "news feed returned no items; nothing to measure (feeds down or empty)"}
+ monkeypatch.setattr(news_market, "fetch_news_market_reaction", _fake(err))
+ result = _invoke("news-reaction")
+ assert result.exit_code == 0
+ assert "Error: news feed returned no items" in result.output
+ assert "Companies" not in result.output
+
+ monkeypatch.setattr(news_market, "fetch_news_market_reaction", _fake(_NEWS_REACTION))
+ result = _invoke("--json-output", "news-reaction")
+ assert result.exit_code == 0
+ assert '"excess_return_pct": -0.8196' in result.output
+ assert "Companies" not in result.output
diff --git a/src/world_intel_mcp/tests/test_news_market.py b/src/world_intel_mcp/tests/test_news_market.py
new file mode 100644
index 0000000..12376b0
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_news_market.py
@@ -0,0 +1,827 @@
+"""Tests for analysis.news_market: news vs market reaction.
+
+Yahoo v8 chart fixtures reproduce the live response shape captured
+2026-10-17 (meta incl. exchangeTimezoneName and currentTradingPeriod,
+timestamp[], indicators.quote[0].close, indicators.adjclose[0].adjclose)
+and carry the live daily closes of AAPL, SPY and 000001.SS for the dates
+used, so the expected returns are real market moves: Labor Day
+(2026-09-07) and China's Mid-Autumn / Golden Week closures are in the
+data, and SPY's 2026-09-18 ex-dividend bar is where close and adjusted
+close disagree. The SEC fixture is a subset of the live
+company_tickers.json. Clustering and entity matching run for real on
+headlines in the live feed-item shape; only the RSS fetch is faked.
+"""
+
+from datetime import datetime, timezone
+
+import httpx
+import pytest
+import respx
+
+import world_intel_mcp.fetcher as fetcher_mod
+from world_intel_mcp.analysis import news_market as nm
+from world_intel_mcp.cache import Cache
+from world_intel_mcp.circuit_breaker import CircuitBreaker
+from world_intel_mcp.fetcher import Fetcher
+
+_CHART = "https://query1.finance.yahoo.com/v8/finance/chart/{}"
+_SEC = "https://www.sec.gov/files/company_tickers.json"
+
+# Live currentTradingPeriod blocks (2026-10-16 sessions).
+_US_PERIOD = {
+ "pre": {"timezone": "EDT", "start": 1792137600, "end": 1792157400, "gmtoffset": -14400},
+ "regular": {"timezone": "EDT", "start": 1792157400, "end": 1792180800, "gmtoffset": -14400},
+ "post": {"timezone": "EDT", "start": 1792180800, "end": 1792195200, "gmtoffset": -14400},
+}
+_SH_PERIOD = {
+ "pre": {"timezone": "CST", "start": 1792114200, "end": 1792114200, "gmtoffset": 28800},
+ "regular": {"timezone": "CST", "start": 1792114200, "end": 1792134000, "gmtoffset": 28800},
+ "post": {"timezone": "CST", "start": 1792134000, "end": 1792134000, "gmtoffset": 28800},
+}
+
+# (timestamp = session open, close, adjclose), live values.
+_AAPL = [
+ (1788442200, 328.2099914550781, 328.2099914550781), # 2026-09-03
+ (1788528600, 319.9700012207031, 319.9700012207031), # 2026-09-04
+ (1788874200, 316.2200012207031, 316.2200012207031), # 2026-09-08 (after Labor Day)
+ (1789651800, 337.0, 337.0), # 2026-09-17
+ (1789738200, 336.1300048828125, 336.1300048828125), # 2026-09-18
+ (1791379800, 336.6700134277344, 336.6700134277344), # 2026-10-07
+ (1791466200, 340.4200134277344, 340.4200134277344), # 2026-10-08
+ (1791552600, 336.6400146484375, 336.6400146484375), # 2026-10-09
+ (1791811800, 340.9700012207031, 340.9700012207031), # 2026-10-12
+ (1791898200, 341.2699890136719, 341.2699890136719), # 2026-10-13
+ (1791984600, 342.9599914550781, 342.9599914550781), # 2026-10-14
+ (1792071000, 342.0, 342.0), # 2026-10-15
+ (1792157400, 343.4599914550781, 343.4599914550781), # 2026-10-16
+]
+_SPY = [
+ (1788442200, 773.1699829101562, 771.2548217773438), # 2026-09-03
+ (1788528600, 770.1900024414062, 768.2822265625), # 2026-09-04
+ (1788874200, 765.9600219726562, 764.0626831054688), # 2026-09-08
+ (1789651800, 762.5999755859375, 760.7109985351562), # 2026-09-17
+ (1789738200, 761.6900024414062, 761.6900024414062), # 2026-09-18 (ex-dividend)
+ (1791379800, 777.219970703125, 777.219970703125), # 2026-10-07
+ (1791466200, 773.9299926757812, 773.9299926757812), # 2026-10-08
+ (1791552600, 778.5700073242188, 778.5700073242188), # 2026-10-09
+ (1791811800, 778.0999755859375, 778.0999755859375), # 2026-10-12
+ (1791898200, 778.010009765625, 778.010009765625), # 2026-10-13
+ (1791984600, 769.5999755859375, 769.5999755859375), # 2026-10-14
+ (1792071000, 771.7899780273438, 771.7899780273438), # 2026-10-15
+ (1792157400, 763.25, 763.25), # 2026-10-16
+]
+_SSE = [
+ (1789435800, 3864.279052734375), # 2026-09-15
+ (1789522200, 3891.60107421875), # 2026-09-16
+ (1789608600, 3875.60400390625), # 2026-09-17
+ (1789695000, 3911.87109375), # 2026-09-18
+ (1789954200, 3949.906982421875), # 2026-09-21
+ (1790040600, 3952.1279296875), # 2026-09-22
+ (1790127000, 3936.52001953125), # 2026-09-23
+ (1790213400, 3888.3740234375), # 2026-09-24 (09-25 Mid-Autumn: closed)
+ (1790559000, 3823.62109375), # 2026-09-28
+ (1790645400, 3830.450927734375), # 2026-09-29
+ (1790731800, 3842.195068359375), # 2026-09-30 (Golden Week to 10-07)
+ (1791423000, 3811.904052734375), # 2026-10-08
+ # Live close written as its exact binary fraction (the decimal form
+ # trips a PII scanner's digit-run rule).
+ (1791509400, 1952661 / 512), # 2026-10-09
+ (1791768600, 3797.241943359375), # 2026-10-12
+ (1791855000, 3800.864990234375), # 2026-10-13
+ (1791941400, 3767.22705078125), # 2026-10-14
+ (1792027800, 3707.47607421875), # 2026-10-15
+ (1792114200, 3716.283935546875), # 2026-10-16
+]
+
+_SEC_SUBSET = {
+ "0": {"cik_str": 1045810, "ticker": "NVDA", "title": "NVIDIA CORP"},
+ "1": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."},
+ "133": {"cik_str": 936468, "ticker": "LMT", "title": "LOCKHEED MARTIN CORP"},
+ "7177": {"cik_str": 884394, "ticker": "SPY", "title": "SPDR S&P 500 ETF TRUST"},
+}
+
+# Saturday 2026-10-17 16:00 UTC: US and Shanghai closed for the weekend.
+_SATURDAY = datetime(2026, 10, 17, 16, 0, tzinfo=timezone.utc)
+
+
+def _chart(symbol, bars, *, tz="America/New_York", abbr="EDT", gmtoffset=-14400,
+ period=None, instrument="EQUITY", exchange="NMS", full="NasdaqGS"):
+ stamps = [b[0] for b in bars]
+ closes = [b[1] for b in bars]
+ adj = [b[2] if len(b) > 2 else b[1] for b in bars]
+ return {
+ "chart": {
+ "result": [{
+ "meta": {
+ "currency": "USD" if tz == "America/New_York" else "CNY",
+ "symbol": symbol,
+ "exchangeName": exchange,
+ "fullExchangeName": full,
+ "instrumentType": instrument,
+ "regularMarketTime": stamps[-1],
+ "gmtoffset": gmtoffset,
+ "timezone": abbr,
+ "exchangeTimezoneName": tz,
+ "chartPreviousClose": closes[0],
+ "currentTradingPeriod": period or _US_PERIOD,
+ "dataGranularity": "1d",
+ "range": "3mo",
+ },
+ "timestamp": stamps,
+ "indicators": {
+ "quote": [{"open": closes, "high": closes, "low": closes,
+ "close": closes, "volume": [1000] * len(bars)}],
+ "adjclose": [{"adjclose": adj}],
+ },
+ }],
+ "error": None,
+ }
+ }
+
+
+def _sse_chart(bars=_SSE):
+ return _chart("000001.SS", bars, tz="Asia/Shanghai", abbr="CST", gmtoffset=28800,
+ period=_SH_PERIOD, instrument="INDEX", exchange="SHH", full="Shanghai")
+
+
+def _bars(symbol, payload):
+ bars, err = nm.parse_bars(symbol, payload)
+ assert err is None
+ return bars
+
+
+def _item(title, published, category="technology", feed="Ars Technica"):
+ """Feed item in the live sources/news.py shape."""
+ return {
+ "title": title,
+ "link": "https://example.com/" + title.lower().replace(" ", "-"),
+ "published": published,
+ "summary": "",
+ "feed_name": feed,
+ "category": category,
+ "source_tier": "major",
+ }
+
+
+def fast_fetcher(tmp_path, monkeypatch):
+ """Fetcher without retries or Yahoo spacing so failure paths stay fast."""
+ monkeypatch.setattr(fetcher_mod, "_YAHOO_MIN_INTERVAL", 0.0)
+ monkeypatch.setitem(fetcher_mod._SOURCE_RATE_LIMITS, "yahoo-finance", 0.0)
+ return Fetcher(cache=Cache(db_path=tmp_path / "nm.db"), breaker=CircuitBreaker(),
+ default_timeout=5.0, max_retries=0)
+
+
+def _feed(monkeypatch, items):
+ async def _fake(fetcher, category=None, limit=50):
+ return {"items": items, "count": len(items), "source": "rss-aggregator"}
+
+ monkeypatch.setattr(nm.news, "fetch_news_feed", _fake)
+
+
+# ---------------------------------------------------------------------------
+# Story time
+# ---------------------------------------------------------------------------
+
+
+def test_parse_published_forms():
+ assert nm.parse_published("2026-10-16T19:43:52Z") == datetime(2026, 10, 16, 19, 43, 52, tzinfo=timezone.utc)
+ # RFC 822 with an offset (a feed's raw string when feedparser could not parse it)
+ assert nm.parse_published("Sat, 17 Oct 2026 19:43:52 +0500") == datetime(2026, 10, 17, 14, 43, 52, tzinfo=timezone.utc)
+ # A naive timestamp states no zone: unknown, not assumed UTC
+ assert nm.parse_published("2026-10-16T19:43:52") is None
+ assert nm.parse_published("yesterday") is None
+ assert nm.parse_published(None) is None
+ assert nm.parse_published("") is None
+
+
+# ---------------------------------------------------------------------------
+# Bars
+# ---------------------------------------------------------------------------
+
+
+def test_parse_bars_reads_live_shape():
+ bars = _bars("AAPL", _chart("AAPL", _AAPL))
+ assert bars.tz_name == "America/New_York"
+ assert bars.close_time.isoformat() == "16:00:00"
+ assert bars.dates[0].isoformat() == "2026-09-03"
+ assert bars.dates[-1].isoformat() == "2026-10-16"
+ assert len(bars.dates) == 13
+ sse = _bars("000001.SS", _sse_chart())
+ assert sse.close_time.isoformat() == "15:00:00"
+
+
+def test_parse_bars_uses_adjusted_close_on_ex_dividend_day():
+ """SPY went ex-dividend 2026-09-18: close-to-close reads -0.1193%,
+ the adjusted series +0.1287%. The adjusted one is the return."""
+ bars = _bars("SPY", _chart("SPY", _SPY))
+ prior, ret = nm.session_return(bars, datetime(2026, 9, 18).date())
+ assert prior.isoformat() == "2026-09-17"
+ assert round(ret * 100, 4) == 0.1287
+
+
+def test_parse_bars_null_close_is_a_missing_bar_not_zero():
+ payload = _chart("AAPL", _AAPL[-3:])
+ payload["chart"]["result"][0]["indicators"]["adjclose"][0]["adjclose"][1] = None
+ bars = _bars("AAPL", payload)
+ assert [d.isoformat() for d in bars.dates] == ["2026-10-14", "2026-10-16"]
+ assert 0.0 not in bars.closes.values()
+
+
+def test_parse_bars_failures_name_the_symbol():
+ assert nm.parse_bars("^TASI", None) == (
+ None, "^TASI: Yahoo chart returned no data (request failed or symbol unknown)")
+ bars, err = nm.parse_bars("ZZZZ", {"chart": {"result": None, "error": {
+ "code": "Not Found", "description": "No data found, symbol may be delisted"}}})
+ assert bars is None and err == "ZZZZ: Yahoo chart error (No data found, symbol may be delisted)"
+ broken = _chart("AAPL", _AAPL)
+ del broken["chart"]["result"][0]["meta"]["exchangeTimezoneName"]
+ bars, err = nm.parse_bars("AAPL", broken)
+ assert bars is None and err.startswith("AAPL: unexpected Yahoo chart structure")
+ mismatched = _chart("AAPL", _AAPL)
+ mismatched["chart"]["result"][0]["indicators"] = {"quote": [{"close": [1.0]}]}
+ assert nm.parse_bars("AAPL", mismatched)[1] == (
+ "AAPL: Yahoo chart has no close series matching its timestamps")
+ empty = _chart("AAPL", _AAPL[:2])
+ empty["chart"]["result"][0]["indicators"]["adjclose"][0]["adjclose"] = [None, None]
+ assert nm.parse_bars("AAPL", empty)[1] == "AAPL: Yahoo chart has no usable closes"
+
+
+def test_parse_bars_same_date_later_bar_wins():
+ # Yahoo can append a live bar stamped later on the same local date.
+ bars_in = _AAPL[-2:] + [(1792180700, 344.0, 344.0)] # 2026-10-16 15:58 EDT
+ bars = _bars("AAPL", _chart("AAPL", bars_in))
+ assert bars.dates[-1].isoformat() == "2026-10-16"
+ assert bars.closes[bars.dates[-1]] == 344.0
+
+
+# ---------------------------------------------------------------------------
+# Session assignment
+# ---------------------------------------------------------------------------
+
+
+def _assign(published, bars, now=_SATURDAY):
+ return nm.assign_session(nm.parse_published(published), bars, now)
+
+
+def test_session_before_close_is_same_session():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ s = _assign("2026-10-15T19:59:59Z", aapl) # 15:59:59 EDT
+ assert (s["status"], s["session_date"], s["basis"]) == ("assigned", "2026-10-15", "same_session")
+ assert s["published_local"] == "2026-10-15T15:59:59-04:00"
+
+
+def test_session_at_or_after_close_is_next_session():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ at_close = _assign("2026-10-15T20:00:00Z", aapl) # exactly 16:00 EDT
+ assert (at_close["session_date"], at_close["basis"]) == ("2026-10-16", "next_session_after_close")
+ late = _assign("2026-10-16T01:30:00Z", aapl) # 21:30 EDT on the 15th
+ assert (late["session_date"], late["basis"]) == ("2026-10-16", "next_session_after_close")
+
+
+def test_session_weekend_maps_to_monday():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ s = _assign("2026-10-10T15:00:00Z", aapl) # Saturday
+ assert (s["session_date"], s["basis"]) == ("2026-10-12", "next_session_non_trading_day")
+ friday_late = _assign("2026-10-09T21:00:00Z", aapl) # Friday after close
+ assert friday_late["session_date"] == "2026-10-12"
+ assert friday_late["after_close"] is True
+
+
+def test_session_holiday_from_the_listings_own_bars():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ labor_day = _assign("2026-09-07T14:00:00Z", aapl) # Monday 10:00 EDT, NYSE closed
+ assert (labor_day["session_date"], labor_day["basis"]) == ("2026-09-08", "next_session_non_trading_day")
+ sse = _bars("000001.SS", _sse_chart())
+ golden_week = _assign("2026-10-02T03:00:00Z", sse) # 11:00 Shanghai, market closed
+ assert (golden_week["session_date"], golden_week["basis"]) == ("2026-10-08", "next_session_non_trading_day")
+ mid_autumn = _assign("2026-09-25T02:00:00Z", sse) # Friday 10:00 Shanghai, closed
+ assert mid_autumn["session_date"] == "2026-09-28"
+
+
+def test_session_timezone_is_the_exchanges():
+ """One instant, two exchanges: 16:00 Shanghai is after its close but
+ 04:00 in New York is before the US session of the same date."""
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ sse = _bars("000001.SS", _sse_chart())
+ midday = "2026-10-15T05:00:00Z" # 13:00 Shanghai, 01:00 New York
+ assert _assign(midday, sse)["session_date"] == "2026-10-15"
+ assert _assign(midday, aapl)["session_date"] == "2026-10-15"
+ evening = "2026-10-15T08:00:00Z" # 16:00 Shanghai (after close), 04:00 New York
+ assert _assign(evening, sse)["session_date"] == "2026-10-16"
+ assert _assign(evening, aapl)["session_date"] == "2026-10-15"
+
+
+def test_session_not_yet_traded_is_pending():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ s = _assign("2026-10-16T21:00:00Z", aapl) # Friday after close; now Saturday
+ assert s["status"] == "pending"
+ assert s["reason"] == "no AAPL session on or after 2026-10-17 yet (last bar 2026-10-16)"
+
+
+def test_session_in_progress_is_pending():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ midday = datetime(2026, 10, 16, 18, 0, tzinfo=timezone.utc) # 14:00 EDT Friday
+ s = _assign("2026-10-16T13:00:00Z", aapl, now=midday)
+ assert s["status"] == "pending"
+ assert s["session_date"] == "2026-10-16"
+ assert "has not closed yet" in s["reason"]
+ after = datetime(2026, 10, 16, 20, 0, tzinfo=timezone.utc) # 16:00 EDT: closed
+ assert _assign("2026-10-16T13:00:00Z", aapl, now=after)["status"] == "assigned"
+
+
+def test_session_before_the_bar_range_is_out_of_range():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ s = _assign("2025-01-28T00:26:00Z", aapl)
+ assert s["status"] == "out_of_range"
+ assert "predates the first AAPL bar in range (2026-09-03)" in s["reason"]
+
+
+# ---------------------------------------------------------------------------
+# Measurement
+# ---------------------------------------------------------------------------
+
+
+def test_measure_company_excess_return_arithmetic():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ spy = _bars("SPY", _chart("SPY", _SPY))
+ # After the 2026-10-15 close -> the 2026-10-16 session.
+ row = nm.measure_company(nm.parse_published("2026-10-15T20:30:00Z"), aapl, spy, _SATURDAY)
+ assert row["status"] == "measured"
+ assert row["session_date"] == "2026-10-16"
+ assert row["prior_session_date"] == "2026-10-15"
+ assert row["session_basis"] == "next_session_after_close"
+ assert row["stock_return_pct"] == 0.4269 # 343.46 / 342.00 - 1
+ assert row["benchmark_return_pct"] == -1.1065 # 763.25 / 771.79 - 1
+ assert row["excess_return_pct"] == 1.5334 # from unrounded returns
+
+
+def test_measure_company_holiday_and_adjusted_benchmark():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ spy = _bars("SPY", _chart("SPY", _SPY))
+ labor_day = nm.measure_company(nm.parse_published("2026-09-07T14:00:00Z"), aapl, spy, _SATURDAY)
+ assert (labor_day["session_date"], labor_day["prior_session_date"]) == ("2026-09-08", "2026-09-04")
+ assert labor_day["session_basis"] == "next_session_non_trading_day"
+ assert (labor_day["stock_return_pct"], labor_day["benchmark_return_pct"], labor_day["excess_return_pct"]) == (
+ -1.172, -0.5492, -0.6228)
+ ex_div = nm.measure_company(nm.parse_published("2026-09-18T14:00:00Z"), aapl, spy, _SATURDAY)
+ assert (ex_div["stock_return_pct"], ex_div["benchmark_return_pct"], ex_div["excess_return_pct"]) == (
+ -0.2582, 0.1287, -0.3869)
+
+
+def test_measure_company_weekend_story():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ spy = _bars("SPY", _chart("SPY", _SPY))
+ row = nm.measure_company(nm.parse_published("2026-10-10T15:00:00Z"), aapl, spy, _SATURDAY)
+ assert (row["session_date"], row["prior_session_date"]) == ("2026-10-12", "2026-10-09")
+ assert (row["stock_return_pct"], row["benchmark_return_pct"], row["excess_return_pct"]) == (
+ 1.2862, -0.0604, 1.3466)
+
+
+def test_measure_company_benchmark_missing_bar_is_a_gap_with_no_excess():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ spy = _bars("SPY", _chart("SPY", [b for b in _SPY if b[0] != 1792071000])) # no 10-15
+ row = nm.measure_company(nm.parse_published("2026-10-16T14:00:00Z"), aapl, spy, _SATURDAY)
+ assert row["status"] == "data_gap"
+ assert row["stock_return_pct"] == 0.4269
+ assert "benchmark_return_pct" not in row and "excess_return_pct" not in row
+ assert row["gap"] == "benchmark SPY has no bar for 2026-10-15 or 2026-10-16"
+
+
+def test_measure_company_stock_missing_a_day_the_benchmark_traded_is_a_gap():
+ """No 2026-10-15 AAPL bar while SPY traded: a halt or missing data,
+ not a holiday, so the story is not shifted to the 16th."""
+ aapl = _bars("AAPL", _chart("AAPL", [b for b in _AAPL if b[0] != 1792071000]))
+ spy = _bars("SPY", _chart("SPY", _SPY))
+ row = nm.measure_company(nm.parse_published("2026-10-15T14:00:00Z"), aapl, spy, _SATURDAY)
+ assert row["status"] == "data_gap"
+ assert row["gap"] == "SPY traded on 2026-10-15 but the AAPL series has no bar for it; the session cannot be assigned"
+ assert "stock_return_pct" not in row
+
+
+def test_measure_company_timezone_mismatch_is_a_gap():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ sse = _bars("000001.SS", _sse_chart())
+ row = nm.measure_company(nm.parse_published("2026-10-15T14:00:00Z"), aapl, sse, _SATURDAY)
+ assert row["status"] == "data_gap"
+ assert "trades in Asia/Shanghai" in row["gap"]
+
+
+def test_measure_company_first_bar_has_no_prior():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ spy = _bars("SPY", _chart("SPY", _SPY))
+ row = nm.measure_company(nm.parse_published("2026-09-03T14:00:00Z"), aapl, spy, _SATURDAY)
+ assert row["status"] == "data_gap"
+ assert row["gap"] == "no AAPL bar before 2026-09-03 in range"
+
+
+def test_measure_company_pending_and_out_of_range_carry_no_return():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ spy = _bars("SPY", _chart("SPY", _SPY))
+ pending = nm.measure_company(nm.parse_published("2026-10-16T21:00:00Z"), aapl, spy, _SATURDAY)
+ assert pending["status"] == "pending" and "stock_return_pct" not in pending
+ old = nm.measure_company(nm.parse_published("2025-01-28T00:26:00Z"), aapl, spy, _SATURDAY)
+ assert old["status"] == "data_gap" and "stock_return_pct" not in old
+
+
+def test_measure_country_return_and_zscore():
+ sse = _bars("000001.SS", _sse_chart())
+ row = nm.measure_country(nm.parse_published("2026-10-16T01:00:00Z"), sse, _SATURDAY)
+ assert row["status"] == "measured"
+ assert (row["session_date"], row["prior_session_date"]) == ("2026-10-16", "2026-10-15")
+ assert row["index_return_pct"] == 0.2376
+ # 16 earlier session returns in the fixture (09-16 .. 10-15)
+ assert (row["zscore"], row["trailing_sessions"]) == (0.6, 16)
+ golden = nm.measure_country(nm.parse_published("2026-10-02T03:00:00Z"), sse, _SATURDAY)
+ assert (golden["session_date"], golden["prior_session_date"], golden["index_return_pct"]) == (
+ "2026-10-08", "2026-09-30", -0.7884)
+
+
+def test_measure_country_short_history_has_no_zscore():
+ sse = _bars("000001.SS", _sse_chart(_SSE[-6:]))
+ row = nm.measure_country(nm.parse_published("2026-10-16T01:00:00Z"), sse, _SATURDAY)
+ assert row["status"] == "measured"
+ assert row["zscore"] is None and row["trailing_sessions"] == 4
+ pending = nm.measure_country(nm.parse_published("2026-10-16T09:00:00Z"), sse, _SATURDAY)
+ assert pending["status"] == "pending"
+ older = nm.measure_country(nm.parse_published("2026-10-08T01:00:00Z"), sse, _SATURDAY)
+ assert older["status"] == "data_gap"
+ assert older["gap"] == (
+ "story session 2026-10-08 predates the first 000001.SS bar in range (2026-10-09)")
+
+
+def test_measure_country_first_bar_has_no_prior():
+ sse = _bars("000001.SS", _sse_chart(_SSE[-6:])) # first bar 2026-10-09
+ row = nm.measure_country(nm.parse_published("2026-10-09T01:00:00Z"), sse, _SATURDAY)
+ assert row["status"] == "data_gap"
+ assert row["gap"] == "no 000001.SS bar before 2026-10-09 in range"
+
+
+def test_trailing_zscore_flat_series_is_none():
+ flat = [(1789435800 + i * 86400, 100.0) for i in range(14)]
+ bars = _bars("FLAT", _chart("FLAT", flat))
+ assert nm.trailing_zscore(bars, bars.dates[-1], 0.01) == (None, 13)
+
+
+def test_benchmark_for():
+ assert nm.benchmark_for("AAPL") == ("SPY", None)
+ assert nm.benchmark_for("BA.L") == ("^FTSE", None)
+ assert nm.benchmark_for("RHM.DE") == ("^GDAXI", None)
+ assert nm.benchmark_for("005930.KS") == ("^KS11", None)
+ assert nm.benchmark_for("2222.SR") == ("^TASI", None)
+ assert nm.benchmark_for("X.QQ") == (None, "no benchmark mapped for exchange suffix .QQ")
+
+
+def test_benchmark_for_country_without_index(monkeypatch):
+ monkeypatch.setitem(nm.SUFFIX_COUNTRY, "XX", "ZZZ")
+ assert nm.benchmark_for("ACME.XX") == (None, "no primary index mapped for ZZZ (exchange suffix .XX)")
+
+
+# ---------------------------------------------------------------------------
+# Entities
+# ---------------------------------------------------------------------------
+
+
+def test_ambiguous_company_excluded_with_reason():
+ mapped, unmapped, excluded = nm.classify_companies("Shell fire hits border town", {"geopolitics"})
+ assert mapped == [] and unmapped == []
+ assert excluded[0]["entity"]["name"] == "Shell"
+ assert excluded[0]["reason"].startswith("'shell' is also an artillery round")
+ assert "and no article from a energy feed" in excluded[0]["reason"]
+ # "25 bp" is basis points; a finance feed does not make it the company
+ _, _, bp = nm.classify_companies("Fed cuts rates by 25 bp", {"finance"})
+ assert bp[0]["entity"]["name"] == "Bp"
+ assert "basis points" in bp[0]["reason"]
+
+
+def test_ambiguous_company_admitted_by_term_or_feed_category():
+ mapped, _, excluded = nm.classify_companies("Apple foldable iPhones sell out in hours", {"geopolitics"})
+ assert excluded == []
+ assert mapped == [{"type": "company", "name": "Apple", "sector": "tech",
+ "admitted_by": "corroborating term 'iphones'", "ticker": "AAPL"}]
+ mapped, _, excluded = nm.classify_companies(
+ "Meta removes language that may have allowed it to scrape news sites", {"technology"})
+ assert excluded == [] and mapped[0]["ticker"] == "META"
+ assert mapped[0]["admitted_by"] == "article from a technology feed"
+ # Samsung has no feed context: only a corroborating term admits it
+ _, _, excluded = nm.classify_companies("Samsung shipyard wins LNG carrier order", {"technology"})
+ assert excluded[0]["reason"].endswith("in the headlines")
+
+
+def test_hyphen_joined_name_is_not_admitted_by_feed_category():
+ mapped, _, excluded = nm.classify_companies(
+ "Meta-analysis links screen time to sleep loss", {"technology"})
+ assert mapped == []
+ assert excluded[0]["entity"]["name"] == "Meta"
+ assert excluded[0]["reason"] == (
+ "'meta' is also a common word and prefix; no corroborating term (facebook, "
+ "instagram, whatsapp, zuckerberg, meta platforms) in the headlines; the "
+ "technology feed does not count because 'meta' only appears hyphen-joined")
+ # a corroborating term still admits a hyphen-joined use
+ mapped, _, excluded = nm.classify_companies("Meta-owned WhatsApp adds usernames", {"geopolitics"})
+ assert excluded == []
+ assert mapped[0]["ticker"] == "META"
+ assert mapped[0]["admitted_by"] == "corroborating term 'whatsapp'"
+ # one standalone use is enough for the feed category to count
+ mapped, _, excluded = nm.classify_companies(
+ "Meta trims teen features after a meta-analysis on screen time", {"technology"})
+ assert excluded == []
+ assert mapped[0]["admitted_by"] == "article from a technology feed"
+
+
+def test_exclusion_reason_article_agrees_with_feed_name():
+ _, _, excluded = nm.classify_companies("Chevron insignia stolen from base", {"military"})
+ assert excluded[0]["reason"].endswith("in the headlines and no article from an energy feed")
+ _, _, excluded = nm.classify_companies("Apple orchards hit by early frost", {"geopolitics"})
+ assert excluded[0]["reason"].endswith(
+ "in the headlines and no article from a technology or finance feed")
+
+
+def test_unambiguous_and_unlisted_companies():
+ mapped, unmapped, excluded = nm.classify_companies(
+ "Lockheed Martin and OpenAI sign deal; Google and Alphabet shares rise", set())
+ assert [m["ticker"] for m in mapped] == ["LMT", "GOOGL"] # one row per ticker
+ assert unmapped == [{"entity": {"type": "company", "name": "Openai", "sector": "ai"},
+ "reason": "no public listing in the entity table (private or unlisted)"}]
+ assert excluded == []
+
+
+def test_classify_countries():
+ mapped, unmapped = nm.classify_countries("China and Ukraine talks")
+ assert mapped == [{"type": "country", "iso3": "CHN", "name": "China", "index": "000001.SS"}]
+ assert unmapped[0]["entity"]["iso3"] == "UKR"
+ assert "no primary index mapped for UKR" in unmapped[0]["reason"]
+
+
+# ---------------------------------------------------------------------------
+# Composite (real clustering + entities; Yahoo + SEC via respx)
+# ---------------------------------------------------------------------------
+
+
+def _mock_markets(fail=()):
+ for symbol, payload in {
+ "AAPL": _chart("AAPL", _AAPL),
+ "SPY": _chart("SPY", _SPY, instrument="ETF", exchange="PCX", full="NYSEArca"),
+ "LMT": _chart("LMT", _AAPL),
+ "000001.SS": _sse_chart(),
+ }.items():
+ route = respx.get(_CHART.format(symbol))
+ if symbol in fail:
+ route.mock(return_value=httpx.Response(
+ 404, json={"chart": {"result": None, "error": {"code": "Not Found"}}}))
+ else:
+ route.mock(return_value=httpx.Response(200, json=payload))
+ respx.get(_CHART.format("NVDA")).mock(return_value=httpx.Response(500, text="upstream error"))
+
+
+_ITEMS = [
+ _item("Apple foldable iPhones sell out in hours", "2026-10-15T20:30:00Z"),
+ _item("Lockheed Martin wins hypersonic contract", "2026-10-16T21:00:00Z", "military", "Defense One"),
+ _item("Shell fire hits border town", "2026-10-16T12:00:00Z", "geopolitics", "BBC World"),
+ _item("OpenAI raises new funding round", "2026-10-16T12:00:00Z"),
+ _item("Ukraine grain corridor reopens", "2026-10-16T12:00:00Z", "geopolitics", "BBC World"),
+ _item("China stimulus lifts property developers", "2026-10-16T01:00:00Z", "finance", "CNBC"),
+ _item("Nvidia unveils new AI chip", "2026-10-16T14:00:00Z"),
+]
+
+
+async def test_composite_end_to_end(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, list(_ITEMS))
+ _mock_markets()
+ sec = respx.get(_SEC).mock(return_value=httpx.Response(200, json=_SEC_SUBSET))
+
+ out = await nm.fetch_news_market_reaction(fast_fetcher, min_cluster_size=1, now=_SATURDAY)
+
+ assert "error" not in out
+ rows = {r["symbol"]: r for r in out["company_reactions"]}
+ apple = rows["AAPL"]
+ assert apple["status"] == "measured"
+ assert apple["story"]["headline"] == "Apple foldable iPhones sell out in hours"
+ assert apple["story"]["first_published"] == "2026-10-15T20:30:00Z"
+ assert apple["benchmark"] == "SPY"
+ assert apple["registrant"] == {"cik": "0000320193", "name": "Apple Inc."}
+ assert apple["exchange_timezone"] == "America/New_York"
+ assert (apple["session_date"], apple["session_basis"]) == ("2026-10-16", "next_session_after_close")
+ assert (apple["stock_return_pct"], apple["benchmark_return_pct"], apple["excess_return_pct"]) == (
+ 0.4269, -1.1065, 1.5334)
+
+ lmt = rows["LMT"]
+ assert lmt["status"] == "pending" # Friday after close; Monday not yet traded
+ assert lmt["registrant"]["name"] == "LOCKHEED MARTIN CORP"
+
+ # Failed quote: a data gap with no number, never 0%
+ nvda = rows["NVDA"]
+ assert nvda["status"] == "data_gap"
+ assert nvda["gap"] == "no daily bars for NVDA"
+ assert all(k not in nvda for k in ("stock_return_pct", "benchmark_return_pct", "excess_return_pct"))
+ assert "NVDA: Yahoo chart returned no data (request failed or symbol unknown)" in out["data_gaps"]
+
+ china = out["country_reactions"]
+ assert [(c["entity"]["iso3"], c["symbol"], c["status"], c["index_return_pct"]) for c in china] == [
+ ("CHN", "000001.SS", "measured", 0.2376)]
+
+ assert [e["entity"]["name"] for e in out["excluded"]] == ["Shell"]
+ assert sorted((u["entity"].get("iso3") or u["entity"]["name"]) for u in out["unmapped"]) == ["Openai", "UKR"]
+
+ s = out["summary"]
+ assert (s["news_items"], s["stories_considered"], s["stories_with_entities"]) == (7, 7, 7)
+ assert (s["companies_measured"], s["companies_pending"], s["companies_data_gap"]) == (1, 1, 1)
+ assert (s["countries_measured"], s["unmapped"], s["excluded"]) == (1, 2, 1)
+ assert s["symbols_fetched"] == 4 # AAPL, SPY, LMT, 000001.SS; NVDA failed
+ assert sec.call_count == 1
+ assert out["interpretation"].startswith("Same-session co-movement only")
+ assert "not a trading signal" in out["interpretation"]
+ assert "next session" in out["method"]["session_rule"]
+
+
+async def test_composite_benchmark_failure_and_sec_outage(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [_ITEMS[0]])
+ _mock_markets(fail=("SPY",))
+ respx.get(_SEC).mock(return_value=httpx.Response(503))
+
+ out = await nm.fetch_news_market_reaction(fast_fetcher, min_cluster_size=1, now=_SATURDAY)
+
+ row = out["company_reactions"][0]
+ assert row["status"] == "data_gap"
+ assert row["gap"] == "no daily bars for benchmark SPY"
+ assert "stock_return_pct" not in row
+ assert "registrant" not in row
+ assert "SEC company_tickers.json unavailable; US registrants not confirmed" in out["data_gaps"]
+ assert "SPY: Yahoo chart returned no data (request failed or symbol unknown)" in out["data_gaps"]
+
+
+async def test_composite_unknown_sec_ticker_is_noted(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [_ITEMS[0]])
+ _mock_markets()
+ respx.get(_SEC).mock(return_value=httpx.Response(200, json={
+ "0": {"cik_str": 1045810, "ticker": "NVDA", "title": "NVIDIA CORP"},
+ "1": {"ticker": "BROKEN"}, # malformed rows are skipped, not fatal
+ "2": "not a row",
+ }))
+ out = await nm.fetch_news_market_reaction(fast_fetcher, min_cluster_size=1, now=_SATURDAY)
+ row = out["company_reactions"][0]
+ assert row["registrant"] is None
+ assert row["registrant_note"] == "ticker not found in SEC company_tickers.json"
+ assert row["status"] == "measured"
+
+
+async def test_composite_default_needs_multi_article_clusters(fast_fetcher, monkeypatch):
+ """Default min_cluster_size=2: a story two outlets carry is measured,
+ single-article stories are not considered."""
+ items = [
+ _item("Apple foldable iPhones sell out in hours", "2026-10-15T21:00:00Z", feed="The Verge"),
+ _item("Apple foldable iPhones sell out within hours", "2026-10-15T20:30:00Z", "finance", "CNBC"),
+ _item("Nvidia unveils new AI chip", "2026-10-16T14:00:00Z"),
+ ]
+ _feed(monkeypatch, items)
+ _mock_markets()
+ respx.get(_SEC).mock(return_value=httpx.Response(200, json=_SEC_SUBSET))
+
+ out = await nm.fetch_news_market_reaction(fast_fetcher, now=_SATURDAY)
+
+ assert out["summary"]["stories_considered"] == 1
+ [row] = out["company_reactions"]
+ assert row["story"]["articles"] == 2 and row["story"]["outlets"] == 2
+ # Earliest member time is the story time
+ assert row["story"]["first_published"] == "2026-10-15T20:30:00Z"
+ assert row["status"] == "measured" and row["excess_return_pct"] == 1.5334
+
+
+async def test_composite_story_time_problems_are_gaps(fast_fetcher, monkeypatch):
+ items = [
+ _item("Apple foldable iPhones sell out in hours", "2026-10-17T21:18:34Z"), # after "now"
+ _item("Lockheed Martin wins hypersonic contract", "not a date", "military"),
+ ]
+ _feed(monkeypatch, items)
+ _mock_markets()
+ respx.get(_SEC).mock(return_value=httpx.Response(200, json=_SEC_SUBSET))
+
+ out = await nm.fetch_news_market_reaction(fast_fetcher, min_cluster_size=1, now=_SATURDAY)
+
+ rows = {r["symbol"]: r for r in out["company_reactions"]}
+ assert rows["AAPL"]["status"] == "data_gap"
+ assert rows["AAPL"]["gap"] == (
+ "story timestamp 2026-10-17T21:18:34Z is later than the collection time "
+ "2026-10-17T16:00:00Z (feed timestamp error)")
+ assert rows["LMT"]["status"] == "data_gap"
+ assert rows["LMT"]["gap"] == "no parseable published time in the cluster"
+
+
+async def test_composite_html_entities_in_titles(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [_item("Apple&#8217;s updated App Store rules", "2026-10-15T20:30:00Z", "geopolitics")])
+ _mock_markets()
+ respx.get(_SEC).mock(return_value=httpx.Response(200, json=_SEC_SUBSET))
+ out = await nm.fetch_news_market_reaction(fast_fetcher, min_cluster_size=1, now=_SATURDAY)
+ [row] = out["company_reactions"]
+ assert row["story"]["headline"] == "Apple's updated App Store rules"
+ assert row["entity"]["admitted_by"] == "corroborating term 'app store'"
+
+
+async def test_composite_symbol_budget_and_no_countries(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [_ITEMS[0], _ITEMS[1], _ITEMS[5]])
+ _mock_markets()
+ respx.get(_SEC).mock(return_value=httpx.Response(200, json=_SEC_SUBSET))
+
+ out = await nm.fetch_news_market_reaction(
+ fast_fetcher, min_cluster_size=1, max_symbols=2, include_countries=False, now=_SATURDAY)
+
+ assert out["country_reactions"] == []
+ rows = {r["symbol"]: r for r in out["company_reactions"]}
+ assert rows["AAPL"]["status"] == "measured" # AAPL + SPY fit the budget of 2
+ assert rows["LMT"]["status"] == "data_gap"
+ assert rows["LMT"]["gap"] == "no daily bars for LMT (symbol budget)"
+ assert out["data_gaps"] == ["symbol budget 2 reached; not fetched: LMT"]
+
+
+async def test_composite_foreign_listing_without_benchmark(fast_fetcher, monkeypatch):
+ """A listing whose exchange has no mapped index is a gap, not a
+ comparison against the wrong market."""
+ monkeypatch.setitem(nm.entities._COMPANY_KW, "acme", {"ticker": "ACME.PA", "sector": "test"})
+ monkeypatch.setattr(nm.entities, "_COMPANY_RE", nm.entities._compile_keywords(nm.entities._COMPANY_KW))
+ _feed(monkeypatch, [_item("Acme recalls widgets", "2026-10-16T12:00:00Z")])
+ with respx.mock:
+ respx.get(_CHART.format("ACME.PA")).mock(return_value=httpx.Response(200, json=_chart(
+ "ACME.PA", _AAPL, tz="Europe/Paris", abbr="CEST", gmtoffset=7200)))
+ out = await nm.fetch_news_market_reaction(fast_fetcher, min_cluster_size=1, now=_SATURDAY)
+ [row] = out["company_reactions"]
+ assert row["benchmark"] is None
+ assert row["status"] == "data_gap"
+ assert row["gap"] == "no benchmark mapped for exchange suffix .PA"
+ assert "registrant" not in row
+
+
+async def test_composite_benchmark_cut_by_symbol_budget(fast_fetcher, monkeypatch):
+ monkeypatch.setitem(nm.entities._COMPANY_KW, "acme", {"ticker": "ACME.L", "sector": "test"})
+ monkeypatch.setattr(nm.entities, "_COMPANY_RE", nm.entities._compile_keywords(nm.entities._COMPANY_KW))
+ _feed(monkeypatch, [_item("Acme recalls widgets", "2026-10-16T12:00:00Z")])
+ with respx.mock:
+ respx.get(_CHART.format("ACME.L")).mock(return_value=httpx.Response(200, json=_chart(
+ "ACME.L", _AAPL, tz="Europe/London", abbr="BST", gmtoffset=3600)))
+ out = await nm.fetch_news_market_reaction(
+ fast_fetcher, min_cluster_size=1, max_symbols=1, now=_SATURDAY)
+ [row] = out["company_reactions"]
+ assert row["benchmark"] == "^FTSE"
+ assert row["status"] == "data_gap"
+ assert row["gap"] == "no daily bars for benchmark ^FTSE (symbol budget)"
+ assert out["data_gaps"] == ["symbol budget 1 reached; not fetched: ^FTSE"]
+
+
+async def test_composite_empty_feed_is_an_error_not_zero(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [])
+ out = await nm.fetch_news_market_reaction(fast_fetcher, now=_SATURDAY)
+ assert out["error"].startswith("news feed returned no items")
+ assert "company_reactions" not in out
+
+
+async def test_composite_feed_error_passes_through(fast_fetcher, monkeypatch):
+ async def _bad(fetcher, category=None, limit=50):
+ return {"items": [], "count": 0, "error": "Unknown category 'nope'."}
+
+ monkeypatch.setattr(nm.news, "fetch_news_feed", _bad)
+ out = await nm.fetch_news_market_reaction(fast_fetcher, category="nope", now=_SATURDAY)
+ assert out["error"] == "Unknown category 'nope'."
+ assert out["category"] == "nope"
+
+
+# ---------------------------------------------------------------------------
+# Tool registration
+# ---------------------------------------------------------------------------
+
+
+async def test_tool_handler_passes_arguments(monkeypatch):
+ from world_intel_mcp import tools
+ from world_intel_mcp.tools import news_market as tool_mod
+
+ calls = []
+
+ async def _fake(fetcher, **kwargs):
+ calls.append(kwargs)
+ return {"ok": True}
+
+ monkeypatch.setattr(nm, "fetch_news_market_reaction", _fake)
+ assert "intel_news_market_reaction" in tools.ALL_HANDLERS
+ assert [t.name for t in tool_mod.TOOLS] == ["intel_news_market_reaction"]
+ result = await tools.ALL_HANDLERS["intel_news_market_reaction"](
+ {"category": "finance", "min_cluster_size": 1, "include_countries": False})
+ assert result == {"ok": True}
+ assert calls == [{"category": "finance", "limit": 150, "threshold": 0.25, "min_cluster_size": 1,
+ "include_countries": False, "max_symbols": 40}]
diff --git a/src/world_intel_mcp/tools/__init__.py b/src/world_intel_mcp/tools/__init__.py
index d1b68a7..ea58643 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,
+ news_market,
society,
synthesis,
system,
@@ -49,6 +50,7 @@ _MODULES = [
geospatial,
synthesis,
finance,
+ news_market,
vector,
aoi,
system,
diff --git a/src/world_intel_mcp/tools/news_market.py b/src/world_intel_mcp/tools/news_market.py
new file mode 100644
index 0000000..80fa535
--- /dev/null
+++ b/src/world_intel_mcp/tools/news_market.py
@@ -0,0 +1,80 @@
+"""News vs market reaction tool (Phase 29).
+
+Same-session moves of the companies and countries named in recent story
+clusters; see ``analysis/news_market.py`` for the method.
+"""
+
+from typing import Any
+
+from mcp.types import Tool
+
+from .. import runtime
+
+TOOLS: list[Tool] = [
+ Tool(
+ name="intel_news_market_reaction",
+ description=(
+ "Companies and countries named in recent news story clusters, mapped to tickers "
+ "(SEC-confirmed for US listings) and country indices, with the move on the story's "
+ "market session from Yahoo daily bars: stock, benchmark (SPY or the exchange "
+ "country's index) and excess return; country index return with a trailing z-score. "
+ "A story after the close maps to the next session, weekends and holidays to the next "
+ "trading day, all in the exchange's timezone. Unmapped and ambiguous names are "
+ "listed with reasons; a failed quote is a data gap, never a 0% move. Same-session "
+ "co-movement, not causation; not a trading signal."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "category": {
+ "type": "string",
+ "description": "RSS feed category filter (finance, technology, geopolitics, energy, etc.). Default: all",
+ },
+ "limit": {
+ "type": "integer",
+ "description": "News items to cluster (default 150, max 300)",
+ "default": 150,
+ },
+ "threshold": {
+ "type": "number",
+ "description": "Jaccard similarity threshold for clustering (default 0.25)",
+ "default": 0.25,
+ },
+ "min_cluster_size": {
+ "type": "integer",
+ "description": "Minimum articles per story (default 2; 1 includes single-article stories)",
+ "default": 2,
+ },
+ "include_countries": {
+ "type": "boolean",
+ "description": "Also measure the primary index of countries named (default true)",
+ "default": True,
+ },
+ "max_symbols": {
+ "type": "integer",
+ "description": "Cap on tickers and indices fetched in one call (default 40, max 60)",
+ "default": 40,
+ },
+ },
+ },
+ ),
+]
+
+
+async def _news_market_reaction(arguments: dict[str, Any]) -> Any:
+ from ..analysis.news_market import fetch_news_market_reaction
+
+ return await fetch_news_market_reaction(
+ runtime.fetcher,
+ category=arguments.get("category"),
+ limit=arguments.get("limit", 150),
+ threshold=arguments.get("threshold", 0.25),
+ min_cluster_size=arguments.get("min_cluster_size", 2),
+ include_countries=arguments.get("include_countries", True),
+ max_symbols=arguments.get("max_symbols", 40),
+ )
+
+
+HANDLERS = {
+ "intel_news_market_reaction": _news_market_reaction,
+}