Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(loaders): land RSSHub event/sentiment provider with explicit feed config

Haozhe Wuccfe50fff263
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index fbd2b7a9d..58c3a3e1c 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -20,6 +20,12 @@ from typing import Any, Callable, Dict, List, Optional
import pandas as pd
+from backtest.loaders.rsshub_events import (
+ FeedSpec,
+ RSSHubEventProvider,
+ enrich_price_frames_with_events,
+ feed_specs_from_config,
+)
from backtest.loaders.tushare_fundamentals import (
TushareFundamentalProvider,
enrich_price_frames_with_fundamentals,
@@ -202,6 +208,47 @@ def _maybe_enrich_fundamentals(
) from exc
+def _event_feed_specs(config: Dict[str, Any]) -> List[FeedSpec]:
+ """Parse the optional ``event_feeds`` feed definitions from backtest config.
+
+ ``event_feeds`` is a list of feed-definition dicts (there is no built-in
+ catalogue) — each with ``name``/``route_template``/``event_type`` and an
+ optional ``code_style``. An empty/absent value means "no event enrichment".
+ """
+ raw_feeds = config.get("event_feeds")
+ if raw_feeds in (None, [], {}):
+ return []
+ if not isinstance(raw_feeds, (list, tuple)):
+ raise ValueError("event_feeds must be a list of feed definitions")
+ return feed_specs_from_config(raw_feeds)
+
+
+def _maybe_enrich_events(
+ data_map: Dict[str, pd.DataFrame],
+ config: Dict[str, Any],
+) -> Dict[str, pd.DataFrame]:
+ """Attach a point-in-time-safe ``event_score`` column before signal generation."""
+ specs = _event_feed_specs(config)
+ if not specs:
+ return data_map
+
+ try:
+ provider = RSSHubEventProvider(feeds=specs)
+ if not provider.is_available():
+ raise RuntimeError(f"RSSHub base URL not configured (set ${'RSSHUB_BASE_URL'})")
+ return enrich_price_frames_with_events(
+ data_map,
+ provider,
+ as_of=config.get("end_date", ""),
+ decay_lambda=float(config.get("event_decay_lambda", 0.1)),
+ lookback=int(config.get("event_lookback", 30)),
+ )
+ except Exception as exc:
+ raise RuntimeError(
+ f"event_feeds requested but RSSHub enrichment failed: {exc}"
+ ) from exc
+
+
# ─── Base Engine ───
@@ -348,6 +395,7 @@ class BaseEngine(ABC):
print(json.dumps({"error": "No data fetched"}))
sys.exit(1)
data_map = _maybe_enrich_fundamentals(data_map, config)
+ data_map = _maybe_enrich_events(data_map, config)
# 2. Generate signals
signal_map = signal_engine.generate(data_map)
diff --git a/agent/backtest/loaders/rsshub_events.py b/agent/backtest/loaders/rsshub_events.py
new file mode 100644
index 000000000..10a6733fc
--- /dev/null
+++ b/agent/backtest/loaders/rsshub_events.py
@@ -0,0 +1,566 @@
+"""RSSHub event/sentiment provider with point-in-time safeguards.
+
+A news / announcement / sentiment provider that runs parallel to the Tushare
+fundamental layer (:mod:`backtest.loaders.tushare_fundamentals`). It pulls feeds
+from a self-hosted `RSSHub <https://docs.rsshub.app>`_ instance, normalises each
+item into the ``event-driven`` skill schema (``date, event_type, score, source,
+summary``), and attaches a point-in-time-safe ``event_score`` column to daily
+price frames.
+
+Point-in-time discipline (mirrors the fundamentals enricher): every item is
+stamped with a *knowable date* — the date a backtest could first have acted on
+it (items published after the close roll to the next session) — and only items
+with ``knowable_date <= as_of`` are ever returned. No feed item can leak into a
+bar dated before it became knowable.
+
+Scoring is pluggable. A deterministic, dependency-free lexicon scorer is used by
+default; callers may pass any ``scorer(title, summary) -> float`` (e.g. an LLM
+judge, as the ``event-driven`` skill describes) to override it.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import time
+from dataclasses import dataclass
+from email.utils import parsedate_to_datetime
+from typing import Any, Callable, Iterable, Mapping
+from xml.etree.ElementTree import ParseError
+
+import numpy as np
+import pandas as pd
+from defusedxml import ElementTree as ET
+from defusedxml.common import DefusedXmlException
+
+from backtest.loaders.base import retry_with_budget
+
+logger = logging.getLogger(__name__)
+
+RSSHUB_BASE_URL_ENV = "RSSHUB_BASE_URL"
+RSSHUB_BASE_URL_PLACEHOLDERS = {"", "https://rsshub.example.com"}
+RSSHUB_TIMEOUT_ENV = "RSSHUB_TIMEOUT_S"
+RSSHUB_BUDGET_ENV = "RSSHUB_FETCH_BUDGET_S"
+DEFAULT_TIMEOUT_S = 15.0
+DEFAULT_BUDGET_S = 60.0
+
+#: Hour (local to the feed timestamps) at/after which a publication is treated as
+#: knowable only on the next calendar day, matching the event-driven skill's
+#: "released after market close -> use the next trading day" rule.
+DEFAULT_CLOSE_CUTOFF_HOUR = 16
+
+#: Canonical column order for the tidy event frame.
+EVENT_COLUMNS: tuple[str, ...] = (
+ "ts_code",
+ "knowable_date",
+ "event_type",
+ "score",
+ "source",
+ "summary",
+)
+
+ScorerFn = Callable[[str, str], float]
+
+
+class EventProviderError(Exception):
+ """Base error for event-provider failures."""
+
+
+class UnknownFeedError(EventProviderError):
+ """Raised when a requested feed name is not registered."""
+
+
+#: Supported ``code_style`` values for per-symbol routes.
+CODE_STYLES: frozenset[str] = frozenset({"raw", "exchange_prefix", "bare"})
+
+
+def format_code_for_route(code: str, style: str) -> str:
+ """Convert a backtest code (e.g. ``"600519.SH"``) to a route's expected form.
+
+ RSSHub routes disagree on instrument formatting: some take the exchange-
+ prefixed form (``SH600519``, e.g. xueqiu), some the bare number (``600519``),
+ some a vendor-specific string. The backtest engine always passes the dotted
+ ``"600519.SH"`` form, so a feed declares the shape its route needs.
+
+ Args:
+ code: Dotted instrument code (``"600519.SH"``); passed through if it has
+ no ``.`` suffix.
+ style: One of :data:`CODE_STYLES` — ``"raw"`` (unchanged), ``"bare"``
+ (symbol only, ``"600519"``), or ``"exchange_prefix"`` (``"SH600519"``).
+
+ Returns:
+ The code formatted for the route.
+
+ Raises:
+ ValueError: If ``style`` is not a recognised code style.
+ """
+ if style not in CODE_STYLES:
+ raise ValueError(f"Unknown code_style {style!r}; expected one of {sorted(CODE_STYLES)}")
+ if style == "raw":
+ return code
+ symbol, _, suffix = code.partition(".")
+ if style == "bare":
+ return symbol
+ return f"{suffix.upper()}{symbol}" if suffix else symbol
+
+
+@dataclass(frozen=True)
+class FeedSpec:
+ """Machine-readable metadata for one RSSHub feed route.
+
+ Attributes:
+ name: Stable feed identifier used in configs (e.g. ``"sina_announcements"``).
+ route_template: RSSHub route with a ``{code}`` placeholder, joined to the
+ base URL (e.g. ``"/sina/announcement/{code}"``). Routes without a
+ ``{code}`` placeholder are treated as market-wide feeds.
+ event_type: Event class emitted for items from this feed; one of the
+ event-driven taxonomy (``earnings``/``macro``/``policy``/
+ ``sentiment``/``insider``/``technical_break``).
+ code_style: How the dotted backtest code is rewritten before it is
+ substituted into a per-symbol ``route_template`` — one of
+ :data:`CODE_STYLES`. Ignored for market-wide routes.
+ """
+
+ name: str
+ route_template: str
+ event_type: str
+ code_style: str = "raw"
+
+ def __post_init__(self) -> None:
+ if self.code_style not in CODE_STYLES:
+ raise ValueError(
+ f"FeedSpec {self.name!r}: unknown code_style {self.code_style!r}; "
+ f"expected one of {sorted(CODE_STYLES)}"
+ )
+
+ @property
+ def is_per_symbol(self) -> bool:
+ """Whether the route is parameterised by instrument code."""
+ return "{code}" in self.route_template
+
+
+def feed_specs_from_config(entries: Iterable[Mapping[str, Any]]) -> list[FeedSpec]:
+ """Build :class:`FeedSpec` objects from backtest-config dicts.
+
+ Each entry must carry ``name``, ``route_template`` and ``event_type``; an
+ optional ``code_style`` defaults to ``"raw"``. There is intentionally no
+ built-in feed catalogue — routes evolve and silently rot, so feeds are always
+ declared explicitly in config (or passed to the provider constructor).
+
+ Args:
+ entries: Iterable of mapping objects, one per feed.
+
+ Returns:
+ Parsed feed specs.
+
+ Raises:
+ ValueError: If an entry is missing a required key or has a duplicate name.
+ """
+ specs: list[FeedSpec] = []
+ seen: set[str] = set()
+ for entry in entries:
+ if not isinstance(entry, Mapping):
+ raise ValueError("each event feed must be a mapping with name/route_template/event_type")
+ missing = [k for k in ("name", "route_template", "event_type") if not str(entry.get(k, "")).strip()]
+ if missing:
+ raise ValueError(f"event feed is missing required field(s): {', '.join(missing)}")
+ name = str(entry["name"]).strip()
+ if name in seen:
+ raise ValueError(f"duplicate event feed name: {name!r}")
+ seen.add(name)
+ specs.append(
+ FeedSpec(
+ name=name,
+ route_template=str(entry["route_template"]).strip(),
+ event_type=str(entry["event_type"]).strip(),
+ code_style=str(entry.get("code_style", "raw")).strip() or "raw",
+ )
+ )
+ return specs
+
+
+#: No built-in feed catalogue: RSSHub routes change and break, so feeds are always
+#: supplied explicitly (via config ``event_feeds`` or the provider constructor).
+DEFAULT_FEEDS: tuple[FeedSpec, ...] = ()
+
+# ── Default dependency-free lexicon scorer ───────────────────────────────────
+
+_POSITIVE_TERMS: frozenset[str] = frozenset(
+ {
+ "beat",
+ "beats",
+ "surge",
+ "surges",
+ "soar",
+ "record",
+ "growth",
+ "profit",
+ "upgrade",
+ "upgraded",
+ "outperform",
+ "bullish",
+ "approval",
+ "approved",
+ "win",
+ "wins",
+ "buyback",
+ "dividend",
+ "expansion",
+ "breakthrough",
+ }
+)
+_NEGATIVE_TERMS: frozenset[str] = frozenset(
+ {
+ "miss",
+ "misses",
+ "plunge",
+ "plunges",
+ "fall",
+ "falls",
+ "loss",
+ "losses",
+ "downgrade",
+ "downgraded",
+ "underperform",
+ "bearish",
+ "fraud",
+ "probe",
+ "lawsuit",
+ "recall",
+ "default",
+ "bankruptcy",
+ "halt",
+ "warning",
+ "decline",
+ }
+)
+
+
+def default_lexicon_scorer(title: str, summary: str) -> float:
+ """Score text in ``[-1, 1]`` by net positive/negative term frequency.
+
+ A deterministic, dependency-free baseline. It is intentionally simple — the
+ provider is the data layer; richer scoring (e.g. an LLM judge) is plugged in
+ via the ``scorer`` argument on :meth:`RSSHubEventProvider.query_events`.
+
+ Args:
+ title: Item headline.
+ summary: Item summary/description (may be empty).
+
+ Returns:
+ Sentiment score in ``[-1.0, 1.0]``; ``0.0`` when no terms match.
+ """
+ tokens = f"{title} {summary}".lower().replace("/", " ").split()
+ if not tokens:
+ return 0.0
+ pos = sum(1 for tok in tokens if tok.strip(".,;:!?\"'()") in _POSITIVE_TERMS)
+ neg = sum(1 for tok in tokens if tok.strip(".,;:!?\"'()") in _NEGATIVE_TERMS)
+ hits = pos + neg
+ if hits == 0:
+ return 0.0
+ return max(-1.0, min(1.0, (pos - neg) / hits))
+
+
+def _knowable_date(published: pd.Timestamp, cutoff_hour: int) -> pd.Timestamp:
+ """Return the date an item becomes actionable (post-cutoff rolls to next day).
+
+ Args:
+ published: Parsed publication timestamp (tz dropped to naive local).
+ cutoff_hour: Hour at/after which publication rolls to the next day.
+
+ Returns:
+ Normalised (midnight) timestamp of the knowable date.
+ """
+ stamp = published.tz_localize(None) if published.tzinfo is not None else published
+ base = stamp.normalize()
+ if stamp.hour >= cutoff_hour:
+ base = base + pd.Timedelta(days=1)
+ return base
+
+
+def _clean_summary(text: str | None) -> str:
+ """Collapse whitespace and strip commas so the value is CSV-safe."""
+ if not text:
+ return ""
+ return " ".join(text.replace(",", " ").split())
+
+
+class RSSHubEventProvider:
+ """Point-in-time-safe event/sentiment provider backed by RSSHub.
+
+ Attributes:
+ base_url: Root of the RSSHub instance (no trailing slash).
+ feeds: Registered feed specs keyed by name.
+ close_cutoff_hour: Hour after which items roll to the next knowable day.
+ """
+
+ def __init__(
+ self,
+ base_url: str | None = None,
+ *,
+ feeds: Iterable[FeedSpec] | None = None,
+ client: Any | None = None,
+ close_cutoff_hour: int = DEFAULT_CLOSE_CUTOFF_HOUR,
+ ) -> None:
+ """Initialise the provider.
+
+ Args:
+ base_url: RSSHub root URL; defaults to ``$RSSHUB_BASE_URL``.
+ feeds: Feed specs to register; defaults to :data:`DEFAULT_FEEDS`.
+ client: Optional injected HTTP client exposing ``get(url, timeout=...)``
+ that returns an object with ``.text`` and ``.raise_for_status()``
+ (an ``httpx.Client``-like). Injectable for offline testing.
+ close_cutoff_hour: Knowable-date roll cutoff (0-23).
+ """
+ resolved = (base_url if base_url is not None else os.getenv(RSSHUB_BASE_URL_ENV, "")).strip()
+ self.base_url = resolved.rstrip("/")
+ specs = tuple(feeds) if feeds is not None else DEFAULT_FEEDS
+ self.feeds: dict[str, FeedSpec] = {spec.name: spec for spec in specs}
+ self.close_cutoff_hour = close_cutoff_hour
+ self._client = client
+
+ def is_available(self) -> bool:
+ """Whether a usable RSSHub base URL is configured."""
+ return self.base_url not in {p.rstrip("/") for p in RSSHUB_BASE_URL_PLACEHOLDERS}
+
+ def list_feeds(self) -> list[str]:
+ """Return registered feed names in stable order."""
+ return sorted(self.feeds)
+
+ def describe_feed(self, feed: str) -> FeedSpec:
+ """Return the spec for a registered feed.
+
+ Raises:
+ UnknownFeedError: If ``feed`` is not registered.
+ """
+ try:
+ return self.feeds[feed]
+ except KeyError as exc:
+ raise UnknownFeedError(f"Unknown RSSHub feed: {feed}") from exc
+
+ def query_events(
+ self,
+ codes: Iterable[str],
+ *,
+ as_of: str | pd.Timestamp,
+ feeds: Iterable[str] | None = None,
+ scorer: ScorerFn | None = None,
+ ) -> pd.DataFrame:
+ """Fetch and normalise feed items, dropping anything not yet knowable.
+
+ Args:
+ codes: Instrument codes to query.
+ as_of: Point-in-time boundary; items with ``knowable_date > as_of``
+ are excluded (no look-ahead).
+ feeds: Feed names to query; defaults to all registered feeds.
+ scorer: Optional ``scorer(title, summary) -> float`` override;
+ defaults to :func:`default_lexicon_scorer`.
+
+ Returns:
+ Tidy frame with :data:`EVENT_COLUMNS`, sorted by
+ ``(ts_code, knowable_date)`` and de-duplicated.
+ """
+ score_fn = scorer or default_lexicon_scorer
+ feed_names = list(feeds) if feeds is not None else self.list_feeds()
+ as_of_date = pd.Timestamp(as_of).normalize()
+
+ code_list = list(codes)
+ rows: list[dict[str, Any]] = []
+ attempted = 0
+ failed = 0
+ for feed_name in feed_names:
+ spec = self.describe_feed(feed_name)
+ for code in code_list:
+ attempted += 1
+ xml_text = self._fetch_feed(spec, code)
+ if not xml_text:
+ failed += 1
+ continue
+ rows.extend(self._parse_items(xml_text, code, spec, score_fn))
+
+ # A configured-but-fully-unreachable provider must fail loudly rather than
+ # silently scoring every bar 0.0 (which reads as "sentiment considered, no
+ # signal"). A reachable feed that simply returned no items is legitimate.
+ if attempted and failed == attempted:
+ raise EventProviderError(
+ f"All {attempted} RSSHub feed fetch(es) failed for base_url "
+ f"{self.base_url!r}; verify the instance is reachable and the "
+ f"configured routes exist (feeds={feed_names})"
+ )
+
+ if not rows:
+ return pd.DataFrame(columns=EVENT_COLUMNS)
+
+ frame = pd.DataFrame(rows, columns=list(EVENT_COLUMNS))
+ frame = frame[frame["knowable_date"] <= as_of_date]
+ frame = frame.drop_duplicates(subset=["ts_code", "knowable_date", "event_type", "summary"])
+ frame = frame.sort_values(["ts_code", "knowable_date"]).reset_index(drop=True)
+ return frame
+
+ def _fetch_feed(self, spec: FeedSpec, code: str) -> str:
+ """Fetch raw RSS XML for one feed/code, bounded by a wall-clock budget.
+
+ Returns the response body on success, or ``""`` when the fetch could not
+ complete within the budget — the caller logs and counts that as a failed
+ feed so an all-feeds-unreachable run can be surfaced loudly.
+ """
+ if spec.is_per_symbol:
+ route = spec.route_template.format(code=format_code_for_route(code, spec.code_style))
+ else:
+ route = spec.route_template
+ url = f"{self.base_url}{route}"
+ timeout = float(os.getenv(RSSHUB_TIMEOUT_ENV, DEFAULT_TIMEOUT_S))
+ budget = float(os.getenv(RSSHUB_BUDGET_ENV, DEFAULT_BUDGET_S))
+ client = self._client or self._default_client()
+ deadline = time.monotonic() + budget
+
+ def _do() -> str:
+ response = client.get(url, timeout=timeout)
+ response.raise_for_status()
+ return response.text
+
+ try:
+ return retry_with_budget(
+ _do,
+ transient=Exception,
+ deadline=deadline,
+ label=f"rsshub fetch {spec.name} for {code}",
+ )
+ except TimeoutError:
+ logger.warning(
+ "RSSHub feed %r for %s unreachable within %.0fs budget (%s); "
+ "no items contributed from this feed",
+ spec.name,
+ code,
+ budget,
+ url,
+ )
+ return ""
+
+ @staticmethod
+ def _default_client() -> Any:
+ """Construct a default httpx client (imported lazily)."""
+ import httpx
+
+ return httpx.Client(follow_redirects=True)
+
+ def _parse_items(
+ self,
+ xml_text: str,
+ code: str,
+ spec: FeedSpec,
+ score_fn: ScorerFn,
+ ) -> list[dict[str, Any]]:
+ """Parse RSS 2.0 ``<item>`` nodes into normalised event rows.
+
+ Uses ``defusedxml`` to neutralise XXE / entity-expansion attacks in the
+ untrusted feed payload; malformed or hostile XML yields no rows.
+ """
+ try:
+ root = ET.fromstring(xml_text)
+ except (ParseError, DefusedXmlException):
+ return []
+
+ rows: list[dict[str, Any]] = []
+ for item in root.iter("item"):
+ title = (item.findtext("title") or "").strip()
+ summary = _clean_summary(item.findtext("description"))
+ pub_raw = item.findtext("pubDate")
+ published = _parse_pubdate(pub_raw)
+ if published is None:
+ continue
+ rows.append(
+ {
+ "ts_code": code,
+ "knowable_date": _knowable_date(published, self.close_cutoff_hour),
+ "event_type": spec.event_type,
+ "score": float(score_fn(title, summary)),
+ "source": spec.name,
+ "summary": summary or title,
+ }
+ )
+ return rows
+
+
+def _parse_pubdate(value: str | None) -> pd.Timestamp | None:
+ """Parse an RFC-822 (RSS) or ISO ``pubDate`` into a Timestamp, or None."""
+ if not value or not value.strip():
+ return None
+ try:
+ return pd.Timestamp(parsedate_to_datetime(value))
+ except (TypeError, ValueError):
+ pass
+ try:
+ return pd.Timestamp(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def enrich_price_frames_with_events(
+ data_map: dict[str, pd.DataFrame],
+ provider: RSSHubEventProvider,
+ *,
+ as_of: str | pd.Timestamp,
+ feeds: Iterable[str] | None = None,
+ decay_lambda: float = 0.1,
+ lookback: int = 30,
+ min_abs_score: float = 0.0,
+ scorer: ScorerFn | None = None,
+) -> dict[str, pd.DataFrame]:
+ """Attach a point-in-time-safe ``event_score`` column to price frames.
+
+ For each bar ``t`` the score aggregates only events whose ``knowable_date``
+ falls in ``(t - lookback, t]``, exponentially decayed by age — the same
+ formula as the ``event-driven`` skill — so no future item can influence an
+ earlier bar. Two columns are added: ``event_score`` (decayed sum, clipped to
+ ``[-1, 1]``) and ``event_count`` (events in the window).
+
+ Args:
+ data_map: Mapping ``{code: OHLCV DataFrame}`` (DatetimeIndex).
+ provider: Configured :class:`RSSHubEventProvider`.
+ as_of: Point-in-time boundary passed through to the provider.
+ feeds: Feed names to query; defaults to all registered feeds.
+ decay_lambda: Exponential decay per day (higher decays faster).
+ lookback: Window in days; older events are excluded.
+ min_abs_score: Drop events with ``|score|`` below this threshold.
+ scorer: Optional scoring override forwarded to the provider.
+
+ Returns:
+ A new mapping with the same frames plus ``event_score``/``event_count``.
+ """
+ if not data_map:
+ return data_map
+
+ codes = list(data_map)
+ events = provider.query_events(codes, as_of=as_of, feeds=feeds, scorer=scorer)
+ enriched = {code: frame.copy() for code, frame in data_map.items()}
+ if events.empty:
+ for frame in enriched.values():
+ frame["event_score"] = 0.0
+ frame["event_count"] = 0
+ return enriched
+
+ if min_abs_score > 0.0:
+ events = events[events["score"].abs() >= min_abs_score]
+
+ for code, frame in enriched.items():
+ rows = events[events["ts_code"] == code]
+ bar_dates = pd.DatetimeIndex(pd.to_datetime(frame.index)).normalize()
+ scores = pd.Series(0.0, index=frame.index)
+ counts = pd.Series(0, index=frame.index)
+ if not rows.empty and len(frame) > 0:
+ ev_dates = rows["knowable_date"].to_numpy(dtype="datetime64[ns]")
+ ev_scores = rows["score"].to_numpy(dtype=float)
+ window = np.timedelta64(lookback, "D")
+ for pos, bar in enumerate(bar_dates):
+ bar64 = np.datetime64(bar, "ns")
+ mask = (ev_dates <= bar64) & (ev_dates > bar64 - window)
+ if not mask.any():
+ continue
+ ages = (bar64 - ev_dates[mask]) / np.timedelta64(1, "D")
+ decayed = float((ev_scores[mask] * np.exp(-decay_lambda * ages)).sum())
+ scores.iloc[pos] = max(-1.0, min(1.0, decayed))
+ counts.iloc[pos] = int(mask.sum())
+ frame["event_score"] = scores
+ frame["event_count"] = counts
+ return enriched
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index 420303c9c..887b892f7 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -14,7 +14,7 @@ import json
import logging
import sys
from pathlib import Path
-from typing import Dict, List, Optional
+from typing import Any, Dict, List, Optional
import pandas as pd
from pydantic import BaseModel, ConfigDict, model_validator, field_validator
@@ -62,6 +62,7 @@ class BacktestConfigSchema(BaseModel):
interval: str = "1D"
engine: str = "daily"
fundamental_fields: Optional[Dict[str, List[str]]] = None
+ event_feeds: Optional[List[Dict[str, Any]]] = None
@field_validator("codes")
@classmethod
@@ -117,6 +118,21 @@ class BacktestConfigSchema(BaseModel):
raise ValueError("fundamental_fields field names must be non-empty strings")
return v
+ @field_validator("event_feeds")
+ @classmethod
+ def valid_event_feeds(cls, v: Optional[List[Dict[str, Any]]]) -> Optional[List[Dict[str, Any]]]:
+ if v is None:
+ return v
+ for entry in v:
+ if not isinstance(entry, dict):
+ raise ValueError(
+ "each event_feeds entry must be an object with name/route_template/event_type"
+ )
+ for key in ("name", "route_template", "event_type"):
+ if not str(entry.get(key, "")).strip():
+ raise ValueError(f"event_feeds entry missing required field: {key}")
+ return v
+
@model_validator(mode="after")
def start_before_end(self) -> "BacktestConfigSchema":
if pd.Timestamp(self.start_date) > pd.Timestamp(self.end_date):
diff --git a/agent/src/skills/event-driven/example_signal_engine.py b/agent/src/skills/event-driven/example_signal_engine.py
new file mode 100644
index 000000000..ef97f7493
--- /dev/null
+++ b/agent/src/skills/event-driven/example_signal_engine.py
@@ -0,0 +1,104 @@
+"""Event-driven example signal engine (sentiment pre-filter / long-only).
+
+Companion to ``fundamental-filter/example_signal_engine.py``. It consumes the
+point-in-time-safe ``event_score`` column produced by
+:func:`backtest.loaders.rsshub_events.enrich_price_frames_with_events` (set
+``event_feeds`` in the backtest config) and goes equal-weight long on the names
+whose decayed sentiment clears a threshold on each bar.
+
+The ``event_score`` is already look-ahead-safe: for bar ``t`` it only reflects
+events knowable on or before ``t``. This engine therefore just reads the column;
+it never shifts it forward.
+"""
+
+from typing import Dict, List
+
+import numpy as np
+import pandas as pd
+
+
+class SignalEngine:
+ """Long-only sentiment pre-filter over the enriched ``event_score`` column.
+
+ Attributes:
+ score_threshold: Minimum ``event_score`` for a name to qualify on a bar.
+ top_n: Optional cap on the number of names held per bar (highest score
+ first); ``None`` holds all qualifiers.
+ """
+
+ def __init__(self, score_threshold: float = 0.2, top_n: int | None = None) -> None:
+ """Initialise the engine.
+
+ Args:
+ score_threshold: Minimum decayed sentiment to qualify (``[-1, 1]``).
+ top_n: Max names to hold per bar; ``None`` for unbounded.
+ """
+ self.score_threshold = score_threshold
+ self.top_n = top_n
+
+ def generate(self, data_map: Dict[str, pd.DataFrame]) -> Dict[str, pd.Series]:
+ """Equal-weight long the top-sentiment names on each bar.
+
+ Args:
+ data_map: Mapping ``{code: DataFrame}``; each frame must carry an
+ ``event_score`` column (enrichment adds it, defaulting to 0.0).
+
+ Returns:
+ Mapping ``{code: signal Series}`` aligned to each frame's index.
+ """
+ codes = list(data_map)
+ if not codes:
+ return {}
+
+ all_dates = sorted(set().union(*(df.index for df in data_map.values())))
+ date_index = pd.DatetimeIndex(all_dates)
+ signals: Dict[str, pd.Series] = {code: pd.Series(0.0, index=date_index) for code in codes}
+
+ for dt in date_index:
+ scored: List[tuple[str, float]] = []
+ for code, df in data_map.items():
+ if dt not in df.index:
+ continue
+ score = df.loc[dt].get("event_score", np.nan)
+ if pd.notna(score) and score >= self.score_threshold:
+ scored.append((code, float(score)))
+
+ if not scored:
+ continue
+ scored.sort(key=lambda item: item[1], reverse=True)
+ if self.top_n is not None:
+ scored = scored[: self.top_n]
+
+ weight = 1.0 / len(scored)
+ for code, _ in scored:
+ signals[code].at[dt] = weight
+
+ return {code: signals[code].reindex(df.index).fillna(0.0) for code, df in data_map.items()}
+
+
+if __name__ == "__main__":
+ # Demo: two names with injected event_score, one consistently positive.
+ dates = pd.bdate_range("2024-01-01", "2024-03-31")
+ rng = np.random.default_rng(7)
+
+ def _mock(score_center: float) -> pd.DataFrame:
+ n = len(dates)
+ return pd.DataFrame(
+ {
+ "open": rng.uniform(10, 50, n),
+ "high": rng.uniform(10, 50, n),
+ "low": rng.uniform(10, 50, n),
+ "close": rng.uniform(10, 50, n),
+ "volume": rng.uniform(1e6, 1e7, n),
+ "event_score": np.clip(rng.normal(score_center, 0.2, n), -1.0, 1.0),
+ "event_count": rng.integers(0, 4, n),
+ },
+ index=dates,
+ )
+
+ data_map = {"AAA": _mock(0.5), "BBB": _mock(-0.3)}
+ engine = SignalEngine(score_threshold=0.2, top_n=1)
+ signals = engine.generate(data_map)
+ for code in data_map:
+ active = (signals[code] > 0).sum()
+ print(f"{code}: {active}/{len(signals[code])} days held")
diff --git a/agent/tests/test_rsshub_events_lookahead.py b/agent/tests/test_rsshub_events_lookahead.py
new file mode 100644
index 000000000..784aa118d
--- /dev/null
+++ b/agent/tests/test_rsshub_events_lookahead.py
@@ -0,0 +1,96 @@
+"""No-look-ahead guarantee for RSSHub event enrichment.
+
+Echoes the discipline of ``agent/tests/factors/test_lookahead.py``: corrupting
+the future must not change the present. Here, adding a future-dated event must
+not alter ``event_score`` on any earlier bar.
+"""
+
+from __future__ import annotations
+
+from typing import Iterable
+
+import numpy as np
+import pandas as pd
+
+from backtest.loaders.rsshub_events import EVENT_COLUMNS, enrich_price_frames_with_events
+
+
+class _StubProvider:
+ """Returns a fixed event frame verbatim (ignores ``as_of``).
+
+ Ignoring ``as_of`` is deliberate: it forces the *enricher's* per-bar masking
+ to be the only thing standing between a future event and an earlier bar.
+ """
+
+ def __init__(self, events: pd.DataFrame) -> None:
+ self._events = events
+
+ def query_events(self, codes: Iterable[str], *, as_of, feeds=None, scorer=None) -> pd.DataFrame:
+ return self._events[self._events["ts_code"].isin(list(codes))].copy()
+
+
+def _events(rows: list[tuple[str, str, str, float, str, str]]) -> pd.DataFrame:
+ frame = pd.DataFrame(rows, columns=list(EVENT_COLUMNS))
+ frame["knowable_date"] = pd.to_datetime(frame["knowable_date"])
+ return frame
+
+
+def _price_frame() -> pd.DataFrame:
+ dates = pd.bdate_range("2024-01-01", "2024-01-31")
+ n = len(dates)
+ return pd.DataFrame(
+ {
+ "open": np.linspace(10, 20, n),
+ "high": np.linspace(11, 21, n),
+ "low": np.linspace(9, 19, n),
+ "close": np.linspace(10, 20, n),
+ "volume": np.full(n, 1e6),
+ },
+ index=dates,
+ )
+
+
+def test_future_event_does_not_leak_into_earlier_bars() -> None:
+ data_map = {"AAA": _price_frame()}
+ probe = pd.Timestamp("2024-01-15")
+
+ past = _events([("AAA", "2024-01-10", "sentiment", 0.8, "news", "good")])
+ past_plus_future = _events(
+ [
+ ("AAA", "2024-01-10", "sentiment", 0.8, "news", "good"),
+ ("AAA", "2024-01-25", "sentiment", -1.0, "news", "bad future"),
+ ]
+ )
+
+ base = enrich_price_frames_with_events({"AAA": _price_frame()}, _StubProvider(past), as_of=probe)
+ poisoned = enrich_price_frames_with_events(
+ {"AAA": _price_frame()}, _StubProvider(past_plus_future), as_of=probe
+ )
+
+ # The future (2024-01-25) event must not move the score at 2024-01-15.
+ assert base["AAA"].loc[probe, "event_score"] == poisoned["AAA"].loc[probe, "event_score"]
+ assert base["AAA"].loc[probe, "event_score"] > 0 # the past event does register
+
+ # Sanity: the future event DOES register once the bar reaches it.
+ late = pd.Timestamp("2024-01-26")
+ assert poisoned["AAA"].loc[late, "event_score"] < base["AAA"].loc[late, "event_score"]
+ assert data_map # frame fixture used
+
+
+def test_decay_is_monotonic_with_age() -> None:
+ events = _events([("AAA", "2024-01-02", "sentiment", 1.0, "news", "one shot")])
+ enriched = enrich_price_frames_with_events(
+ {"AAA": _price_frame()}, _StubProvider(events), as_of="2024-01-31", lookback=60
+ )
+ score = enriched["AAA"]["event_score"]
+ active = score[score > 0]
+ assert active.is_monotonic_decreasing # single event decays as bars age away
+
+
+def test_empty_events_yield_zero_columns() -> None:
+ empty = _events([])
+ enriched = enrich_price_frames_with_events(
+ {"AAA": _price_frame()}, _StubProvider(empty), as_of="2024-01-31"
+ )
+ assert (enriched["AAA"]["event_score"] == 0.0).all()
+ assert (enriched["AAA"]["event_count"] == 0).all()
diff --git a/agent/tests/test_rsshub_events_provider.py b/agent/tests/test_rsshub_events_provider.py
new file mode 100644
index 000000000..4c80340e6
--- /dev/null
+++ b/agent/tests/test_rsshub_events_provider.py
@@ -0,0 +1,237 @@
+"""Unit tests for the RSSHub event/sentiment provider (no network)."""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from backtest.loaders.rsshub_events import (
+ DEFAULT_FEEDS,
+ EVENT_COLUMNS,
+ EventProviderError,
+ FeedSpec,
+ RSSHubEventProvider,
+ UnknownFeedError,
+ default_lexicon_scorer,
+ feed_specs_from_config,
+ format_code_for_route,
+)
+
+_RSS = """<?xml version="1.0" encoding="UTF-8"?>
+<rss version="2.0"><channel>
+ <item>
+ <title>Company beats earnings</title>
+ <description>Q4 revenue surges on strong demand</description>
+ <pubDate>Mon, 15 Jan 2024 09:00:00 +0000</pubDate>
+ </item>
+ <item>
+ <title>Regulator opens probe</title>
+ <description>probe into accounting, shares plunge</description>
+ <pubDate>Tue, 16 Jan 2024 18:30:00 +0000</pubDate>
+ </item>
+</channel></rss>"""
+
+# A billion-laughs payload: must be neutralised by defusedxml, never expanded.
+_HOSTILE = """<?xml version="1.0"?>
+<!DOCTYPE lolz [
+ <!ENTITY lol "lol">
+ <!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
+ <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
+]>
+<rss version="2.0"><channel><item><title>&lol3;</title>
+<pubDate>Mon, 15 Jan 2024 09:00:00 +0000</pubDate></item></channel></rss>"""
+
+
+class _FakeResponse:
+ def __init__(self, text: str) -> None:
+ self.text = text
+
+ def raise_for_status(self) -> None:
+ return None
+
+
+class _FakeClient:
+ """Minimal httpx.Client stand-in returning a fixed payload."""
+
+ def __init__(self, payload: str) -> None:
+ self.payload = payload
+ self.calls: list[str] = []
+
+ def get(self, url: str, timeout: float | None = None) -> _FakeResponse:
+ self.calls.append(url)
+ return _FakeResponse(self.payload)
+
+
+def _provider(payload: str = _RSS) -> RSSHubEventProvider:
+ return RSSHubEventProvider(
+ "https://rsshub.local",
+ feeds=[FeedSpec("news", "/stock/news/{code}", "sentiment")],
+ client=_FakeClient(payload),
+ )
+
+
+def test_is_available_true_with_base_url() -> None:
+ assert _provider().is_available() is True
+
+
[email protected]("base", ["", "https://rsshub.example.com", " "])
+def test_is_available_false_without_real_base_url(base: str) -> None:
+ assert RSSHubEventProvider(base, client=_FakeClient(_RSS)).is_available() is False
+
+
+def test_query_events_schema_and_scoring() -> None:
+ frame = _provider().query_events(["AAA"], as_of="2024-01-31")
+ assert list(frame.columns) == list(EVENT_COLUMNS)
+ assert set(frame["ts_code"]) == {"AAA"}
+ assert (frame["event_type"] == "sentiment").all()
+
+ by_summary = {row.summary: row.score for row in frame.itertuples()}
+ bullish = next(s for t, s in by_summary.items() if "revenue" in t)
+ bearish = next(s for t, s in by_summary.items() if "probe" in t)
+ assert bullish > 0
+ assert bearish < 0
+
+
+def test_after_close_publication_rolls_to_next_day() -> None:
+ frame = _provider().query_events(["AAA"], as_of="2024-01-31")
+ dates = dict(zip(frame["summary"], frame["knowable_date"]))
+ intraday = next(v for k, v in dates.items() if "revenue" in k) # 09:00 -> same day
+ after_close = next(v for k, v in dates.items() if "probe" in k) # 18:30 -> next day
+ assert intraday == pd.Timestamp("2024-01-15")
+ assert after_close == pd.Timestamp("2024-01-17")
+
+
+def test_point_in_time_filter_excludes_future_items() -> None:
+ frame = _provider().query_events(["AAA"], as_of="2024-01-15")
+ assert (frame["knowable_date"] <= pd.Timestamp("2024-01-15")).all()
+ assert len(frame) == 1 # only the 09:00 item is knowable by the 15th
+
+
+def test_duplicate_items_are_deduplicated() -> None:
+ items = _RSS.split("<channel>")[1].split("</channel>")[0]
+ doubled = f'<?xml version="1.0"?><rss version="2.0"><channel>{items}{items}</channel></rss>'
+ frame = _provider(doubled).query_events(["AAA"], as_of="2024-01-31")
+ assert len(frame) == 2 # 4 items in, 2 unique out
+ assert frame.duplicated(subset=["ts_code", "knowable_date", "event_type", "summary"]).sum() == 0
+
+
+def test_hostile_xml_is_neutralised() -> None:
+ frame = _provider(_HOSTILE).query_events(["AAA"], as_of="2024-01-31")
+ assert frame.empty
+
+
+def test_unknown_feed_raises() -> None:
+ with pytest.raises(UnknownFeedError):
+ _provider().query_events(["AAA"], as_of="2024-01-31", feeds=["does_not_exist"])
+
+
+def test_custom_scorer_override() -> None:
+ frame = _provider().query_events(["AAA"], as_of="2024-01-31", scorer=lambda t, s: 0.5)
+ assert (frame["score"] == 0.5).all()
+
+
+def test_default_lexicon_scorer_bounds() -> None:
+ assert default_lexicon_scorer("", "") == 0.0
+ assert default_lexicon_scorer("neutral filler text", "") == 0.0
+ assert -1.0 <= default_lexicon_scorer("loss plunge fraud", "") <= 0.0
+ assert 0.0 <= default_lexicon_scorer("beat surge record", "") <= 1.0
+
+
+# ── No-default-catalogue + per-symbol code formatting + loud failures ─────────
+
+
+class _FailingClient:
+ """Client whose every request raises a transient error."""
+
+ def get(self, url: str, timeout: float | None = None) -> _FakeResponse:
+ raise ConnectionError(f"unreachable: {url}")
+
+
+def test_no_builtin_feed_catalogue() -> None:
+ # Routes rot as RSSHub evolves, so feeds are always declared explicitly.
+ assert DEFAULT_FEEDS == ()
+
+
+ "code,style,expected",
+ [
+ ("600519.SH", "raw", "600519.SH"),
+ ("600519.SH", "bare", "600519"),
+ ("600519.SH", "exchange_prefix", "SH600519"),
+ ("000001.SZ", "exchange_prefix", "SZ000001"),
+ ("AAPL", "exchange_prefix", "AAPL"), # no exchange suffix -> symbol only
+ ],
+)
+def test_format_code_for_route(code: str, style: str, expected: str) -> None:
+ assert format_code_for_route(code, style) == expected
+
+
+def test_format_code_for_route_rejects_unknown_style() -> None:
+ with pytest.raises(ValueError):
+ format_code_for_route("600519.SH", "nope")
+
+
+def test_feedspec_rejects_unknown_code_style() -> None:
+ with pytest.raises(ValueError):
+ FeedSpec("x", "/x/{code}", "earnings", code_style="bogus")
+
+
+def test_per_symbol_route_applies_code_style() -> None:
+ client = _FakeClient(_RSS)
+ provider = RSSHubEventProvider(
+ "https://rsshub.local",
+ feeds=[FeedSpec("xq", "/xueqiu/stock/{code}", "earnings", code_style="exchange_prefix")],
+ client=client,
+ )
+ provider.query_events(["600519.SH"], as_of="2024-01-31")
+ assert client.calls == ["https://rsshub.local/xueqiu/stock/SH600519"]
+
+
+def test_feed_specs_from_config_parses_and_validates() -> None:
+ specs = feed_specs_from_config(
+ [
+ {"name": "a", "route_template": "/x/{code}", "event_type": "earnings"},
+ {"name": "b", "route_template": "/y", "event_type": "macro", "code_style": "bare"},
+ ]
+ )
+ assert [s.name for s in specs] == ["a", "b"]
+ assert specs[1].code_style == "bare"
+ assert specs[0].code_style == "raw" # default
+
+
+ "bad",
+ [
+ [{"name": "", "route_template": "/x", "event_type": "earnings"}], # blank name
+ [{"route_template": "/x", "event_type": "earnings"}], # missing name
+ [{"name": "a", "route_template": "/x"}], # missing event_type
+ [
+ {"name": "a", "route_template": "/x", "event_type": "e"},
+ {"name": "a", "route_template": "/y", "event_type": "e"}, # duplicate name
+ ],
+ ["not-a-mapping"],
+ ],
+)
+def test_feed_specs_from_config_rejects_bad(bad: list) -> None:
+ with pytest.raises(ValueError):
+ feed_specs_from_config(bad)
+
+
+def test_all_feeds_unreachable_raises(monkeypatch) -> None:
+ # A configured-but-fully-unreachable provider must fail loudly, never score
+ # every bar 0.0 silently. Zero budget makes the retry abort immediately.
+ monkeypatch.setenv("RSSHUB_FETCH_BUDGET_S", "0")
+ provider = RSSHubEventProvider(
+ "https://rsshub.local",
+ feeds=[FeedSpec("news", "/stock/news/{code}", "sentiment")],
+ client=_FailingClient(),
+ )
+ with pytest.raises(EventProviderError):
+ provider.query_events(["AAA"], as_of="2024-01-31")
+
+
+def test_reachable_but_empty_feed_does_not_raise() -> None:
+ # A feed that fetched fine but had no <item>s is legitimate, not an error.
+ empty_rss = '<?xml version="1.0"?><rss version="2.0"><channel></channel></rss>'
+ frame = _provider(empty_rss).query_events(["AAA"], as_of="2024-01-31")
+ assert frame.empty
diff --git a/pyproject.toml b/pyproject.toml
index ba05b4b98..679a372b4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -26,6 +26,7 @@ dependencies = [
"langgraph-checkpoint>=2.1.0,<5",
"python-dotenv>=1.0.0",
"httpx>=0.28.0",
+ "defusedxml>=0.7.1",
"oauth-cli-kit>=0.1.3",
"pandas>=2.0.0",
"openpyxl>=3.1.0",