Spaces:
Running

PolyHedra / src /polyhedra /agents /quant /datafetcher.py
yf176
feat: add typed DataFetcher execution
e1c1f66
Raw History Blame Contribute Delete
23.2 kB
"""DataFetcherAgent β€” Market Data Engineer for Polyhedra V4.1.
Pulls raw market data from Finnhub for all watchlist tickers and writes:
- quant/raw/<TICKER>_<date>.json β€” full raw data (source of truth)
- quant/raw/<TICKER>_<date>_summary.md β€” human-readable summary for LLM agents
All other quant agents read the summary file β€” no agent calls Finnhub directly.
DISCLAIMER: This is a paper trading simulation for research and educational
purposes only. No real capital is involved.
"""
from __future__ import annotations
import json
import logging
import os
import re
from collections.abc import Callable
from datetime import date, datetime, timezone
from typing import Any
from polyhedra.agents.base import Agent, AgentResponse, Mention
from polyhedra.agents.quant.market_data_contracts import (
DataFetcherInput, DataFetcherOutput, MarketDataArtifact, TickerFetchResult,
)
from polyhedra.core.artifacts import Availability
from polyhedra.core.dependency_executor import AgentCompletion
from polyhedra.services.artifact_publisher import ArtifactPublisher
from polyhedra.services.file_writer import ScopedFileWriter
from polyhedra.services.finnhub import FinnhubService, RateLimitExceeded
from polyhedra.services.market_data_normalizer import (
normalize_finnhub_market_data, render_market_data_markdown,
)
logger = logging.getLogger(__name__)
# V4.4 FIX-8: Validate tokens by pattern instead of a manually maintained blocklist.
# POLYHEDRA_VALID_TICKERS: optional comma-separated override list.
_VALID_TICKERS_ENV: frozenset[str] = frozenset(
t.strip().upper()
for t in os.environ.get("POLYHEDRA_VALID_TICKERS", "").split(",")
if t.strip()
)
# Common English words that look like tickers but aren't β€” mirrors slack.py stopwords.
_TICKER_STOPWORDS: frozenset[str] = frozenset({
"A", "I", "AN", "AS", "AT", "BE", "BY", "DO", "GO", "HE", "IF", "IN",
"IS", "IT", "ME", "MY", "NO", "OF", "OK", "ON", "OR", "SO", "TO", "UP",
"US", "WE",
"ADD", "ALL", "AND", "ANY", "ARE", "CAN", "DID", "END", "FOR", "GET",
"GOT", "HAD", "HAS", "HER", "HIM", "HIS", "HOW", "ITS", "LET", "MAY",
"NEW", "NOT", "NOW", "OLD", "ONE", "OUR", "OUT", "OWN", "PUT", "RUN",
"SAY", "SEE", "SET", "SHE", "THE", "TOO", "TOP", "TRY", "TWO", "USE",
"WAS", "WHO", "WHY", "YET",
"ALSO", "BACK", "BEEN", "COME", "EACH", "EVEN", "FROM", "GOOD", "HAVE",
"HERE", "HIGH", "HOLD", "INTO", "KEEP", "KNOW", "LAST", "LIKE", "LIST",
"LOOK", "MAKE", "MANY", "MODE", "MORE", "MOST", "MUCH", "MUST", "NEXT",
"ONLY", "OVER", "PART", "PAST", "ROLE", "SAME", "SAID", "SHOW", "SOME",
"SUCH", "TAKE", "THAN", "THAT", "THEM", "THEN", "THEY", "THIS", "TIME",
"USED", "VERY", "WANT", "WELL", "WERE", "WHAT", "WHEN", "WITH", "WORK",
"YEAR", "YOUR",
"ABOUT", "AFTER", "AGAIN", "BELOW", "BRIEF", "CHECK", "COULD", "DOING",
"EVERY", "FETCH", "FIRST", "GIVEN", "GOING", "GREAT", "HELLO", "HELPS",
"HUMAN", "INITS", "LATER", "MIGHT", "NEEDS", "OTHER", "POSTS", "PRIOR",
"QUERY", "READY", "REPLY", "RIGHT", "SHALL", "SINCE", "START", "STATE",
"STILL", "STORE", "THEIR", "THERE", "THESE", "THOSE", "THREE", "UNDER",
"UNTIL", "USING", "WATCH", "WEEKS", "WHERE", "WHICH", "WHILE", "WOULD",
"WRITE",
# DataFetcher-specific dispatch words
"DATA", "MARKET", "PRICE", "STOCK", "TRADE", "QUOTE", "CHART", "DAILY",
"TREND", "ANALYSIS", "REPORT", "SUMMARY", "WATCHLIST",
})
def _is_valid_ticker(token: str) -> bool:
"""Return True if *token* is a plausible exchange-listed ticker symbol.
Accepts 1–5 uppercase letters (NYSE/NASDAQ convention).
Also accepts tickers explicitly listed in POLYHEDRA_VALID_TICKERS regardless
of the pattern.
"""
if token in _VALID_TICKERS_ENV:
return True
if token in _TICKER_STOPWORDS:
return False
return bool(re.match(r'^[A-Z]{1,5}$', token))
def _env_watchlist() -> list[str]:
raw = os.environ.get("POLYHEDRA_QUANT_WATCHLIST", "")
return [t.strip().upper() for t in raw.split(",") if t.strip()]
class DataFetcherAgent(Agent):
"""
Market Data Engineer β€” fetches and stores raw Finnhub market data.
Does not use an LLM for routing; routing logic is deterministic:
- Success (full or partial) β†’ @trendanalyst
- Total failure / rate-limit with zero data β†’ @human
"""
name = "DataFetcher"
role = "datafetcher"
role_title = "Market Data Engineer"
system_prompt = (
"You are DataFetcher, the Market Data Engineer for a collaborative quant research team. "
"Your job is to retrieve complete, fresh market data from Finnhub for all tickers "
"in scope. You are the single source of truth for raw data. "
"Report clearly what was fetched, what failed, and why."
)
def __init__(self, finnhub: FinnhubService | None = None) -> None:
super().__init__()
self._fh = finnhub or FinnhubService()
async def can_handle(self, mention: Mention) -> bool:
return mention.mentioned_role == self.role
async def execute_typed(
self,
inputs: DataFetcherInput,
*,
files: ScopedFileWriter,
publisher: ArtifactPublisher,
now: Callable[[], datetime] | None = None,
) -> AgentCompletion:
"""Run the existing providers and publish the V8 DataFetcher artifacts."""
if type(inputs) is not DataFetcherInput:
raise TypeError("DataFetcher typed execution requires DataFetcherInput")
if (files.agent, files.run_id, files.ticker_scope) != (
"DataFetcher", inputs.run_id, tuple(inputs.ticker_scope),
):
raise ValueError("DataFetcher input contradicts its scoped file activation")
if (publisher.run_id, publisher.session_id) != (inputs.run_id, inputs.session_id):
raise ValueError("DataFetcher publisher contradicts activation identity")
clock = now or (lambda: datetime.now(tz=timezone.utc))
publisher.record_input("DataFetcher", inputs)
results: list[TickerFetchResult] = []
rate_limited = False
for ticker in inputs.ticker_scope:
if rate_limited:
payload = _unavailable_payload("Rate limit reached before this ticker was fetched")
else:
try:
payload = await self._fh.fetch_ticker_data(ticker, None)
except RateLimitExceeded as exc:
payload = _unavailable_payload(str(exc))
rate_limited = True
except Exception as exc:
payload = _unavailable_payload(f"{type(exc).__name__}: {exc}")
if payload.get("_cap_hit"):
endpoint = str(payload.get("_cap_at_endpoint") or "PROVIDER")
payload.setdefault(f"_{endpoint}_error", "Finnhub rate limit reached")
rate_limited = True
artifact = normalize_finnhub_market_data(
ticker=ticker,
payload=payload,
run_id=inputs.run_id,
session_id=inputs.session_id,
retrieved_at=clock(),
baseline_ref=inputs.baseline_refs.get(ticker),
)
raw = publisher.publish_auxiliary(
files,
artifact,
schema=MarketDataArtifact,
json_path=f"quant/runs/{inputs.run_id}/raw/{ticker}.json",
markdown_path=f"quant/runs/{inputs.run_id}/raw/{ticker}_summary.md",
render_markdown=render_market_data_markdown,
)
results.append(TickerFetchResult.from_artifact(
artifact, raw.artifact_ref, raw.rendering_ref,
))
statuses = {item.status for item in results}
overall = (
Availability.COMPLETE if statuses == {Availability.COMPLETE} else
Availability.UNAVAILABLE if statuses == {Availability.UNAVAILABLE} else
Availability.PARTIAL
)
manifest = DataFetcherOutput(
schema_version="8.0",
artifact_id=f"{inputs.run_id}-data-fetch",
run_id=inputs.run_id,
session_id=inputs.session_id,
completed_at=clock(),
ticker_scope=inputs.ticker_scope,
overall_status=overall,
ticker_results=results,
)
manifest.validate_for_input(inputs)
published = publisher.publish(
files,
manifest,
json_path=f"quant/runs/{inputs.run_id}/data_fetch.json",
markdown_path=f"quant/runs/{inputs.run_id}/data_fetch.md",
)
return AgentCompletion(
artifact_ref=published.artifact_ref,
result_status=manifest.overall_status,
)
async def handle(
self,
mention: Mention,
thread_context: list[dict[str, Any]],
research_state: dict[str, Any],
) -> AgentResponse:
from pathlib import Path
session_dir = Path(mention.metadata.get("session_dir", "."))
watchlist = self._resolve_watchlist(mention, research_state)
if not watchlist:
return AgentResponse(
agent_role=self.role,
content=(
"πŸ“‘ **DataFetcher** β€” No tickers in watchlist.\n\n"
"Add tickers with `/poly watchlist add AAPL MSFT NVDA` "
"then re-run `/poly quant`."
),
mentions=[],
)
fetched, failed, cap_hit, cap_hit_ticker, all_ohlcv_failed = await self._fetch_all(
watchlist, session_dir
)
# FR-5.3: route to @human if all OHLCV fetches failed (Finnhub + yfinance both down)
if all_ohlcv_failed:
return AgentResponse(
agent_role=self.role,
content=(
"⚠️ **DataFetcher** β€” OHLCV fetch failed for all tickers.\n\n"
"The configured OHLCV providers returned no usable daily price history. "
"News/earnings providers may still have partial data, but TrendAnalyst "
"requires OHLCV before the LLM agent pipeline can continue. "
"Manual OHLCV paste-in, provider retry, or provider replacement is required."
),
mentions=[],
updates_state=True,
state_patch={"yfinance_alert": True}, # FR-5.4: recorded in QuantState.alerts
)
# V4.1: write plain-text summary for each successfully fetched ticker
for raw_ticker in fetched:
ticker = raw_ticker.rstrip("*")
raw_path = f"quant/raw/{ticker}_{date.today().isoformat()}.json"
raw_content = self.files.read(raw_path)
if raw_content:
try:
data = json.loads(raw_content)
summary = _build_ticker_summary(ticker, data)
summary += _build_yolo_data_delta_context(self.files, research_state, ticker)
self.files.write(
f"quant/raw/{ticker}_{date.today().isoformat()}_summary.md",
summary,
mode="overwrite",
)
except Exception as exc:
logger.warning("DataFetcher: failed to write summary for %s: %s", ticker, exc)
content = self._build_response(fetched, failed, cap_hit, cap_hit_ticker)
quant_state = research_state.get("quant_state") or {}
if isinstance(quant_state, dict) and quant_state.get("yolo_run_mode") == "session_delta":
content += (
"\n\nV7 session-delta context: current raw summaries include prior "
"baseline excerpts when available."
)
# If trend analysis for today already exists, DataFetcher was called mid-chain
# (e.g. by TrendAnalyst requesting more data). Skip straight to sentimentanalyst.
trend_exists = bool(self.files.read(f"quant/trend_analysis_{date.today().isoformat()}.md"))
if not fetched and cap_hit:
next_mentions = []
elif trend_exists:
next_mentions = ["sentimentanalyst"]
else:
next_mentions = ["trendanalyst"]
return AgentResponse(
agent_role=self.role,
content=content,
mentions=next_mentions,
updates_state=False,
)
# ------------------------------------------------------------------ #
# Internals
# ------------------------------------------------------------------ #
def _resolve_watchlist(
self, mention: Mention, research_state: dict[str, Any]
) -> list[str]:
quant = research_state.get("quant_state") or {}
watchlist: list[str] = list(quant.get("watchlist", []))
if not watchlist:
for t in self._extract_tickers(mention.content):
if t not in watchlist:
watchlist.append(t)
for t in _env_watchlist():
if t not in watchlist:
watchlist.append(t)
return watchlist
async def _fetch_all(
self, watchlist: list[str], session_dir: Any
) -> tuple[list[str], list[str], bool, str, bool]:
fetched: list[str] = []
failed: list[str] = []
cap_hit = False
cap_hit_ticker = ""
ohlcv_failures: int = 0
for ticker in watchlist:
done, cap_hit, cap_hit_ticker, has_ohlcv = await self._fetch_one(
ticker, watchlist, session_dir, fetched, failed, cap_hit, cap_hit_ticker
)
if not has_ohlcv:
ohlcv_failures += 1
if done:
break
all_ohlcv_failed = ohlcv_failures >= len(watchlist) and bool(watchlist)
return fetched, failed, cap_hit, cap_hit_ticker, all_ohlcv_failed
async def _fetch_one(
self,
ticker: str,
watchlist: list[str],
session_dir: Any,
fetched: list[str],
failed: list[str],
cap_hit: bool,
cap_hit_ticker: str,
) -> tuple[bool, bool, str, bool]:
"""Fetch one ticker. Returns (should_stop, cap_hit, cap_hit_ticker, has_ohlcv)."""
try:
data = await self._fh.fetch_ticker_data(ticker, session_dir)
if data.get("_cap_hit"):
fetched.append(f"{ticker}*")
remaining_idx = watchlist.index(ticker) + 1
failed.extend(watchlist[remaining_idx:])
return True, True, ticker, True
has_ohlcv = bool(
data.get("TIME_SERIES_DAILY_ADJUSTED", {}).get("Time Series (Daily)")
)
if not has_ohlcv:
err = data.get("_CANDLE_error", "empty response")
logger.error("DataFetcher: %s returned no OHLCV data: %s", ticker, err)
failed.append(ticker)
else:
fetched.append(ticker)
return False, cap_hit, cap_hit_ticker, has_ohlcv
except RateLimitExceeded:
failed.extend(watchlist[watchlist.index(ticker):])
return True, True, ticker, False
except Exception as exc:
logger.error("DataFetcher: failed to fetch %s: %s", ticker, exc)
failed.append(ticker)
return False, cap_hit, cap_hit_ticker, False
def _build_response(
self,
fetched: list[str],
failed: list[str],
cap_hit: bool,
cap_hit_ticker: str,
) -> str:
lines = ["πŸ“‘ **DataFetcher** β€” Market data fetch summary.\n"]
lines.append(
f"βœ… **Fetched ({len(fetched)}):** {', '.join(fetched) if fetched else '_none_'}"
)
if failed:
lines.append(f"❌ **Failed ({len(failed)}):** {', '.join(failed)}")
if cap_hit:
remaining = self._fh.calls_remaining_today()
lines += [
"",
f"β›” **Finnhub rate limit reached** at ticker `{cap_hit_ticker}` "
f"(~{remaining} calls available in current minute).",
"Partial results have been saved. The team will continue with available data.",
"If the limit persists, wait ~60 seconds and retry with `/poly quant`.",
]
else:
lines.append(
"\nRaw data + summaries written to `quant/raw/` β€” handing off to TrendAnalyst."
)
return "\n".join(lines)
@staticmethod
def _extract_tickers(text: str) -> list[str]:
"""Extract 1–5 uppercase letter tokens from free text as potential tickers."""
found = []
for token in re.findall(r'\b([A-Z]{1,5})\b', text.upper()):
if _is_valid_ticker(token) and token not in found:
found.append(token)
return found
# ---------------------------------------------------------------------------
# V4.1: plain-text ticker summary β€” read by TrendAnalyst and SentimentAnalyst
# ---------------------------------------------------------------------------
def _unavailable_payload(reason: str) -> dict[str, str]:
return {
"_CANDLE_error": reason,
"_NEWS_error": reason,
"_EARNINGS_error": reason,
}
def _build_ticker_summary(ticker: str, data: dict[str, Any]) -> str:
"""Build a human-readable summary of raw Finnhub data for LLM consumption."""
lines = [f"# {ticker} β€” Market Data Summary", f"Fetched: {data.get('fetched_at', 'unknown')}", ""]
lines += _summary_data_quality(data)
lines += _summary_ohlcv(data)
lines += _summary_indicators(data)
lines += _summary_news(data)
lines += _summary_earnings(data)
return "\n".join(lines)
def _build_yolo_data_delta_context(files: Any, research_state: dict[str, Any], ticker: str) -> str:
quant_state = research_state.get("quant_state") or {}
if not isinstance(quant_state, dict):
return ""
if quant_state.get("yolo_run_mode") != "session_delta":
return ""
snapshot_dir = str(quant_state.get("yolo_baseline_snapshot_dir") or "")
if not snapshot_dir:
return "\n## V7 Session Delta Data Context\n_No prior raw summary snapshot found._\n"
prior_paths = [
path
for path in files.list(f"{snapshot_dir}/quant/raw")
if path.split("/")[-1].startswith(f"{ticker}_") and path.endswith("_summary.md")
]
if not prior_paths:
return (
"\n## V7 Session Delta Data Context\n"
f"_No prior raw summary snapshot found for {ticker}._\n"
)
prior = files.read(sorted(prior_paths)[-1]) or ""
return (
"\n## V7 Session Delta Data Context\n"
"Prior baseline raw summary excerpt. Downstream agents should compare this with the fresh data above.\n\n"
f"{prior[:1200]}\n"
)
def _summary_ohlcv(data: dict[str, Any]) -> list[str]:
ts = data.get("TIME_SERIES_DAILY_ADJUSTED", {}).get("Time Series (Daily)", {})
if not ts:
return []
recent = sorted(ts.keys(), reverse=True)[:10]
rows = [
"## OHLCV (last 10 days)",
"Date | Open | High | Low | Close | Volume",
"-------------|---------|---------|---------|---------|----------",
]
for d in recent:
row = ts[d]
rows.append(
f"{d} | {row.get('1. open','?'):7} | {row.get('2. high','?'):7} | "
f"{row.get('3. low','?'):7} | {row.get('4. close','?'):7} | "
f"{row.get('6. volume','?')}"
)
rows.append("")
return rows
def _summary_data_quality(data: dict[str, Any]) -> list[str]:
quality = data.get("TIME_SERIES_DAILY_ADJUSTED", {}).get("_data_quality", {})
if not quality:
return []
rows = ["## Data Quality"]
status = quality.get("status", "unknown")
rows.append(f"OHLCV status: {status}")
note = quality.get("note")
if note:
rows.append(str(note))
excluded = quality.get("excluded_rows") or []
if excluded:
rows.append("")
rows.append("Excluded provider rows:")
for row in excluded[:5]:
date_value = row.get("date", "unknown date")
reason = row.get("reason", "invalid OHLCV row")
values = row.get("provider_values") or {}
volume = values.get("6. volume", "?")
rows.append(f"- {date_value}: {reason}; reported volume={volume}")
if len(excluded) > 5:
rows.append(f"- plus {len(excluded) - 5} more excluded row(s)")
rows.append("")
return rows
def _summary_indicators(data: dict[str, Any]) -> list[str]:
lines: list[str] = []
rsi_series = data.get("RSI", {}).get("Technical Analysis: RSI", {})
if rsi_series:
d = sorted(rsi_series.keys(), reverse=True)[0]
lines.append(f"## RSI-14: {rsi_series[d].get('RSI', '?')} ({d})")
lines.append("")
macd_series = data.get("MACD", {}).get("Technical Analysis: MACD", {})
if macd_series:
d = sorted(macd_series.keys(), reverse=True)[0]
m = macd_series[d]
lines.append(
f"## MACD ({d})\n"
f"MACD={m.get('MACD','?')} Signal={m.get('MACD_Signal','?')} "
f"Hist={m.get('MACD_Hist','?')}"
)
lines.append("")
has_ma = False
for ind_key, ind_name in (("SMA", "SMA-20"), ("EMA", "EMA-20")):
ind_series = data.get(ind_key, {}).get(f"Technical Analysis: {ind_key}", {})
if ind_series:
d = sorted(ind_series.keys(), reverse=True)[0]
lines.append(f"## {ind_name}: {ind_series[d].get(ind_key, '?')} ({d})")
has_ma = True
if has_ma:
lines.append("")
return lines
def _summary_news(data: dict[str, Any]) -> list[str]:
feed = data.get("NEWS_SENTIMENT", {}).get("feed", [])
if not feed:
return ["## News\n_No news data available._\n"]
lines = [f"## News ({len(feed)} articles, last 30 days)"]
for article in feed[:15]:
score = article.get("overall_sentiment_score", "N/A")
label = article.get("overall_sentiment_label", "")
title = article.get("title", "")[:100]
try:
lines.append(f" [{float(score):+.3f} {label}] {title}")
except (TypeError, ValueError):
lines.append(f" [{score} {label}] {title}")
lines.append("")
return lines
def _summary_earnings(data: dict[str, Any]) -> list[str]:
quarterly = data.get("EARNINGS", {}).get("quarterlyEarnings", [])
if not quarterly:
return [] # ETFs have no earnings β€” omit section per V4.1 ETF fix
lines = ["## Quarterly Earnings (last 4 quarters)"]
for q in quarterly[:4]:
surprise = q.get("surprisePercentage", "N/A")
beat_miss = "beat" if float(q.get("surprise", 0) or 0) > 0 else "miss"
lines.append(
f" {q.get('period','?')}: EPS={q.get('actual','?')} "
f"Est={q.get('estimate','?')} {beat_miss} by {surprise}%"
)
lines.append("")
return lines