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.

news_market: review fixes (stale copies, bar finality, sessions, entities)

Phoenix Agent (mac-studio)9a3b8df04cd4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f675f0c..65983e0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,29 +5,45 @@
### 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.
+ table's ticker; a US ticker is annotated with its registrant when SEC's
+ company_tickers.json lists it) 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,
+ `published` in the cluster; that article also gives the headline and link)
+ 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. Each row names the close it used (`close_time_used`). A
+ session that has not closed, or whose last bar Yahoo has not finalized
+ (its regularMarketTime is before the close), is `pending`.
+- Honest gaps: a failed quote, an expired cached chart or SEC file served
+ during an outage, a missing benchmark bar, a stock series missing a day its
+ benchmark traded (also between the two dates of a return), a cluster whose
+ articles map to different sessions, a story timestamp later than the
+ collection time and a story older than the bar range are each a `data_gap`
+ row or line with the reason and no number, never a 0% move. A bar Yahoo
+ fills for a day without trading (open, high, low and close equal to the
+ previous close, no volume) is dropped, not read as a 0% session.
+ `data_gaps` also names a listing whose Yahoo close differs from its zone's
+ standard close, and a chart without adjusted closes. Stories whose earliest
+ article is older than `max_age_hours` (default 168) are left out and
+ counted. Unmapped names (companies without a ticker in the entity table,
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.
+ corroborating term or an article comes from a feed where the company sense
+ dominates (a hyphen-joined use such as "meta-analysis" does not count); a
+ phrase marking the other sense ("big apple", "amazon rainforest", "chevron
+ ruling", "25 bp") excludes the name. A country gets an index row only when
+ the headlines use its name; one named only by a demonym, capital or code,
+ or inside a longer name such as "Gulf of Mexico", is listed as excluded.
+ 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
diff --git a/README.md b/README.md
index e285433..d4a424b 100644
--- a/README.md
+++ b/README.md
@@ -203,7 +203,7 @@ collector.py (daemon) ─┘
### 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 |
+| `intel_news_market_reaction` | Companies and countries named in recent story clusters, mapped to tickers from the entity table (US tickers annotated with their SEC registrant) 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; a session not yet closed or not yet final is pending. Unmapped and ambiguous names are listed with reasons; a failed quote or an expired cached copy 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 43cca17..1cf3ce3 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -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 | :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 |
+| 1 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :yellow_circle: Built 2026-10-17, unreleased; 7 test expectations await correction at merge: `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); a last bar Yahoo has not finalized is pending. 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: |
diff --git a/src/world_intel_mcp/analysis/news_market.py b/src/world_intel_mcp/analysis/news_market.py
index d1f29c4..63bc3c5 100644
--- a/src/world_intel_mcp/analysis/news_market.py
+++ b/src/world_intel_mcp/analysis/news_market.py
@@ -3,11 +3,11 @@
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.
+to a listing: a company to the ticker in the entity table (a US ticker is
+annotated with its registrant when SEC's ``company_tickers.json`` lists
+it); 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
@@ -20,24 +20,39 @@ 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.
+session. A session that has not closed yet, or whose last bar Yahoo has
+not finalized (its regularMarketTime is before the close), 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.
+not a trading signal. A failed quote, or an expired cached chart served
+because Yahoo failed, 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.
+ on an early-close day its shortened close is applied to every day. A
+ data_gaps line says so when that close differs from the zone's standard
+ close in ``STANDARD_CLOSE``; zones missing from that table get no check.
+- A bar counts as final once Yahoo's regularMarketTime reaches the close.
+ Last prints after the stated close are common (measured 2026-10-15/16:
+ ^NSEI 1 minute, ^TWII 3, ^FTSE 5, 2222.SR 20, ^MXX 26, ^GDAXI and BA.L
+ 30 minutes after it), so a chart fetched in that window counts as final
+ before its last print. A listing whose last trade came before the close
+ stays pending until the next bar arrives.
+- Yahoo's regular period for Seoul listings ends 15:00, but the closing
+ print came at 15:30 (005930.KS, 2026-10-16): those rows use 15:00 and
+ carry the nonstandard-close data_gaps line.
- 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.
+- Admitting an ambiguous company name by its feed is a stated heuristic,
+ and the phrases that mark the other sense are a short list; 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.
+- Story times are read from ``sources/news.py`` as it reports them; 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.
"""
@@ -45,15 +60,17 @@ Gaps / not covered:
from __future__ import annotations
import asyncio
+import functools
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 typing import Any, NamedTuple
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+from ..config.countries import TIER1_COUNTRIES
from ..config.exchanges import COUNTRY_INDEX_TICKERS
from ..fetcher import Fetcher
from ..sources import news
@@ -71,6 +88,30 @@ 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)
+# Stories whose earliest article is older than this are left out; the
+# upper limit is about the 3-month bar range.
+MAX_AGE_HOURS = 168
+MAX_AGE_LIMIT = 2160
+# A Jaccard threshold of 0 would merge every pair of headlines.
+THRESHOLD_MIN = 0.01
+
+# Regular close on a full trading day per exchange timezone, measured on
+# the 2026-10-16 sessions (2026-10-15 for Riyadh): Yahoo's
+# currentTradingPeriod.regular.end for the zone's listings, except
+# Asia/Seoul, where Yahoo's period ends 15:00 but the closing print of
+# 005930.KS (regularMarketTime) came at 15:30:05. Only used to flag a
+# close that differs. America/Mexico_City is left out: its hours may move
+# with US daylight saving time, and only one season was measured.
+STANDARD_CLOSE: dict[str, time] = {
+ "America/New_York": time(16, 0),
+ "Europe/London": time(16, 30),
+ "Europe/Berlin": time(17, 30),
+ "Asia/Riyadh": time(15, 0),
+ "Asia/Seoul": time(15, 30),
+ "Asia/Shanghai": time(15, 0),
+ "Asia/Taipei": time(13, 30),
+ "Asia/Kolkata": time(15, 30),
+}
# Yahoo exchange suffix -> ISO-3 of the exchange's country, so a foreign
# listing is benchmarked against the index intel_country_stocks maps.
@@ -82,66 +123,123 @@ SUFFIX_COUNTRY: dict[str, str] = {
"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).
+# Finance feeds whose headlines are mostly company news; FT World,
+# Bloomberg and Zero Hedge also carry world and macro stories.
+_COMPANY_DESKS = ("CNBC", "MarketWatch", "WSJ Markets")
+
+
+class Ambiguous(NamedTuple):
+ """An entity-table company keyword that is also an ordinary word or
+ names more than one listed company."""
+
+ reason: str
+ # Terms that settle the company sense when the headlines carry one.
+ terms: tuple[str, ...]
+ # Feed category -> the feeds in it where the company sense dominates
+ # (None: every feed in the category).
+ context: dict[str, tuple[str, ...] | None]
+ # Phrases (regex) that mark the other sense; one excludes the name
+ # whatever else admits it.
+ other_sense: tuple[str, ...] = ()
+
+
# 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": (
+# or one of its articles comes from a context feed and the name is not
+# only hyphen-joined, and no other-sense phrase appears; otherwise it is
+# excluded with the reason.
+AMBIGUOUS_COMPANIES: dict[str, Ambiguous] = {
+ "apple": Ambiguous(
"'apple' is also the fruit",
("iphone", "ipad", "macbook", "app store", "tim cook", "apple inc", "airpods", "ios"),
- ("technology", "finance"),
+ {"technology": None, "finance": _COMPANY_DESKS},
+ (r"big apple", r"apple hospitality",
+ r"apple (?:orchards?|growers?|harvests?|cider|pies?|juice|trees?)"),
),
- "amazon": (
+ "amazon": Ambiguous(
"'amazon' is also the river and rainforest",
("aws", "amazon web services", "bezos", "jassy", "amazon.com", "alexa", "prime video"),
- ("technology", "finance"),
+ {"technology": None, "finance": _COMPANY_DESKS},
+ (r"pan-amazon\w*", r"(?:brazilian|peruvian|colombian|ecuadorian|bolivian) amazon",
+ r"amazon (?:rainforest|basin|river|region|forests?|fires?)", r"rainforests?", r"deforestation"),
),
- "meta": (
+ "meta": Ambiguous(
"'meta' is also a common word and prefix",
("facebook", "instagram", "whatsapp", "zuckerberg", "meta platforms"),
- ("technology", "finance"),
+ {"technology": None, "finance": _COMPANY_DESKS},
+ # "meta-analysis" is left to the hyphen rule, so a corroborating
+ # term still admits "Meta trims ... after a meta-analysis".
+ (r"meta analys[ie]s",),
),
- "shell": (
+ "shell": Ambiguous(
"'shell' is also an artillery round, a casing and a shell company",
("shell plc", "royal dutch shell", "shell oil", "sawan"),
- ("energy",),
+ {"energy": None},
+ (r"shell (?:fire|hits?|strikes?|struck|lands?|landed|explodes|exploded"
+ r"|compan(?:y|ies)|corporations?)", r"artillery", r"mortars?"),
),
- "bp": (
+ "bp": Ambiguous(
# 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",),
+ {"energy": None},
+ (r"\d+(?:\.\d+)? ?bps?", r"basis points?", r"blood pressure"),
),
- "alphabet": (
+ "alphabet": Ambiguous(
"'alphabet' is also a common word",
("google", "waymo", "pichai", "alphabet inc"),
- ("technology", "finance"),
+ {"technology": None, "finance": _COMPANY_DESKS},
+ (r"alphabet soup", r"(?:phonetic|latin|cyrillic|greek|arabic|hebrew) alphabet"),
),
- "chevron": (
+ "chevron": Ambiguous(
"'chevron' is also an insignia and a US legal doctrine",
- ("chevron corp", "chevron's", "oil", "refinery", "crude", "wirth"),
- ("energy",),
+ # Not "oil", "crude", "refinery" or "chevron's": a headline on the
+ # doctrine can carry each of them.
+ ("chevron corp", "chevron corporation", "wirth", "hess"),
+ # Only the oil and gas trade feeds: the energy category's policy
+ # feeds can mean the doctrine.
+ {"energy": ("Oil Price", "Rigzone")},
+ (r"chevron (?:ruling|doctrine|deference|decision|precedent)", r"post-chevron",
+ r"(?:overturn\w*|overrul\w*|scrapp\w*|demise of) chevron", r"loper bright"),
),
- "samsung": (
+ "samsung": Ambiguous(
"'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()
+ kw: re.compile(r"\b(?:" + "|".join(re.escape(t) for t in amb.terms) + r")s?\b")
+ for kw, amb in AMBIGUOUS_COMPANIES.items()
+}
+_OTHER_SENSE_RE: dict[str, re.Pattern[str]] = {
+ kw: re.compile(r"\b(?:" + "|".join(amb.other_sense) + r")\b")
+ for kw, amb in AMBIGUOUS_COMPANIES.items()
+ if amb.other_sense
+}
+
+# A country index row needs the country's name: a demonym, capital or
+# code also names airlines, oceans and food ("American Airlines",
+# "Indian Ocean", "Tex-Mex"), and some longer names contain the
+# country's name without meaning it.
+COUNTRY_NAMES: dict[str, tuple[str, ...]] = {"USA": ("United States", "USA")}
+NOT_THE_COUNTRY: dict[str, tuple[str, ...]] = {
+ "USA": ("united states steel", "usa today", "team usa"),
+ "CHN": ("south china sea", "east china sea"),
+ "MEX": ("new mexico", "gulf of mexico", "mexico city"),
+ "TWN": ("taiwan semiconductor",),
}
METHOD = {
"story_time": (
- "Earliest `published` timestamp among the cluster's articles (UTC, as "
- "the RSS feeds state it)."
+ "Earliest `published` timestamp among the cluster's articles, as sources/news.py "
+ "reports it, read as UTC (a time without a zone counts as unknown). An article "
+ "time later than the collection time makes the story a data gap. The headline and "
+ "link are the earliest article's; last_published and span_hours show how far the "
+ "cluster spreads, and a cluster whose first and last articles map to different "
+ "sessions of a listing is a data gap for that listing. Stories whose earliest "
+ "article is older than max_age_hours are left out and counted in the summary."
),
"session_rule": (
"The story time is converted to the listing's exchange timezone "
@@ -150,18 +248,27 @@ METHOD = {
"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."
+ "applied to every day, so early-close days are not modelled; each row gives "
+ "the close it used (close_time_used), and a data_gaps line names a listing whose "
+ "close differs from its zone's standard close. A listing's last bar counts only "
+ "once Yahoo's regularMarketTime is at or after that day's close; until then the "
+ "row is pending."
),
"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 "
+ "close of the prior session in the listing's own daily bars, minus 1 (raw "
+ "closes, with a data_gaps line, when the chart has no adjusted closes). A bar "
+ "Yahoo fills for a day without trading (open = high = low = close = the "
+ "previous close, volume 0) is dropped, so that day counts as no session. 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."
+ "return - benchmark return, a simple difference, not beta-adjusted. A session "
+ "the benchmark traded that the stock series lacks, inside that window or where "
+ "the story's session would be, makes the row a data gap."
),
"countries": (
"Country rows measure the country's primary index on the assigned session, "
@@ -171,11 +278,19 @@ METHOD = {
"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."
+ "(apple, amazon, meta, shell, bp, alphabet, chevron, samsung) are kept only "
+ "with a corroborating term in the headlines, or an article from a feed where the "
+ "company sense dominates: technology feeds, and the CNBC, MarketWatch and WSJ "
+ "Markets finance feeds, for apple, amazon, meta and alphabet; energy feeds for "
+ "shell and bp; Oil Price and Rigzone for chevron; none for samsung. A feed counts "
+ "only when the name stands on its own, not hyphen-joined ('meta-analysis', "
+ "'Pan-Amazon'). A phrase marking the other sense ('big apple', 'amazon "
+ "rainforest', 'chevron ruling', 'shell fire', '25 bp') excludes the name whatever "
+ "else admits it. Each kept name says what admitted it and each excluded one why. "
+ "A country gets an index row only when the headlines use its name (for the United "
+ "States also 'USA'); one named only by a demonym, capital or code, or inside a "
+ "longer name such as 'New Mexico' or 'Gulf of Mexico', is listed as excluded with "
+ "the reason."
),
}
@@ -190,6 +305,12 @@ def _utc_now() -> datetime:
return datetime.now(timezone.utc)
+def _age(data: dict) -> str:
+ """How old the fetcher's expired fallback copy is, for a gap line."""
+ age = data.get("_stale_age_seconds")
+ return f"{age:.0f} s old" if isinstance(age, (int, float)) else "of unknown age"
+
+
# ---------------------------------------------------------------------------
# Story time
# ---------------------------------------------------------------------------
@@ -222,22 +343,56 @@ def parse_published(value: Any) -> datetime | None:
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]):
+ def __init__(
+ self,
+ symbol: str,
+ tz: ZoneInfo,
+ close_time: time,
+ closes: dict[date, float],
+ market_time: datetime | None = None,
+ notes: list[str] | None = None,
+ ):
self.symbol = symbol
self.tz = tz
self.close_time = close_time
self.closes = closes
self.dates = sorted(closes)
+ # Yahoo's regularMarketTime: the last bar is final only once the
+ # last regular-market print is at or after that day's close.
+ self.market_time = market_time
+ self.last_final = market_time is not None and market_time >= datetime.combine(
+ self.dates[-1], close_time, tz
+ )
+ # Data-gap lines about this series (raw closes, dropped bars, a
+ # nonstandard close).
+ self.notes = list(notes or [])
@property
def tz_name(self) -> str:
return self.tz.key
+def _placeholder(quote: dict, i: int, prev_close: float | None) -> bool:
+ """A bar Yahoo fills for a day without trading: open, high, low and
+ close all equal the previous close, and no volume."""
+ if prev_close is None:
+ return False
+ for key in ("open", "high", "low", "close"):
+ seq = quote.get(key)
+ if not isinstance(seq, list) or i >= len(seq) or seq[i] != prev_close:
+ return False
+ volume = quote.get("volume")
+ return not (isinstance(volume, list) and i < len(volume) and volume[i])
+
+
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)"
+ if data.get("_stale"):
+ # The fetcher's expired last-known-good copy after a failed
+ # request: an old chart is never read as the current one.
+ return None, f"{symbol}: Yahoo unavailable; a cached chart {_age(data)} was not used"
chart = data.get("chart") or {}
results = chart.get("result")
if not results:
@@ -250,25 +405,64 @@ def parse_bars(symbol: str, data: Any) -> tuple[Bars | None, str | None]:
tz = ZoneInfo(meta["exchangeTimezoneName"])
end = meta["currentTradingPeriod"]["regular"]["end"]
close_time = datetime.fromtimestamp(end, tz).time()
+ rmt = meta.get("regularMarketTime")
+ market_time = datetime.fromtimestamp(rmt, tz) if isinstance(rmt, (int, float)) else None
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")
+ quote = (indicators.get("quote") or [{}])[0]
+ raw = quote.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
+ notes: list[str] = []
+ raw_ok = isinstance(raw, list) and len(raw) == len(stamps)
+ if isinstance(adj, list) and len(adj) == len(stamps):
+ values = adj
+ else:
+ values = raw
+ if raw_ok:
+ notes.append(
+ f"{symbol}: no adjusted closes in the Yahoo chart; raw closes used, so a "
+ "dividend or split in range distorts its returns"
+ )
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):
+ filled: list[str] = []
+ prev_close = None
+ for i, (ts, value) in enumerate(zip(stamps, values)):
# A null close is a missing bar, never a zero price.
if ts is None or value is None:
continue
+ day = datetime.fromtimestamp(ts, tz).date()
+ if _placeholder(quote, i, prev_close):
+ filled.append(day.isoformat())
+ continue
+ if raw_ok and raw[i] is not None:
+ prev_close = raw[i]
# A later bar on the same local date (Yahoo's live bar) replaces it.
- closes[datetime.fromtimestamp(ts, tz).date()] = float(value)
+ closes[day] = float(value)
if not closes:
return None, f"{symbol}: Yahoo chart has no usable closes"
- return Bars(symbol, tz, close_time, closes), None
+ if filled:
+ what = (
+ "a day without trading, not a 0% session"
+ if len(filled) == 1
+ else "days without trading, not 0% sessions"
+ )
+ notes.append(
+ f"{symbol}: placeholder bar{'s' if len(filled) > 1 else ''} dropped for "
+ f"{', '.join(filled)} (open = high = low = close = the previous close, volume 0): {what}"
+ )
+ standard = STANDARD_CLOSE.get(tz.key)
+ if standard is not None and close_time != standard:
+ notes.append(
+ f"{symbol}: Yahoo's current regular close, {close_time.isoformat(timespec='minutes')} "
+ f"{tz.key}, differs from the standard {standard.isoformat(timespec='minutes')} for that "
+ "zone; it is applied to every day in range, so a story published between the two "
+ "times may map to the wrong session"
+ )
+ return Bars(symbol, tz, close_time, closes, market_time, notes), None
async def fetch_bars(fetcher: Fetcher, symbol: str) -> tuple[Bars | None, str | None]:
@@ -288,11 +482,23 @@ async def fetch_bars(fetcher: Fetcher, symbol: str) -> tuple[Bars | None, str |
# ---------------------------------------------------------------------------
+def _not_final(bars: Bars) -> str:
+ last = bars.dates[-1].isoformat()
+ if bars.market_time is None:
+ return f"the {last} {bars.symbol} bar may not be final: Yahoo gave no regularMarketTime"
+ return (
+ f"the {last} {bars.symbol} bar is not final: Yahoo's last regular-market time is "
+ f"{bars.market_time.isoformat()}, before the {bars.close_time.isoformat(timespec='minutes')} close"
+ )
+
+
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``.
+ Returns a dict with ``status`` ("assigned", "pending" or
+ "out_of_range"), and when assigned: ``session_date``, ``basis``,
+ ``published_local``. A pending result says why in ``pending``:
+ "no_session_yet", "in_progress" or "not_final".
"""
local = story_utc.astimezone(bars.tz)
after_close = local.time() >= bars.close_time
@@ -311,7 +517,7 @@ def assign_session(story_utc: datetime, bars: Bars, now_utc: datetime) -> dict:
return out
session = next((d for d in bars.dates if d >= candidate), None)
if session is None:
- out["status"] = "pending"
+ out.update({"status": "pending", "pending": "no_session_yet"})
out["reason"] = (
f"no {bars.symbol} session on or after {candidate.isoformat()} yet "
f"(last bar {bars.dates[-1].isoformat()})"
@@ -319,10 +525,13 @@ def assign_session(story_utc: datetime, bars: Bars, now_utc: datetime) -> dict:
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.update({"status": "pending", "pending": "in_progress", "session_date": session.isoformat()})
out["reason"] = f"the {session.isoformat()} session has not closed yet; its move is not final"
return out
+ if session == bars.dates[-1] and not bars.last_final:
+ out.update({"status": "pending", "pending": "not_final", "session_date": session.isoformat()})
+ out["reason"] = _not_final(bars)
+ return out
if session > candidate:
basis = "next_session_non_trading_day"
elif after_close:
@@ -337,6 +546,22 @@ def assign_session(story_utc: datetime, bars: Bars, now_utc: datetime) -> dict:
_UNASSIGNED = {"pending": "pending", "out_of_range": "data_gap"}
+def _span_gap(first_utc: datetime, last_utc: datetime | None, bars: Bars, now_utc: datetime,
+ session: date) -> str | None:
+ """Why a cluster cannot be tied to one session of this listing, if so."""
+ if last_utc is None or last_utc == first_utc:
+ return None
+ later = assign_session(last_utc, bars, now_utc).get("session_date")
+ if later == session.isoformat():
+ return None
+ other = later or f"a session after {bars.dates[-1].isoformat()}"
+ return (
+ f"the story's articles run from {_stamp(first_utc)} to {_stamp(last_utc)}, which map "
+ f"to different {bars.symbol} sessions ({session.isoformat()} and {other}); the move "
+ "cannot be tied to one session"
+ )
+
+
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)
@@ -386,8 +611,22 @@ def benchmark_for(symbol: str) -> tuple[str | None, str | None]:
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."""
+def _missing_bar(bench: Bars, bars: Bars, day: date) -> str:
+ return f"{bench.symbol} traded on {day.isoformat()} but the {bars.symbol} series has no bar for it"
+
+
+def measure_company(
+ story_utc: datetime,
+ bars: Bars,
+ bench: Bars,
+ now_utc: datetime,
+ story_last_utc: datetime | None = None,
+) -> dict:
+ """Stock, benchmark and excess return on the story's session.
+
+ ``story_last_utc`` is the cluster's latest article time; a cluster
+ whose first and last articles map to different sessions is a gap.
+ """
if bench.tz_name != bars.tz_name:
return {
"status": "data_gap",
@@ -398,29 +637,55 @@ def measure_company(story_utc: datetime, bars: Bars, bench: Bars, now_utc: datet
}
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}
+ candidate = date.fromisoformat(sess["candidate_date"])
if sess["status"] != "assigned":
+ if sess.get("pending") == "no_session_yet":
+ # The benchmark already closed a session the stock series
+ # lacks: missing stock data, not a session still to come.
+ closed = [d for d in bench.dates if d >= candidate and (d < bench.dates[-1] or bench.last_final)]
+ if closed:
+ out.update({
+ "status": "data_gap",
+ "gap": _missing_bar(bench, bars, closed[0]) + "; the session cannot be assigned",
+ })
+ return out
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"
- ),
+ "gap": _missing_bar(bench, bars, skipped[0]) + "; the session cannot be assigned",
})
return out
out["session_basis"] = sess["basis"]
+ span = _span_gap(story_utc, story_last_utc, bars, now_utc, session)
+ if span:
+ out.update({"status": "data_gap", "gap": span})
+ return out
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()
+ # The same gap one step back: a benchmark session between the stock's
+ # prior bar and the session would make this a multi-session return.
+ between = [d for d in bench.dates if prior < d < session]
+ if between:
+ out.update({
+ "status": "data_gap",
+ "gap": (
+ _missing_bar(bench, bars, between[0]) + f"; the {prior.isoformat()} to "
+ f"{session.isoformat()} return would span more than one session"
+ ),
+ })
+ return out
+ if session == bench.dates[-1] and not bench.last_final:
+ out.update({"status": "pending", "gap": _not_final(bench)})
+ return out
bench_ret = window_return(bench, prior, session)
if bench_ret is None:
out.update({
@@ -441,7 +706,9 @@ def measure_company(story_utc: datetime, bars: Bars, bench: Bars, now_utc: datet
return out
-def measure_country(story_utc: datetime, bars: Bars, now_utc: datetime) -> dict:
+def measure_country(
+ story_utc: datetime, bars: Bars, now_utc: datetime, story_last_utc: datetime | None = None
+) -> 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}
@@ -450,6 +717,10 @@ def measure_country(story_utc: datetime, bars: Bars, now_utc: datetime) -> dict:
return out
session = date.fromisoformat(sess["session_date"])
out["session_basis"] = sess["basis"]
+ span = _span_gap(story_utc, story_last_utc, bars, now_utc, session)
+ if span:
+ out.update({"status": "data_gap", "gap": span})
+ return out
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"})
@@ -475,15 +746,70 @@ def _a(phrase: str) -> str:
return ("an " if phrase[:1] in "aeiou" else "a ") + phrase
+def _either(names: tuple[str, ...] | list[str], word: str = "or") -> str:
+ """"A", "A or B", "A, B or C"."""
+ names = list(names)
+ return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} {word} {names[-1]}"
+
+
+def _ambiguity(keyword: str, amb: Ambiguous, lowered: str,
+ feeds: frozenset[tuple[str, str]]) -> tuple[str | None, str]:
+ """(what admits the name, or None) and, when it is excluded, why."""
+ term = _CORROBORATOR_RE[keyword].search(lowered)
+ other = _OTHER_SENSE_RE[keyword].search(lowered) if keyword in _OTHER_SENSE_RE else None
+ in_context = sorted((cat, name) for cat, name in feeds if cat in amb.context)
+ counting = [(cat, name) for cat, name in in_context if amb.context[cat] is None or name in amb.context[cat]]
+ # "meta-analysis", "Pan-Amazon": a hyphen-joined use is the common
+ # word, so a feed alone does not admit it.
+ standalone = re.search(r"(?<!-)\b" + re.escape(keyword) + r"\b(?!-)", lowered) is not None
+ if term:
+ by = f"corroborating term '{term.group(0)}'"
+ elif counting and standalone:
+ cat, name = counting[0]
+ by = f"article from {_a(cat)} feed" + (f" ({name})" if name else "")
+ else:
+ by = None
+ if by and other is None:
+ return by, ""
+ clauses = [amb.reason]
+ if other is not None:
+ clauses.append(f"'{other.group(0)}' in the headlines points to the other sense")
+ if by:
+ clauses.append(f"that outweighs the {by}")
+ else:
+ if counting:
+ where = (
+ f"; the {counting[0][0]} feed does not count because '{keyword}' only appears "
+ "hyphen-joined"
+ )
+ elif in_context:
+ cat = in_context[0][0]
+ names = sorted({name for c, name in in_context if c == cat and name})
+ where = f"; {cat} articles count only from {_either(amb.context[cat])}"
+ if names:
+ where += f", and this story's are from {_either(names, 'and')}"
+ elif amb.context:
+ where = f" and no article from {_a(' or '.join(amb.context))} feed"
+ else:
+ where = ""
+ clauses.append(f"no corroborating term ({', '.join(amb.terms)}) in the headlines{where}")
+ return None, "; ".join(clauses)
+
+
def classify_companies(
- text: str, categories: frozenset[str] | set[str] = frozenset()
+ text: str,
+ categories: frozenset[str] | set[str] = frozenset(),
+ feeds: frozenset[tuple[str, str]] | set[tuple[str, str]] | None = None,
) -> 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.
+ ``feeds`` are the story's (category, feed name) pairs; with only
+ ``categories`` no feed name is known, so a category whose context is
+ limited to named feeds (finance for apple) admits nothing.
"""
lowered = text.lower()
+ feed_pairs = frozenset(feeds) if feeds is not None else frozenset((c, "") for c in categories)
mapped: list[dict] = []
unmapped: list[dict] = []
excluded: list[dict] = []
@@ -491,45 +817,16 @@ def classify_companies(
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}"
- ),
- })
+ amb = AMBIGUOUS_COMPANIES.get(keyword)
+ if amb:
+ admitted_by, reason = _ambiguity(keyword, amb, lowered, feed_pairs)
+ if admitted_by is None:
+ excluded.append({"entity": entity, "reason": reason})
continue
+ entity["admitted_by"] = admitted_by
ticker = comp.get("ticker")
if not ticker:
- unmapped.append({
- "entity": entity,
- "reason": "no public listing in the entity table (private or unlisted)",
- })
+ unmapped.append({"entity": entity, "reason": "no ticker in the entity table"})
continue
if ticker in seen:
continue
@@ -538,8 +835,32 @@ def classify_companies(
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)."""
[email protected]_cache(maxsize=None)
+def _country_forms(iso3: str) -> re.Pattern[str]:
+ """Every form the entity matcher accepts for a country, plus the longer
+ names in NOT_THE_COUNTRY, longest first so those win over the name."""
+ info = TIER1_COUNTRIES[iso3]
+ forms = {kw.lower() for kw in info["keywords"]} | {info["name"].lower(), iso3.lower()}
+ forms |= set(NOT_THE_COUNTRY.get(iso3, ()))
+ parts = []
+ for form in sorted(forms, key=len, reverse=True):
+ esc = re.escape(form)
+ # The entity matcher's plural rule ("Americans").
+ if len(form) >= 5 and form.isalpha():
+ esc += "s?"
+ parts.append(esc)
+ return re.compile(r"\b(?:" + "|".join(parts) + r")\b")
+
+
+def classify_countries(text: str, excluded: list[dict] | None = None) -> tuple[list[dict], list[dict]]:
+ """Split the countries a text names into (mapped to an index, unmapped).
+
+ A country with an index that the text names only by a demonym,
+ capital or code, or only inside a longer name (``NOT_THE_COUNTRY``),
+ gets no index row: it goes to ``excluded`` with the reason when a list
+ is given, else to the unmapped list, so it is never dropped.
+ """
+ lowered = text.lower()
mapped: list[dict] = []
unmapped: list[dict] = []
for c in entities.extract_entities(text)["entities"]["countries"]:
@@ -554,17 +875,33 @@ def classify_countries(text: str) -> tuple[list[dict], list[dict]]:
),
})
continue
- mapped.append({**entity, "index": index})
+ names = COUNTRY_NAMES.get(c["iso3"], (c["name"],))
+ found = list(dict.fromkeys(m.group(0) for m in _country_forms(c["iso3"]).finditer(lowered)))
+ if any(form in {n.lower() for n in names} for form in found):
+ mapped.append({**entity, "index": index})
+ continue
+ forms = ", ".join(f"'{form}'" for form in found) or "a form other than its name"
+ (unmapped if excluded is None else excluded).append({
+ "entity": entity,
+ "reason": (
+ f"named only as {forms}, not by the country's name ({' or '.join(names)}); "
+ "an index row needs the name itself"
+ ),
+ })
return mapped, unmapped
# ---------------------------------------------------------------------------
-# SEC registrant confirmation
+# SEC registrant annotation
# ---------------------------------------------------------------------------
-async def _sec_registrants(fetcher: Fetcher) -> dict[str, dict] | None:
- """Ticker -> {cik, name} from SEC's company_tickers.json, or None."""
+async def _sec_registrants(fetcher: Fetcher, notes: list[str] | None = None) -> dict[str, dict] | None:
+ """Ticker -> {cik, name} from SEC's company_tickers.json, or None.
+
+ An expired copy the fetcher served because SEC failed is not used;
+ the reason goes to ``notes`` when a list is given.
+ """
data = await fetcher.get_json(
_TICKERS_URL,
source="sec-edgar",
@@ -574,6 +911,13 @@ async def _sec_registrants(fetcher: Fetcher) -> dict[str, dict] | None:
)
if not isinstance(data, dict):
return None
+ if data.get("_stale"):
+ if notes is not None:
+ notes.append(
+ f"SEC company_tickers.json unavailable; a cached copy {_age(data)} was not used, "
+ "so US registrants are not confirmed"
+ )
+ return None
out: dict[str, dict] = {}
for entry in data.values():
if not isinstance(entry, dict) or not entry.get("ticker"):
@@ -597,20 +941,36 @@ def _clean_title(title: Any) -> str:
return html.unescape(str(title or "")).replace("’", "'")
+def _stamp(dt: datetime | None) -> str | None:
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ") if dt else None
+
+
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]
+ stamped = []
+ for m in members:
+ t = parse_published(m.get("published"))
+ if t is not None:
+ stamped.append((t, m))
+ stamped.sort(key=lambda pair: pair[0])
+ first, last = (stamped[0][0], stamped[-1][0]) if stamped else (None, None)
+ # Headline and link come from the article whose time is the story time.
+ rep = stamped[0][1] if stamped else 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,
+ "first_published": _stamp(first),
+ "last_published": _stamp(last),
+ "span_hours": round((last - first).total_seconds() / 3600, 2) if stamped else None,
"_time": first,
+ "_last": last,
"_text": " ".join(_clean_title(m.get("title")) for m in members),
"_categories": frozenset(m["category"] for m in members if m.get("category")),
+ "_feeds": frozenset(
+ (m["category"], str(m.get("feed_name") or "")) for m in members if m.get("category")
+ ),
}
@@ -626,13 +986,16 @@ async def fetch_news_market_reaction(
min_cluster_size: int = 2,
include_countries: bool = True,
max_symbols: int = 40,
+ max_age_hours: float = MAX_AGE_HOURS,
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))
+ threshold = max(THRESHOLD_MIN, min(float(threshold), 1.0))
min_cluster_size = max(1, int(min_cluster_size))
max_symbols = max(1, min(int(max_symbols), 60))
+ max_age_hours = max(1.0, min(float(max_age_hours), float(MAX_AGE_LIMIT)))
feed = await news.fetch_news_feed(fetcher, category=category, limit=limit)
base = {
@@ -652,6 +1015,15 @@ async def fetch_news_market_reaction(
c for c in clustering.cluster_articles(items, similarity_threshold=threshold)
if c["member_count"] >= min_cluster_size
]
+ cutoff = now_utc - timedelta(hours=max_age_hours)
+ stories: list[dict] = []
+ dropped_by_age = 0
+ for c in clusters:
+ story = _story(items, c["member_indices"])
+ if story["_time"] is not None and story["_time"] < cutoff:
+ dropped_by_age += 1
+ continue
+ stories.append(story)
data_gaps: list[str] = []
unmapped: list[dict] = []
@@ -659,15 +1031,19 @@ async def fetch_news_market_reaction(
# (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:
+ for story in stories:
+ companies, c_unmapped, c_excluded = classify_companies(
+ story["_text"], story["_categories"], feeds=story["_feeds"]
+ )
+ k_excluded: list[dict] = []
+ countries, k_unmapped = (
+ classify_countries(story["_text"], excluded=k_excluded) if include_countries else ([], [])
+ )
+ if companies or countries or c_unmapped or c_excluded or k_unmapped or k_excluded:
stories_with_entities += 1
for row in c_unmapped + k_unmapped:
unmapped.append({"story": story["headline"], **row})
- for row in c_excluded:
+ for row in c_excluded + k_excluded:
excluded.append({"story": story["headline"], **row})
for comp in companies:
pending_rows.append((story, comp, comp["ticker"], "company"))
@@ -699,15 +1075,17 @@ async def fetch_news_market_reaction(
for symbol, (b, err) in zip(fetch_list, fetched):
if b is not None:
bars[symbol] = b
+ data_gaps.extend(b.notes)
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)
+ sec_notes: list[str] = []
+ registrants = await _sec_registrants(fetcher, sec_notes)
if registrants is None:
- data_gaps.append("SEC company_tickers.json unavailable; US registrants not confirmed")
+ data_gaps.extend(sec_notes or ["SEC company_tickers.json unavailable; US registrants not confirmed"])
company_rows: list[dict] = []
country_rows: list[dict] = []
@@ -723,13 +1101,12 @@ async def fetch_news_market_reaction(
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:
+ elif story["_last"] > 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)"
+ f"story timestamp {story['last_published']} is later than the collection "
+ f"time {_stamp(now_utc)} (a timestamp error in the feed or in its parsing)"
),
})
elif b is None:
@@ -739,9 +1116,11 @@ async def fetch_news_market_reaction(
})
elif kind == "country":
row["exchange_timezone"] = b.tz_name
- row.update(measure_country(story["_time"], b, now_utc))
+ row["close_time_used"] = b.close_time.isoformat(timespec="minutes")
+ row.update(measure_country(story["_time"], b, now_utc, story["_last"]))
else:
row["exchange_timezone"] = b.tz_name
+ row["close_time_used"] = b.close_time.isoformat(timespec="minutes")
if bench_sym is None:
row.update({"status": "data_gap", "gap": bench_reason})
elif bench_sym not in bars:
@@ -751,7 +1130,7 @@ async def fetch_news_market_reaction(
+ (" (symbol budget)" if bench_sym in over_budget else ""),
})
else:
- row.update(measure_company(story["_time"], b, bars[bench_sym], now_utc))
+ row.update(measure_company(story["_time"], b, bars[bench_sym], now_utc, story["_last"]))
(company_rows if kind == "company" else country_rows).append(row)
def _count(rows: list[dict], status: str) -> int:
@@ -765,7 +1144,10 @@ async def fetch_news_market_reaction(
"excluded": excluded,
"summary": {
"news_items": len(items),
- "stories_considered": len(clusters),
+ "stories_considered": len(stories),
+ "stories_dropped_by_age": dropped_by_age,
+ "max_age_hours": max_age_hours,
+ "threshold": threshold,
"stories_with_entities": stories_with_entities,
"min_cluster_size": min_cluster_size,
"companies_measured": _count(company_rows, "measured"),
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index c6f60e9..5ba20cb 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -1613,18 +1613,40 @@ def _signed_pct(value: Any) -> str:
return f"[{style}]{value:+.2f}%[/{style}]"
+def _session_cell(row: dict) -> Text:
+ """Session date, the prior session the return starts from, and the
+ story's exchange-local time, so a return over more than one session
+ or a misplaced story time shows on the row."""
+ lines = [str(row.get("session_date") or "-")]
+ if row.get("prior_session_date"):
+ lines.append(f"from {row['prior_session_date']}")
+ story_time = row.get("published_local") or row.get("story", {}).get("first_published")
+ if story_time:
+ lines.append(f"story {story_time}")
+ return _cell("\n".join(lines))
+
+
@main.command(name="news-reaction")
@click.option("--category", "-c", default=None, help="RSS category (finance, technology, energy, ...)")
@click.option("--limit", "-n", default=150, type=int, help="News items to cluster (max 300)")
@click.option("--min-size", default=2, type=int, help="Minimum articles per story (1 includes single-article stories)")
[email protected]("--max-age-hours", default=None, type=float, help="Leave out stories older than this (default 168)")
@click.option("--no-countries", is_flag=True, help="Skip the country-index rows")
@click.pass_context
def news_reaction(
- ctx: click.Context, category: str | None, limit: int, min_size: int, no_countries: bool
+ ctx: click.Context,
+ category: str | None,
+ limit: int,
+ min_size: int,
+ max_age_hours: float | None,
+ 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
+ kwargs: dict[str, Any] = {}
+ if max_age_hours is not None:
+ kwargs["max_age_hours"] = max_age_hours
data = _run(
fetch_news_market_reaction(
_get_fetcher(),
@@ -1632,16 +1654,21 @@ def news_reaction(
limit=limit,
min_cluster_size=min_size,
include_countries=not no_countries,
+ **kwargs,
)
)
if _bail_on_error(ctx, data):
return
s = data.get("summary", {})
+ dropped = s.get("stories_dropped_by_age") or 0
+ aged_out = (
+ f"; {dropped} stories older than {s.get('max_age_hours', 0):g} h left out" if dropped else ""
+ )
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"
+ f"{s.get('unmapped', 0)} unmapped, {s.get('excluded', 0)} excluded as ambiguous{aged_out}"
)
console.print(f"[dim]{escape(str(data.get('interpretation', '')))}[/dim]\n")
@@ -1660,7 +1687,7 @@ def news_reaction(
_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 "-"),
+ _session_cell(r),
_signed_pct(r.get("stock_return_pct")),
_signed_pct(r.get("benchmark_return_pct")),
_signed_pct(r.get("excess_return_pct")),
@@ -1684,7 +1711,7 @@ def news_reaction(
_cell(r.get("story", {}).get("headline", "")),
_cell(r.get("entity", {}).get("name", "")),
_cell(r.get("symbol", "")),
- _cell(r.get("session_date") or "-"),
+ _session_cell(r),
_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', '')}"),
diff --git a/src/world_intel_mcp/tests/test_cli.py b/src/world_intel_mcp/tests/test_cli.py
index 8eb3dd5..14e5234 100644
--- a/src/world_intel_mcp/tests/test_cli.py
+++ b/src/world_intel_mcp/tests/test_cli.py
@@ -2823,3 +2823,39 @@ def test_news_reaction_error_dict_and_json_mode(monkeypatch: pytest.MonkeyPatch)
assert result.exit_code == 0
assert '"excess_return_pct": -0.8196' in result.output
assert "Companies" not in result.output
+
+
+def test_news_reaction_shows_window_story_time_and_age_cut(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The prior session and the story's exchange-local time are on the
+ row, so a return over more than one session cannot pass unseen."""
+ import world_intel_mcp.analysis.news_market as news_market
+
+ apple = {
+ "story": {"headline": "Apple foldable iPhones sell out in hours",
+ "first_published": "2026-10-15T20:30:00Z"},
+ "entity": {"type": "company", "name": "Apple"},
+ "symbol": "AAPL",
+ "benchmark": "SPY",
+ "published_local": "2026-10-15T16:30:00-04:00",
+ "session_date": "2026-10-16",
+ "prior_session_date": "2026-10-15",
+ "status": "measured",
+ "stock_return_pct": 0.4269,
+ "benchmark_return_pct": -1.1065,
+ "excess_return_pct": 1.5334,
+ }
+ data = {
+ **_NEWS_REACTION,
+ "company_reactions": [apple],
+ "summary": {**_NEWS_REACTION["summary"], "stories_dropped_by_age": 3, "max_age_hours": 168.0},
+ }
+ calls: list = []
+ monkeypatch.setattr(news_market, "fetch_news_market_reaction", _fake(data, calls))
+ result = _invoke("news-reaction", "--max-age-hours", "24")
+ assert result.exit_code == 0
+ assert calls[0]["max_age_hours"] == 24.0
+ out = result.output
+ assert "from 2026-10-15" in out
+ assert "story 2026-10-15T16:30:00-04:00" in out
+ assert "3 stories older than 168 h left out" in out
+ assert "+0.43%" in out and "+1.53%" in out
diff --git a/src/world_intel_mcp/tests/test_news_market.py b/src/world_intel_mcp/tests/test_news_market.py
index 7e60d43..a6e241b 100644
--- a/src/world_intel_mcp/tests/test_news_market.py
+++ b/src/world_intel_mcp/tests/test_news_market.py
@@ -12,7 +12,9 @@ company_tickers.json. Clustering and entity matching run for real on
headlines in the live feed-item shape; only the RSS fetch is faked.
"""
+import re
from datetime import datetime, timezone
+from zoneinfo import ZoneInfo
import httpx
import pytest
@@ -104,11 +106,26 @@ _SEC_SUBSET = {
_SATURDAY = datetime(2026, 10, 17, 16, 0, tzinfo=timezone.utc)
+def _market_time(last_stamp, tz, period):
+ """regularMarketTime as Yahoo sends it: a finished daily bar (stamped
+ at the session open) carries its day's closing print, as the live
+ AAPL 16:00:01 and SPY 16:00:00 captures do; a bar stamped later is a
+ live intraday print and carries that stamp."""
+ zone = ZoneInfo(tz)
+ regular = period["regular"]
+ last = datetime.fromtimestamp(last_stamp, zone)
+ if last.time() != datetime.fromtimestamp(regular["start"], zone).time():
+ return last_stamp
+ close = datetime.fromtimestamp(regular["end"], zone).time()
+ return int(datetime.combine(last.date(), close, zone).timestamp())
+
+
def _chart(symbol, bars, *, tz="America/New_York", abbr="EDT", gmtoffset=-14400,
- period=None, instrument="EQUITY", exchange="NMS", full="NasdaqGS"):
+ period=None, instrument="EQUITY", exchange="NMS", full="NasdaqGS", market_time=None):
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]
+ period = period or _US_PERIOD
return {
"chart": {
"result": [{
@@ -118,12 +135,13 @@ def _chart(symbol, bars, *, tz="America/New_York", abbr="EDT", gmtoffset=-14400,
"exchangeName": exchange,
"fullExchangeName": full,
"instrumentType": instrument,
- "regularMarketTime": stamps[-1],
+ "regularMarketTime": (
+ _market_time(stamps[-1], tz, period) if market_time is None else market_time),
"gmtoffset": gmtoffset,
"timezone": abbr,
"exchangeTimezoneName": tz,
"chartPreviousClose": closes[0],
- "currentTradingPeriod": period or _US_PERIOD,
+ "currentTradingPeriod": period,
"dataGranularity": "1d",
"range": "3mo",
},
@@ -854,3 +872,544 @@ async def test_tool_handler_passes_arguments(monkeypatch):
assert result == {"ok": True}
assert calls == [{"category": "finance", "limit": 150, "threshold": 0.25, "min_cluster_size": 1,
"include_countries": False, "max_symbols": 40}]
+
+
+async def test_tool_handler_passes_max_age_hours_when_given(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)
+ await tools.ALL_HANDLERS["intel_news_market_reaction"]({"max_age_hours": 24})
+ assert calls[0]["max_age_hours"] == 24
+ [tool] = tool_mod.TOOLS
+ assert tool.inputSchema["properties"]["max_age_hours"]["default"] == 168
+ # The SEC lookup annotates a US ticker with its registrant; it confirms nothing.
+ assert "SEC-confirmed" not in tool.description
+
+
+# ---------------------------------------------------------------------------
+# Stale cache copies, bar finality, placeholder bars
+# ---------------------------------------------------------------------------
+
+
+def test_parse_bars_stale_cached_chart_is_a_gap_naming_its_age():
+ """When Yahoo fails the fetcher serves an expired copy marked _stale;
+ an old chart must never become a measured row."""
+ payload = _chart("AAPL", _AAPL)
+ payload.update({"_stale": True, "_stale_age_seconds": 259200.4})
+ assert nm.parse_bars("AAPL", payload) == (
+ None, "AAPL: Yahoo unavailable; a cached chart 259200 s old was not used")
+ del payload["_stale_age_seconds"]
+ assert nm.parse_bars("AAPL", payload)[1] == (
+ "AAPL: Yahoo unavailable; a cached chart of unknown age was not used")
+
+
+async def test_composite_stale_yahoo_and_sec_copies_are_gaps(fast_fetcher, monkeypatch):
+ """Yahoo and SEC down, expired copies in the cache: no row is measured
+ from the old charts and no registrant comes from the old file."""
+ _feed(monkeypatch, [_ITEMS[0]])
+ fast_fetcher.cache.set("news_market:bars:AAPL", _chart("AAPL", _AAPL), -1)
+ fast_fetcher.cache.set("news_market:bars:SPY", _chart("SPY", _SPY), -1)
+ fast_fetcher.cache.set("sec:company_tickers", _SEC_SUBSET, -1)
+ respx.get(_CHART.format("AAPL")).mock(return_value=httpx.Response(503))
+ respx.get(_CHART.format("SPY")).mock(return_value=httpx.Response(503))
+ 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"]
+ assert row["status"] == "data_gap"
+ assert row["gap"] == "no daily bars for AAPL"
+ assert "stock_return_pct" not in row and "registrant" not in row
+ gaps = " | ".join(out["data_gaps"])
+ assert re.search(r"AAPL: Yahoo unavailable; a cached chart \d+ s old was not used", gaps)
+ assert re.search(r"SPY: Yahoo unavailable; a cached chart \d+ s old was not used", gaps)
+ assert re.search(r"SEC company_tickers\.json unavailable; a cached copy \d+ s old was not used, "
+ r"so US registrants are not confirmed", gaps)
+ assert out["summary"]["symbols_fetched"] == 0
+
+
+def test_bars_keep_regular_market_time_and_last_bar_finality():
+ final = _bars("AAPL", _chart("AAPL", _AAPL)) # closing print at 16:00 on 2026-10-16
+ assert final.market_time.isoformat() == "2026-10-16T16:00:00-04:00"
+ assert final.last_final is True
+ live = _bars("AAPL", _chart("AAPL", _AAPL, market_time=1792180680)) # a 15:58 print
+ assert live.last_final is False
+ one_past = _bars("AAPL", _chart("AAPL", _AAPL, market_time=1792180801)) # 16:00:01, as live AAPL
+ assert one_past.last_final is True
+
+
+def test_last_bar_printed_before_the_close_is_pending_after_the_close():
+ """A chart read at 15:58 and cached is still served at 16:05: the
+ clock says the session closed, but the last bar is the 15:58 print."""
+ cached = _bars("AAPL", _chart("AAPL", _AAPL, market_time=1792180680))
+ after_close = datetime(2026, 10, 16, 20, 5, tzinfo=timezone.utc) # 16:05 EDT
+ s = _assign("2026-10-16T14:00:00Z", cached, now=after_close)
+ assert s["status"] == "pending"
+ assert s["session_date"] == "2026-10-16"
+ assert s["reason"] == (
+ "the 2026-10-16 AAPL bar is not final: Yahoo's last regular-market time is "
+ "2026-10-16T15:58:00-04:00, before the 16:00 close")
+ # An earlier session of the same series is final whatever the last bar is
+ assert _assign("2026-10-15T14:00:00Z", cached, now=after_close)["status"] == "assigned"
+ no_time = _chart("AAPL", _AAPL)
+ del no_time["chart"]["result"][0]["meta"]["regularMarketTime"]
+ s = _assign("2026-10-16T14:00:00Z", _bars("AAPL", no_time), now=after_close)
+ assert s["status"] == "pending"
+ assert s["reason"] == "the 2026-10-16 AAPL bar may not be final: Yahoo gave no regularMarketTime"
+
+
+def test_measure_company_benchmark_bar_not_final_is_pending():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL))
+ spy = _bars("SPY", _chart("SPY", _SPY, market_time=1792180680))
+ row = nm.measure_company(nm.parse_published("2026-10-16T14:00:00Z"), aapl, spy, _SATURDAY)
+ assert row["status"] == "pending"
+ assert row["gap"] == (
+ "the 2026-10-16 SPY bar is not final: Yahoo's last regular-market time is "
+ "2026-10-16T15:58:00-04:00, before the 16:00 close")
+ assert "stock_return_pct" not in row and "excess_return_pct" not in row
+
+
+async def test_composite_bars_cached_before_the_close_stay_pending(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [_item("Apple foldable iPhones sell out in hours", "2026-10-16T14:00:00Z")])
+ aapl = respx.get(_CHART.format("AAPL")).mock(return_value=httpx.Response(
+ 200, json=_chart("AAPL", _AAPL[:-1] + [(1792180680, 341.1, 341.1)]))) # 15:58 print
+ respx.get(_CHART.format("SPY")).mock(return_value=httpx.Response(
+ 200, json=_chart("SPY", _SPY[:-1] + [(1792180680, 766.4, 766.4)])))
+ respx.get(_SEC).mock(return_value=httpx.Response(200, json=_SEC_SUBSET))
+
+ before = await nm.fetch_news_market_reaction(
+ fast_fetcher, min_cluster_size=1, now=datetime(2026, 10, 16, 19, 58, tzinfo=timezone.utc))
+ after = await nm.fetch_news_market_reaction(
+ fast_fetcher, min_cluster_size=1, now=datetime(2026, 10, 16, 20, 5, tzinfo=timezone.utc))
+
+ assert aapl.call_count == 1 # the 16:05 call read the 15:58 chart from the cache
+ assert before["company_reactions"][0]["status"] == "pending"
+ row = after["company_reactions"][0]
+ assert row["status"] == "pending"
+ assert row["gap"].startswith("the 2026-10-16 AAPL bar is not final")
+ assert "stock_return_pct" not in row
+
+
+# Live 2222.SR daily bars (Yahoo v8, range 3mo, read 2026-10-17). Sunday
+# 2026-08-16 is a bar in which nothing traded: open, high, low and close
+# all equal Thursday's close and volume is 0.
+_ARAMCO = [ # (timestamp = session open, open, high, low, close, volume, adjclose)
+ (1786431600, 26.639999389648438, 26.860000610351562, 26.600000381469727, 26.600000381469727,
+ 10714020, 26.26120948791504), # 2026-08-11
+ (1786518000, 26.600000381469727, 26.68000030517578, 26.520000457763672, 26.600000381469727,
+ 6601208, 26.26120948791504), # 2026-08-12
+ (1786604400, 26.559999465942383, 26.600000381469727, 26.479999542236328, 26.479999542236328,
+ 7482066, 26.142736434936523), # 2026-08-13
+ (1786863600, 26.479999542236328, 26.479999542236328, 26.479999542236328, 26.479999542236328,
+ 0, 26.142736434936523), # 2026-08-16 (nothing traded)
+ (1786950000, 26.700000762939453, 26.700000762939453, 26.520000457763672, 26.520000457763672,
+ 9968769, 26.182228088378906), # 2026-08-17
+ (1787036400, 26.579999923706055, 26.700000762939453, 26.559999465942383, 26.579999923706055,
+ 10271573, 26.241464614868164), # 2026-08-18
+]
+# Live 2222.SR currentTradingPeriod (2026-10-15 session).
+_RIYADH_PERIOD = {
+ "pre": {"timezone": "AST", "start": 1792047600, "end": 1792047600, "gmtoffset": 10800},
+ "regular": {"timezone": "AST", "start": 1792047600, "end": 1792065600, "gmtoffset": 10800},
+ "post": {"timezone": "AST", "start": 1792065600, "end": 1792065600, "gmtoffset": 10800},
+}
+
+
+def _aramco_chart(rows=_ARAMCO):
+ payload = _chart("2222.SR", [(r[0], r[4], r[6]) for r in rows], tz="Asia/Riyadh", abbr="AST",
+ gmtoffset=10800, period=_RIYADH_PERIOD, exchange="SAU", full="Saudi")
+ result = payload["chart"]["result"][0]
+ result["meta"]["currency"] = "SAR"
+ result["indicators"]["quote"] = [{
+ "open": [r[1] for r in rows], "high": [r[2] for r in rows], "low": [r[3] for r in rows],
+ "close": [r[4] for r in rows], "volume": [r[5] for r in rows]}]
+ return payload
+
+
+def test_parse_bars_drops_a_bar_in_which_nothing_traded():
+ bars = _bars("2222.SR", _aramco_chart())
+ assert [d.isoformat() for d in bars.dates] == [
+ "2026-08-11", "2026-08-12", "2026-08-13", "2026-08-17", "2026-08-18"]
+ assert bars.notes == [
+ "2222.SR: placeholder bar dropped for 2026-08-16 (open = high = low = close = the "
+ "previous close, volume 0): a day without trading, not a 0% session"]
+ # A Sunday story maps to Monday, measured from Thursday's close
+ s = _assign("2026-08-16T07:30:00Z", bars) # 10:30 Riyadh
+ assert (s["session_date"], s["basis"]) == ("2026-08-17", "next_session_non_trading_day")
+ prior, ret = nm.session_return(bars, datetime(2026, 8, 17).date())
+ assert (prior.isoformat(), round(ret * 100, 4)) == ("2026-08-13", 0.1511)
+ # The same flat bar with any volume traded and stays
+ traded = [r[:5] + (5,) + r[6:] if r[0] == 1786863600 else r for r in _ARAMCO]
+ assert "2026-08-16" in [d.isoformat() for d in _bars("2222.SR", _aramco_chart(traded)).dates]
+
+
+def test_placeholder_bar_does_not_enter_the_zscore_sample():
+ """A volume-0 bar copying the previous close on a closed weekday
+ (2026-09-25, Mid-Autumn) would add a fake 0.0% return to the sample."""
+ filler = (1790299800, 3888.3740234375) # 2026-09-25 09:30 Shanghai, 09-24's close again
+ rows = sorted(_SSE + [filler])
+ payload = _sse_chart(rows)
+ payload["chart"]["result"][0]["indicators"]["quote"][0]["volume"][rows.index(filler)] = 0
+ sse = _bars("000001.SS", payload)
+ row = nm.measure_country(nm.parse_published("2026-10-16T01:00:00Z"), sse, _SATURDAY)
+ assert (row["index_return_pct"], row["zscore"], row["trailing_sessions"]) == (0.2376, 0.6, 16)
+ assert sse.notes == [
+ "000001.SS: placeholder bar dropped for 2026-09-25 (open = high = low = close = the "
+ "previous close, volume 0): a day without trading, not a 0% session"]
+
+
+def test_parse_bars_raw_closes_without_adjclose_are_noted():
+ payload = _chart("SPY", _SPY)
+ del payload["chart"]["result"][0]["indicators"]["adjclose"]
+ bars = _bars("SPY", payload)
+ _prior, ret = nm.session_return(bars, datetime(2026, 9, 18).date())
+ assert round(ret * 100, 4) == -0.1193 # the unadjusted ex-dividend move
+ assert bars.notes == [
+ "SPY: no adjusted closes in the Yahoo chart; raw closes used, so a dividend or split "
+ "in range distorts its returns"]
+
+
+def test_close_differing_from_the_zone_standard_is_noted():
+ assert _bars("AAPL", _chart("AAPL", _AAPL)).notes == []
+ # A US early-close day: Yahoo's current period ends 13:00 and that
+ # close is applied to every day in range.
+ early = {"regular": {"timezone": "EDT", "start": 1792157400, "end": 1792170000, "gmtoffset": -14400}}
+ bars = _bars("AAPL", _chart("AAPL", _AAPL, period=early))
+ assert bars.close_time.isoformat() == "13:00:00"
+ assert bars.notes == [
+ "AAPL: Yahoo's current regular close, 13:00 America/New_York, differs from the standard "
+ "16:00 for that zone; it is applied to every day in range, so a story published between "
+ "the two times may map to the wrong session"]
+ # KRX: Yahoo's period ends 15:00 (live, 2026-10-16) but the closing
+ # print of 005930.KS that day was at 15:30:05.
+ seoul = {"regular": {"timezone": "KST", "start": 1792108800, "end": 1792130400, "gmtoffset": 32400}}
+ krx = _bars("005930.KS", _chart("005930.KS", [(1792022400, 100.0), (1792108800, 101.0)],
+ tz="Asia/Seoul", abbr="KST", gmtoffset=32400, period=seoul,
+ market_time=1792132205))
+ assert krx.last_final is True
+ assert krx.notes == [
+ "005930.KS: Yahoo's current regular close, 15:00 Asia/Seoul, differs from the standard "
+ "15:30 for that zone; it is applied to every day in range, so a story published between "
+ "the two times may map to the wrong session"]
+
+
+async def test_composite_rows_name_the_close_used_and_bar_notes_reach_data_gaps(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [_ITEMS[0], _ITEMS[5]])
+ early = {"regular": {"timezone": "EDT", "start": 1792157400, "end": 1792170000, "gmtoffset": -14400}}
+ respx.get(_CHART.format("AAPL")).mock(return_value=httpx.Response(
+ 200, json=_chart("AAPL", _AAPL, period=early)))
+ spy = _chart("SPY", _SPY, instrument="ETF", exchange="PCX", full="NYSEArca")
+ del spy["chart"]["result"][0]["indicators"]["adjclose"]
+ respx.get(_CHART.format("SPY")).mock(return_value=httpx.Response(200, json=spy))
+ respx.get(_CHART.format("000001.SS")).mock(return_value=httpx.Response(200, json=_sse_chart()))
+ 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)
+
+ [apple] = out["company_reactions"]
+ assert apple["close_time_used"] == "13:00"
+ assert apple["status"] == "measured" and apple["benchmark_return_pct"] == -1.1065
+ [china] = out["country_reactions"]
+ assert china["close_time_used"] == "15:00"
+ assert out["data_gaps"] == [
+ "AAPL: Yahoo's current regular close, 13:00 America/New_York, differs from the standard "
+ "16:00 for that zone; it is applied to every day in range, so a story published between "
+ "the two times may map to the wrong session",
+ "SPY: no adjusted closes in the Yahoo chart; raw closes used, so a dividend or split "
+ "in range distorts its returns",
+ ]
+
+
+# ---------------------------------------------------------------------------
+# Session windows and story spans
+# ---------------------------------------------------------------------------
+
+
+def test_measure_company_stock_missing_the_prior_session_is_a_gap():
+ """AAPL lacks 2026-10-15 while SPY traded: a 10-16 story would be
+ measured from 10-14, a two-session return labelled same_session."""
+ 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-16T14: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 2026-10-14 to "
+ "2026-10-16 return would span more than one session")
+ assert "stock_return_pct" not in row
+
+
+def test_measure_company_benchmark_already_closed_the_pending_session_is_a_gap():
+ aapl = _bars("AAPL", _chart("AAPL", _AAPL[:-1])) # series ends 2026-10-15
+ spy = _bars("SPY", _chart("SPY", _SPY)) # 2026-10-16 bar is final
+ row = nm.measure_company(nm.parse_published("2026-10-15T20:30:00Z"), aapl, spy, _SATURDAY)
+ assert row["status"] == "data_gap"
+ assert row["gap"] == (
+ "SPY traded on 2026-10-16 but the AAPL series has no bar for it; the session cannot be assigned")
+ # While the benchmark's own 10-16 bar is not final either, it stays pending
+ live_spy = _bars("SPY", _chart("SPY", _SPY, market_time=1792180680))
+ row = nm.measure_company(nm.parse_published("2026-10-15T20:30:00Z"), aapl, live_spy, _SATURDAY)
+ assert row["status"] == "pending"
+
+
+_MULTI_DAY = [ # sources/news.py sorts newest first
+ _item("Apple shares rise after analyst upgrade", "2026-10-16T14:00:00Z", "finance", "CNBC"),
+ _item("Apple shares fall after earnings miss", "2026-10-08T14:00:00Z", "finance", "MarketWatch"),
+]
+
+
+async def test_composite_cluster_spanning_sessions_is_a_gap(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, list(_MULTI_DAY))
+ _mock_markets()
+ respx.get(_SEC).mock(return_value=httpx.Response(200, json=_SEC_SUBSET))
+
+ out = await nm.fetch_news_market_reaction(fast_fetcher, max_age_hours=400, now=_SATURDAY)
+
+ [row] = out["company_reactions"]
+ story = row["story"]
+ # Headline, link and time all come from the earliest article
+ assert story["headline"] == "Apple shares fall after earnings miss"
+ assert story["link"] == "https://example.com/apple-shares-fall-after-earnings-miss"
+ assert (story["first_published"], story["last_published"], story["span_hours"]) == (
+ "2026-10-08T14:00:00Z", "2026-10-16T14:00:00Z", 192.0)
+ assert row["status"] == "data_gap"
+ assert row["gap"] == (
+ "the story's articles run from 2026-10-08T14:00:00Z to 2026-10-16T14:00:00Z, which map "
+ "to different AAPL sessions (2026-10-08 and 2026-10-16); the move cannot be tied to one session")
+ assert "stock_return_pct" not in row
+
+
+async def test_composite_cluster_with_a_future_article_is_a_gap(fast_fetcher, monkeypatch):
+ """Any article stamped after the collection time puts the cluster's
+ times in doubt, not only the earliest one."""
+ _feed(monkeypatch, [
+ _item("Apple foldable iPhones sell out in hours worldwide", "2026-10-17T21:18:34Z"),
+ _item("Apple foldable iPhones sell out in hours", "2026-10-16T14:00:00Z"),
+ ])
+ _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)
+
+ [row] = out["company_reactions"]
+ assert (row["story"]["first_published"], row["story"]["last_published"]) == (
+ "2026-10-16T14:00:00Z", "2026-10-17T21:18:34Z")
+ assert row["status"] == "data_gap"
+ assert row["gap"].startswith(
+ "story timestamp 2026-10-17T21:18:34Z is later than the collection time 2026-10-17T16:00:00Z")
+ assert "stock_return_pct" not in row
+
+
+async def test_composite_country_cluster_spanning_sessions_is_a_gap(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [
+ _item("China shares rise after stimulus pledge", "2026-10-16T01:00:00Z", "finance", "CNBC"),
+ _item("China shares fall after stimulus pledge", "2026-10-14T01:00:00Z", "finance", "MarketWatch"),
+ ])
+ _mock_markets()
+
+ out = await nm.fetch_news_market_reaction(fast_fetcher, now=_SATURDAY)
+
+ [row] = out["country_reactions"]
+ assert row["symbol"] == "000001.SS"
+ assert row["status"] == "data_gap"
+ assert row["gap"] == (
+ "the story's articles run from 2026-10-14T01:00:00Z to 2026-10-16T01:00:00Z, which map "
+ "to different 000001.SS sessions (2026-10-14 and 2026-10-16); the move cannot be tied to one session")
+ assert "index_return_pct" not in row
+
+
+async def test_composite_leaves_out_stories_older_than_max_age(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, list(_MULTI_DAY))
+ _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) # default 168 h
+
+ assert out["company_reactions"] == []
+ s = out["summary"]
+ assert (s["stories_considered"], s["stories_dropped_by_age"], s["max_age_hours"]) == (0, 1, 168)
+
+
+async def test_composite_clamps_threshold_and_max_age(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [_ITEMS[3]]) # OpenAI: unmapped, no market data needed
+ seen = []
+ real = nm.clustering.cluster_articles
+
+ def _recording(articles, similarity_threshold=0.3, title_field="title"):
+ seen.append(similarity_threshold)
+ return real(articles, similarity_threshold, title_field)
+
+ monkeypatch.setattr(nm.clustering, "cluster_articles", _recording)
+ low = await nm.fetch_news_market_reaction(
+ fast_fetcher, min_cluster_size=1, threshold=0, max_age_hours=0, now=_SATURDAY)
+ high = await nm.fetch_news_market_reaction(
+ fast_fetcher, min_cluster_size=1, threshold=7, max_age_hours=10**6, now=_SATURDAY)
+ assert seen == [0.01, 1.0]
+ assert (low["summary"]["threshold"], low["summary"]["max_age_hours"]) == (0.01, 1)
+ assert (high["summary"]["threshold"], high["summary"]["max_age_hours"]) == (1.0, 2160)
+ assert low["summary"]["stories_dropped_by_age"] == 1 # 28 h old against a 1 h limit
+
+
+def test_method_describes_what_the_module_reads():
+ story_time = nm.METHOD["story_time"]
+ # Feed timestamps are read as sources/news.py reports them; nothing
+ # here can vouch that the feed or its parsing got them right.
+ assert "as the RSS feeds state it" not in story_time
+ assert "sources/news.py" in story_time and "UTC" in story_time
+
+
+# ---------------------------------------------------------------------------
+# Ambiguous company names and country names
+# ---------------------------------------------------------------------------
+
+
[email protected]("headline, feeds, phrase", [
+ ("Pan-Amazon summit ends without deforestation deal", {("finance", "CNBC")}, "pan-amazon"),
+ ("Lula vows to end illegal Amazon deforestation by 2030", {("finance", "CNBC")}, "deforestation"),
+ ("Big Apple office vacancies hit record as hybrid work sticks", {("finance", "CNBC")}, "big apple"),
+ ("Apple Hospitality REIT raises monthly dividend", {("finance", "MarketWatch")}, "apple hospitality"),
+ ("Post-Chevron, utilities challenge FERC transmission rule", {("energy", "Oil Price")}, "post-chevron"),
+ ("Supreme Court's Chevron ruling unleashes oil industry lawsuits against EPA",
+ {("energy", "Rigzone")}, "chevron ruling"),
+ ("Alphabet soup of rescue facilities confuses bond traders", {("finance", "WSJ Markets")}, "alphabet soup"),
+ ("Shell strikes Zaporizhzhia nuclear plant's power line", {("energy", "Oil Price")}, "shell strikes"),
+ ("A new meta analysis of AI coding tools finds small gains",
+ {("technology", "MIT Tech Review")}, "meta analysis"),
+ ("Oil majors slip as Fed signals 50 bp hike", {("energy", "Oil Price")}, "50 bp"),
+])
+def test_other_sense_phrases_exclude_ambiguous_names(headline, feeds, phrase):
+ mapped, _, excluded = nm.classify_companies(nm._clean_title(headline), feeds=feeds)
+ assert mapped == []
+ assert f"'{phrase}' in the headlines points to the other sense" in excluded[0]["reason"]
+
+
[email protected]("headline, feeds, ticker, admitted_by", [
+ ("Shell profit beats forecasts on strong LNG trading", {("energy", "Oil Price")}, "SHEL",
+ "article from an energy feed (Oil Price)"),
+ ("Chevron completes Hess takeover after arbitration win", {("finance", "FT World")}, "CVX",
+ "corroborating term 'hess'"),
+ ("Meta signs nuclear power deal for AI data centers", {("technology", "The Verge")}, "META",
+ "article from a technology feed (The Verge)"),
+ ("Samsung Electronics profit jumps on memory demand", {("asia_pacific", "Nikkei Asia")}, "005930.KS",
+ "corroborating term 'samsung electronics'"),
+ ("Amazon to cut 14,000 corporate jobs", {("finance", "WSJ Markets")}, "AMZN",
+ "article from a finance feed (WSJ Markets)"),
+])
+def test_company_sense_still_admitted(headline, feeds, ticker, admitted_by):
+ mapped, _, excluded = nm.classify_companies(headline, feeds=feeds)
+ assert excluded == []
+ assert (mapped[0]["ticker"], mapped[0]["admitted_by"]) == (ticker, admitted_by)
+
+
+def test_feed_context_counts_only_from_the_listed_feeds():
+ apple_terms = "iphone, ipad, macbook, app store, tim cook, apple inc, airpods, ios"
+ mapped, _, excluded = nm.classify_companies(
+ "Apple to open new campus in Texas", feeds={("finance", "FT World"), ("finance", "Zero Hedge")})
+ assert mapped == []
+ assert excluded[0]["reason"].endswith(
+ f"no corroborating term ({apple_terms}) in the headlines; finance articles count only from "
+ "CNBC, MarketWatch or WSJ Markets, and this story's are from FT World and Zero Hedge")
+ mapped, _, _ = nm.classify_companies("Apple to open new campus in Texas", feeds={("finance", "CNBC")})
+ assert mapped[0]["admitted_by"] == "article from a finance feed (CNBC)"
+ # Categories alone name no feed, so a finance category admits nothing
+ mapped, _, excluded = nm.classify_companies("Apple to open new campus in Texas", {"finance"})
+ assert mapped == []
+ assert excluded[0]["reason"].endswith(
+ "in the headlines; finance articles count only from CNBC, MarketWatch or WSJ Markets")
+ # Chevron: energy context only from Oil Price and Rigzone; "chevron's",
+ # "oil", "crude" and "refinery" no longer corroborate
+ _, _, excluded = nm.classify_companies(
+ "Chevron's demise leaves agencies exposed in court", feeds={("energy", "Utility Dive")})
+ assert excluded[0]["reason"].endswith(
+ "in the headlines; energy articles count only from Oil Price or Rigzone, and this story's "
+ "are from Utility Dive")
+ _, _, excluded = nm.classify_companies("Chevron's demise leaves agencies exposed in court", {"government"})
+ assert excluded[0]["entity"]["name"] == "Chevron"
+
+
+def test_name_hyphen_joined_on_either_side_is_not_admitted_by_a_feed():
+ mapped, _, excluded = nm.classify_companies(
+ "Anti-Amazon protests spread across French warehouses", feeds={("technology", "Wired")})
+ assert mapped == []
+ assert excluded[0]["reason"].endswith(
+ "; the technology feed does not count because 'amazon' only appears hyphen-joined")
+
+
+async def test_composite_passes_feed_names_to_the_ambiguity_rule(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [_item("Apple to open new campus in Texas", "2026-10-16T12:00:00Z",
+ "finance", "FT World")])
+ out = await nm.fetch_news_market_reaction(fast_fetcher, min_cluster_size=1, now=_SATURDAY)
+ assert out["company_reactions"] == []
+ assert out["excluded"][0]["reason"].endswith("and this story's are from FT World")
+
+
+def test_company_without_a_ticker_says_so():
+ _, unmapped, _ = nm.classify_companies("Gazprom export revenue slumps")
+ assert unmapped == [{"entity": {"type": "company", "name": "Gazprom", "sector": "energy"},
+ "reason": "no ticker in the entity table"}]
+
+
+def test_country_index_rows_need_the_country_name():
+ excluded = []
+ mapped, unmapped = nm.classify_countries("American Airlines pilots vote to strike", excluded=excluded)
+ assert mapped == [] and unmapped == []
+ assert excluded == [{
+ "entity": {"type": "country", "iso3": "USA", "name": "United States"},
+ "reason": ("named only as 'american', not by the country's name (United States or USA); "
+ "an index row needs the name itself"),
+ }]
+ for headline, iso3, form in [
+ ("Indian Ocean cyclone forces port closures", "IND", "'indian'"),
+ ("Tex-Mex chain files for bankruptcy", "MEX", "'mex'"),
+ ("New Mexico wildfire forces evacuations", "MEX", "'new mexico'"),
+ ("Gulf of Mexico output recovers after storm", "MEX", "'gulf of mexico'"),
+ ("Beijing hosts trade envoys", "CHN", "'beijing'"),
+ ]:
+ excluded = []
+ mapped, _ = nm.classify_countries(headline, excluded=excluded)
+ assert mapped == [], headline
+ assert excluded[0]["entity"]["iso3"] == iso3
+ assert excluded[0]["reason"].startswith(f"named only as {form}, not by the country's name")
+ mapped, _ = nm.classify_countries("USA and Mexico agree on steel quotas")
+ assert [m["index"] for m in mapped] == ["^GSPC", "^MXX"]
+ # Without a collector the row goes to unmapped: listed, never dropped
+ mapped, unmapped = nm.classify_countries("American Airlines pilots vote to strike")
+ assert mapped == [] and unmapped[0]["reason"].startswith("named only as 'american'")
+
+
+async def test_composite_lists_countries_named_only_by_a_demonym(fast_fetcher, monkeypatch):
+ _feed(monkeypatch, [_item("American Airlines pilots vote to strike", "2026-10-16T12:00:00Z",
+ "geopolitics", "BBC World")])
+ out = await nm.fetch_news_market_reaction(fast_fetcher, min_cluster_size=1, now=_SATURDAY)
+ assert out["country_reactions"] == []
+ [row] = out["excluded"]
+ assert row["story"] == "American Airlines pilots vote to strike"
+ assert row["entity"]["iso3"] == "USA"
+ assert (out["summary"]["excluded"], out["summary"]["stories_with_entities"]) == (1, 1)
diff --git a/src/world_intel_mcp/tools/news_market.py b/src/world_intel_mcp/tools/news_market.py
index 80fa535..d52a9fb 100644
--- a/src/world_intel_mcp/tools/news_market.py
+++ b/src/world_intel_mcp/tools/news_market.py
@@ -15,13 +15,15 @@ TOOLS: list[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."
+ "from the entity table (US tickers annotated with their SEC registrant when SEC "
+ "lists them) 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; a session not yet closed or not yet final is pending. Unmapped "
+ "and ambiguous names are listed with reasons; a failed quote or an expired cached "
+ "copy is a data gap, never a 0% move. Same-session co-movement, not causation; not "
+ "a trading signal."
),
inputSchema={
"type": "object",
@@ -55,6 +57,11 @@ TOOLS: list[Tool] = [
"description": "Cap on tickers and indices fetched in one call (default 40, max 60)",
"default": 40,
},
+ "max_age_hours": {
+ "type": "number",
+ "description": "Leave out stories older than this many hours (default 168, max 2160)",
+ "default": 168,
+ },
},
},
),
@@ -64,6 +71,9 @@ TOOLS: list[Tool] = [
async def _news_market_reaction(arguments: dict[str, Any]) -> Any:
from ..analysis.news_market import fetch_news_market_reaction
+ extra: dict[str, Any] = {}
+ if arguments.get("max_age_hours") is not None:
+ extra["max_age_hours"] = arguments["max_age_hours"]
return await fetch_news_market_reaction(
runtime.fetcher,
category=arguments.get("category"),
@@ -72,6 +82,7 @@ async def _news_market_reaction(arguments: dict[str, Any]) -> Any:
min_cluster_size=arguments.get("min_cluster_size", 2),
include_countries=arguments.get("include_countries", True),
max_symbols=arguments.get("max_symbols", 40),
+ **extra,
)