"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(swarm): pre-fetch market data and ground worker prompts in real prices
Teerapat Vatpitakb1d363b33c50
diff --git a/agent/src/swarm/grounding.py b/agent/src/swarm/grounding.pynew file mode 100644index 000000000..f3c7b84bd--- /dev/null+++ b/agent/src/swarm/grounding.py@@ -0,0 +1,195 @@+"""Pre-fetch market data for symbols mentioned in a swarm's user_vars.++Why this exists+---------------+Swarm workers are LLMs. Without explicit grounding they cheerfully quote+prices from their training data — which is wrong by definition for any+asset that has traded since the model's cutoff. The fix can only be+structural: feed the worker the real recent prices before it starts+reasoning, and tell it those are the only prices it may cite.++What this module does+---------------------+* Scans every value in ``user_vars`` for tokens that match one of the+ data-source-suffixed symbol shapes the loaders already understand+ (``NVDA.US``, ``700.HK``, ``600519.SH``, ``BTC-USDT``, etc.).+* Pulls the last ``DEFAULT_WINDOW_DAYS`` of OHLCV for each detected+ symbol via ``backtest.loaders.registry.resolve_loader`` with+ ``source="auto"``. Failures (delisted ticker, network blip) are+ swallowed per-symbol so they do not poison the whole run.+* Renders a compact markdown block the worker prompt can splice in.++What this module **does not** do+--------------------------------+* It does not match bare tickers (``NVDA`` without ``.US``) — too easy+ to false-positive on common English words. Users supply suffixed+ symbols already in every shipped preset.+* It does not refresh data mid-run. The block is a snapshot taken once+ at ``start_run`` time; long-running swarms will see stale data after+ many minutes, but that is still strictly better than training-data+ prices from a year ago.+"""++from __future__ import annotations++import logging+import re+from datetime import date, timedelta+from typing import Iterable++logger = logging.getLogger(__name__)+++# Window of OHLCV bars to fetch per symbol. 30 calendar days yields+# roughly 21 US trading days — enough for a "recent" view without+# bloating the worker prompt.+DEFAULT_WINDOW_DAYS = 30++# How many of the most-recent rows to render in the worker prompt.+# The full window is still used to compute the min/max line; the table+# is truncated for readability.+PROMPT_TABLE_TAIL = 5++# Symbol patterns understood by the bundled loaders. Anchored on word+# boundaries so substrings of longer text don't trigger.+_SYMBOL_PATTERNS: tuple[re.Pattern[str], ...] = (+ re.compile(r"\b[A-Z]{1,5}\.US\b"),+ re.compile(r"\b\d{3,5}\.HK\b"),+ re.compile(r"\b\d{6}\.(?:SZ|SH|BJ)\b"),+ re.compile(r"\b[A-Z]{2,6}-USDT\b"),+)+++def extract_symbols_from_user_vars(user_vars: dict[str, str]) -> list[str]:+ """Return the deduplicated list of symbols mentioned anywhere in *user_vars*.++ Order is preserved from first occurrence so the worker prompt is+ deterministic when nothing else changes.+ """+ seen: dict[str, None] = {} # ordered set+ for value in user_vars.values():+ if not isinstance(value, str):+ continue+ for pattern in _SYMBOL_PATTERNS:+ for match in pattern.findall(value):+ seen.setdefault(match, None)+ return list(seen.keys())+++def fetch_grounding_data(+ symbols: Iterable[str],+ *,+ window_days: int = DEFAULT_WINDOW_DAYS,+ today: date | None = None,+) -> dict[str, list[dict]]:+ """Fetch OHLCV for *symbols* and return a code -> list-of-bars mapping.++ Each bar is a plain dict with ``trade_date`` (ISO string), ``open``,+ ``high``, ``low``, ``close``, ``volume``. Symbols that fail to+ resolve are simply omitted from the result with a logged warning.++ Args:+ symbols: Iterable of suffixed symbols (``NVDA.US`` etc.).+ window_days: Calendar-day lookback. Defaults to+ :data:`DEFAULT_WINDOW_DAYS`.+ today: Override the upper bound (mainly for tests). Defaults to+ ``date.today()``.++ Returns:+ Dict keyed by the *original* symbol string with the bars list as+ value. Empty if no symbols resolve.+ """+ symbols_list = list(symbols)+ if not symbols_list:+ return {}++ end = today or date.today()+ start = end - timedelta(days=window_days)+ start_str = start.isoformat()+ end_str = end.isoformat()++ # Imported lazily so unit tests of the extraction / formatting layer+ # don't have to drag in pandas + the loader graph just to import.+ from backtest.loaders.registry import resolve_loader++ out: dict[str, list[dict]] = {}+ for code in symbols_list:+ try:+ loader_cls = resolve_loader(code)+ loader = loader_cls()+ df_map = loader.fetch([code], start_str, end_str, interval="1D")+ except Exception as exc: # pragma: no cover — depends on network+ logger.warning(+ "grounding: failed to fetch %s — %s", code, exc, exc_info=False+ )+ continue+ df = df_map.get(code)+ if df is None or df.empty:+ logger.info("grounding: no data returned for %s", code)+ continue+ rows: list[dict] = []+ for ts, row in df.iterrows():+ rows.append({+ "trade_date": getattr(ts, "isoformat", lambda: str(ts))(),+ "open": float(row.get("open", 0.0)),+ "high": float(row.get("high", 0.0)),+ "low": float(row.get("low", 0.0)),+ "close": float(row.get("close", 0.0)),+ "volume": float(row.get("volume", 0.0)),+ })+ if rows:+ out[code] = rows+ return out+++def format_grounding_block(grounding: dict[str, list[dict]]) -> str:+ """Render *grounding* as a markdown block ready to splice into a prompt.++ Returns the empty string if no symbol has any data — callers can use+ that as a falsy guard so the section is omitted entirely instead of+ rendering an empty heading.+ """+ if not grounding:+ return ""++ sections: list[str] = []+ for code, rows in grounding.items():+ if not rows:+ continue+ first_date = rows[0]["trade_date"][:10]+ last_date = rows[-1]["trade_date"][:10]+ closes = [row["close"] for row in rows]+ window_low = min(closes)+ window_high = max(closes)+ last_close = closes[-1]++ lines = [+ f"### {code} (window {first_date} → {last_date})",+ "",+ "| Date | Close | Volume |",+ "| --- | ---: | ---: |",+ ]+ for row in rows[-PROMPT_TABLE_TAIL:]:+ lines.append(+ f"| {row['trade_date'][:10]} | {row['close']:.2f} "+ f"| {int(row['volume']):,} |"+ )+ lines.append("")+ lines.append(+ f"**Latest close:** {last_close:.2f} ({last_date}) "+ f"**Window range:** {window_low:.2f} – {window_high:.2f}"+ )+ sections.append("\n".join(lines))++ if not sections:+ return ""++ header = (+ "## Ground Truth — Recent Market Data\n\n"+ "**These are the authoritative current prices for this run.** Do NOT "+ "cite prices, valuations, multiples, or returns from your training "+ "data — markets have moved. If you need a price outside this window, "+ "call `get_market_data` for the relevant range. When you state a "+ "price, cite the date from this table."+ )+ return header + "\n\n" + "\n\n".join(sections)diff --git a/agent/src/swarm/models.py b/agent/src/swarm/models.pyindex c1b3c16bc..707347812 100644--- a/agent/src/swarm/models.py+++ b/agent/src/swarm/models.py@@ -174,6 +174,13 @@ class SwarmRun(BaseModel):field is the run-level default.model: LLM model name in effect when the run started, captured from``LANGCHAIN_MODEL_NAME``. Same scoping rules as :attr:`provider`.+ grounding_data: Pre-fetched OHLCV bars for any suffixed stock or+ crypto symbols mentioned in :attr:`user_vars`. Captured once at+ run-creation time by :mod:`src.swarm.grounding` so workers see+ real recent prices instead of training-data prices. Keyed by the+ original symbol string; each value is the list of bars returned+ by the loader. ``None`` when no symbols were detected or every+ fetch failed."""id: str@@ -189,6 +196,7 @@ class SwarmRun(BaseModel):total_output_tokens: int = 0provider: str | None = Nonemodel: str | None = None+ grounding_data: dict[str, list[dict]] | None = Noneclass WorkerResult(BaseModel):diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.pyindex ffd5ec258..309408271 100644--- a/agent/src/swarm/runtime.py+++ b/agent/src/swarm/runtime.py@@ -20,6 +20,7 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Callable+from src.swarm import groundingfrom src.swarm.mailbox import Mailboxfrom src.swarm.models import (RunStatus,@@ -102,6 +103,24 @@ class SwarmRuntime:run.provider = (os.getenv("LANGCHAIN_PROVIDER") or "").strip().lower() or Nonerun.model = (os.getenv("LANGCHAIN_MODEL_NAME") or "").strip() or None+ # Pre-fetch market data for any suffixed stock / crypto symbols+ # mentioned in user_vars and pin it on the run. Workers read these+ # bars off run.grounding_data instead of hallucinating prices from+ # their training cutoff. Failures are non-fatal — the run still+ # proceeds, just without the grounding block.+ symbols = grounding.extract_symbols_from_user_vars(user_vars)+ if symbols:+ try:+ fetched = grounding.fetch_grounding_data(symbols)+ except Exception:+ logger.warning(+ "grounding: pre-fetch failed for run %s symbols=%s",+ run.id, symbols, exc_info=True,+ )+ fetched = {}+ if fetched:+ run.grounding_data = fetched+self._store.create_run(run)cancel_event = threading.Event()@@ -220,6 +239,11 @@ class SwarmRuntime:# Build agent lookupagent_map: dict[str, SwarmAgentSpec] = {a.id: a for a in run.agents}+ # Render the grounding block once and pass it to every worker on+ # this run. The block is empty when no symbols were detected, in+ # which case workers see no extra section.+ grounding_block = grounding.format_grounding_block(run.grounding_data or {})+# Compute execution layerslayers = topological_layers(run.tasks)task_summaries: dict[str, str] = {}@@ -409,6 +433,7 @@ class SwarmRuntime:event_callback=_event_callback,run_id=run.id,include_shell_tools=include_shell_tools,+ grounding_block=grounding_block,)futures[future] = tidper_task_budget = agent_spec.timeout_seconds * (agent_spec.max_retries + 1)@@ -463,6 +488,7 @@ class SwarmRuntime:event_callback: Callable[[SwarmEvent], None] | None,run_id: str,include_shell_tools: bool = False,+ grounding_block: str = "",) -> WorkerResult:"""Run a worker with automatic retry on failure.@@ -479,6 +505,9 @@ class SwarmRuntime:event_callback: Optional event callback.run_id: Run identifier for event emission.include_shell_tools: Whether the worker may register shell tools.+ grounding_block: Pre-rendered "Ground Truth" markdown spliced+ into the worker's system prompt. Empty string when no+ symbols were extracted from user_vars.Returns:WorkerResult from the last attempt.@@ -513,6 +542,7 @@ class SwarmRuntime:run_dir=run_dir,event_callback=event_callback,include_shell_tools=include_shell_tools,+ grounding_block=grounding_block,)cumulative_input_tokens += result.input_tokensdiff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex 12eeac1a9..ca2cc4856 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -123,6 +123,7 @@ def build_worker_prompt(agent_spec: SwarmAgentSpec,upstream_summaries: dict[str, str],skill_descriptions: str,+ grounding_block: str = "",) -> str:"""Build the worker's system prompt with role, upstream context, and skills.@@ -130,6 +131,11 @@ def build_worker_prompt(agent_spec: The agent's role specification.upstream_summaries: Mapping of context_key -> upstream task summary.skill_descriptions: Pre-filtered skill description text.+ grounding_block: Optional "Ground Truth" markdown produced by+ :func:`src.swarm.grounding.format_grounding_block`. Spliced in+ ahead of the Execution Rules section so the worker sees real+ recent prices before any tool decision. Empty string skips the+ section entirely.Returns:Complete system prompt string for the worker LLM.@@ -154,6 +160,12 @@ def build_worker_prompt(f"## Available Skills (use load_skill to access full documentation)\n\n{skill_descriptions}")+ if grounding_block:+ # Placed before Execution Rules so it's in scope when the worker+ # plans its first tool call. The block already contains an explicit+ # instruction to prefer these prices over training data.+ prompt_parts.append(grounding_block)+prompt_parts.append("## Execution Rules\n\n""You have a HARD LIMIT of 20 tool calls. After that you will be cut off. Work efficiently.\n\n"@@ -187,6 +199,7 @@ def run_worker(run_dir: Path,event_callback: Callable[[SwarmEvent], None] | None = None,include_shell_tools: bool = False,+ grounding_block: str = "",) -> WorkerResult:"""Execute a single worker task using a lightweight ReAct loop.@@ -207,6 +220,9 @@ def run_worker(run_dir: Path to .swarm/runs/{run_id}/ directory.event_callback: Optional callback for swarm events.include_shell_tools: Whether this worker may register shell tools.+ grounding_block: Optional pre-rendered "Ground Truth" markdown that+ anchors the worker on real recent prices for symbols mentioned in+ ``user_vars``. Forwarded verbatim to :func:`build_worker_prompt`.Returns:WorkerResult with status, summary, artifacts, and iteration count.@@ -227,7 +243,9 @@ def run_worker(# 3. Build system prompt with filtered skillsskills_loader = SkillsLoader()skill_desc = _filter_skill_descriptions(skills_loader, agent_spec.skills)- system_prompt = build_worker_prompt(agent_spec, upstream_summaries, skill_desc)+ system_prompt = build_worker_prompt(+ agent_spec, upstream_summaries, skill_desc, grounding_block=grounding_block,+ )# 4. Resolve prompt template with user vars (missing vars → LLM infers)class _FallbackDict(dict):diff --git a/agent/tests/test_swarm_grounding.py b/agent/tests/test_swarm_grounding.pynew file mode 100644index 000000000..bc53316f6--- /dev/null+++ b/agent/tests/test_swarm_grounding.py@@ -0,0 +1,187 @@+"""Unit tests for the swarm grounding module.++Network-touching paths (the actual loader fetch) are exercised through a+monkeypatched stub so the suite stays offline; symbol extraction and the+markdown formatter are pure-function tests.+"""++from __future__ import annotations++from datetime import date++import pandas as pd+import pytest++from src.swarm import grounding+from src.swarm.worker import build_worker_prompt+from src.swarm.models import SwarmAgentSpec+++# --------------------------------------------------------------------------- #+# extract_symbols_from_user_vars+# --------------------------------------------------------------------------- #++def test_extract_us_hk_a_share_and_crypto_symbols() -> None:+ user_vars = {+ "target": "NVDA.US",+ "secondary": "Compare with 700.HK and 600519.SH",+ "crypto": "Hedge with BTC-USDT",+ "shenzhen": "000001.SZ for liquidity",+ "beijing": "Listed on 430090.BJ recently",+ }+ found = grounding.extract_symbols_from_user_vars(user_vars)+ assert set(found) == {+ "NVDA.US", "700.HK", "600519.SH", "BTC-USDT", "000001.SZ", "430090.BJ",+ }+++def test_extract_preserves_first_occurrence_order() -> None:+ user_vars = {+ "a": "Look at NVDA.US",+ "b": "Compare to AAPL.US",+ "c": "And NVDA.US again",+ }+ assert grounding.extract_symbols_from_user_vars(user_vars) == ["NVDA.US", "AAPL.US"]+++def test_extract_returns_empty_when_no_symbol_present() -> None:+ user_vars = {+ "goal": "Q2 2026 outlook",+ "market": "US equities", # no suffixed symbol+ }+ assert grounding.extract_symbols_from_user_vars(user_vars) == []+++def test_extract_skips_non_string_values() -> None:+ user_vars = {+ "ticker": "TSM", # bare ticker — intentionally not matched+ "weight": 0.5, # type: ignore[dict-item] — not a str+ "real_target": "TSLA.US",+ }+ assert grounding.extract_symbols_from_user_vars(user_vars) == ["TSLA.US"]+++def test_extract_does_not_match_substrings_inside_words() -> None:+ user_vars = {+ # \b boundary should keep "FOO.USDA" / "BLAH.USA" from matching .US+ "noisy": "regulator FOO.USDA approved BLAH.USAID rules",+ }+ assert grounding.extract_symbols_from_user_vars(user_vars) == []+++# --------------------------------------------------------------------------- #+# fetch_grounding_data — monkeypatched loader+# --------------------------------------------------------------------------- #++class _StubLoader:+ """Mimics enough of the loader contract for grounding.fetch."""++ def __init__(self, frame: pd.DataFrame) -> None:+ self._frame = frame++ def fetch(self, codes, start_date, end_date, *, interval="1D"):+ return {code: self._frame for code in codes}+++def _three_bar_frame() -> pd.DataFrame:+ idx = pd.to_datetime(["2026-05-06", "2026-05-07", "2026-05-08"])+ return pd.DataFrame(+ {+ "open": [200.0, 208.3, 213.0],+ "high": [208.3, 214.2, 217.8],+ "low": [198.6, 206.5, 212.9],+ "close": [207.8, 211.5, 215.2],+ "volume": [188e6, 168e6, 136e6],+ },+ index=idx,+ )+++def test_fetch_returns_normalized_bars(monkeypatch) -> None:+ frame = _three_bar_frame()+ monkeypatch.setattr(+ grounding,+ "fetch_grounding_data",+ grounding.fetch_grounding_data, # keep real fn, only stub the loader+ )+ # Patch the loader registry that fetch_grounding_data imports lazily.+ import backtest.loaders.registry as reg+ monkeypatch.setattr(reg, "resolve_loader", lambda code: lambda: _StubLoader(frame))++ bars = grounding.fetch_grounding_data(["NVDA.US"], today=date(2026, 5, 9))++ assert "NVDA.US" in bars+ rows = bars["NVDA.US"]+ assert len(rows) == 3+ assert rows[-1]["close"] == pytest.approx(215.2)+ assert rows[0]["trade_date"].startswith("2026-05-06")+++def test_fetch_skips_symbols_with_no_data(monkeypatch) -> None:+ import backtest.loaders.registry as reg+ monkeypatch.setattr(+ reg, "resolve_loader",+ lambda code: lambda: _StubLoader(pd.DataFrame()), # empty frame+ )++ bars = grounding.fetch_grounding_data(["NOPE.US"])+ assert bars == {}+++def test_fetch_returns_empty_for_empty_input() -> None:+ assert grounding.fetch_grounding_data([]) == {}+++# --------------------------------------------------------------------------- #+# format_grounding_block+# --------------------------------------------------------------------------- #++def test_format_returns_empty_for_empty_grounding() -> None:+ assert grounding.format_grounding_block({}) == ""+ assert grounding.format_grounding_block({"NVDA.US": []}) == ""+++def test_format_renders_table_and_range() -> None:+ rows = [+ {"trade_date": "2026-05-06T00:00:00", "open": 200.0, "high": 208.3,+ "low": 198.6, "close": 207.8, "volume": 188_000_000.0},+ {"trade_date": "2026-05-07T00:00:00", "open": 208.3, "high": 214.2,+ "low": 206.5, "close": 211.5, "volume": 168_000_000.0},+ {"trade_date": "2026-05-08T00:00:00", "open": 213.0, "high": 217.8,+ "low": 212.9, "close": 215.2, "volume": 136_000_000.0},+ ]+ block = grounding.format_grounding_block({"NVDA.US": rows})++ assert "Ground Truth" in block+ assert "NVDA.US" in block+ assert "215.20" in block # last close+ assert "207.80 – 215.20" in block # window range (min/max close)+ assert "2026-05-06 → 2026-05-08" in block+ # The instruction text must survive — it's the whole point.+ assert "Do NOT cite prices" in block+++# --------------------------------------------------------------------------- #+# Worker prompt integration+# --------------------------------------------------------------------------- #++def _spec() -> SwarmAgentSpec:+ return SwarmAgentSpec(+ id="dummy",+ role="research analyst",+ system_prompt="Analyse the asset.",+ )+++def test_worker_prompt_includes_grounding_block_when_provided() -> None:+ block = "## Ground Truth — Recent Market Data\n\nNVDA.US ..."+ prompt = build_worker_prompt(_spec(), {}, "(no matching skills)", grounding_block=block)+ assert block in prompt+ # Block must appear before the Execution Rules so it's in scope when+ # the worker plans its first call.+ assert prompt.index(block) < prompt.index("## Execution Rules")+++def test_worker_prompt_omits_grounding_section_when_block_empty() -> None:+ prompt = build_worker_prompt(_spec(), {}, "(no matching skills)")+ assert "Ground Truth" not in prompt