"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(data): global data layer — 8 new sources + 18 read-only data tools (#270)
Haozhe Wuadfbc8230323
diff --git a/README.md b/README.mdindex 07f4d7277..ce8044b5f 100644--- a/README.md+++ b/README.md@@ -50,12 +50,14 @@## 📰 News+- **2026-06-19** 🌍 **Global data layer — 8 new sources + 18 read-only data tools**: The market-data loader registry grows from 10 to 18 sources — four free direct-API additions (**Eastmoney**, **Sina**, **Stooq**, and a direct-HTTP **Yahoo** client) plus four optional key-gated US providers (**Finnhub**, **Alpha Vantage**, **Tiingo**, **FMP**), with the fallback chains re-ordered by IP-ban risk. On top of them sit **18 new read-only data tools** reaching past OHLCV into fundamentals and flow — fund flow, dragon-tiger board, northbound (Stock-Connect) flow, margin trading, block trades, shareholder count, lockup expiry, sector membership, research reports, news, SEC filings (EDGAR + XBRL), financial statements, options chains, institutional holdings, full-market screening, and symbol search — across A-share / US / HK, all exposed over MCP. A consolidated `data-routing` index plus per-source `eastmoney` / `sec-edgar` skills document the layer, which was validated end-to-end with a live LLM-routing + data smoke pass.- **2026-06-18** 🔬 **Research Autopilot Phase 1 + a local Data Bridge loader, plus a Discord security notice**: Two new agent tools wire the **Hypothesis Registry → Research Goal → backtest** path end to end — `run_research_autopilot` turns a `hypothesis_id` into a research goal (thesis as objective, backtest-relevant acceptance criteria, next-step hints), and `generate_backtest_config` auto-writes a backtest `config.json` from the hypothesis's universe and data sources, so the agent can go straight from idea → `signal_engine.py` → run (**50 tools** now) ([#260](https://github.com/HKUDS/Vibe-Trading/pull/260), thanks @Robin1987China). A new **`local` data loader** reads OHLCV straight from your own **CSV / Parquet / DuckDB** files: map symbols to files in `~/.vibe-trading/data-bridge/config.yaml` and prefix a symbol with `local:` to route it to your data, with normal fallback-chain support ([#252](https://github.com/HKUDS/Vibe-Trading/pull/252), thanks @Robin1987China). A fast follow-up repaired runtime defects both shipped with — Autopilot never received the host `session_id` (every call errored), `generate_backtest_config` wrote under a run root `safe_run_dir` rejected, and the local loader silently emptied tz-aware inputs on a tz-naive timestamp comparison ([#266](https://github.com/HKUDS/Vibe-Trading/pull/266)). DeepSeek's `DSML`-wrapped tool calls now parse correctly ([#261](https://github.com/HKUDS/Vibe-Trading/issues/261)), the Robinhood OAuth handshake gets a longer init timeout with the MCP `initTimeout` key now documented ([#263](https://github.com/HKUDS/Vibe-Trading/pull/263)), and an identifier-containment hardening wave landed: persistent-memory type validation ([#257](https://github.com/HKUDS/Vibe-Trading/pull/257)), MCP swarm run-id containment ([#258](https://github.com/HKUDS/Vibe-Trading/pull/258)), and a strict `mp_[0-9a-f]{32}` mandate proposal-id format now enforced consistently across the relay, preview, and commit gate ([#256](https://github.com/HKUDS/Vibe-Trading/pull/256), [#264](https://github.com/HKUDS/Vibe-Trading/pull/264)). ⚠️ **Security notice:** the former community invite now resolves to a server we no longer control that runs a fake Collab.Land wallet-"verification" phishing scam — it has been removed from every README and the issue template, and the **only** official Discord is now the HKUDS community server ([discord.gg/6TdQnT5xcF](https://discord.gg/6TdQnT5xcF)). Vibe-Trading will never ask you to "verify" or connect a crypto wallet.- **2026-06-17** 🧩 **Install compatibility + Opus/Kimi provider fixes**: Baseline `pip install vibe-trading-ai` no longer pulls the optional `pyharmonics` / `ta` dependency chain; harmonic detection now lives behind `vibe-trading-ai[harmonic]` while the bundled detector remains available ([#250](https://github.com/HKUDS/Vibe-Trading/pull/250), closes [#249](https://github.com/HKUDS/Vibe-Trading/issues/249)). The agent loop also avoids assistant-prefill handoff messages rejected by Opus 4.8+, and Kimi/Moonshot can override the client `User-Agent` with `MOONSHOT_USER_AGENT` ([#248](https://github.com/HKUDS/Vibe-Trading/pull/248), closes [#246](https://github.com/HKUDS/Vibe-Trading/issues/246) and [#204](https://github.com/HKUDS/Vibe-Trading/issues/204)); follow-up tests now directly cover background-result and auto-compact handoff paths ([#251](https://github.com/HKUDS/Vibe-Trading/pull/251)).-- **2026-06-16** 🛡️ **Security/API hardening + GLM/Zhipu alias**: Settings writes require auth when configured ([#245](https://github.com/HKUDS/Vibe-Trading/pull/245)); API shell-capable tools require explicit `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` opt-in ([#243](https://github.com/HKUDS/Vibe-Trading/pull/243)); local shutdown requires auth when an API key is configured ([#241](https://github.com/HKUDS/Vibe-Trading/pull/241)); and untrusted loopback-looking hosts are rejected instead of treated as local ([#242](https://github.com/HKUDS/Vibe-Trading/pull/242)). Runtime edges also got cleaned up: Web chat syncs completed attempts ([#236](https://github.com/HKUDS/Vibe-Trading/pull/236)), run cards emit strict JSON for non-finite metrics ([#238](https://github.com/HKUDS/Vibe-Trading/pull/238)), malformed `RSSHUB_TIMEOUT_S` / `RSSHUB_FETCH_BUDGET_S` falls back safely ([#240](https://github.com/HKUDS/Vibe-Trading/pull/240)), and ddgs retry fallback is regression-covered ([#239](https://github.com/HKUDS/Vibe-Trading/pull/239)). GLM/Zhipu is now a first-class provider alias with model-name inference ([#247](https://github.com/HKUDS/Vibe-Trading/pull/247), closes [#237](https://github.com/HKUDS/Vibe-Trading/issues/237)).<details><summary>Earlier news</summary>+- **2026-06-16** 🛡️ **Security/API hardening + GLM/Zhipu alias**: Settings writes require auth when configured ([#245](https://github.com/HKUDS/Vibe-Trading/pull/245)); API shell-capable tools require explicit `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` opt-in ([#243](https://github.com/HKUDS/Vibe-Trading/pull/243)); local shutdown requires auth when an API key is configured ([#241](https://github.com/HKUDS/Vibe-Trading/pull/241)); and untrusted loopback-looking hosts are rejected instead of treated as local ([#242](https://github.com/HKUDS/Vibe-Trading/pull/242)). Runtime edges also got cleaned up: Web chat syncs completed attempts ([#236](https://github.com/HKUDS/Vibe-Trading/pull/236)), run cards emit strict JSON for non-finite metrics ([#238](https://github.com/HKUDS/Vibe-Trading/pull/238)), malformed `RSSHUB_TIMEOUT_S` / `RSSHUB_FETCH_BUDGET_S` falls back safely ([#240](https://github.com/HKUDS/Vibe-Trading/pull/240)), and ddgs retry fallback is regression-covered ([#239](https://github.com/HKUDS/Vibe-Trading/pull/239)). GLM/Zhipu is now a first-class provider alias with model-name inference ([#247](https://github.com/HKUDS/Vibe-Trading/pull/247), closes [#237](https://github.com/HKUDS/Vibe-Trading/issues/237)).+- **2026-06-15** 🧭 **Web-search resilience + Web UI run-continuity fixes**: `web_search` no longer fails when a single engine is rate-limited — it now queries several free, no-key engines in order (DuckDuckGo, Google, Bing, Brave, Mojeek, Yahoo) with retry/backoff, treats "no results" as an empty answer rather than an error, and returns an actionable message instead of a bare ❌ when every engine is throttled (override the engine list with `VIBE_TRADING_SEARCH_BACKENDS`) ([#232](https://github.com/HKUDS/Vibe-Trading/pull/232), closes [#231](https://github.com/HKUDS/Vibe-Trading/issues/231), thanks @Ethan-sun01). In the Web UI, switching pages during a run no longer freezes it — the chat re-subscribes to the live stream and replays missed progress on return ([#234](https://github.com/HKUDS/Vibe-Trading/pull/234)) — and the Stop button now takes effect mid-stream and between tools instead of only at iteration boundaries ([#235](https://github.com/HKUDS/Vibe-Trading/pull/235)), closing both halves of [#229](https://github.com/HKUDS/Vibe-Trading/issues/229) (thanks @kalkinj). The baostock loader also accepts native `sh.601398` / `sz.000001` codes alongside tushare-style `601398.SH` ([#230](https://github.com/HKUDS/Vibe-Trading/pull/230), thanks @bhlt).- **2026-06-14** 📊 **Per-run token usage + progressive Run Detail charts**: Every agent run now persists provider-reported token usage as a run-scoped `llm_usage.json` — provider/model, aggregate totals, and per-iteration counts — surfaced additively on `/runs/{id}`, so a finished run's token cost stays auditable after the live stream is gone (provider-reported only; no prompt/content capture, no price estimation) ([#223](https://github.com/HKUDS/Vibe-Trading/pull/223), thanks @LemonCANDY42). The Run Detail page no longer loads every symbol's candlesticks up front: the default `/runs/{id}` response is unchanged, but the UI now renders the run summary first and loads each symbol's chart on demand through opt-in `?chart_payload=summary` / `?chart_symbol=` modes, with per-symbol loading state and a load-all-with-progress control ([#225](https://github.com/HKUDS/Vibe-Trading/pull/225), thanks @LemonCANDY42). Two loader fixes close the cycle: yfinance's exclusive `end` boundary no longer drops the final requested trading day — the download now passes `end + 1 day` while cache keys keep the original range ([#226](https://github.com/HKUDS/Vibe-Trading/pull/226), thanks @gyx09212214-prog) — and a malformed `CCXT_TIMEOUT_MS` / `OKX_TIMEOUT_S` value now warns and falls back to its default instead of raising at import and blocking startup ([#227](https://github.com/HKUDS/Vibe-Trading/pull/227), thanks @gyx09212214-prog).@@ -251,6 +253,34 @@ Most runs follow the same evidence path: route the request, load the right marke---+## 📡 Data Sources & Smart Fallback++One `get_market_data` call, **18 market-data sources**. Set `source: "auto"` — the loader picks by symbol, then walks a per-market chain ordered by **IP-ban risk**: never-banned public sources first, throttled / key-gated ones last. Zero config, no single point of failure.++| Source | Markets | Auth | Role |+|--------|---------|------|------|+| `tencent` · `mootdx` | A-share | none | never IP-banned (`mootdx` = 通达信 TCP) |+| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) |+| `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks |+| `tushare` | A / futures / fund / macro | token | richest A-share |+| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |+| `yfinance` | US / HK | none | wrapper |+| `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |+| `okx` · `ccxt` | crypto | none | OKX + 100+ exchanges |+| `futu` | HK / A | OpenD | optional local FutuOpenD |+| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |++**Fallback chains (by IP-ban risk):**++- **A-share** → `tencent` · `mootdx` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`+- **US** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `akshare` · `local`+- **HK** → `eastmoney` · `yahoo` · `futu` · `yfinance` · `akshare` · `local`+- **Crypto** → `okx` · `ccxt` · `yfinance` · `local` · *(futures / fund / macro / forex → `tushare`/`akshare` → `local`)*++Beyond OHLCV, **18 read-only data tools** reach into fundamentals & flow — fund flow, dragon-tiger, northbound, margin, block trades, shareholder count, lockup, sector, research reports, news, SEC filings, financial statements, options chains, institutional holdings, market screening, symbol search, and macro — all exposed over MCP. An explicit `local:` symbol never silently falls back to a network source.++---+## 🔩 Detailed CapabilitiesDetailed inventories are folded below to keep the main README scannable. Open them when you want to inspect the available building blocks.@@ -264,7 +294,7 @@ Detailed inventories are folded below to keep the main README scannable. Open th| Category | Skills | Examples ||----------|--------|----------|-| Data Source | 7 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -1029,7 +1059,7 @@ Vibe-Trading/├── agent/ # Backend (Python)│ ├── cli/ # CLI package — interactive TUI + subcommands│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE-│ ├── mcp_server.py # MCP server — 36 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 54 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent core@@ -1070,7 +1100,7 @@ Vibe-Trading/│ ││ └── backtest/ # Backtest engines│ ├── engines/ # 7 engines + composite cross-market engine + options_portfolio-│ ├── loaders/ # 7 sources: tushare, okx, yfinance, akshare, mootdx, ccxt, futu+│ ├── loaders/ # 18 sources: tushare, okx, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + auto-fallback chains│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_ar.md b/README_ar.mdindex fae9ae102..d3da16b66 100644--- a/README_ar.md+++ b/README_ar.md@@ -50,12 +50,14 @@## 📰 الأخبار+- **2026-06-19** 🌍 **طبقة بيانات عالمية —— 8 مصادر جديدة + 18 أداة بيانات للقراءة فقط**: يكبر سجلّ محمّلات بيانات السوق من 10 مصادر إلى 18 —— أربع إضافات مجانية مباشرة عبر الـ API (**Eastmoney** و**Sina** و**Stooq** وعميل **Yahoo** مباشر عبر HTTP)، إضافةً إلى أربعة مزوّدين أمريكيين اختياريين محكومين بمفتاح (**Finnhub** و**Alpha Vantage** و**Tiingo** و**FMP**)، مع إعادة ترتيب سلاسل fallback حسب خطر حظر الـ IP. وفوقها تجلس **18 أداة بيانات جديدة للقراءة فقط** تتجاوز OHLCV إلى الأساسيات والتدفقات —— تدفق الأموال، ولوحة التنين والنمر، وتدفق الشمال (Stock-Connect)، والتداول بالهامش، والصفقات الكتلية، وعدد المساهمين، وانتهاء فترات الحظر، وعضوية القطاعات، وتقارير البحث، والأخبار، وملفّات SEC (EDGAR + XBRL)، والقوائم المالية، وسلاسل الخيارات، والحيازات المؤسسية، وفرز كامل السوق، والبحث عن الرموز —— عبر أسواق الأسهم الصينية / الأمريكية / هونغ كونغ، وكلّها مكشوفة عبر MCP. ويوثّق هذه الطبقة فهرس `data-routing` موحّد إضافةً إلى مهارتي `eastmoney` / `sec-edgar` لكل مصدر، وقد تم التحقق منها من طرف إلى طرف عبر تمرير حيّ لتوجيه LLM + اختبار بيانات سريع.- **2026-06-18** 🔬 **المرحلة الأولى من Research Autopilot + محمّل Data Bridge محلي، إضافةً إلى تنبيه أمني بشأن Discord**: تربط أداتان جديدتان للوكيل مسار **Hypothesis Registry → Research Goal → backtest** من طرف إلى طرف — تحوّل `run_research_autopilot` رقم `hypothesis_id` إلى research goal (الأطروحة كهدف، ومعايير قبول موجّهة للـ backtest، وتلميحات للخطوة التالية)، وتكتب `generate_backtest_config` ملف `config.json` للـ backtest تلقائياً من universe ومصادر بيانات الفرضية، فيستطيع الوكيل الانتقال مباشرةً من الفكرة → `signal_engine.py` → التشغيل (الآن **50 أداة**) ([#260](https://github.com/HKUDS/Vibe-Trading/pull/260)، شكراً @Robin1987China). ويقرأ **محمّل البيانات `local`** الجديد بيانات OHLCV مباشرةً من ملفاتك **CSV / Parquet / DuckDB**: اربط الرموز بالملفات في `~/.vibe-trading/data-bridge/config.yaml` وأضف بادئة `local:` للرمز ليُوجَّه إلى بياناتك المحلية، مع دعم سلسلة fallback المعتادة ([#252](https://github.com/HKUDS/Vibe-Trading/pull/252)، شكراً @Robin1987China). وأصلح تتبّع سريع عيوب وقت التشغيل التي رافقت كليهما — لم يكن Autopilot يتلقى `session_id` المضيف (تخفق كل استدعاء)، وكتبت `generate_backtest_config` ضمن جذر run يرفضه `safe_run_dir`، وأفرغ المحمّل المحلي بصمت مدخلات tz-aware عند مقارنة طابع زمني tz-naive ([#266](https://github.com/HKUDS/Vibe-Trading/pull/266)). وتُحلَّل الآن استدعاءات أدوات DeepSeek المغلّفة بـ `DSML` بشكل صحيح ([#261](https://github.com/HKUDS/Vibe-Trading/issues/261))، وحصلت مصافحة Robinhood OAuth على مهلة تهيئة أطول مع توثيق مفتاح إعداد MCP `initTimeout` ([#263](https://github.com/HKUDS/Vibe-Trading/pull/263))، ونزلت دفعة من تقوية احتواء المعرّفات: التحقق من نوع الذاكرة الدائمة ([#257](https://github.com/HKUDS/Vibe-Trading/pull/257))، واحتواء معرّفات تشغيل swarm في MCP ([#258](https://github.com/HKUDS/Vibe-Trading/pull/258))، وفرض صيغة صارمة `mp_[0-9a-f]{32}` لمعرّف mandate proposal-id باتساق عبر relay وpreview وبوابة commit ([#256](https://github.com/HKUDS/Vibe-Trading/pull/256)، [#264](https://github.com/HKUDS/Vibe-Trading/pull/264)). ⚠️ **تنبيه أمني**: دعوة المجتمع القديمة تشير الآن إلى خادم لم نعد نتحكم به ويُشغّل عملية تصيّد بانتحال "تحقّق" محفظة Collab.Land — أُزيلت من كل ملفات README ومن قالب المشكلات، وأصبح خادم HKUDS المجتمعي ([discord.gg/6TdQnT5xcF](https://discord.gg/6TdQnT5xcF)) هو Discord الرسمي **الوحيد**. لن يطلب منك Vibe-Trading أبداً "التحقّق" من محفظة عملات رقمية أو ربطها.- **2026-06-17** 🧩 **توافق التثبيت + إصلاحات مزوّدي Opus/Kimi**: لم يعد التثبيت الأساسي `pip install vibe-trading-ai` يجلب سلسلة الاعتماد الاختيارية `pyharmonics` / `ta`؛ أصبح كشف الأنماط التوافقية خلف extra باسم `vibe-trading-ai[harmonic]` مع بقاء detector المضمّن متاحاً ([#250](https://github.com/HKUDS/Vibe-Trading/pull/250)، يغلق [#249](https://github.com/HKUDS/Vibe-Trading/issues/249)). ولم يعد Agent loop يرسل رسائل assistant-prefill handoff التي يرفضها Opus 4.8+، كما يمكن لـ Kimi/Moonshot تجاوز `User-Agent` عبر `MOONSHOT_USER_AGENT` ([#248](https://github.com/HKUDS/Vibe-Trading/pull/248)، يغلق [#246](https://github.com/HKUDS/Vibe-Trading/issues/246) و[#204](https://github.com/HKUDS/Vibe-Trading/issues/204))؛ وتغطي اختبارات المتابعة مساري background-result وauto-compact handoff مباشرة ([#251](https://github.com/HKUDS/Vibe-Trading/pull/251)).-- **2026-06-16** 🛡️ **تعزيز الأمان/API + alias لـ GLM/Zhipu**: تتطلب كتابات Settings المصادقة عند تفعيلها ([#245](https://github.com/HKUDS/Vibe-Trading/pull/245))؛ وتتطلب أدوات shell-capable في جلسات API تفعيلًا صريحًا عبر `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` ([#243](https://github.com/HKUDS/Vibe-Trading/pull/243))؛ ويتطلب local shutdown المصادقة عند ضبط API key ([#241](https://github.com/HKUDS/Vibe-Trading/pull/241))؛ وتُرفض Host التي تبدو كـ loopback لكنها غير موثوقة بدل معاملتها كمحلية ([#242](https://github.com/HKUDS/Vibe-Trading/pull/242)). كما صُقلت تفاصيل التشغيل: يتزامن Web chat مع المحاولات المكتملة ([#236](https://github.com/HKUDS/Vibe-Trading/pull/236))، وتُصدر run cards صيغة strict JSON للمقاييس غير المنتهية ([#238](https://github.com/HKUDS/Vibe-Trading/pull/238))، وتتراجع قيم `RSSHUB_TIMEOUT_S` / `RSSHUB_FETCH_BUDGET_S` المشوهة بأمان ([#240](https://github.com/HKUDS/Vibe-Trading/pull/240))، وثُبّت fallback إعادة المحاولة في ddgs باختبار انحدار ([#239](https://github.com/HKUDS/Vibe-Trading/pull/239)). وأصبح GLM/Zhipu alias من الدرجة الأولى مع استنتاج اسم النموذج ([#247](https://github.com/HKUDS/Vibe-Trading/pull/247)، يغلق [#237](https://github.com/HKUDS/Vibe-Trading/issues/237)).<details><summary>أخبار سابقة</summary>+- **2026-06-16** 🛡️ **تعزيز الأمان/API + alias لـ GLM/Zhipu**: تتطلب كتابات Settings المصادقة عند تفعيلها ([#245](https://github.com/HKUDS/Vibe-Trading/pull/245))؛ وتتطلب أدوات shell-capable في جلسات API تفعيلًا صريحًا عبر `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` ([#243](https://github.com/HKUDS/Vibe-Trading/pull/243))؛ ويتطلب local shutdown المصادقة عند ضبط API key ([#241](https://github.com/HKUDS/Vibe-Trading/pull/241))؛ وتُرفض Host التي تبدو كـ loopback لكنها غير موثوقة بدل معاملتها كمحلية ([#242](https://github.com/HKUDS/Vibe-Trading/pull/242)). كما صُقلت تفاصيل التشغيل: يتزامن Web chat مع المحاولات المكتملة ([#236](https://github.com/HKUDS/Vibe-Trading/pull/236))، وتُصدر run cards صيغة strict JSON للمقاييس غير المنتهية ([#238](https://github.com/HKUDS/Vibe-Trading/pull/238))، وتتراجع قيم `RSSHUB_TIMEOUT_S` / `RSSHUB_FETCH_BUDGET_S` المشوهة بأمان ([#240](https://github.com/HKUDS/Vibe-Trading/pull/240))، وثُبّت fallback إعادة المحاولة في ddgs باختبار انحدار ([#239](https://github.com/HKUDS/Vibe-Trading/pull/239)). وأصبح GLM/Zhipu alias من الدرجة الأولى مع استنتاج اسم النموذج ([#247](https://github.com/HKUDS/Vibe-Trading/pull/247)، يغلق [#237](https://github.com/HKUDS/Vibe-Trading/issues/237)).+- **2026-06-15** 🧭 **متانة بحث الويب + إصلاحات استمرارية التشغيل في واجهة الويب**: لم يعد `web_search` يفشل عند تقييد مزوّد بحث واحد——إذ يستعلم الآن عدة محركات مجانية بلا مفاتيح بالترتيب (DuckDuckGo، Google، Bing، Brave، Mojeek، Yahoo) مع إعادة محاولة/تراجع، ويعامل "لا نتائج" كإجابة فارغة لا كخطأ، ويعيد رسالة قابلة للتنفيذ بدل ❌ مجرّدة عندما تُقيَّد كل المحركات (يمكن تجاوز قائمة المحركات عبر `VIBE_TRADING_SEARCH_BACKENDS`) ([#232](https://github.com/HKUDS/Vibe-Trading/pull/232)، يغلق [#231](https://github.com/HKUDS/Vibe-Trading/issues/231)، شكراً @Ethan-sun01). وفي واجهة الويب، لم يعد تبديل الصفحات أثناء التشغيل يُجمِّده——إذ تعيد المحادثة الاشتراك في البث الحي وتعيد تشغيل التقدّم الفائت عند العودة ([#234](https://github.com/HKUDS/Vibe-Trading/pull/234))——وأصبح زر الإيقاف يسري أثناء البث وبين الأدوات لا عند حدود التكرار فقط ([#235](https://github.com/HKUDS/Vibe-Trading/pull/235))، ما يغلق شِقَّي [#229](https://github.com/HKUDS/Vibe-Trading/issues/229) (شكراً @kalkinj). كما أصبح محمّل baostock يقبل الرموز الأصلية `sh.601398` / `sz.000001` إلى جانب صيغة tushare `601398.SH` ([#230](https://github.com/HKUDS/Vibe-Trading/pull/230)، شكراً @bhlt).- **2026-06-14** 📊 **استهلاك التوكنات لكل تشغيل + تحميل رسوم Run Detail عند الطلب**: أصبح كل تشغيل agent يحفظ استهلاك التوكنات المُبلَّغ من المزوّد كملف `llm_usage.json` على مستوى التشغيل——المزوّد/النموذج، والإجماليات التراكمية، والعدّ لكل تكرار——ويُعرَض إضافيًا على `/runs/{id}`، بحيث تبقى تكلفة التوكنات قابلة للتدقيق بعد انتهاء التشغيل واختفاء البث الحي (قيم المزوّد فقط؛ بلا التقاط prompt/محتوى ولا تقدير سعر) ([#223](https://github.com/HKUDS/Vibe-Trading/pull/223)، شكراً @LemonCANDY42). كما لم تعد صفحة Run Detail تُحمّل شموع كل الرموز مقدمًا: تبقى استجابة `/runs/{id}` الافتراضية دون تغيير، لكن الواجهة الآن تعرض ملخّص التشغيل أولًا ثم تُحمّل رسم كل رمز عند الطلب عبر وضعَي `?chart_payload=summary` / `?chart_symbol=` الاختياريين، مع حالة تحميل لكل رمز وزر "تحميل الكل مع شريط تقدّم" ([#225](https://github.com/HKUDS/Vibe-Trading/pull/225)، شكراً @LemonCANDY42). ويُختتم ذلك بإصلاحين في الـ loader: لم تعد حدود `end` الحصرية في yfinance تُسقِط آخر يوم تداول في النطاق المطلوب——إذ يمرّر الاستدعاء الآن `end + يوم واحد` بينما تحتفظ مفاتيح الكاش بالنطاق الأصلي ([#226](https://github.com/HKUDS/Vibe-Trading/pull/226)، شكراً @gyx09212214-prog)——وأصبحت القيمة المُشوَّهة لـ `CCXT_TIMEOUT_MS` / `OKX_TIMEOUT_S` تُصدر تحذيرًا وتعود إلى قيمتها الافتراضية بدل أن ترفع استثناءً عند الـ import وتعطّل الإقلاع ([#227](https://github.com/HKUDS/Vibe-Trading/pull/227)، شكراً @gyx09212214-prog).@@ -252,6 +254,34 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an---+## 📡 مصادر البيانات والتراجع الذكي++استدعاء واحد لـ `get_market_data`، **18 مصدر بيانات سوقية**. اضبط `source: "auto"` — يختار المُحمّل حسب الرمز، ثم يسير عبر سلسلة لكل سوق مرتبة بحسب **خطر حظر عنوان IP**: المصادر العامة التي لا تُحظر أبداً أولاً، والمصادر المُقيّدة أو المحمية بمفتاح أخيراً. بلا أي إعداد، ولا نقطة فشل واحدة.++| Source | Markets | Auth | Role |+|--------|---------|------|------|+| `tencent` · `mootdx` | A-share | none | never IP-banned (`mootdx` = 通达信 TCP) |+| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) |+| `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks |+| `tushare` | A / futures / fund / macro | token | richest A-share |+| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |+| `yfinance` | US / HK | none | wrapper |+| `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |+| `okx` · `ccxt` | crypto | none | OKX + 100+ exchanges |+| `futu` | HK / A | OpenD | optional local FutuOpenD |+| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |++**سلاسل التراجع (بحسب خطر حظر عنوان IP):**++- **أسهم A** → `tencent` · `mootdx` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`+- **أسهم US** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `akshare` · `local`+- **أسهم HK** → `eastmoney` · `yahoo` · `futu` · `yfinance` · `akshare` · `local`+- **الكريبتو** → `okx` · `ccxt` · `yfinance` · `local` · *(العقود الآجلة / الصناديق / الاقتصاد الكلي / الفوركس → `tushare`/`akshare` → `local`)*++إلى جانب OHLCV، تصل **18 أداة بيانات للقراءة فقط** إلى الأساسيات والتدفقات — تدفق الأموال، والتنين والنمر، والتدفق الشمالي، والهامش، والصفقات الكتلية، وعدد المساهمين، وفترة الإغلاق، والقطاعات، وتقارير الأبحاث، والأخبار، وإيداعات SEC، والقوائم المالية، وسلاسل الخيارات، والحيازات المؤسسية، وفحص السوق، والبحث عن الرموز، والاقتصاد الكلي — وكلها مكشوفة عبر MCP. ولا يتراجع رمز `local:` صريح أبداً وبصمت إلى مصدر شبكي.++---+## 🔩 القدرات التفصيليةالقوائم التفصيلية مطوية أدناه حتى يبقى README سهل القراءة. افتحها عندما تريد فحص اللبنات المتاحة.@@ -265,7 +295,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| الفئة | المهارات | أمثلة ||----------|--------|----------|-| Data Source | 7 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -845,7 +875,7 @@ Vibe-Trading/├── agent/ # Backend (Python)│ ├── cli/ # CLI package — interactive TUI + subcommands│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE-│ ├── mcp_server.py # MCP server — 36 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 54 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent core@@ -886,7 +916,7 @@ Vibe-Trading/│ ││ └── backtest/ # Backtest engines│ ├── engines/ # 7 engines + composite cross-market engine + options_portfolio-│ ├── loaders/ # 7 sources: tushare, okx, yfinance, akshare, mootdx, ccxt, futu+│ ├── loaders/ # 18 sources: tushare, okx, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + auto-fallback chains│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_ja.md b/README_ja.mdindex 6791762f3..6dededc1a 100644--- a/README_ja.md+++ b/README_ja.md@@ -50,12 +50,14 @@## 📰 ニュース+- **2026-06-19** 🌍 **グローバルデータレイヤー — 新規 8 データソース + 18 個の読み取り専用データツール**:市場データの loader レジストリが 10 から 18 ソースへ拡大しました——無料の直接 API 追加 4 件(**Eastmoney**、**Sina**、**Stooq**、そして直接 HTTP の **Yahoo** クライアント)に加え、任意のキー必須な米国プロバイダ 4 件(**Finnhub**、**Alpha Vantage**、**Tiingo**、**FMP**)で、fallback チェーンは IP-ban リスク順に並べ替えました。その上に **18 個の新しい読み取り専用データツール**が乗り、OHLCV を越えてファンダメンタルズやフローにまで到達します——資金フロー、龍虎榜、北向き(Stock-Connect)フロー、信用取引、大口取引(ブロックトレード)、株主数、ロックアップ解除、セクター構成、調査レポート、ニュース、SEC 提出書類(EDGAR + XBRL)、財務諸表、オプションチェーン、機関投資家の保有、全市場スクリーニング、シンボル検索を、A 株 / 米国 / 香港にまたがって、すべて MCP 経由で公開します。集約された `data-routing` インデックスとソース別の `eastmoney` / `sec-edgar` skill がこのレイヤーを文書化し、ライブ LLM ルーティング + データのスモークパスでエンドツーエンド検証済みです。- **2026-06-18** 🔬 **Research Autopilot 第1フェーズ + ローカル Data Bridge ローダー、加えて Discord セキュリティ通知**:2 つの新しい agent ツールが **Hypothesis Registry → Research Goal → backtest** の経路を端から端までつなぎます——`run_research_autopilot` は `hypothesis_id` を research goal に変換し(テーゼを目的に、backtest 向けの受け入れ基準、次のステップのヒント付き)、`generate_backtest_config` は hypothesis の universe とデータソースから backtest の `config.json` を自動生成するので、agent はアイデア → `signal_engine.py` → 実行まで一直線に進めます(現在 **50 ツール**)([#260](https://github.com/HKUDS/Vibe-Trading/pull/260)、@Robin1987China さんに感謝)。新しい **`local` データローダー**は、自分の **CSV / Parquet / DuckDB** ファイルから直接 OHLCV を読み込みます:`~/.vibe-trading/data-bridge/config.yaml` でシンボルをファイルに対応付け、シンボルに `local:` を前置するとローカルデータへルーティングされ、通常の fallback チェーンにも対応します([#252](https://github.com/HKUDS/Vibe-Trading/pull/252)、@Robin1987China さんに感謝)。直後の追従修正で、両者が抱えていた実行時の欠陥を修正しました——Autopilot はホストの `session_id` を受け取れず(毎回エラー)、`generate_backtest_config` は `safe_run_dir` が拒否する run ルートに書き込み、ローカルローダーは tz-naive なタイムスタンプ比較で tz-aware 入力を黙って空にしていました([#266](https://github.com/HKUDS/Vibe-Trading/pull/266))。DeepSeek の `DSML` でラップされた tool call が正しくパースされるようになり([#261](https://github.com/HKUDS/Vibe-Trading/issues/261))、Robinhood OAuth ハンドシェイクの初期化タイムアウトが延長され、MCP `initTimeout` 設定キーもドキュメント化されました([#263](https://github.com/HKUDS/Vibe-Trading/pull/263))。さらに識別子の封じ込め強化が一括で入りました:永続メモリの型バリデーション([#257](https://github.com/HKUDS/Vibe-Trading/pull/257))、MCP swarm run-id の封じ込め([#258](https://github.com/HKUDS/Vibe-Trading/pull/258))、そして relay・preview・commit ゲート間で一貫して強制される厳格な `mp_[0-9a-f]{32}` mandate proposal-id フォーマット([#256](https://github.com/HKUDS/Vibe-Trading/pull/256)、[#264](https://github.com/HKUDS/Vibe-Trading/pull/264))。⚠️ **セキュリティ通知**:以前のコミュニティ招待は、現在私たちが管理していないサーバーに解決され、偽の Collab.Land ウォレット「認証」フィッシング詐欺を実行しています——すべての README と issue テンプレートから削除され、**唯一**の公式 Discord は HKUDS コミュニティサーバー([discord.gg/6TdQnT5xcF](https://discord.gg/6TdQnT5xcF))になりました。Vibe-Trading が暗号ウォレットの「認証」や接続を求めることは決してありません。- **2026-06-17** 🧩 **インストール互換性 + Opus/Kimi プロバイダ修正**:通常の `pip install vibe-trading-ai` では、任意機能の `pyharmonics` / `ta` 依存チェーンを引かなくなりました。harmonic detection は `vibe-trading-ai[harmonic]` extra の背後に移しつつ、同梱 fallback detector はそのまま使えます([#250](https://github.com/HKUDS/Vibe-Trading/pull/250)、[#249](https://github.com/HKUDS/Vibe-Trading/issues/249) をクローズ)。Agent loop は Opus 4.8+ が拒否する assistant-prefill handoff message を送らなくなり、Kimi/Moonshot は `MOONSHOT_USER_AGENT` で client `User-Agent` を上書きできます([#248](https://github.com/HKUDS/Vibe-Trading/pull/248)、[#246](https://github.com/HKUDS/Vibe-Trading/issues/246) と [#204](https://github.com/HKUDS/Vibe-Trading/issues/204) をクローズ)。follow-up tests は background-result と auto-compact の handoff 経路を直接カバーします([#251](https://github.com/HKUDS/Vibe-Trading/pull/251))。-- **2026-06-16** 🛡️ **セキュリティ/API 強化 + GLM/Zhipu alias**:Settings 書き込みは認証設定時に auth 必須になりました([#245](https://github.com/HKUDS/Vibe-Trading/pull/245));API session の shell-capable tools は明示的な `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` opt-in が必要です([#243](https://github.com/HKUDS/Vibe-Trading/pull/243));API key 設定時の local shutdown も auth 必須です([#241](https://github.com/HKUDS/Vibe-Trading/pull/241));loopback に見えるが信頼できない Host は local 扱いせず拒否します([#242](https://github.com/HKUDS/Vibe-Trading/pull/242))。実行時の細部も改善: Web chat は完了済み attempts と同期し([#236](https://github.com/HKUDS/Vibe-Trading/pull/236))、run card は非有限メトリクスを strict JSON として出力([#238](https://github.com/HKUDS/Vibe-Trading/pull/238))、不正な `RSSHUB_TIMEOUT_S` / `RSSHUB_FETCH_BUDGET_S` は安全に fallback([#240](https://github.com/HKUDS/Vibe-Trading/pull/240))、ddgs retry fallback は regression coverage 付きです([#239](https://github.com/HKUDS/Vibe-Trading/pull/239))。GLM/Zhipu は first-class provider alias となり、model-name inference も追加されました([#247](https://github.com/HKUDS/Vibe-Trading/pull/247)、[#237](https://github.com/HKUDS/Vibe-Trading/issues/237) をクローズ)。<details><summary>過去のニュース</summary>+- **2026-06-16** 🛡️ **セキュリティ/API 強化 + GLM/Zhipu alias**:Settings 書き込みは認証設定時に auth 必須になりました([#245](https://github.com/HKUDS/Vibe-Trading/pull/245));API session の shell-capable tools は明示的な `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` opt-in が必要です([#243](https://github.com/HKUDS/Vibe-Trading/pull/243));API key 設定時の local shutdown も auth 必須です([#241](https://github.com/HKUDS/Vibe-Trading/pull/241));loopback に見えるが信頼できない Host は local 扱いせず拒否します([#242](https://github.com/HKUDS/Vibe-Trading/pull/242))。実行時の細部も改善: Web chat は完了済み attempts と同期し([#236](https://github.com/HKUDS/Vibe-Trading/pull/236))、run card は非有限メトリクスを strict JSON として出力([#238](https://github.com/HKUDS/Vibe-Trading/pull/238))、不正な `RSSHUB_TIMEOUT_S` / `RSSHUB_FETCH_BUDGET_S` は安全に fallback([#240](https://github.com/HKUDS/Vibe-Trading/pull/240))、ddgs retry fallback は regression coverage 付きです([#239](https://github.com/HKUDS/Vibe-Trading/pull/239))。GLM/Zhipu は first-class provider alias となり、model-name inference も追加されました([#247](https://github.com/HKUDS/Vibe-Trading/pull/247)、[#237](https://github.com/HKUDS/Vibe-Trading/issues/237) をクローズ)。+- **2026-06-15** 🧭 **Web 検索の堅牢化 + Web UI のラン継続性修正**:`web_search` は単一エンジンがレート制限されても失敗しなくなりました——複数の無料・キー不要のエンジン(DuckDuckGo、Google、Bing、Brave、Mojeek、Yahoo)を順に照会し、リトライ/バックオフを行い、「結果なし」をエラーではなく空の回答として扱い、すべてのエンジンが制限された場合は素っ気ない ❌ ではなく実行可能なメッセージを返します(エンジン一覧は `VIBE_TRADING_SEARCH_BACKENDS` で上書き可能)([#232](https://github.com/HKUDS/Vibe-Trading/pull/232)、[#231](https://github.com/HKUDS/Vibe-Trading/issues/231) をクローズ、@Ethan-sun01 さんに感謝)。Web UI では、ラン中にページを切り替えても固まらなくなりました——チャットは戻った際にライブストリームへ再購読し、見逃した進捗を再生します([#234](https://github.com/HKUDS/Vibe-Trading/pull/234))——そして停止ボタンはイテレーション境界だけでなく、ストリーミング中やツール間でも有効になりました([#235](https://github.com/HKUDS/Vibe-Trading/pull/235))。これにより [#229](https://github.com/HKUDS/Vibe-Trading/issues/229) の両方が解決します(@kalkinj さんに感謝)。baostock loader は tushare 形式の `601398.SH` に加え、ネイティブの `sh.601398` / `sz.000001` コードも受け付けるようになりました([#230](https://github.com/HKUDS/Vibe-Trading/pull/230)、@bhlt さんに感謝)。- **2026-06-14** 📊 **ラン単位のトークン使用量 + Run Detail チャートの遅延読み込み**: 各 agent ランは、プロバイダ報告のトークン使用量をラン単位の `llm_usage.json` として永続化するようになりました——プロバイダ/モデル、累計合計、イテレーションごとの件数——`/runs/{id}` に追加的に提供されるため、ランが終わってライブストリームが消えた後もトークンコストを監査できます(プロバイダ報告値のみ;prompt/内容のキャプチャや価格推定はなし)([#223](https://github.com/HKUDS/Vibe-Trading/pull/223)、@LemonCANDY42 さんに感謝)。Run Detail ページは、もはや全シンボルのローソク足を最初に読み込みません: 既定の `/runs/{id}` レスポンスは変更なしのまま、UI はまずランのサマリーを描画し、オプトインの `?chart_payload=summary` / `?chart_symbol=` モードで各シンボルのチャートをオンデマンドに読み込みます。シンボルごとの読み込み状態と「全件読み込み + 進捗」コントロール付きです([#225](https://github.com/HKUDS/Vibe-Trading/pull/225)、@LemonCANDY42 さんに感謝)。2 つの loader 修正で締めくくり: yfinance の排他的な `end` 境界が、要求範囲の最終取引日を取りこぼさなくなりました——ダウンロード呼び出しは `end + 1 日` を渡し、キャッシュキーは元の範囲を保持します([#226](https://github.com/HKUDS/Vibe-Trading/pull/226)、@gyx09212214-prog さんに感謝)——そして不正な `CCXT_TIMEOUT_MS` / `OKX_TIMEOUT_S` 値は、import 時に例外を投げて起動を妨げる代わりに、警告して既定値にフォールバックするようになりました([#227](https://github.com/HKUDS/Vibe-Trading/pull/227)、@gyx09212214-prog さんに感謝)。@@ -252,6 +254,34 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an---+## 📡 データソースとスマートフォールバック++1 回の `get_market_data` 呼び出しで **18 のマーケットデータソース**にアクセスできます。`source: "auto"` を指定すれば、loader が銘柄に応じてソースを選び、**IP 規制リスク**の順に並んだ市場別チェーンをたどります。規制を受けない公開ソースを先に、スロットリングや key を要するソースを最後に試します。設定不要、単一障害点なし。++| Source | Markets | Auth | Role |+|--------|---------|------|------|+| `tencent` · `mootdx` | A-share | none | never IP-banned (`mootdx` = 通达信 TCP) |+| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) |+| `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks |+| `tushare` | A / futures / fund / macro | token | richest A-share |+| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |+| `yfinance` | US / HK | none | wrapper |+| `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |+| `okx` · `ccxt` | crypto | none | OKX + 100+ exchanges |+| `futu` | HK / A | OpenD | optional local FutuOpenD |+| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |++**フォールバックチェーン(IP 規制リスク順):**++- **A 株** → `tencent` · `mootdx` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`+- **米国株** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `akshare` · `local`+- **香港株** → `eastmoney` · `yahoo` · `futu` · `yfinance` · `akshare` · `local`+- **暗号資産** → `okx` · `ccxt` · `yfinance` · `local` · *(先物 / ファンド / マクロ / FX → `tushare`/`akshare` → `local`)*++OHLCV にとどまらず、**18 の読み取り専用データツール**がファンダメンタルズと資金フローまで踏み込みます。資金フロー、龍虎榜、北向資金、信用取引、大口取引、株主数、ロックアップ、セクター、調査レポート、ニュース、SEC filings、財務諸表、オプションチェーン、機関投資家保有、市場スクリーニング、銘柄検索、マクロまで、すべて MCP 経由で公開されます。明示的な `local:` 銘柄が暗黙のうちにネットワークソースへフォールバックすることは決してありません。++---+## 🔩 詳細な機能メイン README を読みやすく保つため、詳細な一覧は以下に折りたたんでいます。利用できる構成要素を確認したいときに開いてください。@@ -265,7 +295,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| Category | Skills | Examples ||----------|--------|----------|-| Data Source | 7 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -842,7 +872,7 @@ Vibe-Trading/├── agent/ # バックエンド (Python)│ ├── cli/ # CLI パッケージ — インタラクティブ TUI + サブコマンド│ ├── api_server.py # FastAPI サーバー — runs、sessions、upload、swarm、SSE-│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 36 tools+│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 54 tools│ ││ ├── src/│ │ ├── agent/ # ReAct エージェントコア@@ -883,7 +913,7 @@ Vibe-Trading/│ ││ └── backtest/ # バックテストエンジン│ ├── engines/ # 7 エンジン + クロスマーケット composite engine + options_portfolio-│ ├── loaders/ # 7 ソース: tushare、okx、yfinance、akshare、mootdx、ccxt、futu+│ ├── loaders/ # 18 ソース: tushare、okx、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + 自動フォールバックチェーン│ └── optimizers/ # MVO、equal vol、max div、risk paritydiff --git a/README_ko.md b/README_ko.mdindex 10de00fbf..3fb085119 100644--- a/README_ko.md+++ b/README_ko.md@@ -50,12 +50,14 @@## 📰 뉴스+- **2026-06-19** 🌍 **글로벌 데이터 계층 — 새 소스 8종 + 읽기 전용 데이터 도구 18종**: 시장 데이터 로더 레지스트리가 10개에서 18개 소스로 늘었습니다 — 무료 다이렉트 API 소스 네 종(**Eastmoney**, **Sina**, **Stooq**, 그리고 다이렉트 HTTP **Yahoo** 클라이언트)에 더해 키 기반 옵션형 미국 프로바이더 네 종(**Finnhub**, **Alpha Vantage**, **Tiingo**, **FMP**)이 추가됐고, fallback 체인은 IP 차단 위험 순으로 재정렬됐습니다. 그 위에 OHLCV를 넘어 펀더멘털과 자금 흐름까지 닿는 **읽기 전용 데이터 도구 18종**을 얹었습니다 — 자금 흐름, 용호방(dragon-tiger board), 북향(Stock-Connect) 자금 흐름, 신용거래, 대종거래(block trades), 주주 수, 보호예수 만기, 섹터 구성, 리서치 리포트, 뉴스, SEC 공시(EDGAR + XBRL), 재무제표, 옵션 체인, 기관 보유, 전체 시장 스크리닝, 심볼 검색 — A주 / 미국 / 홍콩 전반에 걸쳐 모두 MCP로 노출됩니다. 통합 `data-routing` 인덱스와 소스별 `eastmoney` / `sec-edgar` 스킬이 이 계층을 문서화하며, 실제 LLM 라우팅 + 데이터 스모크 패스로 엔드투엔드 검증했습니다.- **2026-06-18** 🔬 **Research Autopilot 1단계 + 로컬 Data Bridge 로더, 그리고 Discord 보안 공지**: 두 개의 새 agent 도구가 **Hypothesis Registry → Research Goal → backtest** 경로를 끝까지 연결합니다 — `run_research_autopilot`은 `hypothesis_id`를 research goal로 바꾸고(주장을 목표로, backtest 지향 수용 기준, 다음 단계 힌트 포함), `generate_backtest_config`는 hypothesis의 universe와 데이터 소스로부터 backtest `config.json`을 자동 작성하므로, agent가 아이디어 → `signal_engine.py` → 실행까지 곧장 진행할 수 있습니다(이제 **50개 도구**)([#260](https://github.com/HKUDS/Vibe-Trading/pull/260), @Robin1987China 님 감사합니다). 새 **`local` 데이터 로더**는 사용자 본인의 **CSV / Parquet / DuckDB** 파일에서 직접 OHLCV를 읽습니다: `~/.vibe-trading/data-bridge/config.yaml`에서 심볼을 파일에 매핑하고 심볼에 `local:` 접두사를 붙이면 로컬 데이터로 라우팅되며, 일반 fallback 체인도 지원합니다([#252](https://github.com/HKUDS/Vibe-Trading/pull/252), @Robin1987China 님 감사합니다). 직후 후속 수정으로 둘이 함께 들어온 런타임 결함을 고쳤습니다 — Autopilot이 호스트 `session_id`를 받지 못했고(매 호출이 오류), `generate_backtest_config`가 `safe_run_dir`이 거부하는 run 루트에 기록했으며, 로컬 로더가 tz-naive 타임스탬프 비교에서 tz-aware 입력을 조용히 비웠습니다([#266](https://github.com/HKUDS/Vibe-Trading/pull/266)). DeepSeek의 `DSML`로 감싼 tool call이 이제 올바르게 파싱되고([#261](https://github.com/HKUDS/Vibe-Trading/issues/261)), Robinhood OAuth 핸드셰이크의 초기화 타임아웃이 늘어났으며 MCP `initTimeout` 설정 키도 문서화됐습니다([#263](https://github.com/HKUDS/Vibe-Trading/pull/263)). 또한 식별자 봉쇄 강화가 한 번에 들어왔습니다: 영속 메모리 타입 검증([#257](https://github.com/HKUDS/Vibe-Trading/pull/257)), MCP swarm run-id 봉쇄([#258](https://github.com/HKUDS/Vibe-Trading/pull/258)), 그리고 relay·preview·commit 게이트 전반에서 일관되게 강제되는 엄격한 `mp_[0-9a-f]{32}` mandate proposal-id 형식([#256](https://github.com/HKUDS/Vibe-Trading/pull/256), [#264](https://github.com/HKUDS/Vibe-Trading/pull/264)). ⚠️ **보안 공지**: 이전 커뮤니티 초대는 이제 우리가 더 이상 관리하지 않는 서버로 연결되며, 가짜 Collab.Land 지갑 "인증" 피싱 사기를 운영합니다 — 모든 README와 issue 템플릿에서 제거됐고, **유일한** 공식 Discord는 이제 HKUDS 커뮤니티 서버([discord.gg/6TdQnT5xcF](https://discord.gg/6TdQnT5xcF))입니다. Vibe-Trading은 절대 암호화폐 지갑을 "인증"하거나 연결하라고 요구하지 않습니다.- **2026-06-17** 🧩 **설치 호환성 + Opus/Kimi 프로바이더 수정**: 기본 `pip install vibe-trading-ai`는 더 이상 선택 기능인 `pyharmonics` / `ta` 의존성 체인을 끌어오지 않습니다. harmonic detection은 `vibe-trading-ai[harmonic]` extra 뒤로 이동했고, 내장 fallback detector는 그대로 사용할 수 있습니다([#250](https://github.com/HKUDS/Vibe-Trading/pull/250), [#249](https://github.com/HKUDS/Vibe-Trading/issues/249) 종료). Agent loop는 Opus 4.8+가 거부하는 assistant-prefill handoff message를 보내지 않으며, Kimi/Moonshot은 `MOONSHOT_USER_AGENT`로 client `User-Agent`를 덮어쓸 수 있습니다([#248](https://github.com/HKUDS/Vibe-Trading/pull/248), [#246](https://github.com/HKUDS/Vibe-Trading/issues/246) 및 [#204](https://github.com/HKUDS/Vibe-Trading/issues/204) 종료). 후속 테스트는 background-result와 auto-compact handoff 경로를 직접 커버합니다([#251](https://github.com/HKUDS/Vibe-Trading/pull/251)).-- **2026-06-16** 🛡️ **보안/API 강화 + GLM/Zhipu alias**: Settings 쓰기는 인증 설정 시 auth가 필요합니다([#245](https://github.com/HKUDS/Vibe-Trading/pull/245)); API session의 shell-capable tools는 명시적인 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` opt-in이 필요합니다([#243](https://github.com/HKUDS/Vibe-Trading/pull/243)); API key가 설정된 local shutdown도 auth가 필요합니다([#241](https://github.com/HKUDS/Vibe-Trading/pull/241)); loopback처럼 보이지만 신뢰할 수 없는 Host는 local로 취급하지 않고 거부합니다([#242](https://github.com/HKUDS/Vibe-Trading/pull/242)). 런타임 세부도 다듬었습니다: Web chat은 완료된 attempts와 동기화되고([#236](https://github.com/HKUDS/Vibe-Trading/pull/236)), run card는 유한하지 않은 metric을 strict JSON으로 출력하며([#238](https://github.com/HKUDS/Vibe-Trading/pull/238)), 잘못된 `RSSHUB_TIMEOUT_S` / `RSSHUB_FETCH_BUDGET_S`는 안전하게 fallback합니다([#240](https://github.com/HKUDS/Vibe-Trading/pull/240)). ddgs retry fallback도 regression coverage가 추가됐습니다([#239](https://github.com/HKUDS/Vibe-Trading/pull/239)). GLM/Zhipu는 first-class provider alias가 되었고 model-name inference도 추가됐습니다([#247](https://github.com/HKUDS/Vibe-Trading/pull/247), [#237](https://github.com/HKUDS/Vibe-Trading/issues/237) 종료).<details><summary>이전 뉴스</summary>+- **2026-06-16** 🛡️ **보안/API 강화 + GLM/Zhipu alias**: Settings 쓰기는 인증 설정 시 auth가 필요합니다([#245](https://github.com/HKUDS/Vibe-Trading/pull/245)); API session의 shell-capable tools는 명시적인 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` opt-in이 필요합니다([#243](https://github.com/HKUDS/Vibe-Trading/pull/243)); API key가 설정된 local shutdown도 auth가 필요합니다([#241](https://github.com/HKUDS/Vibe-Trading/pull/241)); loopback처럼 보이지만 신뢰할 수 없는 Host는 local로 취급하지 않고 거부합니다([#242](https://github.com/HKUDS/Vibe-Trading/pull/242)). 런타임 세부도 다듬었습니다: Web chat은 완료된 attempts와 동기화되고([#236](https://github.com/HKUDS/Vibe-Trading/pull/236)), run card는 유한하지 않은 metric을 strict JSON으로 출력하며([#238](https://github.com/HKUDS/Vibe-Trading/pull/238)), 잘못된 `RSSHUB_TIMEOUT_S` / `RSSHUB_FETCH_BUDGET_S`는 안전하게 fallback합니다([#240](https://github.com/HKUDS/Vibe-Trading/pull/240)). ddgs retry fallback도 regression coverage가 추가됐습니다([#239](https://github.com/HKUDS/Vibe-Trading/pull/239)). GLM/Zhipu는 first-class provider alias가 되었고 model-name inference도 추가됐습니다([#247](https://github.com/HKUDS/Vibe-Trading/pull/247), [#237](https://github.com/HKUDS/Vibe-Trading/issues/237) 종료).+- **2026-06-15** 🧭 **웹 검색 견고성 + Web UI 실행 연속성 수정**: `web_search`는 단일 엔진이 레이트리밋되어도 더 이상 실패하지 않습니다——이제 여러 무료·키 불필요 엔진(DuckDuckGo, Google, Bing, Brave, Mojeek, Yahoo)을 순서대로 조회하고 재시도/백오프를 적용하며, "결과 없음"을 오류가 아닌 빈 답변으로 처리하고, 모든 엔진이 제한될 때는 무미건조한 ❌ 대신 실행 가능한 메시지를 반환합니다(엔진 목록은 `VIBE_TRADING_SEARCH_BACKENDS`로 재정의 가능)([#232](https://github.com/HKUDS/Vibe-Trading/pull/232), [#231](https://github.com/HKUDS/Vibe-Trading/issues/231) 종료, @Ethan-sun01 님 감사합니다). Web UI에서는 실행 중 페이지를 전환해도 더 이상 멈추지 않습니다——채팅이 돌아올 때 라이브 스트림에 다시 구독하고 놓친 진행을 재생합니다([#234](https://github.com/HKUDS/Vibe-Trading/pull/234))——그리고 중지 버튼이 이터레이션 경계뿐 아니라 스트리밍 중과 도구 사이에서도 즉시 적용됩니다([#235](https://github.com/HKUDS/Vibe-Trading/pull/235)). 이로써 [#229](https://github.com/HKUDS/Vibe-Trading/issues/229)의 두 증상이 모두 해결됩니다(@kalkinj 님 감사합니다). baostock loader도 tushare 스타일 `601398.SH`와 함께 네이티브 `sh.601398` / `sz.000001` 코드를 받아들입니다([#230](https://github.com/HKUDS/Vibe-Trading/pull/230), @bhlt 님 감사합니다).- **2026-06-14** 📊 **실행 단위 토큰 사용량 + Run Detail 차트 지연 로딩**: 이제 모든 agent 실행은 프로바이더가 보고한 토큰 사용량을 실행 범위의 `llm_usage.json`으로 영속화합니다——프로바이더/모델, 누적 합계, 이터레이션별 카운트——`/runs/{id}`에 추가로 노출되어, 실행이 끝나고 라이브 스트림이 사라진 뒤에도 토큰 비용을 감사할 수 있습니다(프로바이더 보고값만; prompt/내용 캡처나 가격 추정 없음)([#223](https://github.com/HKUDS/Vibe-Trading/pull/223), @LemonCANDY42 님 감사합니다). Run Detail 페이지는 더 이상 모든 심볼의 캔들을 처음부터 불러오지 않습니다: 기본 `/runs/{id}` 응답은 그대로 유지되지만, UI는 먼저 실행 요약을 렌더링한 뒤 옵트인 `?chart_payload=summary` / `?chart_symbol=` 모드로 각 심볼의 차트를 필요할 때 불러옵니다. 심볼별 로딩 상태와 "전체 로드 + 진행률" 컨트롤이 함께 제공됩니다([#225](https://github.com/HKUDS/Vibe-Trading/pull/225), @LemonCANDY42 님 감사합니다). 두 가지 loader 수정으로 마무리: yfinance의 배타적 `end` 경계가 요청 범위의 마지막 거래일을 더 이상 누락하지 않습니다——다운로드 호출은 `end + 1일`을 전달하고 캐시 키는 원래 범위를 유지합니다([#226](https://github.com/HKUDS/Vibe-Trading/pull/226), @gyx09212214-prog 님 감사합니다)——그리고 잘못된 `CCXT_TIMEOUT_MS` / `OKX_TIMEOUT_S` 값은 import 시 예외를 던져 시작을 막는 대신 경고하고 기본값으로 폴백합니다([#227](https://github.com/HKUDS/Vibe-Trading/pull/227), @gyx09212214-prog 님 감사합니다).@@ -252,6 +254,34 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an---+## 📡 데이터 소스 & 스마트 폴백++`get_market_data` 한 번의 호출, **18개 시장 데이터 소스**. `source: "auto"`로 설정하면 로더가 심볼에 따라 소스를 고르고, 시장별 체인을 **IP 차단 위험** 순으로 따라갑니다: 절대 차단되지 않는 공개 소스를 먼저, 속도 제한 / 키 기반 소스를 마지막에 둡니다. 설정 불필요, 단일 장애 지점 없음.++| Source | Markets | Auth | Role |+|--------|---------|------|------|+| `tencent` · `mootdx` | A-share | none | never IP-banned (`mootdx` = 通达信 TCP) |+| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) |+| `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks |+| `tushare` | A / futures / fund / macro | token | richest A-share |+| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |+| `yfinance` | US / HK | none | wrapper |+| `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |+| `okx` · `ccxt` | crypto | none | OKX + 100+ exchanges |+| `futu` | HK / A | OpenD | optional local FutuOpenD |+| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |++**폴백 체인 (IP 차단 위험 순):**++- **A주** → `tencent` · `mootdx` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`+- **미국** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `akshare` · `local`+- **홍콩** → `eastmoney` · `yahoo` · `futu` · `yfinance` · `akshare` · `local`+- **크립토** → `okx` · `ccxt` · `yfinance` · `local` · *(선물 / 펀드 / 매크로 / 외환 → `tushare`/`akshare` → `local`)*++OHLCV를 넘어 **18개 읽기 전용 데이터 도구**가 펀더멘털과 자금 흐름까지 닿습니다 — 자금 흐름, 용호방(dragon-tiger), 북향(northbound), 신용거래, 대종거래, 주주 수, 보호예수, 섹터, 리서치 리포트, 뉴스, SEC 공시, 재무제표, 옵션 체인, 기관 보유, 시장 스크리닝, 심볼 검색, 매크로 — 모두 MCP로 노출됩니다. 명시적인 `local:` 심볼은 절대 조용히 네트워크 소스로 폴백하지 않습니다.++---+## 🔩 상세 기능메인 README를 읽기 쉽게 유지하기 위해 상세 목록은 아래에 접어 두었습니다. 사용 가능한 구성 요소를 확인하고 싶을 때 열어보세요.@@ -265,7 +295,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| 카테고리 | 스킬 | 예시 ||----------|------|------|-| Data Source | 7 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -845,7 +875,7 @@ Vibe-Trading/├── agent/ # Backend (Python)│ ├── cli/ # CLI package — interactive TUI + subcommands│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE-│ ├── mcp_server.py # MCP server — 36 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 54 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent core@@ -886,7 +916,7 @@ Vibe-Trading/│ ││ └── backtest/ # Backtest engines│ ├── engines/ # 7 engines + composite cross-market engine + options_portfolio-│ ├── loaders/ # 7 sources: tushare, okx, yfinance, akshare, mootdx, ccxt, futu+│ ├── loaders/ # 18 sources: tushare, okx, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + auto-fallback chains│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_zh.md b/README_zh.mdindex 57b7c2870..656e34be0 100644--- a/README_zh.md+++ b/README_zh.md@@ -50,12 +50,14 @@## 📰 News+- **2026-06-19** 🌍 **全球数据层 — 8 个新数据源 + 18 个只读数据工具**:行情数据 loader 从 10 个增至 18 个——四个免费直连源(**东方财富**、**新浪**、**Stooq**、直连 HTTP 的 **Yahoo** 客户端)加四个可选 key 的美股源(**Finnhub**、**Alpha Vantage**、**Tiingo**、**FMP**),fallback 链按"被封 IP 风险"重新排序。在此之上是 **18 个新只读数据工具**,把能力从 OHLCV 拓展到基本面与资金面——资金流、龙虎榜、北向(陆股通)资金、融资融券、大宗交易、股东户数、限售解禁、板块归属、券商研报、新闻、SEC 文件(EDGAR + XBRL)、财务报表、期权链、机构持仓、全市场筛选、代码搜索——覆盖 A股 / 美股 / 港股,全部经 MCP 暴露。统一的 `data-routing` 路由索引与按源的 `eastmoney` / `sec-edgar` skill 将其文档化,并通过真实端到端的 LLM 路由 + 数据冒烟验证。- **2026-06-18** 🔬 **Research Autopilot 第一阶段 + 本地 Data Bridge 加载器,外加一则 Discord 安全提示**:两个新 agent 工具把**假设登记(Hypothesis Registry)→ 研究目标(Research Goal)→ 回测**这条链路打通——`run_research_autopilot` 把一个 `hypothesis_id` 变成一个研究目标(论点即目标、面向回测的验收标准、下一步提示),`generate_backtest_config` 则根据假设的标的池与数据源自动写出回测 `config.json`,让 agent 可以从想法 → `signal_engine.py` → 实跑一气呵成(现在 **50 个工具**)([#260](https://github.com/HKUDS/Vibe-Trading/pull/260),感谢 @Robin1987China)。新的 **`local` 数据加载器**直接从你自己的 **CSV / Parquet / DuckDB** 文件读取 OHLCV:在 `~/.vibe-trading/data-bridge/config.yaml` 里把 symbol 映射到文件,并给 symbol 加 `local:` 前缀即可路由到本地数据,照常支持 fallback 链([#252](https://github.com/HKUDS/Vibe-Trading/pull/252),感谢 @Robin1987China)。一个快速跟进修掉了二者各自带来的运行期缺陷——Autopilot 从未收到宿主 `session_id`(每次调用都报错),`generate_backtest_config` 写到了 `safe_run_dir` 拒绝的 run 根目录,本地加载器在 tz-naive 时间戳比较时静默清空了 tz-aware 输入([#266](https://github.com/HKUDS/Vibe-Trading/pull/266))。DeepSeek 的 `DSML` 包裹式工具调用现在能正确解析([#261](https://github.com/HKUDS/Vibe-Trading/issues/261)),Robinhood OAuth 握手获得了更长的初始化超时,MCP `initTimeout` 配置项也已写进文档([#263](https://github.com/HKUDS/Vibe-Trading/pull/263)),并落地了一波标识符收敛加固:持久记忆类型校验([#257](https://github.com/HKUDS/Vibe-Trading/pull/257))、MCP swarm run-id 收敛([#258](https://github.com/HKUDS/Vibe-Trading/pull/258))、以及在 relay、preview 与 commit 网关之间一致强制的严格 `mp_[0-9a-f]{32}` mandate proposal-id 格式([#256](https://github.com/HKUDS/Vibe-Trading/pull/256)、[#264](https://github.com/HKUDS/Vibe-Trading/pull/264))。⚠️ **安全提示**:旧的社区邀请链接现在指向一个我们已无法控制的服务器,里面跑着假冒 Collab.Land 的钱包"验证"钓鱼骗局——它已从所有 README 和 issue 模板中移除,**唯一**官方 Discord 现在是 HKUDS 社区服务器([discord.gg/6TdQnT5xcF](https://discord.gg/6TdQnT5xcF))。Vibe-Trading 绝不会要求你"验证"或连接加密钱包。- **2026-06-17** 🧩 **安装兼容 + Opus/Kimi provider 修复**:基础 `pip install vibe-trading-ai` 不再拉取可选的 `pyharmonics` / `ta` 依赖链;谐波形态识别现在放到 `vibe-trading-ai[harmonic]` extra 后面,同时保留内置 fallback 检测器([#250](https://github.com/HKUDS/Vibe-Trading/pull/250),关闭 [#249](https://github.com/HKUDS/Vibe-Trading/issues/249))。Agent loop 也不再发送 Opus 4.8+ 会拒绝的 assistant-prefill handoff 消息,Kimi/Moonshot 可通过 `MOONSHOT_USER_AGENT` 覆盖客户端 `User-Agent`([#248](https://github.com/HKUDS/Vibe-Trading/pull/248),关闭 [#246](https://github.com/HKUDS/Vibe-Trading/issues/246) 和 [#204](https://github.com/HKUDS/Vibe-Trading/issues/204));后续测试已直接覆盖 background-result 与 auto-compact 两条 handoff 路径([#251](https://github.com/HKUDS/Vibe-Trading/pull/251))。-- **2026-06-16** 🛡️ **安全/API 加固 + GLM/Zhipu alias**:Settings 写入在配置认证时必须鉴权([#245](https://github.com/HKUDS/Vibe-Trading/pull/245));API session 中 shell-capable 工具必须显式设置 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` 才会暴露([#243](https://github.com/HKUDS/Vibe-Trading/pull/243));配置 API key 后 local shutdown 也要求鉴权([#241](https://github.com/HKUDS/Vibe-Trading/pull/241));看似 loopback 但不可信的 Host 会被拒绝,而不再被当成本地请求([#242](https://github.com/HKUDS/Vibe-Trading/pull/242))。运行边角也继续打磨:Web chat 会同步已完成尝试([#236](https://github.com/HKUDS/Vibe-Trading/pull/236)),run card 对非有限指标写出 strict JSON([#238](https://github.com/HKUDS/Vibe-Trading/pull/238)),畸形 `RSSHUB_TIMEOUT_S` / `RSSHUB_FETCH_BUDGET_S` 会安全回退([#240](https://github.com/HKUDS/Vibe-Trading/pull/240)),ddgs retry fallback 已有回归覆盖([#239](https://github.com/HKUDS/Vibe-Trading/pull/239))。GLM/Zhipu 现在是一等 provider alias,并支持按模型名推断([#247](https://github.com/HKUDS/Vibe-Trading/pull/247),关闭 [#237](https://github.com/HKUDS/Vibe-Trading/issues/237))。<details><summary>更早的更新</summary>+- **2026-06-16** 🛡️ **安全/API 加固 + GLM/Zhipu alias**:Settings 写入在配置认证时必须鉴权([#245](https://github.com/HKUDS/Vibe-Trading/pull/245));API session 中 shell-capable 工具必须显式设置 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` 才会暴露([#243](https://github.com/HKUDS/Vibe-Trading/pull/243));配置 API key 后 local shutdown 也要求鉴权([#241](https://github.com/HKUDS/Vibe-Trading/pull/241));看似 loopback 但不可信的 Host 会被拒绝,而不再被当成本地请求([#242](https://github.com/HKUDS/Vibe-Trading/pull/242))。运行边角也继续打磨:Web chat 会同步已完成尝试([#236](https://github.com/HKUDS/Vibe-Trading/pull/236)),run card 对非有限指标写出 strict JSON([#238](https://github.com/HKUDS/Vibe-Trading/pull/238)),畸形 `RSSHUB_TIMEOUT_S` / `RSSHUB_FETCH_BUDGET_S` 会安全回退([#240](https://github.com/HKUDS/Vibe-Trading/pull/240)),ddgs retry fallback 已有回归覆盖([#239](https://github.com/HKUDS/Vibe-Trading/pull/239))。GLM/Zhipu 现在是一等 provider alias,并支持按模型名推断([#247](https://github.com/HKUDS/Vibe-Trading/pull/247),关闭 [#237](https://github.com/HKUDS/Vibe-Trading/issues/237))。+- **2026-06-15** 🧭 **Web 搜索韧性 + Web UI 运行连续性修复**:`web_search` 不再因单个引擎被限流而失败——现在按序查询多个免费、免 key 的引擎(DuckDuckGo、Google、Bing、Brave、Mojeek、Yahoo),带重试/退避,把"无结果"当作空答案而非错误,所有引擎都被限流时返回可操作的提示而不是一个干巴巴的 ❌(可用 `VIBE_TRADING_SEARCH_BACKENDS` 覆盖引擎列表)([#232](https://github.com/HKUDS/Vibe-Trading/pull/232),关闭 [#231](https://github.com/HKUDS/Vibe-Trading/issues/231),感谢 @Ethan-sun01)。Web UI 方面,运行过程中切换页面不再卡死——聊天页返回时会重新订阅实时流并回放期间错过的进度([#234](https://github.com/HKUDS/Vibe-Trading/pull/234))——停止按钮现在会在流式中和工具之间即时生效,而不只是在迭代边界([#235](https://github.com/HKUDS/Vibe-Trading/pull/235)),两个症状一起关闭了 [#229](https://github.com/HKUDS/Vibe-Trading/issues/229)(感谢 @kalkinj)。baostock loader 也开始接受原生的 `sh.601398` / `sz.000001` 代码格式,与 tushare 风格的 `601398.SH` 并存([#230](https://github.com/HKUDS/Vibe-Trading/pull/230),感谢 @bhlt)。- **2026-06-14** 📊 **按运行记录 token 用量 + Run Detail 图表按需加载**:每次 agent 运行现在都会把 provider 上报的 token 用量持久化为运行级的 `llm_usage.json`——provider/模型、累计总量、逐迭代计数——并附加到 `/runs/{id}` 上,这样一次运行结束、实时流消失后,它的 token 成本依然可审计(仅 provider 上报值;不抓 prompt/内容,不估算价格)([#223](https://github.com/HKUDS/Vibe-Trading/pull/223),感谢 @LemonCANDY42)。Run Detail 页面也不再一上来就加载每个标的的 K 线:默认 `/runs/{id}` 响应保持不变,但 UI 现在先渲染运行摘要,再通过可选的 `?chart_payload=summary` / `?chart_symbol=` 模式按需加载每个标的的图表,带有逐标的的加载状态和一个"全部加载 + 进度"控件([#225](https://github.com/HKUDS/Vibe-Trading/pull/225),感谢 @LemonCANDY42)。两个 loader 修复收尾:yfinance 的排他 `end` 边界不再漏掉请求范围内的最后一个交易日——下载调用现在传 `end + 1 天`,而缓存键仍保留原始范围([#226](https://github.com/HKUDS/Vibe-Trading/pull/226),感谢 @gyx09212214-prog);畸形的 `CCXT_TIMEOUT_MS` / `OKX_TIMEOUT_S` 值现在会告警并回退到默认值,而不是在 import 时抛错、阻塞启动([#227](https://github.com/HKUDS/Vibe-Trading/pull/227),感谢 @gyx09212214-prog)。@@ -251,6 +253,34 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an---+## 📡 数据源与智能 Fallback++一次 `get_market_data` 调用,**18 个行情数据源**。设 `source: "auto"`——loader 按符号自动选源,再沿按 **被封 IP 风险** 排序的同市场链向下走(永不封的公开源在前,限速 / 需 key 的在后)。零配置,无单点故障。++| Source | Markets | Auth | Role |+|--------|---------|------|------|+| `tencent` · `mootdx` | A-share | none | never IP-banned (`mootdx` = 通达信 TCP) |+| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) |+| `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks |+| `tushare` | A / futures / fund / macro | token | richest A-share |+| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |+| `yfinance` | US / HK | none | wrapper |+| `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |+| `okx` · `ccxt` | crypto | none | OKX + 100+ exchanges |+| `futu` | HK / A | OpenD | optional local FutuOpenD |+| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |++**Fallback 链(按被封 IP 风险排序):**++- **A股** → `tencent` · `mootdx` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`+- **美股** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `akshare` · `local`+- **港股** → `eastmoney` · `yahoo` · `futu` · `yfinance` · `akshare` · `local`+- **加密** → `okx` · `ccxt` · `yfinance` · `local` · *(期货 / 基金 / 宏观 / 外汇 → `tushare`/`akshare` → `local`)*++除 OHLCV 外,**18 个只读数据工具**深入基本面与资金面——资金流、龙虎榜、北向、两融、大宗交易、股东户数、解禁、板块、研报、新闻、SEC 文件、财务报表、期权链、机构持仓、全市场筛选、代码搜索、宏观——全部经 MCP 暴露。显式 `local:` 源永不静默 fallback 到网络源。++---+## 🔩 Detailed Capabilities为保持主 README 易读,详细清单折叠在下方。需要检查可用构件时可展开查看。@@ -264,7 +294,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| 类别 | Skills | 示例 ||------|--------|------|-| Data Source | 7 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -839,7 +869,7 @@ Vibe-Trading/├── agent/ # 后端(Python)│ ├── cli/ # CLI 包 —— 交互式 TUI + 子命令│ ├── api_server.py # FastAPI server —— runs、sessions、upload、swarm、SSE-│ ├── mcp_server.py # MCP server —— 36 个工具,面向 OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server —— 54 个工具,面向 OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent 内核@@ -880,7 +910,7 @@ Vibe-Trading/│ ││ └── backtest/ # 回测引擎│ ├── engines/ # 7 个引擎 + 跨市场 composite 引擎 + options_portfolio-│ ├── loaders/ # 7 个数据源:tushare、okx、yfinance、akshare、mootdx、ccxt、futu+│ ├── loaders/ # 18 个数据源:tushare、okx、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + 自动 fallback 链路│ └── optimizers/ # MVO、equal vol、max div、risk paritydiff --git a/agent/.env.example b/agent/.env.exampleindex d364b41db..a3ab5b146 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -109,6 +109,17 @@ TUSHARE_TOKEN=your-tushare-token# Download FutuOpenD: https://www.futunn.com/download/openAPI# FUTU_HOST=127.0.0.1# FUTU_PORT=11111+# Free direct-API sources need NO key and auto-join the fallback chain: Eastmoney / Sina / Stooq / Yahoo.++# Optional API-key data sources (enabled only when the key is set; silently skipped otherwise)+# FINNHUB_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)+# ALPHAVANTAGE_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)+# TIINGO_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)+# FMP_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)+# FRED_API_KEY=xxx # macro series (get_macro_series tool)+# VIBE_TRADING_IWENCAI_KEY=xxx # A-share natural-language research search (iwencai_search tool)+# VIBE_TRADING_SEC_UA="Your Name [email protected]" # SEC EDGAR compliant contact User-Agent (optional; a built-in default UA also works)+# Optional per-source request-spacing overrides for batch jobs — VIBE_TRADING_{EASTMONEY,SINA,STOOQ,YAHOO,SEC,FINNHUB,ALPHAVANTAGE,TIINGO,FMP,FRED,IWENCAI,THS}_MIN_INTERVAL (seconds).# Opt-in local market-data cache for backtest loaders (off by default).# When enabled, every data source caches settled historical bars underdiff --git a/agent/SKILL.md b/agent/SKILL.mdindex 2fdbb9d60..3bea16619 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -1,7 +1,7 @@---name: vibe-tradingversion: 0.1.9-description: Professional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 77 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 7 data sources (tushare, yfinance, okx, akshare, mootdx, ccxt, futu).+description: Professional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 79 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 18 market-data sources (tushare, yfinance, okx, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, plus optional-key finnhub/alphavantage/tiingo/fmp).dependencies:python: ">=3.11"pip:@@ -23,7 +23,7 @@ mcp:# Vibe-Trading-Professional finance research toolkit with AI-powered backtesting (7 engines), multi-agent teams, 77 specialized skills, the **Alpha Zoo** (452 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic with one-line CLI benchmarking), and the Shadow Account loop — extract your implicit trading rules from a journal, backtest them across A股/港股/美股/crypto, then see where they would have served you better.+Professional finance research toolkit with AI-powered backtesting (7 engines), multi-agent teams, 79 specialized skills, the **Alpha Zoo** (452 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic with one-line CLI benchmarking), and the Shadow Account loop — extract your implicit trading rules from a journal, backtest them across A股/港股/美股/crypto, then see where they would have served you better.## Setup@@ -53,12 +53,13 @@ Add to your agent's MCP config:### API Key Requirements-Core research MCP tools work with zero API keys for HK/US/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (452 pre-built alphas), and all 77 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.+Core research MCP tools work with zero API keys for HK/US/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (452 pre-built alphas), and all 79 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.| Feature | Key needed | When ||---------|-----------|------|-| HK/US equities & crypto | None | Always free (yfinance + OKX) |-| China A-share data | `TUSHARE_TOKEN` | Only if you query A-share symbols |+| HK/US equities & crypto | None | Always free (yfinance / stooq / yahoo + OKX) |+| China A-share data | None | Free via akshare / baostock / tencent / sina / eastmoney / mootdx fallback (`TUSHARE_TOKEN` optional for premium quality) |+| Premium US fundamentals/quotes | `FINNHUB_API_KEY` / `ALPHAVANTAGE_API_KEY` / `TIINGO_API_KEY` / `FMP_API_KEY` | Only for optional-key providers (graceful fallback to free sources) || Multi-agent swarm (`run_swarm`) | `OPENAI_API_KEY` + `LANGCHAIN_MODEL_NAME` | Swarm spawns internal LLM workers |## What You Can Do@@ -73,12 +74,14 @@ Feed a CSV broker export (同花顺 / 东财 / 富途 / generic), and the agent5. `scan_shadow_signals` — list today's symbols that match your shadow's entry cadence (research only).### Backtesting-Create and run quantitative strategies across 7 engines (ChinaA, GlobalEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 7 data sources:-- **HK/US equities** via yfinance (free, no API key)+Create and run quantitative strategies across 7 engines (ChinaA, GlobalEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 18 market-data sources (auto-detect + ordered fallback):+- **HK/US equities** via yfinance / stooq / yahoo (free, no API key)- **Cryptocurrency** via OKX or CCXT/100+ exchanges (free, no API key)-- **China A-shares** via Tushare (token) or AKShare (free fallback)+- **China A-shares** via AKShare / baostock / tencent / sina / eastmoney / mootdx (free, no API key) — `TUSHARE_TOKEN` optional for premium quality- **Futures, forex, macro** via AKShare (free, no API key)- **HK & A-share equities** via Futu (broker login required, optional)+- **Local CSV/parquet bars** via the `local` loader (offline, no network)+- **Premium US data** via optional-key finnhub / alphavantage / tiingo / fmp (graceful fallback to free sources)Example workflow:1. Use `list_skills()` to discover strategy patterns@@ -108,7 +111,7 @@ One-line cross-sectional IC / IR / alive-reversed-dead categorisation across fouEach alpha ships with `__alpha_meta__` (formula LaTeX + theme + universe + warmup + columns required), guarded by an AST purity gate + 300-row lookahead sentinel test. Use the `vibe-trading alpha {list,show,bench,compare,export-manifest}` CLI, the `/alpha/*` REST routes (browser at `/alpha-zoo`), or compose multi-factor signals via `ZooSignalEngine.from_zoo(...)`.-### Finance Skills (77)+### Finance Skills (79)Comprehensive knowledge base covering:- Technical analysis (candlestick, Elliott wave, Ichimoku, SMC, harmonic, chanlun)- Quantitative methods (factor research, ML strategy, pair trading, multi-factor)@@ -121,11 +124,11 @@ Comprehensive knowledge base covering:Use `load_skill(name)` to access full methodology docs with code templates.-## Available MCP Tools (35)+## Available MCP Tools (54)| Tool | Description | API Key ||------|-------------|---------|-| `list_skills` | List all 77 finance skills | None |+| `list_skills` | List all 79 finance skills | None || `load_skill` | Load full skill documentation | None || `start_research_goal` | Create an auditable research goal | None || `get_research_goal` | Read the current research goal | None |@@ -135,7 +138,25 @@ Use `load_skill(name)` to access full methodology docs with code templates.| `factor_analysis` | IC/IR analysis + layered backtest | None* || `analyze_options` | Black-Scholes price + Greeks | None || `pattern_recognition` | Detect chart patterns (H&S, double top, etc.) | None |-| `get_market_data` | Fetch OHLCV data across 6 sources (auto-detect + fallback) | None* |+| `get_market_data` | Fetch OHLCV data (auto-detect + ordered fallback across 18 sources) | None* |+| `get_fund_flow` | Capital fund-flow (main/retail net inflow) | None* |+| `get_dragon_tiger` | Dragon-tiger list (龙虎榜) top buyer/seller seats | None* |+| `get_northbound_flow` | Northbound (Stock Connect) net flow | None* |+| `get_margin_trading` | Margin trading & short-selling balances | None* |+| `get_block_trades` | Block-trade (大宗交易) records | None* |+| `get_shareholder_count` | Shareholder-count history per symbol | None* |+| `get_lockup_expiry` | Restricted-share lockup release schedule | None* |+| `get_sector_info` | Sector / industry constituents & performance | None* |+| `get_research_reports` | Sell-side analyst research reports | None* |+| `get_stock_news` | Market & company news headlines | None* |+| `get_sec_filings` | SEC EDGAR filings (10-K/10-Q/8-K, etc.) | None |+| `get_financial_statements` | Income / balance / cash-flow statements | None* |+| `get_options_chain` | Options chain (strikes, IV, OI, Greeks) | None* |+| `get_stock_profile` | Valuation, analyst estimates & institutional holdings (US/HK) | None |+| `screen_market` | Market screener with fundamental/technical filters | None* |+| `search_symbol` | Symbol / ticker search across markets | None |+| `get_macro_series` | FRED macroeconomic series | FRED_API_KEY |+| `iwencai_search` | A-share natural-language research search | IWENCAI_KEY || `web_search` | Search the web via DuckDuckGo | None || `read_url` | Fetch web page as Markdown | None || `read_document` | Extract text from PDF/DOCX/XLSX/PPTX/images | None |@@ -169,7 +190,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.pip install vibe-trading-ai```-That's it — no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 77 skills immediately.+That's it — no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 79 skills immediately.## Loading Tools from External MCP Serversdiff --git a/agent/backtest/loaders/_http.py b/agent/backtest/loaders/_http.pynew file mode 100644index 000000000..fc99cbbca--- /dev/null+++ b/agent/backtest/loaders/_http.py@@ -0,0 +1,179 @@+"""Shared HTTP helpers for direct-API loaders: per-host throttling + JSON/CSV GET.++Several free providers — Eastmoney most notably — rate-limit by source IP and+will temporarily ban a client that bursts requests. Rather than scatter sleep+calls across loaders, every ban-prone call routes through :func:`throttled_get`+here, which enforces a minimum spacing between consecutive requests to the same+*host bucket* (plus a little jitter so concurrent workers don't lock-step) and+reuses one :class:`requests.Session` per process so TCP/TLS setup is amortized.++This module is intentionally provider-agnostic: it knows nothing about+Eastmoney/Sina/Stooq field layouts, only how to space requests politely. A+loader picks its own ``host_key`` and ``min_interval`` and stays ignorant of+the locking mechanics.++All spacing is best-effort and process-local — it does not coordinate across+machines. For batch jobs raise the relevant ``*_MIN_INTERVAL`` env var.+"""++from __future__ import annotations++import logging+import random+import threading+import time+from typing import Any++import requests++from backtest.loaders.base import positive_env_float++logger = logging.getLogger(__name__)++# Default User-Agent. Many free quote endpoints reject the bare urllib/requests+# UA, so we present a normal desktop browser string. Loaders may override.+DEFAULT_USER_AGENT = (+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/124.0 Safari/537.36"+)++# Upper bound on the random jitter (seconds) added on top of the configured+# minimum interval, so parallel callers de-synchronize instead of all firing+# the instant the interval elapses.+_JITTER_MAX_S = 0.4+++class HostThrottle:+ """Process-wide minimum-spacing gate keyed by an arbitrary host bucket.++ One instance guards all callers; ``wait(bucket, min_interval)`` blocks until+ at least ``min_interval`` seconds (plus jitter) have elapsed since the last+ request tagged with the same ``bucket``. The lock is held only for the+ bookkeeping arithmetic, not across the sleep, so distinct buckets never block+ one another.+ """++ def __init__(self) -> None:+ self._last: dict[str, float] = {}+ self._lock = threading.Lock()++ def wait(self, bucket: str, min_interval: float) -> None:+ """Block until ``bucket`` is allowed to fire again, then record the slot.++ The *reserved fire time* — jitter included — is what gets stored, so the+ next caller spaces off this caller's actual fire instant rather than an+ earlier un-jittered one. This keeps consecutive requests at least+ ``min_interval`` apart even when many callers burst concurrently (the+ exact scenario the throttle exists for); the jitter only ever pushes a+ slot later, never earlier.+ """+ if min_interval <= 0:+ return+ with self._lock:+ now = time.monotonic()+ last = self._last.get(bucket)+ if last is None or now >= last + min_interval:+ # Slot is free right now — fire immediately, no jitter needed.+ fire_at = now+ else:+ # Chain off the previous reservation and add jitter to desync+ # concurrent callers, baking the jitter into the stored slot.+ fire_at = last + min_interval + random.uniform(0.0, _JITTER_MAX_S)+ self._last[bucket] = fire_at+ sleep_for = fire_at - time.monotonic()+ if sleep_for > 0:+ time.sleep(sleep_for)+++# One shared gate for the whole process.+_THROTTLE = HostThrottle()++# Per-process session reuse, keyed by host bucket so different providers keep+# independent connection pools and cookie jars.+_SESSIONS: dict[str, requests.Session] = {}+_SESSIONS_LOCK = threading.Lock()+++def _session_for(bucket: str) -> requests.Session:+ with _SESSIONS_LOCK:+ session = _SESSIONS.get(bucket)+ if session is None:+ session = requests.Session()+ _SESSIONS[bucket] = session+ return session+++def resolve_min_interval(env_name: str, default: float) -> float:+ """Resolve a per-provider minimum request interval from the environment.++ Args:+ env_name: Env var carrying an override in seconds (e.g.+ ``VIBE_TRADING_EASTMONEY_MIN_INTERVAL``).+ default: Fallback interval when the env var is absent or invalid.++ Returns:+ The override when it parses to a positive float, else ``default``.+ """+ return positive_env_float(env_name, default)+++def throttled_get(+ url: str,+ *,+ host_key: str,+ min_interval: float,+ params: dict[str, Any] | None = None,+ headers: dict[str, str] | None = None,+ timeout: float = 15.0,+) -> requests.Response:+ """GET ``url`` after waiting out the per-host minimum interval.++ Args:+ url: Fully-qualified request URL.+ host_key: Throttle/session bucket. All calls sharing a key are spaced+ by ``min_interval`` and reuse one session.+ min_interval: Minimum seconds between consecutive calls to ``host_key``.+ params: Optional query parameters.+ headers: Optional headers merged over the default browser UA.+ timeout: Per-request socket timeout in seconds.++ Returns:+ The :class:`requests.Response`; the caller decides how to parse it.++ Raises:+ requests.RequestException: Propagated unchanged for the caller's retry+ policy to classify as transient.+ """+ merged_headers = {"User-Agent": DEFAULT_USER_AGENT}+ if headers:+ merged_headers.update(headers)+ _THROTTLE.wait(host_key, min_interval)+ session = _session_for(host_key)+ return session.get(url, params=params, headers=merged_headers, timeout=timeout)+++def throttled_get_json(+ url: str,+ *,+ host_key: str,+ min_interval: float,+ params: dict[str, Any] | None = None,+ headers: dict[str, str] | None = None,+ timeout: float = 15.0,+) -> Any:+ """Throttled GET that decodes the response body as JSON.++ Same contract as :func:`throttled_get`, plus ``response.raise_for_status()``+ and ``response.json()``. A non-2xx status or undecodable body raises, which+ the caller's bounded-retry wrapper treats as transient.+ """+ response = throttled_get(+ url,+ host_key=host_key,+ min_interval=min_interval,+ params=params,+ headers=headers,+ timeout=timeout,+ )+ response.raise_for_status()+ return response.json()diff --git a/agent/backtest/loaders/alphavantage_loader.py b/agent/backtest/loaders/alphavantage_loader.pynew file mode 100644index 000000000..0098b4b2d--- /dev/null+++ b/agent/backtest/loaders/alphavantage_loader.py@@ -0,0 +1,250 @@+"""Alpha Vantage loader: US-equity daily OHLCV via the free key-gated REST API.++Alpha Vantage serves daily bars at ``/query?function=TIME_SERIES_DAILY`` and+gates access behind a free API key (env ``ALPHAVANTAGE_API_KEY``). The endpoint+rate-limits per IP, so every request routes through+:mod:`backtest.loaders._http` for per-host throttling and session reuse rather+than calling :mod:`requests` directly.++API format::++ https://www.alphavantage.co/query?function=TIME_SERIES_DAILY+ &symbol=AAPL&outputsize=full&apikey=<KEY>++The JSON payload nests the bars under ``"Time Series (Daily)"`` keyed by+``YYYY-MM-DD`` date strings, each mapping to numbered OHLCV fields+(``"1. open"`` .. ``"5. volume"``). Throttle/quota responses arrive as a plain+``"Note"`` / ``"Information"`` envelope, and bad symbols as ``"Error Message"``;+all three are surfaced as a transient-classified error so one symbol's failure+never aborts the batch.+"""++from __future__ import annotations++import logging+import os+from typing import Dict, List, Optional++import pandas as pd++from backtest.loaders._http import resolve_min_interval, throttled_get_json+from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)++_BASE_URL = "https://www.alphavantage.co/query"++# Throttle/session bucket shared by all Alpha Vantage calls. The free tier is+# quota-limited per key/IP, so requests are spaced out by default.+_HOST_KEY = "alphavantage"+_MIN_INTERVAL_ENV = "VIBE_TRADING_ALPHAVANTAGE_MIN_INTERVAL"+_DEFAULT_MIN_INTERVAL = 1.0++_API_KEY_ENV = "ALPHAVANTAGE_API_KEY"+# Env values that are present-but-meaningless and must be treated as absent.+_API_KEY_PLACEHOLDERS = {"", "your-alphavantage-api-key", "demo"}++# Bars live under this top-level key; the per-bar OHLCV fields are numbered.+_TIME_SERIES_KEY = "Time Series (Daily)"+_FIELD_MAP = {+ "open": "1. open",+ "high": "2. high",+ "low": "3. low",+ "close": "4. close",+ "volume": "5. volume",+}+_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]+++def _resolve_api_key() -> str:+ """Return the configured Alpha Vantage API key, or empty when unset.++ Returns:+ The trimmed key, or ``""`` when the env var is absent or a placeholder.+ """+ key = os.getenv(_API_KEY_ENV, "").strip()+ return "" if key in _API_KEY_PLACEHOLDERS else key+++def _min_interval() -> float:+ """Resolve the per-call minimum Alpha Vantage request spacing in seconds."""+ return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL)+++def _extract_provider_message(payload: object) -> Optional[str]:+ """Return any rate-limit / error envelope message from a payload.++ Alpha Vantage signals quota exhaustion and bad requests in-band with a 200+ status, using one of three string envelopes instead of the time series.++ Args:+ payload: The decoded JSON body.++ Returns:+ The envelope message when present, else ``None``.+ """+ if not isinstance(payload, dict):+ return None+ for key in ("Error Message", "Note", "Information"):+ message = payload.get(key)+ if isinstance(message, str) and message.strip():+ return message.strip()+ return None+++@register+class DataLoader:+ """Alpha Vantage US-equity daily OHLCV loader (key-gated REST, throttled)."""++ name = "alphavantage"+ markets = {"us_equity"}+ requires_auth = True++ def is_available(self) -> bool:+ """Available when a non-placeholder ``ALPHAVANTAGE_API_KEY`` is set."""+ return bool(_resolve_api_key())++ def __init__(self) -> None:+ pass++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ """Fetch daily OHLCV bars for ``codes`` within ``[start_date, end_date]``.++ Args:+ codes: US-equity tickers (e.g. ``["AAPL", "MSFT"]``).+ start_date: Inclusive start date ``YYYY-MM-DD``.+ end_date: Inclusive end date ``YYYY-MM-DD``.+ interval: Bar interval; only ``"1D"`` (daily) is supported.+ fields: Ignored — the full OHLCV column set is always returned.++ Returns:+ Mapping ``{symbol: DataFrame}`` with a ``trade_date`` DatetimeIndex+ and float ``open/high/low/close/volume`` columns. Symbols that fail+ or carry no in-range bars are omitted.+ """+ validate_date_range(start_date, end_date)++ api_key = _resolve_api_key()+ if not api_key:+ logger.warning("alphavantage skipped: %s not set", _API_KEY_ENV)+ return {}++ result: Dict[str, pd.DataFrame] = {}+ for code in codes:+ try:+ df = cached_loader_fetch(+ source=self.name,+ symbol=code,+ timeframe=interval,+ start_date=start_date,+ end_date=end_date,+ fields=None,+ fetch=lambda code=code: self._fetch_one(+ code, start_date, end_date, api_key+ ),+ )+ if df is not None and not df.empty:+ result[code] = df+ except Exception as exc: # noqa: BLE001 - one bad symbol must not abort the batch+ logger.warning("alphavantage failed for %s: %s", code, exc)+ return result++ def _fetch_one(+ self, code: str, start_date: str, end_date: str, api_key: str,+ ) -> Optional[pd.DataFrame]:+ """Fetch and slice one symbol's daily bars into an OHLCV DataFrame.++ Args:+ code: US-equity ticker.+ start_date: Inclusive start date ``YYYY-MM-DD``.+ end_date: Inclusive end date ``YYYY-MM-DD``.+ api_key: Resolved Alpha Vantage API key.++ Returns:+ The in-range OHLCV DataFrame, or ``None`` when the payload carries+ no usable bars.++ Raises:+ ValueError: The provider returned a rate-limit / error envelope and+ no usable time series (a data-bearing payload that also carries+ an upsell note is parsed, not rejected).+ requests.RequestException: Network failure, propagated unchanged.+ """+ symbol = code.strip().upper()+ if not symbol:+ return None++ payload = throttled_get_json(+ _BASE_URL,+ host_key=_HOST_KEY,+ min_interval=_min_interval(),+ params={+ "function": "TIME_SERIES_DAILY",+ "symbol": symbol,+ "outputsize": "full",+ "apikey": api_key,+ },+ )++ series = payload.get(_TIME_SERIES_KEY) if isinstance(payload, dict) else None+ if not isinstance(series, dict) or not series:+ # No usable series: a premium-upsell payload can carry both the data+ # key (empty/absent) and a Note/Information envelope, so only now —+ # with nothing to parse — do we surface the envelope as an error.+ message = _extract_provider_message(payload)+ if message is not None:+ raise ValueError(f"alphavantage rejected {symbol}: {message}")+ return None++ rows = [+ row+ for date, bar in series.items()+ if (row := _parse_bar(date, bar)) is not None+ ]+ if not rows:+ return None++ df = pd.DataFrame(rows)+ df["trade_date"] = pd.to_datetime(df["trade_date"])+ df = df.set_index("trade_date").sort_index()+ df = df[_OHLCV_COLUMNS].dropna(subset=["open", "high", "low", "close"])++ start = pd.Timestamp(start_date)+ end = pd.Timestamp(end_date)+ df = df.loc[(df.index >= start) & (df.index <= end)]+ return df+++def _parse_bar(date: str, bar: object) -> Optional[dict]:+ """Parse one ``{date: {"1. open": ...}}`` entry into an OHLCV row dict.++ Args:+ date: The bar's ``YYYY-MM-DD`` date string.+ bar: The per-bar field mapping from the payload.++ Returns:+ A ``{trade_date, open, high, low, close, volume}`` dict, or ``None``+ when the entry is malformed or non-numeric.+ """+ if not isinstance(bar, dict):+ return None+ try:+ return {+ "trade_date": date,+ "open": float(bar[_FIELD_MAP["open"]]),+ "high": float(bar[_FIELD_MAP["high"]]),+ "low": float(bar[_FIELD_MAP["low"]]),+ "close": float(bar[_FIELD_MAP["close"]]),+ "volume": float(bar[_FIELD_MAP["volume"]]),+ }+ except (KeyError, TypeError, ValueError):+ return Nonediff --git a/agent/backtest/loaders/eastmoney_client.py b/agent/backtest/loaders/eastmoney_client.pynew file mode 100644index 000000000..0b9bfb6a1--- /dev/null+++ b/agent/backtest/loaders/eastmoney_client.py@@ -0,0 +1,322 @@+"""Shared Eastmoney HTTP client: secid resolution + push2his kline fetch.++Eastmoney exposes free, no-auth quote endpoints but rate-limits aggressively by+source IP and will temporarily ban a bursting client, so every request here+routes through :mod:`backtest.loaders._http` for per-host throttling and session+reuse. This module is provider-internal plumbing shared by the Eastmoney-backed+loaders; it only knows Eastmoney's ``secid`` addressing scheme and the+``push2his`` kline JSON layout, not any loader's DataFrame conventions.++Eastmoney addresses every instrument by a ``secid`` of the form ``<market>.<code>``:++* A-shares — Shanghai (``.SH``, plus ``.BJ`` Beijing exchange) use market ``1``+ for SH and ``0`` for SZ/BJ.+* Hong Kong (``.HK``) uses market ``116`` with the numeric code zero-padded to+ five digits.+* US (``.US``) markets (NASDAQ ``105`` / NYSE ``106`` / AMEX ``107``) are not+ derivable from the ticker alone, so the market prefix is discovered once via+ Eastmoney's search/suggest endpoint and cached for the life of the process.+"""++from __future__ import annotations++import json+import logging+import re+from typing import Any++from backtest.loaders._http import resolve_min_interval, throttled_get_json++logger = logging.getLogger(__name__)++# Eastmoney kline endpoints. push2his serves historical bars; searchapi resolves+# a free-text ticker to its fully-qualified secid (needed for US tickers).+_KLINE_URL = "https://push2his.eastmoney.com/api/qt/stock/kline/get"+_SEARCH_URL = "https://searchapi.eastmoney.com/api/suggest/get"++# Throttle/session bucket shared by all Eastmoney calls.+_HOST_KEY = "eastmoney"+_MIN_INTERVAL_ENV = "VIBE_TRADING_EASTMONEY_MIN_INTERVAL"+_DEFAULT_MIN_INTERVAL = 1.0++# Eastmoney kline period codes (``klt``) keyed by our interval labels.+KLT_BY_INTERVAL: dict[str, int] = {+ "1D": 101,+ "1W": 102,+ "1M": 103,+ "1m": 1,+ "5m": 5,+ "15m": 15,+ "30m": 30,+ "1H": 60,+ "60m": 60,+}++# push2his column selectors: fields1 picks the per-request meta, fields2 picks+# the per-bar columns in order: date, open, close, high, low, volume, amount.+_FIELDS1 = "f1,f2,f3,f4,f5,f6"+_FIELDS2 = "f51,f52,f53,f54,f55,f56,f57"++# Process-level cache of resolved US secids so a repeated ticker never re-hits+# the search endpoint. Keyed by the upper-cased bare ticker (e.g. "AAPL").+_US_SECID_CACHE: dict[str, str | None] = {}++# A JSONP envelope is a JS callback identifier followed by a parenthesized body,+# optionally terminated by ';'. The identifier is restricted to legal JS names+# (incl. dotted namespaces like "jQuery.cb") so a plain JSON array/object body —+# which never starts this way — is left untouched.+_JSONP_WRAPPER = re.compile(+ r"^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\s*\((.*)\)\s*;?\s*$",+ re.DOTALL,+)+++def _min_interval() -> float:+ """Resolve the per-call minimum Eastmoney request spacing in seconds."""+ return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL)+++def get_json(url: str, *, params: dict[str, Any]) -> Any:+ """Issue a throttled Eastmoney GET and decode the body as JSON.++ Args:+ url: Fully-qualified Eastmoney endpoint URL.+ params: Query parameters for the request.++ Returns:+ The decoded JSON payload (typically a ``dict``).++ Raises:+ requests.RequestException: Network failure, propagated for the caller's+ retry policy.+ requests.HTTPError: Non-2xx response status.+ ValueError: Body is not valid JSON.+ """+ return throttled_get_json(+ url,+ host_key=_HOST_KEY,+ min_interval=_min_interval(),+ params=params,+ )+++def _resolve_a_share_secid(code: str, suffix: str) -> str | None:+ """Map an A-share ``code`` + exchange ``suffix`` to its Eastmoney secid.++ SH instruments live on market ``1``; SZ and BJ (Beijing exchange) on ``0``.+ """+ if suffix == "SH":+ return f"1.{code}"+ if suffix in ("SZ", "BJ"):+ return f"0.{code}"+ return None+++def _parse_us_secid(payload: Any) -> str | None:+ """Extract a US ``<market>.<code>`` secid from a search/suggest payload.++ Eastmoney's suggest endpoint returns candidates under+ ``QuotationCodeTable.Data``, each carrying a ``QuoteID`` already in+ ``<market>.<code>`` form. The first US-market (105/106/107) candidate wins.++ Args:+ payload: Decoded JSON from the search endpoint.++ Returns:+ The first matching US secid, or ``None`` when no US candidate is found.+ """+ if not isinstance(payload, dict):+ return None+ table = payload.get("QuotationCodeTable")+ if not isinstance(table, dict):+ return None+ candidates = table.get("Data")+ if not isinstance(candidates, list):+ return None+ for candidate in candidates:+ if not isinstance(candidate, dict):+ continue+ quote_id = candidate.get("QuoteID")+ if not isinstance(quote_id, str) or "." not in quote_id:+ continue+ market = quote_id.split(".", 1)[0]+ if market in ("105", "106", "107"):+ return quote_id+ return None+++def _strip_jsonp(text: str) -> Any:+ """Decode a possibly JSONP-wrapped body to a Python object.++ The suggest endpoint sometimes wraps its JSON in a ``callback(...)`` envelope.+ A plain JSON body is parsed as-is first; only a body that actually matches a+ leading callback identifier is unwrapped. This avoids corrupting plain JSON+ whose string values contain parentheses (an earlier first-``(`` / last-``)``+ slice mangled such bodies and returned ``None``).++ Args:+ text: Raw response body.++ Returns:+ The decoded object, or ``None`` when nothing parseable is found.+ """+ stripped = text.strip()+ try:+ return json.loads(stripped)+ except (ValueError, TypeError):+ pass+ match = _JSONP_WRAPPER.match(stripped)+ if match is None:+ return None+ try:+ return json.loads(match.group(1).strip())+ except (ValueError, TypeError):+ return None+++def _resolve_us_secid(code: str) -> str | None:+ """Resolve a US ticker to its Eastmoney secid via search, with caching.++ Args:+ code: Bare upper-cased US ticker (e.g. ``"AAPL"``).++ Returns:+ The resolved ``<market>.<code>`` secid, or ``None`` when unresolvable.+ """+ if code in _US_SECID_CACHE:+ return _US_SECID_CACHE[code]++ secid: str | None = None+ try:+ payload = get_json(+ _SEARCH_URL,+ params={"input": code, "type": "14", "count": "10"},+ )+ if isinstance(payload, str):+ payload = _strip_jsonp(payload)+ secid = _parse_us_secid(payload)+ except Exception as exc: # noqa: BLE001 - an unresolved ticker is non-fatal+ logger.warning("eastmoney secid search failed for %s: %s", code, exc)+ secid = None++ _US_SECID_CACHE[code] = secid+ return secid+++def resolve_secid(symbol: str) -> str | None:+ """Map a Vibe-Trading symbol to its Eastmoney secid.++ Supported suffixes: ``.SH`` / ``.SZ`` / ``.BJ`` (A-share), ``.HK`` (Hong+ Kong, code zero-padded to five digits), ``.US`` (resolved via search and+ cached). A symbol with no recognized suffix, or a US ticker the search+ cannot place, returns ``None``.++ Args:+ symbol: Symbol such as ``"600519.SH"``, ``"00700.HK"`` or ``"AAPL.US"``.++ Returns:+ The Eastmoney secid (e.g. ``"1.600519"``), or ``None`` if unresolvable.+ """+ if not symbol or "." not in symbol:+ return None+ code, _, suffix = symbol.rpartition(".")+ code = code.strip().upper()+ suffix = suffix.strip().upper()+ if not code:+ return None++ if suffix in ("SH", "SZ", "BJ"):+ return _resolve_a_share_secid(code, suffix)+ if suffix == "HK":+ return f"116.{code.zfill(5)}"+ if suffix == "US":+ return _resolve_us_secid(code)+ return None+++def _parse_kline_row(raw: str) -> dict[str, Any] | None:+ """Parse one comma-joined push2his kline row into an OHLCV dict.++ Column order follows ``fields2``: date, open, close, high, low, volume,+ amount.++ Args:+ raw: One row string from ``data.klines``.++ Returns:+ A dict ``{trade_date, open, high, low, close, volume, amount}``, or+ ``None`` when the row is malformed.+ """+ parts = raw.split(",")+ if len(parts) < 7:+ return None+ try:+ return {+ "trade_date": parts[0],+ "open": float(parts[1]),+ "close": float(parts[2]),+ "high": float(parts[3]),+ "low": float(parts[4]),+ "volume": float(parts[5]),+ "amount": float(parts[6]),+ }+ except (ValueError, TypeError):+ return None+++def fetch_kline(+ secid: str,+ *,+ klt: int,+ fqt: int = 1,+ beg: str = "0",+ end: str = "20500101",+) -> list[dict]:+ """Fetch ascending OHLCV bars for one ``secid`` from push2his.++ Args:+ secid: Eastmoney secid (e.g. ``"1.600519"``).+ klt: Period code from :data:`KLT_BY_INTERVAL`.+ fqt: Adjustment mode (0 raw, 1 forward-adjusted, 2 back-adjusted).+ beg: Inclusive start date ``YYYYMMDD`` or ``"0"`` for earliest.+ end: Inclusive end date ``YYYYMMDD``.++ Returns:+ Ascending list of ``{trade_date, open, high, low, close, volume,+ amount}`` dicts. Empty when the payload carries no bars.++ Raises:+ requests.RequestException: Network failure.+ requests.HTTPError: Non-2xx response status.+ ValueError: Body is not valid JSON.+ """+ payload = get_json(+ _KLINE_URL,+ params={+ "secid": secid,+ "klt": str(klt),+ "fqt": str(fqt),+ "beg": beg,+ "end": end,+ "fields1": _FIELDS1,+ "fields2": _FIELDS2,+ "rev": "1",+ "lmt": "1000000",+ },+ )++ data = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(data, dict):+ return []+ klines = data.get("klines")+ if not isinstance(klines, list):+ return []++ rows: list[dict] = []+ for raw in klines:+ if not isinstance(raw, str):+ continue+ parsed = _parse_kline_row(raw)+ if parsed is not None:+ rows.append(parsed)+ return rowsdiff --git a/agent/backtest/loaders/eastmoney_loader.py b/agent/backtest/loaders/eastmoney_loader.pynew file mode 100644index 000000000..bc9582716--- /dev/null+++ b/agent/backtest/loaders/eastmoney_loader.py@@ -0,0 +1,176 @@+"""Eastmoney loader: free, no-auth OHLCV across A-share, HK and US equities.++Eastmoney's ``push2his`` quote endpoints are free and require no token, but the+service rate-limits aggressively by source IP. All HTTP goes through the shared+:mod:`backtest.loaders.eastmoney_client`, which routes every call through the+per-host throttle in :mod:`backtest.loaders._http`. This loader only maps our+symbol/interval/DataFrame conventions onto that client; it owns no HTTP itself.++Symbol routing is delegated to :func:`eastmoney_client.resolve_secid`:++* A-share — ``600519.SH`` / ``000001.SZ`` / ``430139.BJ``+* Hong Kong — ``00700.HK`` (numeric code zero-padded to five digits)+* US — ``AAPL.US`` (market prefix discovered via Eastmoney search, cached)+"""++from __future__ import annotations++import logging+from typing import Dict, List, Optional++import pandas as pd++from backtest.loaders import eastmoney_client+from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)++# OHLCV columns the engine consumes, in canonical order.+_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]+++def _to_compact_date(value: str) -> str:+ """Convert a ``YYYY-MM-DD`` date into Eastmoney's ``YYYYMMDD`` form.++ Args:+ value: Date string in any pandas-parseable form.++ Returns:+ The date rendered as ``YYYYMMDD``.++ Raises:+ ValueError: ``value`` is not a parseable date.+ """+ try:+ return pd.Timestamp(value).strftime("%Y%m%d")+ except Exception as exc: # noqa: BLE001 - surfaced as a clear ValueError+ raise ValueError(f"Invalid date for eastmoney: {value!r}") from exc+++@register+class DataLoader:+ """Eastmoney OHLCV loader (free, throttled HTTP, no auth)."""++ name = "eastmoney"+ markets = {"a_share", "hk_equity", "us_equity"}+ requires_auth = False++ def is_available(self) -> bool:+ """Always available — uses unauthenticated throttled HTTP."""+ return True++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ """Fetch OHLCV for each symbol; a single failure never aborts the batch.++ Args:+ codes: Symbols such as ``"600519.SH"``, ``"00700.HK"``, ``"AAPL.US"``.+ start_date: Inclusive start date (``YYYY-MM-DD``).+ end_date: Inclusive end date (``YYYY-MM-DD``).+ interval: Bar interval label (e.g. ``"1D"``, ``"1H"``, ``"5m"``).+ fields: Accepted for protocol parity; the OHLCV columns are fixed.++ Returns:+ Mapping ``{symbol: DataFrame}`` for every symbol that yielded bars.+ Each DataFrame has a ``trade_date`` ``DatetimeIndex`` and float+ columns ``open/high/low/close/volume``. Symbols that resolve to no+ data are omitted.++ Raises:+ ValueError: ``start_date``/``end_date`` are malformed or inverted.+ """+ validate_date_range(start_date, end_date)++ result: Dict[str, pd.DataFrame] = {}+ for code in codes:+ try:+ df = cached_loader_fetch(+ source=self.name,+ symbol=code,+ timeframe=interval,+ start_date=start_date,+ end_date=end_date,+ fields=None,+ fetch=lambda code=code: self._fetch_one(+ code, start_date, end_date, interval+ ),+ )+ if df is not None and not df.empty:+ result[code] = df+ except Exception as exc: # noqa: BLE001 - one bad symbol must not abort+ logger.warning("eastmoney failed for %s: %s", code, exc)+ return result++ def _fetch_one(+ self, code: str, start_date: str, end_date: str, interval: str,+ ) -> Optional[pd.DataFrame]:+ """Resolve one symbol and build its OHLCV frame, or ``None`` on a miss.++ Args:+ code: A single Vibe-Trading symbol.+ start_date: Inclusive start date (``YYYY-MM-DD``).+ end_date: Inclusive end date (``YYYY-MM-DD``).+ interval: Bar interval label.++ Returns:+ An OHLCV DataFrame, or ``None`` when the symbol/interval is+ unsupported or Eastmoney returns no bars.+ """+ klt = eastmoney_client.KLT_BY_INTERVAL.get(interval)+ if klt is None:+ logger.warning("eastmoney unsupported interval %r for %s", interval, code)+ return None++ secid = eastmoney_client.resolve_secid(code)+ if not secid:+ return None++ rows = eastmoney_client.fetch_kline(+ secid,+ klt=klt,+ fqt=1,+ beg=_to_compact_date(start_date),+ end=_to_compact_date(end_date),+ )+ return self._frame_from_rows(rows)++ @staticmethod+ def _frame_from_rows(rows: List[dict]) -> Optional[pd.DataFrame]:+ """Assemble the canonical OHLCV DataFrame from client kline rows.++ Args:+ rows: Ascending ``{trade_date, open, high, low, close, volume, ...}``+ dicts from :func:`eastmoney_client.fetch_kline`.++ Returns:+ A DataFrame indexed by ``trade_date`` with float OHLCV columns, or+ ``None`` when ``rows`` is empty or fully unparseable.+ """+ if not rows:+ return None++ df = pd.DataFrame(rows)+ if df.empty or "trade_date" not in df.columns:+ return None++ df["trade_date"] = pd.to_datetime(df["trade_date"])+ df = df.set_index("trade_date").sort_index()+ df.index.name = "trade_date"++ for column in _OHLCV_COLUMNS:+ if column not in df.columns:+ return None+ df[column] = pd.to_numeric(df[column], errors="coerce").astype(float)++ df = df[_OHLCV_COLUMNS].dropna(subset=["open", "high", "low", "close"])+ if df.empty:+ return None+ return dfdiff --git a/agent/backtest/loaders/finnhub_loader.py b/agent/backtest/loaders/finnhub_loader.pynew file mode 100644index 000000000..b08c78748--- /dev/null+++ b/agent/backtest/loaders/finnhub_loader.py@@ -0,0 +1,268 @@+"""Finnhub loader: key-gated US-equity OHLCV via the public stock-candle API.++Finnhub (https://finnhub.io) serves daily stock candles from a single REST+endpoint, gated by a free API key passed as the ``token`` query parameter:++ https://finnhub.io/api/v1/stock/candle?symbol=AAPL&resolution=D&from=...&to=...&token=...++Like other free quote providers it rate-limits by source IP, so every request+routes through :func:`backtest.loaders._http.throttled_get_json` for per-host+spacing plus session reuse. The endpoint answers with parallel arrays+(``o``/``h``/``l``/``c``/``v`` plus epoch ``t``) and a status field ``s`` that+reads ``"ok"`` on a hit or ``"no_data"`` for an empty window.++Symbol convention (Vibe-Trading -> Finnhub):+ * US ``AAPL.US`` -> ``AAPL`` (Finnhub carries US tickers bare)+ * Anything else is passed through uppercased (e.g. a bare ``MSFT``).++No market data is ever persisted in the repo; settled ranges may be cached to+the user-home loader cache via :func:`cached_loader_fetch`.+"""++from __future__ import annotations++import logging+import os+from typing import Any, Dict, List, Optional++import pandas as pd++from backtest.loaders._http import resolve_min_interval, throttled_get_json+from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)++_API_KEY_ENV = "FINNHUB_API_KEY"+_CANDLE_URL = "https://finnhub.io/api/v1/stock/candle"++# Throttle bucket + default minimum spacing (free tier is ~30 req/s but bursts+# get a 429; one shared bucket keeps the whole process polite).+_HOST_KEY = "finnhub"+_MIN_INTERVAL_ENV = "VIBE_TRADING_FINNHUB_MIN_INTERVAL"+_DEFAULT_MIN_INTERVAL_S = 0.4++# Only daily candles are wired here; Finnhub also exposes intraday resolutions+# but the project's us_equity fallback chain is daily-only.+_RESOLUTION = "D"++# Finnhub packs parallel arrays under these keys; ``t`` carries epoch seconds.+_FINNHUB_TO_OHLCV = {"o": "open", "h": "high", "l": "low", "c": "close", "v": "volume"}+_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]+++def _min_interval() -> float:+ """Resolve the per-call minimum spacing, honoring the env override."""+ return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL_S)+++def _to_finnhub_symbol(code: str) -> str:+ """Translate a project symbol into Finnhub's ticker convention.++ Args:+ code: Project-side symbol, e.g. ``AAPL.US`` or a bare ``MSFT``.++ Returns:+ The Finnhub ticker: the ``.US`` suffix stripped, otherwise the+ uppercased symbol unchanged.+ """+ upper = code.strip().upper()+ if upper.endswith(".US"):+ return upper[: -len(".US")]+ return upper+++def _to_epoch_seconds(date_str: str, *, end_of_day: bool) -> int:+ """Convert a ``YYYY-MM-DD`` date to a UTC epoch-second bound.++ Args:+ date_str: Inclusive date string.+ end_of_day: When ``True`` push the instant to 23:59:59 so the day's+ bar falls inside Finnhub's inclusive ``[from, to]`` window.++ Returns:+ Epoch seconds (UTC) for the requested bound.+ """+ ts = pd.Timestamp(date_str).normalize()+ if end_of_day:+ ts = ts + pd.Timedelta(hours=23, minutes=59, seconds=59)+ return int(ts.value // 1_000_000_000)+++def _rows_from_payload(payload: Any) -> List[Dict[str, Any]]:+ """Zip Finnhub's parallel candle arrays into ascending row dicts.++ Args:+ payload: Decoded JSON body from the stock-candle endpoint.++ Returns:+ Ascending list of ``{trade_date, open, high, low, close, volume}`` dicts+ where ``trade_date`` is the raw epoch-second ``int`` (normalized to a+ ``datetime64[ns]`` index later in :meth:`DataLoader._fetch_one`).+ Empty when the status is not ``"ok"`` or the timestamp array is missing,+ and per-bar gaps (a ``None`` in any OHLC slot) are skipped.+ """+ if not isinstance(payload, dict) or payload.get("s") != "ok":+ return []++ timestamps = payload.get("t") or []+ if not isinstance(timestamps, list):+ return []++ rows: List[Dict[str, Any]] = []+ for index, epoch in enumerate(timestamps):+ values = {+ field: _at(payload.get(key), index)+ for key, field in _FINNHUB_TO_OHLCV.items()+ }+ if any(values[field] is None for field in ("open", "high", "low", "close")):+ continue+ # Keep the raw epoch here; the resolution is normalized in one place+ # (``_fetch_one``) so the index dtype matches the other loaders.+ row: Dict[str, Any] = {"trade_date": int(epoch)}+ row.update({field: _to_float(values[field]) for field in _OHLCV_COLUMNS})+ rows.append(row)+ return rows+++def _at(series: Any, index: int) -> Any:+ """Return ``series[index]`` when in range, else ``None``."""+ if isinstance(series, list) and 0 <= index < len(series):+ return series[index]+ return None+++def _to_float(value: Any) -> Optional[float]:+ """Coerce a Finnhub numeric (or ``None``) to ``float``; ``None`` on failure."""+ if value is None:+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++@register+class DataLoader:+ """Finnhub US-equity daily OHLCV loader (key-gated, throttled HTTP)."""++ name = "finnhub"+ markets = {"us_equity"}+ requires_auth = True++ def __init__(self) -> None:+ """Initialize the loader without touching the network or credentials.++ Construction never raises on a missing key; availability is reported+ separately via :meth:`is_available` so the fallback chain can keep+ walking when the key is absent.+ """+ pass++ def is_available(self) -> bool:+ """Return whether a Finnhub API key is present in the environment."""+ return bool(os.getenv(_API_KEY_ENV))++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ """Fetch daily OHLCV history keyed by the original project symbols.++ Each symbol is fetched independently through the opt-in loader cache;+ a single failing symbol is logged and skipped so it never aborts the+ batch.++ Args:+ codes: Project symbols such as ``AAPL.US``.+ start_date: Inclusive start date in ``YYYY-MM-DD`` format.+ end_date: Inclusive end date in ``YYYY-MM-DD`` format.+ interval: Backtest interval; only daily (``1D``) is supported.+ fields: Ignored; included for interface compatibility.++ Returns:+ Mapping of input symbol to a DataFrame indexed by a ``trade_date``+ :class:`~pandas.DatetimeIndex` with float ``open``/``high``/``low``/+ ``close``/``volume`` columns. Symbols without data are omitted.++ Raises:+ ValueError: If ``start_date`` > ``end_date``.+ """+ del fields+ validate_date_range(start_date, end_date)++ api_key = os.getenv(_API_KEY_ENV)+ if not api_key:+ logger.warning("finnhub fetch skipped: %s not set", _API_KEY_ENV)+ return {}++ result: Dict[str, pd.DataFrame] = {}+ for code in codes:+ try:+ df = cached_loader_fetch(+ source=self.name,+ symbol=code,+ timeframe=interval,+ start_date=start_date,+ end_date=end_date,+ fields=None,+ fetch=lambda code=code: self._fetch_one(+ code, start_date, end_date, api_key+ ),+ )+ if df is not None and not df.empty:+ result[code] = df+ except Exception as exc: # noqa: BLE001 - one symbol must not abort the batch+ logger.warning("finnhub failed for %s: %s", code, exc)+ return result++ def _fetch_one(+ self, code: str, start_date: str, end_date: str, api_key: str+ ) -> Optional[pd.DataFrame]:+ """Fetch and normalize one symbol's daily candles.++ Args:+ code: Project-side symbol.+ start_date: Inclusive start date (``YYYY-MM-DD``).+ end_date: Inclusive end date (``YYYY-MM-DD``).+ api_key: Finnhub API token for the ``token`` query parameter.++ Returns:+ A normalized OHLCV DataFrame, or ``None`` when Finnhub reports no+ usable data for the window.+ """+ payload = throttled_get_json(+ _CANDLE_URL,+ host_key=_HOST_KEY,+ min_interval=_min_interval(),+ params={+ "symbol": _to_finnhub_symbol(code),+ "resolution": _RESOLUTION,+ "from": _to_epoch_seconds(start_date, end_of_day=False),+ "to": _to_epoch_seconds(end_date, end_of_day=True),+ "token": api_key,+ },+ )++ rows = _rows_from_payload(payload)+ if not rows:+ return None++ df = pd.DataFrame(rows)+ # Epoch seconds -> nanosecond-resolution DatetimeIndex so the index+ # dtype (``datetime64[ns]``) stays consistent with the other loaders+ # rather than collapsing to the second resolution pandas infers from a+ # ``unit="s"`` conversion.+ df["trade_date"] = pd.to_datetime(df["trade_date"], unit="s").astype(+ "datetime64[ns]"+ )+ df = df.set_index("trade_date").sort_index()+ df = df[_OHLCV_COLUMNS].astype(float).dropna(+ subset=["open", "high", "low", "close"]+ )+ return dfdiff --git a/agent/backtest/loaders/fmp_loader.py b/agent/backtest/loaders/fmp_loader.pynew file mode 100644index 000000000..fcacabd92--- /dev/null+++ b/agent/backtest/loaders/fmp_loader.py@@ -0,0 +1,220 @@+"""Financial Modeling Prep (FMP) loader: key-gated US-equity OHLCV via HTTP.++FMP exposes a daily historical-price endpoint that, like other free quote+providers, rate-limits by source IP and must be throttled. Every request here+routes through :mod:`backtest.loaders._http` so calls share one process-wide+minimum-spacing gate and a reused session.++API format (public, documented):+ https://financialmodelingprep.com/api/v3/historical-price-full/{SYMBOL}+ ?from=YYYY-MM-DD&to=YYYY-MM-DD&apikey=KEY++The JSON body is ``{"symbol": "AAPL", "historical": [{date, open, high, low,+close, volume}, ...]}`` in descending date order; an unknown symbol or empty+window yields an empty/absent ``historical`` array.++Auth: set ``FMP_API_KEY`` in the environment. Covers US equities only.+"""++from __future__ import annotations++import logging+import os+from typing import Any, Dict, List, Optional++import pandas as pd++from backtest.loaders._http import resolve_min_interval, throttled_get_json+from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)++_API_KEY_ENV = "FMP_API_KEY"+_BASE_URL = "https://financialmodelingprep.com/api/v3/historical-price-full"++# Shared throttle/session bucket for every FMP request in this process.+_HOST_KEY = "fmp"+_MIN_INTERVAL_ENV = "VIBE_TRADING_FMP_MIN_INTERVAL"+_DEFAULT_MIN_INTERVAL_S = 0.3++# FMP daily bars carry these numeric fields; emitted in this column order.+_OHLCV_FIELDS = ("open", "high", "low", "close", "volume")+++def _api_key() -> str:+ """Return the FMP API key from the environment, stripped (``""`` if unset)."""+ return os.getenv(_API_KEY_ENV, "").strip()+++def _min_interval() -> float:+ """Resolve the per-call minimum spacing, honoring the env override."""+ return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL_S)+++def _fmp_symbol(code: str) -> str:+ """Translate a project symbol into FMP's bare-ticker convention.++ FMP carries US tickers bare, so a trailing ``.US`` suffix (the project's+ US-equity marker) is dropped; everything else is upper-cased and passed+ through unchanged.++ Args:+ code: Project-side symbol, e.g. ``AAPL`` or ``AAPL.US``.++ Returns:+ The FMP ticker (suffix stripped, upper-cased).+ """+ cleaned = code.strip().upper()+ if cleaned.endswith(".US"):+ cleaned = cleaned[: -len(".US")]+ return cleaned+++@register+class DataLoader:+ """Financial Modeling Prep US-equity OHLCV loader (key-gated, HTTP)."""++ name = "fmp"+ markets = {"us_equity"}+ requires_auth = True++ def __init__(self) -> None:+ pass++ def is_available(self) -> bool:+ """Available when ``FMP_API_KEY`` is set to a non-empty value."""+ return bool(_api_key())++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ """Fetch daily OHLCV bars from FMP, one symbol at a time.++ A single failing symbol is logged and skipped so it never aborts the+ rest of the batch.++ Args:+ codes: Project symbols (e.g. ``["AAPL", "MSFT.US"]``).+ start_date: Inclusive start date, ``YYYY-MM-DD``.+ end_date: Inclusive end date, ``YYYY-MM-DD``.+ interval: Bar size; only ``"1D"`` is supported (others skipped).+ fields: Ignored — FMP returns a fixed OHLCV schema.++ Returns:+ Mapping ``{symbol: DataFrame(trade_date, open, high, low, close,+ volume)}`` for every symbol that returned non-empty data.++ Raises:+ ValueError: If ``start_date`` > ``end_date`` (via+ :func:`validate_date_range`).+ """+ validate_date_range(start_date, end_date)++ if interval != "1D":+ logger.warning("fmp only supports 1D bars; got interval=%r", interval)+ return {}++ if not self.is_available():+ logger.warning("fmp fetch skipped: %s not set", _API_KEY_ENV)+ return {}++ result: Dict[str, pd.DataFrame] = {}+ for code in codes:+ try:+ df = cached_loader_fetch(+ source=self.name,+ symbol=code,+ timeframe=interval,+ start_date=start_date,+ end_date=end_date,+ fields=None,+ fetch=lambda code=code: self._fetch_one(code, start_date, end_date),+ )+ if df is not None and not df.empty:+ result[code] = df+ except Exception as exc:+ logger.warning("fmp failed for %s: %s", code, exc)+ return result++ def _fetch_one(+ self, code: str, start_date: str, end_date: str,+ ) -> Optional[pd.DataFrame]:+ """Fetch and parse one symbol's daily bars; ``None`` on no data.++ Args:+ code: Project symbol to fetch.+ start_date: Inclusive start date, ``YYYY-MM-DD``.+ end_date: Inclusive end date, ``YYYY-MM-DD``.++ Returns:+ An ascending OHLCV DataFrame indexed by ``trade_date``, or ``None``+ when FMP reports no bars for the symbol/window.++ Raises:+ RuntimeError: If the API key is missing at call time.+ requests.RequestException: Propagated from the HTTP layer.+ """+ api_key = _api_key()+ if not api_key:+ raise RuntimeError(f"{_API_KEY_ENV} is not set")++ symbol = _fmp_symbol(code)+ if not symbol:+ return None++ payload = throttled_get_json(+ f"{_BASE_URL}/{symbol}",+ host_key=_HOST_KEY,+ min_interval=_min_interval(),+ params={"from": start_date, "to": end_date, "apikey": api_key},+ )+ return _parse_historical(payload)+++def _parse_historical(payload: Any) -> Optional[pd.DataFrame]:+ """Convert an FMP historical-price body into an ascending OHLCV frame.++ Args:+ payload: Decoded JSON body from the historical-price endpoint.++ Returns:+ DataFrame indexed by ``trade_date`` with float ``open/high/low/close/+ volume`` columns, or ``None`` when no usable rows are present.+ """+ historical = (payload or {}).get("historical") if isinstance(payload, dict) else None+ if not historical:+ return None++ rows = []+ for bar in historical:+ if not isinstance(bar, dict) or "date" not in bar:+ continue+ rows.append(+ {+ "trade_date": bar["date"],+ **{field: bar.get(field) for field in _OHLCV_FIELDS},+ }+ )++ if not rows:+ return None++ df = pd.DataFrame(rows)+ df["trade_date"] = pd.to_datetime(df["trade_date"])+ for field in _OHLCV_FIELDS:+ # Cast to float (not just to_numeric) so integer volume from the API+ # does not leave the column int64 and break the float-OHLCV contract.+ df[field] = pd.to_numeric(df[field], errors="coerce").astype(float)++ df = df.set_index("trade_date").sort_index()+ df = df[list(_OHLCV_FIELDS)].dropna(subset=["open", "high", "low", "close"])+ if df.empty:+ return None+ return dfdiff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.pyindex eac8dd26e..358203f4a 100644--- a/agent/backtest/loaders/registry.py+++ b/agent/backtest/loaders/registry.py@@ -40,6 +40,14 @@ VALID_SOURCES: set[str] = {"mootdx","ccxt","futu",+ "eastmoney",+ "sina",+ "stooq",+ "yahoo",+ "finnhub",+ "alphavantage",+ "tiingo",+ "fmp","local","auto",}@@ -76,6 +84,14 @@ def _ensure_registered() -> None:"backtest.loaders.mootdx_loader","backtest.loaders.ccxt_loader","backtest.loaders.futu",+ "backtest.loaders.eastmoney_loader",+ "backtest.loaders.sina_loader",+ "backtest.loaders.stooq_loader",+ "backtest.loaders.yahoo_loader",+ "backtest.loaders.finnhub_loader",+ "backtest.loaders.alphavantage_loader",+ "backtest.loaders.tiingo_loader",+ "backtest.loaders.fmp_loader","backtest.loaders.local_loader",]import importlib@@ -86,14 +102,29 @@ def _ensure_registered() -> None:pass+# Sources that must NEVER silently fall through to a network loader when the+# caller asked for them explicitly. ``local`` reads the user's own configured+# files (``~/.vibe-trading/data-bridge/config.yaml``); its ``markets`` set spans+# every market only so the cross-market auto-resolver can *reach* it, not so an+# unavailable ``local`` request can degrade into an unrelated network source.+# An explicit ``local`` request that is unavailable is a config problem the user+# must see, not something to paper over with a Yahoo/Tencent fetch.+_NO_NETWORK_FALLBACK_SOURCES: frozenset[str] = frozenset({"local"})++# ---------------------------------------------------------------------------# Fallback chains: market_type -> ordered list of source names# ---------------------------------------------------------------------------+# Chains are ordered by IP-ban risk first (lighter, throttle-tolerant public+# endpoints lead; key-gated REST and rate-limit-prone sources trail), then by+# data quality. Eastmoney/Sina/Stooq/Yahoo are unauthenticated public sources+# that must be politely throttled; Finnhub/AlphaVantage/Tiingo/FMP are key-gated+# REST fallbacks placed deeper in the chain.FALLBACK_CHAINS: dict[str, list[str]] = {- "a_share": ["tushare", "mootdx", "baostock", "tencent", "akshare", "local"],- "us_equity": ["yfinance", "akshare", "local"],- "hk_equity": ["yfinance", "futu", "akshare", "local"],+ "a_share": ["tencent", "mootdx", "eastmoney", "baostock", "akshare", "tushare", "local"],+ "us_equity": ["yahoo", "stooq", "sina", "eastmoney", "yfinance", "tiingo", "fmp", "finnhub", "alphavantage", "akshare", "local"],+ "hk_equity": ["eastmoney", "yahoo", "futu", "yfinance", "akshare", "local"],"crypto": ["okx", "ccxt", "yfinance", "local"],"futures": ["tushare", "akshare", "local"],"fund": ["tushare", "akshare", "local"],@@ -165,6 +196,19 @@ def get_loader_cls_with_fallback(source: str) -> Type[Any]:if instance is not None and instance.is_available():return loader_cls+ # Some sources must never silently degrade to an unrelated network loader+ # when explicitly requested. ``local`` is the canonical case: its broad+ # ``markets`` set exists only to make it reachable from the cross-market+ # auto-resolver, so falling back through it would fetch network data the+ # user never asked for and mask a Data Bridge config problem. Fail loudly.+ if source in _NO_NETWORK_FALLBACK_SOURCES:+ raise NoAvailableSourceError(+ f"Data source '{source}' is unavailable and does not fall back to a "+ f"network source. Check your local Data Bridge config "+ f"(~/.vibe-trading/data-bridge/config.yaml) — it must exist and list "+ f"at least one source."+ )+# Source unavailable — try same-market fallbackfor market in loader_cls.markets:try:diff --git a/agent/backtest/loaders/sec_edgar_client.py b/agent/backtest/loaders/sec_edgar_client.pynew file mode 100644index 000000000..b0af9fe07--- /dev/null+++ b/agent/backtest/loaders/sec_edgar_client.py@@ -0,0 +1,215 @@+"""Shared SEC EDGAR REST client: ticker->CIK mapping + filings/facts fetch.++The U.S. SEC publishes free, no-auth JSON endpoints for company filings and+XBRL financial facts. Three public facts drive this module:++* ``https://www.sec.gov/files/company_tickers.json`` maps every reporting+ ticker to its numeric CIK (Central Index Key).+* ``https://data.sec.gov/submissions/CIK##########.json`` returns a company's+ recent filing index, keyed by the **zero-padded 10-digit** CIK.+* ``https://data.sec.gov/api/xbrl/companyfacts/CIK##########.json`` returns the+ full set of reported XBRL financial concepts for that same padded CIK.++SEC rate-limits by source IP and asks every client to send a descriptive+``User-Agent`` carrying a contact address; bursting without one earns a+temporary block. Every request therefore routes through the shared+:mod:`backtest.loaders._http` throttle under the ``"sec"`` host bucket, and the+UA defaults to a Vibe-Trading contact string overridable via+``VIBE_TRADING_SEC_UA``.++This module is a thin transport client, not a :class:`DataLoaderProtocol`+implementation: it returns raw decoded JSON for downstream loaders/tools to+shape. The ticker->CIK table is fetched once per process and memoized.+"""++from __future__ import annotations++import logging+import os+import threading+from typing import Any, Dict, Optional++from backtest.loaders._http import (+ DEFAULT_USER_AGENT,+ resolve_min_interval,+ throttled_get_json,+)++logger = logging.getLogger(__name__)++_HOST_KEY = "sec"+# SEC asks for no more than ~10 requests/second; 0.12s spacing keeps us well+# under that even with jitter, and is the floor mandated by the parcel contract.+_MIN_INTERVAL_DEFAULT = 0.12+_MIN_INTERVAL_ENV = "VIBE_TRADING_SEC_MIN_INTERVAL"++_TICKERS_URL = "https://www.sec.gov/files/company_tickers.json"+_SUBMISSIONS_URL = "https://data.sec.gov/submissions/CIK{cik}.json"+_COMPANY_FACTS_URL = "https://data.sec.gov/api/xbrl/companyfacts/CIK{cik}.json"++_UA_ENV = "VIBE_TRADING_SEC_UA"+# SEC's fair-access policy wants a real contact in the UA. Override via env to+# present your own address; this default keeps the client compliant out of box.+_DEFAULT_SEC_UA = f"Vibe-Trading/1.0 (contact: [email protected]) {DEFAULT_USER_AGENT}"++# Process-wide memoized ticker->CIK map ("AAPL" -> "0000320193"), built lazily.+_TICKER_CACHE: Optional[Dict[str, str]] = None+_TICKER_CACHE_LOCK = threading.Lock()+++def _min_interval() -> float:+ """Resolve the effective per-request spacing, never below the 0.12s floor."""+ return max(_MIN_INTERVAL_DEFAULT, resolve_min_interval(_MIN_INTERVAL_ENV, _MIN_INTERVAL_DEFAULT))+++def _user_agent() -> str:+ """Return the compliant contact UA, honoring the ``VIBE_TRADING_SEC_UA`` override."""+ override = os.getenv(_UA_ENV)+ if override and override.strip():+ return override.strip()+ return _DEFAULT_SEC_UA+++def _sec_get_json(url: str) -> Any:+ """GET ``url`` as JSON through the shared SEC-bucket throttle.++ Args:+ url: Fully-qualified SEC endpoint URL.++ Returns:+ The decoded JSON body (typically a ``dict``).++ Raises:+ requests.RequestException: On a non-2xx status or undecodable body,+ propagated unchanged for the caller to classify.+ """+ return throttled_get_json(+ url,+ host_key=_HOST_KEY,+ min_interval=_min_interval(),+ headers={"User-Agent": _user_agent(), "Accept": "application/json"},+ )+++def _pad_cik(cik: str | int) -> str:+ """Normalize a CIK to the SEC's zero-padded 10-digit string form.++ Args:+ cik: A CIK as an int or a string that may already be padded or carry a+ leading ``"CIK"`` prefix.++ Returns:+ The CIK as exactly 10 digits, e.g. ``"0000320193"``.++ Raises:+ ValueError: If ``cik`` contains no digits.+ """+ digits = "".join(ch for ch in str(cik) if ch.isdigit())+ if not digits:+ raise ValueError(f"CIK has no digits: {cik!r}")+ return digits.zfill(10)+++def _build_ticker_map(payload: Any) -> Dict[str, str]:+ """Build an uppercase ticker->padded-CIK map from the tickers payload.++ The SEC payload is a dict of positional string keys to records shaped like+ ``{"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."}``. A+ malformed row is skipped rather than aborting the whole map.++ Args:+ payload: Decoded ``company_tickers.json`` body.++ Returns:+ Mapping of upper-cased ticker to zero-padded 10-digit CIK.+ """+ records = payload.values() if isinstance(payload, dict) else payload+ mapping: Dict[str, str] = {}+ for record in records or []:+ if not isinstance(record, dict):+ continue+ ticker = record.get("ticker")+ cik = record.get("cik_str", record.get("cik"))+ if not ticker or cik is None:+ continue+ try:+ mapping[str(ticker).strip().upper()] = _pad_cik(cik)+ except ValueError:+ logger.debug("skipping ticker row with bad CIK: %r", record)+ return mapping+++def _ticker_map() -> Dict[str, str]:+ """Return the process-wide ticker->CIK map, fetching once and memoizing.++ Returns:+ Mapping of upper-cased ticker to zero-padded 10-digit CIK.++ Raises:+ requests.RequestException: If the one-time tickers fetch fails.+ """+ global _TICKER_CACHE+ if _TICKER_CACHE is not None:+ return _TICKER_CACHE+ with _TICKER_CACHE_LOCK:+ if _TICKER_CACHE is None:+ payload = _sec_get_json(_TICKERS_URL)+ _TICKER_CACHE = _build_ticker_map(payload)+ return _TICKER_CACHE+++def cik_for(ticker: str) -> Optional[str]:+ """Resolve a ticker symbol to its zero-padded 10-digit CIK.++ Args:+ ticker: A U.S. equity ticker (case-insensitive), e.g. ``"AAPL"``.++ Returns:+ The padded CIK string (``"0000320193"``) or ``None`` when the ticker is+ empty or absent from the SEC table.++ Raises:+ requests.RequestException: If the one-time tickers fetch fails.+ """+ if not ticker or not ticker.strip():+ return None+ return _ticker_map().get(ticker.strip().upper())+++def get_submissions(cik: str | int) -> Dict[str, Any]:+ """Fetch the filing-index ("submissions") JSON for a CIK.++ Args:+ cik: A CIK as int or string; padded to 10 digits internally.++ Returns:+ The decoded submissions document (company metadata + recent filings).++ Raises:+ ValueError: If ``cik`` contains no digits.+ requests.RequestException: On a non-2xx status or undecodable body.+ """+ return _sec_get_json(_SUBMISSIONS_URL.format(cik=_pad_cik(cik)))+++def get_company_facts(cik: str | int) -> Dict[str, Any]:+ """Fetch the XBRL ``companyfacts`` JSON for a CIK.++ Args:+ cik: A CIK as int or string; padded to 10 digits internally.++ Returns:+ The decoded company-facts document (all reported XBRL concepts).++ Raises:+ ValueError: If ``cik`` contains no digits.+ requests.RequestException: On a non-2xx status or undecodable body.+ """+ return _sec_get_json(_COMPANY_FACTS_URL.format(cik=_pad_cik(cik)))+++def _reset_ticker_cache_for_tests() -> None:+ """Clear the memoized ticker map. Test-only hook; never called in prod."""+ global _TICKER_CACHE+ with _TICKER_CACHE_LOCK:+ _TICKER_CACHE = Nonediff --git a/agent/backtest/loaders/sina_loader.py b/agent/backtest/loaders/sina_loader.pynew file mode 100644index 000000000..a683b941b--- /dev/null+++ b/agent/backtest/loaders/sina_loader.py@@ -0,0 +1,200 @@+"""Sina Finance loader: free, no-auth US daily OHLCV via the JSONP K-line API.++Sina exposes US daily candles through a JSONP endpoint that wraps a JSON array+of ``{d,o,h,l,c,v}`` bars in a JavaScript variable assignment. We request it,+strip the JSONP wrapper, and reshape into the loader's standard OHLCV frame.++API format (JSONP)::++ https://stock.finance.sina.com.cn/usstock/api/jsonp_v2.php/var%20x=/US_MinKService.getDailyK?symbol=AAPL++Like Eastmoney, Sina rate-limits by source IP, so every request routes through+the shared per-host throttle in :mod:`backtest.loaders._http`.+"""++from __future__ import annotations++import json+import logging+import re+from typing import Dict, List, Optional++import pandas as pd++from backtest.loaders._http import resolve_min_interval, throttled_get+from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)++_BASE_URL = (+ "https://stock.finance.sina.com.cn/usstock/api/jsonp_v2.php/"+ "var%20x=/US_MinKService.getDailyK"+)+_HOST_KEY = "sina"+_MIN_INTERVAL_ENV = "VIBE_TRADING_SINA_MIN_INTERVAL"+_DEFAULT_MIN_INTERVAL = 0.5++# Sina wraps the payload as ``var x=([...]);`` — the JSON array sits inside an+# optional ``(...)``. Capture the outermost bracketed array, ignoring the+# assignment/paren scaffolding around it.+_JSONP_ARRAY_RE = re.compile(r"(\[.*\])", re.DOTALL)+++def _is_us_equity(code: str) -> bool:+ """Return whether ``code`` is a US-equity symbol this loader handles."""+ return bool(code) and code.upper().endswith(".US")+++def _to_sina_symbol(code: str) -> str:+ """Map an internal code to Sina's bare ticker (``"AAPL.US"`` -> ``"AAPL"``)."""+ return code.upper().rsplit(".", 1)[0]+++def _strip_jsonp(raw: str) -> list:+ """Extract the JSON array embedded in Sina's JSONP wrapper.++ Args:+ raw: Raw response body, e.g. ``var x=([{"d":"2024-01-02",...}]);``.++ Returns:+ The decoded list of bar dicts.++ Raises:+ ValueError: If no JSON array can be located or decoded.+ """+ match = _JSONP_ARRAY_RE.search(raw.strip())+ if not match:+ raise ValueError("no JSON array found in Sina JSONP response")+ bars = json.loads(match.group(1))+ if not isinstance(bars, list):+ raise ValueError("Sina JSONP payload is not a list of bars")+ return bars+++def _bars_to_frame(bars: list, start_date: str, end_date: str) -> Optional[pd.DataFrame]:+ """Reshape Sina ``{d,o,h,l,c,v}`` bars into the standard OHLCV frame.++ Args:+ bars: List of per-day dicts with ``d/o/h/l/c/v`` keys.+ start_date: Inclusive window start (YYYY-MM-DD).+ end_date: Inclusive window end (YYYY-MM-DD).++ Returns:+ A DatetimeIndex (named ``trade_date``) frame with float columns+ ``open/high/low/close/volume`` clipped to the window, or ``None`` when+ no usable rows survive parsing.+ """+ rows = []+ for bar in bars:+ if not isinstance(bar, dict) or "d" not in bar:+ continue+ try:+ rows.append(+ {+ "trade_date": bar["d"],+ "open": float(bar["o"]),+ "high": float(bar["h"]),+ "low": float(bar["l"]),+ "close": float(bar["c"]),+ "volume": float(bar["v"]),+ }+ )+ except (KeyError, TypeError, ValueError):+ continue++ if not rows:+ return None++ frame = pd.DataFrame(rows)+ frame["trade_date"] = pd.to_datetime(frame["trade_date"])+ frame = frame.set_index("trade_date").sort_index()+ frame = frame[["open", "high", "low", "close", "volume"]].dropna(+ subset=["open", "high", "low", "close"]+ )+ window = frame.loc[+ (frame.index >= pd.Timestamp(start_date))+ & (frame.index <= pd.Timestamp(end_date))+ ]+ return window if not window.empty else None+++@register+class DataLoader:+ """Sina Finance US-equity daily OHLCV loader (free, HTTP/JSONP, no auth)."""++ name = "sina"+ markets = {"us_equity"}+ requires_auth = False++ def __init__(self) -> None:+ pass++ def is_available(self) -> bool:+ """Always available — uses plain throttled HTTP, no credentials."""+ return True++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ """Fetch US daily OHLCV for each code; skip and log per-symbol failures.++ Args:+ codes: Symbols in ``TICKER.US`` form (e.g. ``"AAPL.US"``).+ start_date: Inclusive window start (YYYY-MM-DD).+ end_date: Inclusive window end (YYYY-MM-DD).+ interval: Bar interval; only daily (``"1D"``) is supported.+ fields: Ignored — the standard OHLCV columns are always returned.++ Returns:+ Mapping ``{code: DataFrame}`` for every code that yielded bars.++ Raises:+ ValueError: If ``interval`` is not daily or the date range is invalid.+ """+ if interval.upper() not in {"1D", "D", "DAY", "DAILY"}:+ raise ValueError(f"Unsupported interval {interval!r}; sina is daily-only")+ validate_date_range(start_date, end_date)++ result: Dict[str, pd.DataFrame] = {}+ for code in codes:+ try:+ df = cached_loader_fetch(+ source=self.name,+ symbol=code,+ timeframe=interval,+ start_date=start_date,+ end_date=end_date,+ fields=None,+ fetch=lambda code=code: self._fetch_one(code, start_date, end_date),+ )+ if df is not None and not df.empty:+ result[code] = df+ except Exception as exc:+ logger.warning("sina failed for %s: %s", code, exc)+ return result++ def _fetch_one(+ self, code: str, start_date: str, end_date: str,+ ) -> Optional[pd.DataFrame]:+ """Fetch and parse one symbol's daily bars, or ``None`` if non-US/empty."""+ if not _is_us_equity(code):+ return None++ symbol = _to_sina_symbol(code)+ response = throttled_get(+ _BASE_URL,+ host_key=_HOST_KEY,+ min_interval=resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL),+ params={"symbol": symbol},+ headers={"Referer": "https://stock.finance.sina.com.cn/"},+ )+ response.raise_for_status()+ bars = _strip_jsonp(response.text)+ return _bars_to_frame(bars, start_date, end_date)diff --git a/agent/backtest/loaders/stooq_loader.py b/agent/backtest/loaders/stooq_loader.pynew file mode 100644index 000000000..e4e8db5ec--- /dev/null+++ b/agent/backtest/loaders/stooq_loader.py@@ -0,0 +1,190 @@+"""Stooq loader: free, no-auth US-equity EOD OHLCV via CSV download.++Stooq publishes free end-of-day bars from a plain CSV endpoint+(``https://stooq.com/q/d/l/``) with no API key. Like other free quote+providers it rate-limits by source IP and must be throttled, so every request+routes through :mod:`backtest.loaders._http` (shared per-host spacing + session+reuse) under the ``"stooq"`` host bucket.++API format:+ https://stooq.com/q/d/l/?s=aapl.us&d1=20240101&d2=20240131&i=d++Symbol convention (Vibe-Trading -> Stooq):+ * ``AAPL.US`` -> ``aapl.us`` (Stooq tickers are lowercase; the ``.US`` market+ suffix is kept, just lower-cased).++Response body is CSV ``Date,Open,High,Low,Close,Volume``. An unknown symbol or+empty window yields the literal ``"N/D"`` or an empty body, both treated as+"no data" for that symbol (skipped, never fatal to the batch).+"""++from __future__ import annotations++import io+import logging+from typing import Dict, List, Optional++import pandas as pd++from backtest.loaders._http import resolve_min_interval, throttled_get+from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)++_BASE_URL = "https://stooq.com/q/d/l/"+HOST_KEY = "stooq"++_MIN_INTERVAL_ENV = "VIBE_TRADING_STOOQ_MIN_INTERVAL"+_DEFAULT_MIN_INTERVAL_S = 0.6++# Stooq's CSV header columns mapped to our output field names.+_COLUMN_MAP = {+ "Open": "open",+ "High": "high",+ "Low": "low",+ "Close": "close",+ "Volume": "volume",+}+_OUTPUT_COLUMNS = ["open", "high", "low", "close", "volume"]+++def _min_interval() -> float:+ """Resolve the per-call minimum spacing, honoring the env override."""+ return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL_S)+++def map_symbol(symbol: str) -> str:+ """Translate a Vibe-Trading symbol into Stooq's ticker convention.++ Args:+ symbol: Project-side symbol, e.g. ``AAPL.US``.++ Returns:+ The lower-cased Stooq ticker, e.g. ``aapl.us``.+ """+ return symbol.strip().lower()+++def _compact_date(value: str) -> str:+ """Render a date string as Stooq's ``YYYYMMDD`` form."""+ return pd.Timestamp(value).strftime("%Y%m%d")+++@register+class DataLoader:+ """Stooq US-equity EOD OHLCV loader (free, HTTP CSV, no auth)."""++ name = "stooq"+ markets = {"us_equity"}+ requires_auth = False++ def __init__(self) -> None:+ pass++ def is_available(self) -> bool:+ """Always available — uses plain throttled HTTP, no credentials."""+ return True++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ """Fetch daily OHLCV bars for ``codes`` over ``[start_date, end_date]``.++ Args:+ codes: Project-side symbols (e.g. ``["AAPL.US", "MSFT.US"]``).+ start_date: Inclusive start date (``YYYY-MM-DD``).+ end_date: Inclusive end date (``YYYY-MM-DD``).+ interval: Bar size; only daily (``"1D"``) is supported by the+ endpoint and any other value is fetched as daily.+ fields: Unused — the CSV always carries the full OHLCV set.++ Returns:+ Mapping ``{symbol: DataFrame}`` for symbols that returned data. Each+ frame has a ``DatetimeIndex`` named ``trade_date`` and float columns+ ``open/high/low/close/volume`` in ascending date order. A symbol that+ errors or has no data is omitted, never aborting the batch.++ Raises:+ ValueError: If ``start_date > end_date`` or a date is unparseable.+ """+ validate_date_range(start_date, end_date)++ result: Dict[str, pd.DataFrame] = {}+ for code in codes:+ try:+ df = cached_loader_fetch(+ source=self.name,+ symbol=code,+ timeframe=interval,+ start_date=start_date,+ end_date=end_date,+ fields=None,+ fetch=lambda code=code: self._fetch_one(code, start_date, end_date),+ )+ if df is not None and not df.empty:+ result[code] = df+ except Exception as exc: # noqa: BLE001 - one bad symbol must not abort the batch+ logger.warning("stooq failed for %s: %s", code, exc)+ return result++ def _fetch_one(+ self, code: str, start_date: str, end_date: str,+ ) -> Optional[pd.DataFrame]:+ """Fetch and parse one symbol's CSV; ``None`` when Stooq has no data."""+ params = {+ "s": map_symbol(code),+ "d1": _compact_date(start_date),+ "d2": _compact_date(end_date),+ "i": "d",+ }+ response = throttled_get(+ _BASE_URL,+ host_key=HOST_KEY,+ min_interval=_min_interval(),+ params=params,+ )+ response.raise_for_status()+ return _parse_csv(response.text)+++def _parse_csv(body: str) -> Optional[pd.DataFrame]:+ """Convert a Stooq EOD CSV body into our OHLCV frame, ``None`` on no data.++ Args:+ body: Raw CSV text ``Date,Open,High,Low,Close,Volume``. An empty body or+ the sentinel ``"N/D"`` (unknown symbol / empty window) means no data.++ Returns:+ A frame indexed by ``trade_date`` with float OHLCV columns sorted+ ascending, or ``None`` when the body carries no usable rows.+ """+ text = (body or "").strip()+ if not text or text.upper().startswith("N/D"):+ return None++ frame = pd.read_csv(io.StringIO(text))+ if frame.empty or "Date" not in frame.columns:+ return None++ rename = {col: _COLUMN_MAP[col] for col in _COLUMN_MAP if col in frame.columns}+ frame = frame.rename(columns=rename)+ if not all(col in frame.columns for col in _OUTPUT_COLUMNS):+ return None++ frame["trade_date"] = pd.to_datetime(frame["Date"], errors="coerce")+ frame = frame.dropna(subset=["trade_date"]).set_index("trade_date").sort_index()+ frame.index.name = "trade_date"++ for col in _OUTPUT_COLUMNS:+ frame[col] = pd.to_numeric(frame[col], errors="coerce")+ frame = frame[_OUTPUT_COLUMNS].dropna(subset=["open", "high", "low", "close"])+ if frame.empty:+ return None+ return frame.astype(float)diff --git a/agent/backtest/loaders/tiingo_loader.py b/agent/backtest/loaders/tiingo_loader.pynew file mode 100644index 000000000..83c9ee7cf--- /dev/null+++ b/agent/backtest/loaders/tiingo_loader.py@@ -0,0 +1,236 @@+"""Tiingo loader: US-equity daily OHLCV via the Tiingo REST API (key-gated).++Tiingo serves end-of-day US-equity bars from a documented public endpoint:++ GET https://api.tiingo.com/tiingo/daily/{symbol}/prices+ ?startDate=YYYY-MM-DD&endDate=YYYY-MM-DD&token={KEY}++The response is a JSON array of per-day objects, each carrying ``date`` plus+``open``/``high``/``low``/``close``/``volume`` (and adjusted variants we ignore).+A token is required; it is read from the ``TIINGO_API_KEY`` environment variable+and is never hard-coded. Like every other ban-prone HTTP loader in this package,+all requests route through :mod:`backtest.loaders._http` for per-host throttling+and session reuse — Tiingo rate-limits by client and rejects unspaced bursts.+"""++from __future__ import annotations++import logging+import os+from typing import Dict, List, Optional++import pandas as pd++from backtest.loaders._http import resolve_min_interval, throttled_get_json+from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)++_BASE_URL = "https://api.tiingo.com/tiingo/daily"++# Throttle/session bucket plus the per-provider minimum spacing override.+_HOST_KEY = "tiingo"+_MIN_INTERVAL_ENV = "VIBE_TRADING_TIINGO_MIN_INTERVAL"+_DEFAULT_MIN_INTERVAL = 0.5++_AUTH_ENV = "TIINGO_API_KEY"++# Placeholder values that must not count as a real key (mirrors how other+# key-gated loaders treat blank/example tokens as "not configured").+_KEY_PLACEHOLDERS = {"", "your_tiingo_api_key", "changeme", "xxx"}++# Target OHLCV schema, in column order.+_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]+++def _resolve_key() -> str:+ """Return the configured Tiingo API key, or an empty string when unset.++ Returns:+ The trimmed ``TIINGO_API_KEY`` value, or ``""`` when absent or a known+ placeholder.+ """+ key = os.getenv(_AUTH_ENV, "").strip()+ return "" if key.lower() in _KEY_PLACEHOLDERS else key+++def _to_tiingo_symbol(code: str) -> Optional[str]:+ """Map a project symbol to a Tiingo ticker, or ``None`` when unsupported.++ Args:+ code: Project symbol such as ``AAPL.US`` or ``AAPL``.++ Returns:+ The bare lower-cased ticker Tiingo expects (e.g. ``aapl``), or ``None``+ for symbols that are clearly not US equities (HK/crypto/A-share).+ """+ upper = code.strip().upper()+ if not upper:+ return None+ if upper.endswith(".US"):+ upper = upper[:-3]+ # Reject non-US market suffixes and crypto pairs outright.+ if "." in upper or "-" in upper:+ return None+ if not upper.isalnum():+ return None+ return upper.lower()+++def _rows_to_frame(rows: List[dict]) -> Optional[pd.DataFrame]:+ """Convert Tiingo's per-day records into the normalized OHLCV frame.++ Args:+ rows: JSON array decoded from the prices endpoint; each item carries a+ ``date`` plus ``open``/``high``/``low``/``close``/``volume``.++ Returns:+ A DataFrame indexed by a ``trade_date`` :class:`~pandas.DatetimeIndex`+ with float ``open``/``high``/``low``/``close``/``volume`` columns, or+ ``None`` when no usable bar is present.+ """+ parsed: List[dict] = []+ for row in rows:+ date = row.get("date")+ if date is None:+ continue+ parsed.append(+ {+ "trade_date": date,+ "open": row.get("open"),+ "high": row.get("high"),+ "low": row.get("low"),+ "close": row.get("close"),+ "volume": row.get("volume"),+ }+ )+ if not parsed:+ return None++ frame = pd.DataFrame(parsed)+ # Tiingo stamps each bar with an ISO-8601 datetime (e.g.+ # "2024-01-02T00:00:00.000Z"); normalize to a tz-naive midnight index.+ index = pd.DatetimeIndex(pd.to_datetime(frame["trade_date"], utc=True, errors="coerce"))+ if getattr(index, "tz", None) is not None:+ index = index.tz_convert(None)+ frame = frame.drop(columns=["trade_date"])+ frame.index = index.normalize()+ frame.index.name = "trade_date"++ frame = frame.apply(pd.to_numeric, errors="coerce")+ # Coerce every OHLCV column to float64 so the schema is uniform: integer+ # JSON volumes would otherwise land as int64, breaking downstream code that+ # assumes a single numeric dtype.+ frame = frame.astype("float64")+ frame["volume"] = frame["volume"].fillna(0.0)+ frame = frame.loc[:, _OHLCV_COLUMNS].sort_index()+ frame = frame.dropna(subset=["open", "high", "low", "close"])+ return frame if not frame.empty else None+++@register+class DataLoader:+ """Fetch US-equity daily OHLCV bars from Tiingo (key-gated REST)."""++ name = "tiingo"+ markets = {"us_equity"}+ requires_auth = True++ def __init__(self) -> None:+ """Initialize the loader (no network or SDK touched at construction)."""+ pass++ def is_available(self) -> bool:+ """Return whether a usable Tiingo API key is configured."""+ return bool(_resolve_key())++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ """Fetch OHLCV history keyed by the original project symbols.++ Each symbol is fetched independently so one failing ticker (bad symbol,+ transient HTTP error) never aborts the rest of the batch.++ Args:+ codes: Project symbols such as ``AAPL.US`` or ``MSFT``.+ start_date: Inclusive start date in ``YYYY-MM-DD`` format.+ end_date: Inclusive end date in ``YYYY-MM-DD`` format.+ interval: Backtest interval; only ``1D`` is served by this endpoint.+ fields: Ignored; included for interface compatibility.++ Returns:+ Mapping of input symbol to a normalized OHLCV DataFrame. Symbols+ with no usable data are omitted.++ Raises:+ ValueError: If ``start_date`` > ``end_date`` or dates are unparseable.+ """+ del fields+ validate_date_range(start_date, end_date)++ key = _resolve_key()+ if not key:+ logger.warning("tiingo skipped: %s not configured", _AUTH_ENV)+ return {}++ result: Dict[str, pd.DataFrame] = {}+ for code in codes:+ try:+ frame = cached_loader_fetch(+ source=self.name,+ symbol=code,+ timeframe=interval,+ start_date=start_date,+ end_date=end_date,+ fields=None,+ fetch=lambda code=code: self._fetch_one(code, start_date, end_date, key),+ )+ if frame is not None and not frame.empty:+ result[code] = frame+ except Exception as exc: # noqa: BLE001 - one symbol must not kill the batch+ logger.warning("tiingo failed for %s: %s", code, exc)+ return result++ def _fetch_one(+ self, code: str, start_date: str, end_date: str, key: str,+ ) -> Optional[pd.DataFrame]:+ """Fetch and normalize a single symbol's daily bars.++ Args:+ code: Original project symbol.+ start_date: Inclusive start date in ``YYYY-MM-DD`` format.+ end_date: Inclusive end date in ``YYYY-MM-DD`` format.+ key: Resolved Tiingo API key.++ Returns:+ Normalized OHLCV DataFrame, or ``None`` when the symbol is not a US+ equity or the endpoint returns no usable bars.+ """+ ticker = _to_tiingo_symbol(code)+ if ticker is None:+ return None++ url = f"{_BASE_URL}/{ticker}/prices"+ payload = throttled_get_json(+ url,+ host_key=_HOST_KEY,+ min_interval=resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL),+ params={+ "startDate": start_date,+ "endDate": end_date,+ "token": key,+ },+ )++ # The prices endpoint returns a JSON array; anything else is empty/error.+ if not isinstance(payload, list) or not payload:+ return None+ return _rows_to_frame(payload)diff --git a/agent/backtest/loaders/yahoo_client.py b/agent/backtest/loaders/yahoo_client.pynew file mode 100644index 000000000..07cabda41--- /dev/null+++ b/agent/backtest/loaders/yahoo_client.py@@ -0,0 +1,386 @@+"""Shared Yahoo Finance public-API client: chart, quote summary, options, search.++Yahoo Finance exposes several unauthenticated JSON endpoints (the same ones the+finance.yahoo.com site itself calls) that, like other free quote providers,+rate-limit by source IP and must be throttled. Every request here routes+through :mod:`backtest.loaders._http` so calls to ``query*.finance.yahoo.com``+share one process-wide minimum-spacing gate and a reused session.++The ``v10/finance/quoteSummary`` endpoint additionally requires a session+cookie plus a matching ``crumb`` token. This client fetches both lazily on the+first call that needs them and refreshes them once on a 401 (the documented+"crumb expired / unauthorized" signal), so callers never manage that handshake.++Symbol convention (Vibe-Trading -> Yahoo):+ * US ``AAPL.US`` -> ``AAPL`` (Yahoo carries US tickers bare)+ * HK ``00700.HK`` -> ``0700.HK`` (Yahoo drops the leading zero to 4 digits)+ * Anything else is passed through unchanged (e.g. ``BTC-USD``, ``^GSPC``).++This module is provider-specific glue only; it returns plain Python+dicts/lists so a downstream loader can map them into the project's OHLCV frame.+"""++from __future__ import annotations++import logging+import threading+from typing import Any, Dict, List, Optional++import requests++from backtest.loaders._http import (+ DEFAULT_USER_AGENT,+ resolve_min_interval,+ throttled_get,+ throttled_get_json,+)++logger = logging.getLogger(__name__)++# All Yahoo endpoints share one throttle/session bucket so spacing is enforced+# across chart/quote/options/search regardless of which host alias is used.+HOST_KEY = "yahoo"++# Yahoo serves the same data from query1/query2; query2 is conventionally used+# for the crumb-gated endpoints. We keep the chart on query1 like the website.+_CHART_BASE = "https://query1.finance.yahoo.com/v8/finance/chart"+_QUOTE_SUMMARY_BASE = "https://query2.finance.yahoo.com/v10/finance/quoteSummary"+_OPTIONS_BASE = "https://query2.finance.yahoo.com/v7/finance/options"+_SEARCH_BASE = "https://query2.finance.yahoo.com/v1/finance/search"+_CRUMB_URL = "https://query2.finance.yahoo.com/v1/test/getcrumb"+# Hitting fc.yahoo.com first hands back the consent/session cookie the crumb+# endpoint then validates.+_COOKIE_URL = "https://fc.yahoo.com"++_MIN_INTERVAL_ENV = "VIBE_TRADING_YAHOO_MIN_INTERVAL"+_DEFAULT_MIN_INTERVAL_S = 0.6++# The columns Yahoo packs into indicators.quote[0], in our output field order.+_QUOTE_FIELDS = ("open", "high", "low", "close", "volume")+++def _min_interval() -> float:+ """Resolve the per-call minimum spacing, honoring the env override."""+ return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL_S)+++def map_symbol(symbol: str) -> str:+ """Translate a Vibe-Trading symbol into Yahoo's ticker convention.++ Args:+ symbol: Project-side symbol, e.g. ``AAPL.US``, ``00700.HK``, ``BTC-USD``.++ Returns:+ The Yahoo ticker: ``.US`` suffix stripped; ``.HK`` codes normalized to+ a 4-digit base (``00700.HK`` -> ``0700.HK``); everything else unchanged.+ """+ cleaned = symbol.strip()+ upper = cleaned.upper()+ if upper.endswith(".US"):+ return cleaned[: -len(".US")]+ if upper.endswith(".HK"):+ base = cleaned[: -len(".HK")]+ digits = base.lstrip("0") or "0"+ return f"{digits.zfill(4)}.HK"+ return cleaned+++class _CrumbStore:+ """Process-wide cookie jar + crumb token for the quoteSummary handshake.++ Holds a single :class:`requests.Session`-independent crumb string and the+ cookies returned by Yahoo's consent endpoint. Refreshing is serialized by a+ lock so a burst of concurrent callers performs the handshake at most once.+ """++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._crumb: Optional[str] = None+ self._cookies: Dict[str, str] = {}++ def get(self, *, force_refresh: bool = False) -> tuple[str, Dict[str, str]]:+ """Return ``(crumb, cookies)``, fetching them on first use or on refresh.++ Args:+ force_refresh: Discard any cached crumb/cookies and re-handshake.++ Returns:+ A tuple of the crumb token and the cookie mapping to send with the+ crumb-gated request.++ Raises:+ requests.RequestException: If the cookie or crumb fetch fails.+ ValueError: If Yahoo returns an empty crumb.+ """+ with self._lock:+ if force_refresh or self._crumb is None:+ self._crumb, self._cookies = self._handshake()+ return self._crumb, dict(self._cookies)++ def _handshake(self) -> tuple[str, Dict[str, str]]:+ cookie_resp = throttled_get(+ _COOKIE_URL,+ host_key=HOST_KEY,+ min_interval=_min_interval(),+ )+ cookies = requests.utils.dict_from_cookiejar(cookie_resp.cookies)+ crumb_resp = throttled_get(+ _CRUMB_URL,+ host_key=HOST_KEY,+ min_interval=_min_interval(),+ headers={"Cookie": _cookie_header(cookies)} if cookies else None,+ )+ crumb_resp.raise_for_status()+ crumb = (crumb_resp.text or "").strip()+ if not crumb:+ raise ValueError("Yahoo returned an empty crumb token")+ return crumb, cookies+++def _cookie_header(cookies: Dict[str, str]) -> str:+ """Render a cookie mapping as a single ``Cookie:`` header value."""+ return "; ".join(f"{name}={value}" for name, value in cookies.items())+++# One shared crumb/cookie store for the whole process.+_CRUMB_STORE = _CrumbStore()+++def get_chart(+ symbol: str,+ *,+ interval: str = "1d",+ period1: Optional[int] = None,+ period2: Optional[int] = None,+ range_: Optional[str] = None,+) -> List[Dict[str, Any]]:+ """Fetch OHLCV bars from the v8 chart endpoint as ascending rows.++ Either supply a ``range_`` (e.g. ``"1y"``, ``"max"``) or a+ ``period1``/``period2`` epoch-second window; ``range_`` wins when both are+ given. Yahoo returns parallel timestamp/indicator arrays which this function+ zips into row dicts, dropping any bar whose OHLC is incomplete (Yahoo emits+ ``null`` for non-trading slots).++ Args:+ symbol: Project-side symbol (mapped via :func:`map_symbol`).+ interval: Bar size accepted by Yahoo (``1d``, ``1h``, ``5m``, ...).+ period1: Inclusive start as epoch seconds, or ``None``.+ period2: Exclusive end as epoch seconds, or ``None``.+ range_: Relative range string; takes precedence over period1/period2.++ Returns:+ Ascending list of ``{trade_date, open, high, low, close, volume}`` dicts+ (``trade_date`` is the bar's epoch-second timestamp). Empty when Yahoo+ reports no data for the symbol/window.++ Raises:+ requests.RequestException: On a network/HTTP failure.+ ValueError: If Yahoo reports an error for the symbol or the payload is+ structurally unusable.+ """+ yahoo_symbol = map_symbol(symbol)+ params: Dict[str, Any] = {"interval": interval}+ if range_:+ params["range"] = range_+ else:+ if period1 is not None:+ params["period1"] = int(period1)+ if period2 is not None:+ params["period2"] = int(period2)++ payload = throttled_get_json(+ f"{_CHART_BASE}/{yahoo_symbol}",+ host_key=HOST_KEY,+ min_interval=_min_interval(),+ params=params,+ )+ return _parse_chart(payload, yahoo_symbol)+++def _parse_chart(payload: Any, yahoo_symbol: str) -> List[Dict[str, Any]]:+ """Convert a v8 chart payload into ascending OHLCV row dicts."""+ chart = (payload or {}).get("chart") or {}+ error = chart.get("error")+ if error:+ description = error.get("description") if isinstance(error, dict) else error+ raise ValueError(f"Yahoo chart error for {yahoo_symbol}: {description}")++ results = chart.get("result") or []+ if not results:+ return []+ result = results[0] or {}++ timestamps = result.get("timestamp") or []+ quotes = (((result.get("indicators") or {}).get("quote")) or [{}])[0] or {}++ rows: List[Dict[str, Any]] = []+ for index, ts in enumerate(timestamps):+ values = {field: _at(quotes.get(field), index) for field in _QUOTE_FIELDS}+ # A non-trading slot leaves OHLC null; skip rather than emit a NaN bar.+ if any(values[field] is None for field in ("open", "high", "low", "close")):+ continue+ row: Dict[str, Any] = {"trade_date": ts}+ row.update({field: _to_float(values[field]) for field in _QUOTE_FIELDS})+ rows.append(row)+ return rows+++def _at(series: Any, index: int) -> Any:+ """Return ``series[index]`` when in range, else ``None``."""+ if isinstance(series, list) and 0 <= index < len(series):+ return series[index]+ return None+++def _to_float(value: Any) -> Optional[float]:+ """Coerce a Yahoo numeric (or ``None``) to ``float``, ``None`` on failure."""+ if value is None:+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def get_quote_summary(symbol: str, modules: List[str]) -> Dict[str, Any]:+ """Fetch v10 quoteSummary modules, handling the cookie+crumb handshake.++ On a 401 (expired/invalid crumb) the crumb and cookies are refreshed once+ and the request is retried; a second 401 propagates.++ Args:+ symbol: Project-side symbol (mapped via :func:`map_symbol`).+ modules: Yahoo module names, e.g. ``["price", "summaryDetail"]``.++ Returns:+ The ``quoteSummary.result[0]`` mapping, or ``{}`` when Yahoo returns no+ result for the symbol.++ Raises:+ requests.RequestException: On a non-401 HTTP failure or a second 401.+ ValueError: If Yahoo reports an error for the symbol.+ """+ yahoo_symbol = map_symbol(symbol)+ modules_param = ",".join(modules)++ payload = _quote_summary_request(yahoo_symbol, modules_param, force_refresh=False)+ return _parse_quote_summary(payload, yahoo_symbol)+++def _quote_summary_request(+ yahoo_symbol: str, modules_param: str, *, force_refresh: bool+) -> Any:+ """Issue one crumb-gated quoteSummary GET, retrying once on a 401."""+ crumb, cookies = _CRUMB_STORE.get(force_refresh=force_refresh)+ headers = {"Cookie": _cookie_header(cookies)} if cookies else None+ response = throttled_get(+ f"{_QUOTE_SUMMARY_BASE}/{yahoo_symbol}",+ host_key=HOST_KEY,+ min_interval=_min_interval(),+ params={"modules": modules_param, "crumb": crumb},+ headers=headers,+ )+ if response.status_code == 401 and not force_refresh:+ logger.info("Yahoo quoteSummary 401 for %s; refreshing crumb", yahoo_symbol)+ return _quote_summary_request(yahoo_symbol, modules_param, force_refresh=True)+ response.raise_for_status()+ return response.json()+++def _parse_quote_summary(payload: Any, yahoo_symbol: str) -> Dict[str, Any]:+ """Extract the first quoteSummary result, raising on a reported error."""+ summary = (payload or {}).get("quoteSummary") or {}+ error = summary.get("error")+ if error:+ description = error.get("description") if isinstance(error, dict) else error+ raise ValueError(f"Yahoo quoteSummary error for {yahoo_symbol}: {description}")+ results = summary.get("result") or []+ if not results:+ return {}+ return results[0] or {}+++def get_options(symbol: str, *, expiration: Optional[int] = None) -> Dict[str, Any]:+ """Fetch the v7 option chain for a symbol, handling the cookie+crumb handshake.++ Like ``v10/quoteSummary``, the ``v7/finance/options`` endpoint now rejects+ bare requests with HTTP 401 and demands the same session cookie plus a+ matching ``crumb`` token. This routes through the shared+ :data:`_CRUMB_STORE` handshake and, on a 401 (expired/invalid crumb),+ refreshes the crumb once and retries; a second 401 propagates.++ Args:+ symbol: Project-side symbol (mapped via :func:`map_symbol`).+ expiration: Optional expiration as epoch seconds; omit for the nearest.++ Returns:+ The ``optionChain.result[0]`` mapping (expirationDates, strikes, the+ calls/puts arrays for the chosen expiry), or ``{}`` when none.++ Raises:+ requests.RequestException: On a non-401 HTTP failure or a second 401.+ ValueError: If Yahoo reports an error for the symbol.+ """+ yahoo_symbol = map_symbol(symbol)+ payload = _options_request(yahoo_symbol, expiration, force_refresh=False)+ return _parse_options(payload, yahoo_symbol)+++def _options_request(+ yahoo_symbol: str, expiration: Optional[int], *, force_refresh: bool+) -> Any:+ """Issue one crumb-gated v7 options GET, retrying once on a 401."""+ crumb, cookies = _CRUMB_STORE.get(force_refresh=force_refresh)+ headers = {"Cookie": _cookie_header(cookies)} if cookies else None+ params: Dict[str, Any] = {"crumb": crumb}+ if expiration is not None:+ params["date"] = int(expiration)+ response = throttled_get(+ f"{_OPTIONS_BASE}/{yahoo_symbol}",+ host_key=HOST_KEY,+ min_interval=_min_interval(),+ params=params,+ headers=headers,+ )+ if response.status_code == 401 and not force_refresh:+ logger.info("Yahoo options 401 for %s; refreshing crumb", yahoo_symbol)+ return _options_request(yahoo_symbol, expiration, force_refresh=True)+ response.raise_for_status()+ return response.json()+++def _parse_options(payload: Any, yahoo_symbol: str) -> Dict[str, Any]:+ """Extract the first optionChain result, raising on a reported error."""+ chain = (payload or {}).get("optionChain") or {}+ error = chain.get("error")+ if error:+ description = error.get("description") if isinstance(error, dict) else error+ raise ValueError(f"Yahoo options error for {yahoo_symbol}: {description}")+ results = chain.get("result") or []+ if not results:+ return {}+ return results[0] or {}+++def search(query: str) -> List[Dict[str, Any]]:+ """Look up matching instruments via the v1 search endpoint.++ Args:+ query: Free-text query (ticker fragment or company name).++ Returns:+ The ``quotes`` list (each a dict with ``symbol``, ``shortname``,+ ``exchange``, ``quoteType``, ...), or an empty list when none match.++ Raises:+ requests.RequestException: On a network/HTTP failure.+ """+ payload = throttled_get_json(+ _SEARCH_BASE,+ host_key=HOST_KEY,+ min_interval=_min_interval(),+ params={"q": query},+ )+ quotes = (payload or {}).get("quotes") or []+ return [quote for quote in quotes if isinstance(quote, dict)]diff --git a/agent/backtest/loaders/yahoo_loader.py b/agent/backtest/loaders/yahoo_loader.pynew file mode 100644index 000000000..2db94a0ff--- /dev/null+++ b/agent/backtest/loaders/yahoo_loader.py@@ -0,0 +1,250 @@+"""Yahoo Finance loader: free, no-auth US/HK equity OHLCV via direct HTTP.++Wraps the shared :mod:`backtest.loaders.yahoo_client` (the public v8 chart+endpoint) rather than the ``yfinance`` package, so it pulls in no new+dependency and shares the process-wide throttle/session that keeps Yahoo from+IP-rate-limiting us. Covers US equities (``AAPL.US``) and HK equities+(``00700.HK``); the client maps each project symbol to Yahoo's ticker form.++The chart endpoint returns each bar's ``trade_date`` as an epoch-second+timestamp; this loader converts those to a tz-naive ``DatetimeIndex`` and clips+the ascending series to the requested inclusive date window.+"""++from __future__ import annotations++import datetime as dt+import logging+from typing import Dict, List, Optional++import pandas as pd++from backtest.loaders import yahoo_client+from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)++_OHLCV_COLUMNS = ("open", "high", "low", "close", "volume")++# Project interval -> Yahoo chart interval. Daily is the only granularity this+# loader exposes for equities; anything else falls back to lowercasing so an+# explicit ``5m``/``1h`` still reaches Yahoo unchanged.+_INTERVAL_MAP = {+ "1D": "1d",+ "1H": "1h",+ "1W": "1wk",+ "1M": "1mo",+}+++def _is_us_or_hk(code: str) -> bool:+ """Return whether *code* is a US or HK equity symbol this loader handles."""+ return code.strip().upper().endswith((".US", ".HK"))+++def _to_yahoo_interval(interval: str) -> str:+ """Map a project interval string to Yahoo's chart interval string.++ Args:+ interval: Backtest interval such as ``1D`` or ``1H``.++ Returns:+ Yahoo-compatible interval string (e.g. ``1d``).+ """+ normalized = str(interval or "1D").strip()+ return _INTERVAL_MAP.get(normalized.upper(), normalized.lower())+++def _is_intraday_interval(interval: str) -> bool:+ """Return whether *interval* is finer than one day (minute/hour bars).++ Daily-and-coarser intervals (``1D``/``1W``/``1M``) carry no meaningful+ intraday time and must be midnight-indexed to align with every other+ loader's daily bars; minute/hour intervals keep their real timestamp.++ Project convention follows the interval map: a bare trailing ``M`` is a+ month (e.g. ``1M``) while a bare trailing lowercase ``m`` is a minute (e.g.+ ``5m``), so case is significant for that one suffix and is NOT folded.++ Args:+ interval: Backtest interval such as ``1D``, ``1H``, ``5m`` or ``30min``.++ Returns:+ ``True`` for minute/hour granularities, ``False`` for day/week/month.+ """+ raw = str(interval or "1D").strip()+ if not raw:+ return False+ lowered = raw.lower()+ # Multi-letter month forms ('mo'/'mth'/'mon') are daily-coarser.+ if lowered.endswith(("mo", "mth", "mon")):+ return False+ # Explicit minute spellings and hours are intraday.+ if lowered.endswith(("min", "h")):+ return True+ # Bare trailing letter: lowercase 'm' = minute (intraday), uppercase+ # 'M' = month (coarser), 'd'/'w' = day/week (coarser).+ return raw.endswith("m")+++def _epoch_seconds(date_str: str) -> int:+ """Convert a ``YYYY-MM-DD`` date to UTC midnight epoch seconds.++ Computed from the parsed calendar date (not ``time.time()``) so the window+ is reproducible and independent of wall-clock fetch time.++ Args:+ date_str: Date string in ``YYYY-MM-DD`` form.++ Returns:+ Epoch seconds for that date's UTC midnight.+ """+ day = pd.Timestamp(date_str).normalize().date()+ moment = dt.datetime(day.year, day.month, day.day, tzinfo=dt.timezone.utc)+ return int(moment.timestamp())+++def _rows_to_frame(+ rows: List[dict], start_date: str, end_date: str, interval: str = "1D"+) -> pd.DataFrame:+ """Build the OHLCV frame from chart rows, clipped to the inclusive window.++ For daily-and-coarser intervals the DatetimeIndex is normalized to midnight+ so the dates line up with every other loader's midnight-indexed daily bars+ (Yahoo stamps daily bars at the US market-open epoch, e.g. 14:30 UTC, which+ would otherwise break fallback merge/join/dedup). Minute/hour intervals keep+ their real intraday timestamp.++ Args:+ rows: Ascending ``{trade_date(epoch s), open, high, low, close, volume}``+ dicts from :func:`yahoo_client.get_chart`.+ start_date: Inclusive window start (``YYYY-MM-DD``).+ end_date: Inclusive window end (``YYYY-MM-DD``).+ interval: Backtest interval such as ``1D`` or ``1H``; selects whether the+ index is normalized to midnight.++ Returns:+ DataFrame indexed by a tz-naive ``trade_date`` with float OHLCV columns,+ or an empty frame when no row carries usable OHLC.+ """+ if not rows:+ return pd.DataFrame()++ frame = pd.DataFrame(rows)+ index = pd.to_datetime(frame["trade_date"], unit="s", utc=True).dt.tz_convert(None)+ if not _is_intraday_interval(interval):+ index = index.dt.normalize()+ frame = frame.drop(columns=["trade_date"])+ frame.index = pd.DatetimeIndex(index)+ frame.index.name = "trade_date"++ for column in _OHLCV_COLUMNS:+ if column not in frame.columns:+ frame[column] = 0.0 if column == "volume" else pd.NA++ frame = frame.loc[:, list(_OHLCV_COLUMNS)].apply(pd.to_numeric, errors="coerce")+ frame["volume"] = frame["volume"].fillna(0.0)+ frame = frame.dropna(subset=["open", "high", "low", "close"])++ lower = pd.Timestamp(start_date).normalize()+ upper = pd.Timestamp(end_date).normalize() + pd.Timedelta(days=1)+ frame = frame[(frame.index >= lower) & (frame.index < upper)]+ return frame.astype(float).sort_index()+++@register+class DataLoader:+ """Yahoo Finance US/HK equity OHLCV loader (free, direct HTTP, no auth)."""++ name = "yahoo"+ markets = {"us_equity", "hk_equity"}+ requires_auth = False++ def is_available(self) -> bool:+ """Always available — uses the throttled public HTTP client."""+ return True++ def __init__(self) -> None:+ """Initialize the loader (no credentials needed for public data)."""+ pass++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ """Fetch OHLCV history keyed by the original project symbols.++ Args:+ codes: Project symbols such as ``AAPL.US`` and ``00700.HK``.+ start_date: Inclusive start date (``YYYY-MM-DD``).+ end_date: Inclusive end date (``YYYY-MM-DD``).+ interval: Backtest interval such as ``1D`` or ``1H``.+ fields: Ignored; included for interface compatibility.++ Returns:+ Mapping of input symbol to a normalized OHLCV DataFrame. A symbol+ that fails or returns no data is omitted; one failure never aborts+ the batch.+ """+ del fields+ if not codes:+ return {}+ validate_date_range(start_date, end_date)++ result: Dict[str, pd.DataFrame] = {}+ for code in codes:+ try:+ df = cached_loader_fetch(+ source=self.name,+ symbol=code,+ timeframe=interval,+ start_date=start_date,+ end_date=end_date,+ fields=None,+ fetch=lambda code=code: self._fetch_one(+ code, start_date, end_date, interval+ ),+ )+ if df is not None and not df.empty:+ result[code] = df+ except Exception as exc:+ logger.warning("yahoo failed for %s: %s", code, exc)+ return result++ def _fetch_one(+ self, code: str, start_date: str, end_date: str, interval: str+ ) -> Optional[pd.DataFrame]:+ """Fetch and normalize one symbol's chart, or ``None`` when unusable.++ Args:+ code: A single project symbol.+ start_date: Inclusive start date (``YYYY-MM-DD``).+ end_date: Inclusive end date (``YYYY-MM-DD``).+ interval: Backtest interval string.++ Returns:+ The OHLCV DataFrame for *code*, ``None`` if it is not a US/HK symbol+ or Yahoo returns no usable bars.+ """+ if not _is_us_or_hk(code):+ return None++ # period2 is exclusive on Yahoo; extend one day past end_date so the+ # final inclusive bar is fetched, then clip precisely in _rows_to_frame.+ period1 = _epoch_seconds(start_date)+ period2 = _epoch_seconds(end_date) + 86400++ rows = yahoo_client.get_chart(+ code,+ interval=_to_yahoo_interval(interval),+ period1=period1,+ period2=period2,+ )+ frame = _rows_to_frame(rows, start_date, end_date, interval)+ return frame if not frame.empty else Nonediff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex c40348540..7cf40fb61 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -6,6 +6,17 @@ Zero API key required for HK/US/crypto research markets (yfinance, OKX,AKShare are free). Trading connector tools are profile-scoped and require theselected connector's own local app or OAuth setup.+Surfaces 54 tools: skills, research goals, backtest/factor/options/pattern+analysis, market data, fundamentals & capital-flow & news & discovery+(get_fund_flow / get_dragon_tiger / get_northbound_flow / get_margin_trading /+get_block_trades / get_shareholder_count / get_lockup_expiry / get_sector_info /+get_research_reports / get_stock_news / get_sec_filings /+get_financial_statements / get_options_chain / get_stock_profile /+screen_market / search_symbol / get_macro_series / iwencai_search), read-only+trading-connector reads, swarm orchestration, trade-journal and shadow-account+analysis. Every exposed tool is read-only or research-only; no order-placing or+order-cancelling tool is ever surfaced via MCP.+Usage:python mcp_server.py # stdio transport (default)python mcp_server.py --transport sse # SSE transport for web clients@@ -1066,6 +1077,427 @@ def get_market_data()+# ---------------------------------------------------------------------------+# Read-only fundamentals, flow, news & discovery tools+#+# Each wrapper delegates to the auto-discovered local registry, exactly like+# factor_analysis / pattern_recognition above. The registry returns a clean+# JSON error envelope when a key-gated tool (get_macro_series needs+# FRED_API_KEY, iwencai_search needs VIBE_TRADING_IWENCAI_KEY) is absent — see+# ``_execute_key_gated`` below, which honours that contract even though the+# tool is excluded from the registry by ``check_available()``. Every tool below+# is strictly read-only data — no order/trading tool is ever surfaced via MCP.+# ---------------------------------------------------------------------------+++# Map of key-gated MCP tools to their concrete tool class. When the required+# API key is unset the class' ``check_available()`` returns False, so the tool+# is excluded from the auto-discovered registry and ``registry.execute`` would+# answer with a generic "Tool not found". That contradicts the documented+# contract above (a clean, env-var-named error). For these tools we therefore+# fall through to the tool's own ``execute()`` — whose missing-key envelope+# names the exact env var (``FRED_API_KEY`` / ``VIBE_TRADING_IWENCAI_KEY``).+def _key_gated_tool_classes() -> dict[str, Any]:+ """Return the {tool_name: tool_class} map for key-gated MCP tools.++ Imported lazily so a missing optional dependency in either module degrades+ to the registry path rather than breaking module import.++ Returns:+ Mapping of MCP tool name to its ``BaseTool`` subclass.+ """+ from src.tools.fred_macro_tool import FredMacroTool+ from src.tools.iwencai_tool import IWenCaiSearchTool++ return {+ "get_macro_series": FredMacroTool,+ "iwencai_search": IWenCaiSearchTool,+ }+++def _execute_key_gated(name: str, params: dict[str, Any]) -> str:+ """Run a key-gated read-only tool, preserving its env-var-named error.++ Prefers the auto-discovered registry (present when the API key is set). When+ the key is absent the tool is excluded from the registry, so we invoke its+ concrete ``execute()`` directly to surface the documented missing-key error+ that names the exact env var — never a generic "Tool not found".++ Args:+ name: MCP tool name (``get_macro_series`` or ``iwencai_search``).+ params: Keyword arguments forwarded to the tool.++ Returns:+ The tool's JSON envelope as a string.+ """+ registry = _get_registry()+ if registry.get(name) is not None:+ return registry.execute(name, params)+ tool_cls = _key_gated_tool_classes().get(name)+ if tool_cls is None:+ return registry.execute(name, params)+ return tool_cls().execute(**params)+++def get_fund_flow(codes: list[str], period: str = "daily", days: int = 30) -> str:+ """Fetch order-bucket net capital inflow (main/super-large/large/medium/small).++ Markets: A-share (.SH/.SZ/.BJ), Hong Kong (.HK) and US (.US). Use this to+ gauge whether large/main-force money is flowing in or out, as daily history+ or the current session's per-minute line. One unresolvable symbol is+ reported per-symbol and does not abort the batch.++ Args:+ codes: Symbols with market suffix, e.g. ["600519.SH", "00700.HK"].+ period: "daily" (daily net-inflow history) or "min" (per-minute line).+ days: For period="daily", number of most-recent daily bars to keep.+ """+ registry = _get_registry()+ return registry.execute("get_fund_flow", {"codes": codes, "period": period, "days": days})+++def get_dragon_tiger(date: str, code: str | None = None) -> str:+ """Fetch the A-share dragon-tiger board (龙虎榜) for a trade date (Eastmoney).++ Markets: China A-share (SH/SZ). Omit ``code`` for the full-market list of+ every security on the board that day; supply ``code`` to also get that+ security's ranked top buy/sell brokerage seats. Read-only, no auth.++ Args:+ date: Trade date in YYYY-MM-DD format (e.g. 2024-01-02).+ code: Optional A-share symbol or bare code (e.g. "600519.SH" or "600519").+ """+ params: dict[str, Any] = {"date": date}+ if code:+ params["code"] = code+ registry = _get_registry()+ return registry.execute("get_dragon_tiger", params)+++def get_northbound_flow(lookback_days: int = 30) -> str:+ """Fetch Northbound (Stock-Connect) net capital flow for China A-shares.++ Returns the latest realtime net inflow plus recent daily history, split into+ Shanghai-Connect (沪股通) and Shenzhen-Connect (深股通) channels (units: 10k+ CNY) from Eastmoney. Read-only; China A-share market only.++ Args:+ lookback_days: Trailing trading days of daily net-inflow history to return.+ """+ registry = _get_registry()+ return registry.execute("get_northbound_flow", {"lookback_days": lookback_days})+++def get_margin_trading(code: str, days: int = 30) -> str:+ """Fetch an A-share stock's daily margin-trading (融资融券) balances (Eastmoney).++ Returns outstanding financing balance, financing buy amount,+ securities-lending balance, and combined RZRQ balance, one row per trading+ day (most recent first). Read-only, no credentials, A-shares only (SH/SZ).++ Args:+ code: A-share code: bare ("600519"), suffixed ("600519.SH"), or+ exchange-prefixed ("sh600519").+ days: Number of most-recent trading days to return.+ """+ registry = _get_registry()+ return registry.execute("get_margin_trading", {"code": code, "days": days})+++def get_block_trades(code: str, days: int = 30) -> str:+ """Fetch recent A-share block trades (大宗交易) for one symbol (Eastmoney).++ Returns per-deal price, volume, amount, the premium/discount versus that+ day's close, and the buyer/seller broker seats (营业部). Markets: China+ A-share only (.SH/.SZ/.BJ). Read-only.++ Args:+ code: A-share symbol with exchange suffix, e.g. "600519.SH", "830799.BJ".+ days: Lookback window in calendar days ending today.+ """+ registry = _get_registry()+ return registry.execute("get_block_trades", {"code": code, "days": days})+++def get_shareholder_count(code: str, max_periods: int = 24) -> str:+ """Fetch mainland A-share quarterly shareholder count (股东户数) (Eastmoney).++ Returns holder count per report period, quarter-over-quarter change+ (absolute and percent), and average holding (shares and market value) per+ account. Markets: China A-shares only (.SH/.SZ/.BJ).++ Args:+ code: A-share symbol in <code>.<exchange> form (SH/SZ/BJ).+ max_periods: Maximum number of most-recent report periods to return.+ """+ registry = _get_registry()+ return registry.execute("get_shareholder_count", {"code": code, "max_periods": max_periods})+++def get_lockup_expiry(code: str | None = None, horizon_days: int = 90) -> str:+ """Fetch Chinese A-share lockup-expiry (restricted-share unlock, 限售解禁) data.++ Pass an A-share ``code`` to get that stock's full historical unlock+ schedule, or omit it for a market-wide calendar of upcoming unlocks within+ the next ``horizon_days`` (Eastmoney). A large near-term unlock adds+ tradable supply and often pressures the stock. Read-only.++ Args:+ code: A-share symbol (e.g. "600519", "600519.SH"). Omit for a+ market-wide upcoming-unlock calendar.+ horizon_days: Upcoming-unlock window in days for the market-wide+ calendar; ignored when ``code`` is given (full history is returned).+ """+ params: dict[str, Any] = {"horizon_days": horizon_days}+ if code:+ params["code"] = code+ registry = _get_registry()+ return registry.execute("get_lockup_expiry", params)+++def get_sector_info(code: str | None = None, mode: str = "membership", limit: int = 30) -> str:+ """Look up Chinese A-share sector / concept board info (Eastmoney, no auth).++ Two modes: (1) membership — given a stock ``code``, list the industry and+ concept boards it belongs to; (2) ranking — set ``mode="ranking"`` to rank+ industry boards by today's percent change (with up/down constituent counts+ and the leading stock). Market: A-share stocks.++ Args:+ code: A-share stock symbol with market suffix. Required when+ mode="membership"; ignored when mode="ranking".+ mode: "membership" (default) or "ranking".+ limit: For mode="ranking", number of top boards to return.+ """+ params: dict[str, Any] = {"mode": mode, "limit": limit}+ if code:+ params["code"] = code+ registry = _get_registry()+ return registry.execute("get_sector_info", params)+++def get_research_reports(code: str, limit: int = 20) -> str:+ """Fetch mainland A-share sell-side research coverage and consensus forecasts.++ Returns recent broker research reports (title, brokerage, analyst, publish+ date, rating) with each broker's per-year EPS and PE forecasts from+ Eastmoney, plus the market consensus (mean) EPS forecast per forward fiscal+ year from THS (同花顺). Markets: China A-shares only (.SH/.SZ/.BJ).++ Args:+ code: A-share symbol in <code>.<exchange> form (SH/SZ/BJ).+ limit: Maximum number of most-recent research reports to return.+ """+ registry = _get_registry()+ return registry.execute("get_research_reports", {"code": code, "limit": limit})+++def get_stock_news(code: str | None = None, scope: str = "stock", limit: int = 20) -> str:+ """Fetch recent financial news headlines, read-only and no auth.++ Markets: China A-share (SH/SZ/BJ) headlines from Eastmoney; US (.US) and+ Hong Kong (.HK) related-instrument matches from Yahoo Finance. Use scope+ "stock" with a ``code`` for one security's headlines, or scope "global"+ (no code) for broad China-market finance news.++ Args:+ code: Symbol whose news to fetch (e.g. "600519.SH", "AAPL.US").+ Required when scope="stock"; ignored when scope="global".+ scope: "stock" (default) or "global".+ limit: Maximum number of headlines to return.+ """+ params: dict[str, Any] = {"scope": scope, "limit": limit}+ if code:+ params["code"] = code+ registry = _get_registry()+ return registry.execute("get_stock_news", params)+++def get_sec_filings(+ ticker: str,+ form: str | None = None,+ metric: str | None = None,+ limit: int = 20,+) -> str:+ """Fetch U.S. SEC EDGAR filings or reported XBRL financials for a company.++ Returns a list of recent filings (10-K / 10-Q / 8-K, etc.) with accession+ number, filing and report dates, and the primary-document URL; or, when+ ``metric`` is given, the reported XBRL us-gaap financial series for that+ concept (e.g. Revenues, NetIncomeLoss, Assets). Markets: United States only.++ Args:+ ticker: U.S. equity ticker, case-insensitive (e.g. "AAPL").+ form: Optional SEC form type filter (e.g. "10-K", "10-Q", "8-K").+ metric: Optional XBRL us-gaap concept name (e.g. "Revenues").+ limit: Maximum number of most-recent filings and metric points to return.+ """+ params: dict[str, Any] = {"ticker": ticker, "limit": limit}+ if form:+ params["form"] = form+ if metric:+ params["metric"] = metric+ registry = _get_registry()+ return registry.execute("get_sec_filings", params)+++def get_financial_statements(code: str, statement: str = "indicators", period: str = "annual") -> str:+ """Fetch a stock's financial statements or key per-period indicators.++ Markets: A-share (.SH/.SZ/.BJ, via Sina), US (.US) and Hong Kong (.HK, via+ Eastmoney). Reports come back newest-first as flat per-period rows. Use this+ to read fundamentals before building a valuation or screen.++ Args:+ code: Single symbol with a market suffix (e.g. "600519.SH", "AAPL.US").+ statement: "balance", "income", "cashflow", or "indicators".+ period: "annual" or "quarter".+ """+ registry = _get_registry()+ return registry.execute(+ "get_financial_statements",+ {"code": code, "statement": statement, "period": period},+ )+++def get_options_chain(ticker: str, expiration: int | None = None) -> str:+ """Fetch the US-listed options chain (calls and puts) for one expiration.++ Returns per-contract strike, bid/ask, last price, volume, open interest,+ implied volatility, and in-the-money flag, plus the list of available+ expirations (epoch seconds) via Yahoo Finance. Read-only US options data.++ Args:+ ticker: US underlying symbol (e.g. "AAPL" or "AAPL.US").+ expiration: Optional expiration as Unix epoch seconds (one of the+ returned expirations). Omit for the nearest expiration.+ """+ params: dict[str, Any] = {"ticker": ticker}+ if expiration is not None:+ params["expiration"] = expiration+ registry = _get_registry()+ return registry.execute("get_options_chain", params)+++def get_stock_profile(ticker: str, sections: list[str] | None = None) -> str:+ """Fetch a read-only company profile for a US or HK listing (Yahoo Finance).++ Returns valuation key statistics, analyst price targets and+ earnings/revenue estimates, institutional and insider ownership, and the+ analyst recommendation trend. Use this for fundamentals and consensus+ context, not for OHLCV price bars (use get_market_data).++ Args:+ ticker: US (bare or .US suffix) or HK (zero-padded .HK code) symbol.+ sections: Profile sections to return, any of: key_stats, financials,+ earnings_trend, institution_ownership, insider_holders,+ recommendation_trend. Defaults to all sections.+ """+ params: dict[str, Any] = {"ticker": ticker}+ clean_sections = _clean_list(sections)+ if clean_sections:+ params["sections"] = clean_sections+ registry = _get_registry()+ return registry.execute("get_stock_profile", params)+++def screen_market(market: str, sort_by: str = "change_pct", top_n: int = 30) -> str:+ """Screen a market's listed instruments and rank the top names by a metric.++ Use this to find today's biggest movers or most-actively-traded names+ without fetching every symbol. Markets: A-share ("a"), US ("us"), Hong+ Kong ("hk").++ Args:+ market: Market universe: "a", "us", or "hk".+ sort_by: Ranking metric (descending): "change_pct", "volume",+ "amount", or "turnover".+ top_n: Number of top-ranked instruments to return.+ """+ registry = _get_registry()+ return registry.execute("screen_market", {"market": market, "sort_by": sort_by, "top_n": top_n})+++def search_symbol(query: str, limit: int = 10) -> str:+ """Resolve a company name or ticker fragment to candidate trading symbols.++ Returns candidates with their market in the project's symbol convention+ (A-shares 600519.SH, Hong Kong 00700.HK, U.S. AAPL.US, plus crypto/index/FX+ from Yahoo). Searches Eastmoney and Yahoo and, for U.S. equities, attaches+ the SEC CIK. Use this to turn an ambiguous name into a concrete symbol+ before calling get_market_data or get_sec_filings.++ Args:+ query: Free-text company name or ticker fragment (Chinese or English).+ limit: Maximum number of merged candidates to return.+ """+ registry = _get_registry()+ return registry.execute("search_symbol", {"query": query, "limit": limit})+++def get_macro_series(+ series_id: str,+ start_date: str | None = None,+ end_date: str | None = None,+ limit: int = 2000,+) -> str:+ """Fetch a FRED macroeconomic time series from the St. Louis Fed.++ Returns dated observations of indicators such as CPI (CPIAUCSL),+ unemployment (UNRATE), real GDP (GDPC1), the federal funds rate (FEDFUNDS),+ or the 10-year Treasury yield (DGS10). Markets: US / global macro data.+ Requires a free FRED API key (FRED_API_KEY); without it the tool returns a+ not-available error.++ Args:+ series_id: FRED series identifier (e.g. "CPIAUCSL", "UNRATE").+ start_date: Inclusive window start, YYYY-MM-DD. Omit for full history.+ end_date: Inclusive window end, YYYY-MM-DD. Omit for the latest date.+ limit: Maximum number of most-recent observations to return.+ """+ params: dict[str, Any] = {"series_id": series_id, "limit": limit}+ if start_date:+ params["start_date"] = start_date+ if end_date:+ params["end_date"] = end_date+ return _execute_key_gated("get_macro_series", params)+++def iwencai_search(query: str, limit: int = 20) -> str:+ """Run a natural-language A-share research query against iWenCai (问财).++ iWenCai is a Chinese-market semantic stock screener. Phrase the question in+ plain language (Chinese works best) and get back the matching China A-share+ (SH/SZ) securities with the metric columns iWenCai parsed from the question.+ Read-only; requires the VIBE_TRADING_IWENCAI_KEY access key (without it the+ tool returns a not-available error).++ Args:+ query: Natural-language research question (Chinese phrasing yields the+ best parse, e.g. "市盈率低于15的银行股").+ limit: Maximum securities to return.+ """+ return _execute_key_gated("iwencai_search", {"query": query, "limit": limit})++# ---------------------------------------------------------------------------# Swarm status & history tools# ---------------------------------------------------------------------------diff --git a/agent/src/market_data.py b/agent/src/market_data.pyindex 9ecd66964..4b670fab6 100644--- a/agent/src/market_data.py+++ b/agent/src/market_data.py@@ -13,11 +13,16 @@ logger = logging.getLogger(__name__)DEFAULT_MAX_ROWS = 250+# Symbol -> preferred source. The matched source is the head of its market's+# fallback chain (registry.FALLBACK_CHAINS), so an unavailable preferred source+# still degrades gracefully to the rest of the chain. US/HK equities route to+# the throttle-tolerant Yahoo public endpoint first (lower IP-ban risk than the+# yfinance SDK), A-shares to the Tencent quote endpoint._SOURCE_PATTERNS = [(re.compile(r"^local:", re.I), "local"),- (re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "tushare"),- (re.compile(r"^[A-Z]+\.US$", re.I), "yfinance"),- (re.compile(r"^\d{3,5}\.HK$", re.I), "yfinance"),+ (re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "tencent"),+ (re.compile(r"^[A-Z]+\.US$", re.I), "yahoo"),+ (re.compile(r"^\d{3,5}\.HK$", re.I), "yahoo"),(re.compile(r"^[A-Z]+-USDT$", re.I), "okx"),(re.compile(r"^[A-Z]+/USDT$", re.I), "ccxt"),]diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.mdindex 16563a667..8193a3aff 100644--- a/agent/src/skills/data-routing/SKILL.md+++ b/agent/src/skills/data-routing/SKILL.md@@ -1,69 +1,125 @@---name: data-routingcategory: data-source-description: Data source selection decision tree. Load this skill BEFORE any backtest or data-fetching task to choose the best available data source.+description: The single ROUTER for every data need. Load this skill BEFORE any backtest, data-fetch, or research task to pick the best available source/tool, honour auth (env) requirements, and avoid ban-risk providers.---+# Data Routing (Router)-## Data Source Overview+This is the one router. It maps (a) every registered backtest data **source** to its+markets / auth / skill, and (b) every research **data need** to the concrete **tool**+that serves it, its market, and the env key it requires. Source names below are a+strict subset of `backtest.loaders.registry.VALID_SOURCES` (enforced by+`tests/test_data_routing_sources_subset.py`).-| Source | Markets | Auth Required | Network | Skill |-|--------|---------|---------------|---------|-------|+## Source Overview++Every name here is a registered OHLCV/backtest source in `VALID_SOURCES`.+"Runner-internal" sources are selected by the backtest runner, not authored as a+per-source skill.++| Source | Markets | Auth (env key) | Network | Skill |+|--------|---------|----------------|---------|-------|| tushare | A-shares, funds, futures, macro | Yes (`TUSHARE_TOKEN`) | China network | tushare || akshare | A-shares, US, HK, futures, macro, forex | No | Unrestricted | akshare |-| yfinance | US stocks, HK stocks, ETFs | No | Needs Yahoo Finance access | yfinance |+| yfinance | US stocks, HK stocks, ETFs | No | Needs Yahoo access | yfinance || okx | Crypto (OKX exchange) | No | Needs okx.com access | okx-market || ccxt | Crypto (100+ exchanges) | No | Needs exchange access | ccxt |+| baostock | A-shares (free daily/min) | No | China network | data-routing |+| tencent | A-shares, HK, US (never-banned) | No | Unrestricted | data-routing |+| mootdx | A-shares (TDX servers, never-banned) | No | China network | data-routing |+| futu | A/HK/US via OpenD gateway | Yes (OpenD running) | Local gateway | data-routing (runner-internal) |+| local | User CSV/parquet on disk | No | Offline | data-routing (runner-internal) |+| eastmoney | A-shares, HK, US equities | No (IP-throttled) | Unrestricted | data-routing |+| sina | US equities (daily OHLCV) | No (IP-throttled) | Unrestricted | data-routing |+| stooq | US equities (daily OHLCV) | No | Unrestricted | data-routing |+| yahoo | US, HK equities | No (IP-throttled) | Needs Yahoo access | data-routing |+| finnhub | US equities | Yes (`FINNHUB_API_KEY`) | Unrestricted | data-routing |+| alphavantage | US equities | Yes (`ALPHAVANTAGE_API_KEY`) | Unrestricted | data-routing |+| tiingo | US equities | Yes (`TIINGO_API_KEY`) | Unrestricted | data-routing |+| fmp | US equities | Yes (`FMP_API_KEY`) | Unrestricted | data-routing |++## Capability → Tool Routing++Pick the tool by the data need. "Market" is the universe the tool covers; "Env key"+is required only where listed (no key listed = free / no auth).++| Data need | Tool | Market | Env key |+|-----------|------|--------|---------|+| OHLCV price bars | `get_market_data` | A-share / US / HK / crypto / futures / forex | per-source (see Source Overview) |+| Fund flow (资金流向) | `get_fund_flow` | A-share, HK, US | — |+| Dragon-tiger (龙虎榜) | `get_dragon_tiger` | A-share | — |+| Northbound flow (北向资金) | `get_northbound_flow` | A-share | — |+| Margin trading (融资融券) | `get_margin_trading` | A-share | — |+| Block trades (大宗交易) | `get_block_trades` | A-share | — |+| Shareholder count (股东户数) | `get_shareholder_count` | A-share | — |+| Lockup expiry (限售解禁) | `get_lockup_expiry` | A-share | — |+| Sector / board taxonomy (板块) | `get_sector_info` | A-share | — |+| Sell-side research reports | `get_research_reports` | A-share | — |+| Stock news | `get_stock_news` | A-share, US, HK | — |+| SEC filings (EDGAR) | `get_sec_filings` | US | — |+| Financial statements | `get_financial_statements` | A-share, US, HK | — |+| Options chain | `get_options_chain` | US | — |+| Stock profile / fundamentals | `get_stock_profile` | US | — |+| Market screen | `screen_market` | A-share | — |+| Symbol search | `search_symbol` | A-share, US | — |+| Macro / FRED series | `get_macro_series` | Macro (US/global) | `FRED_API_KEY` |+| iWenCai NL search (问财) | `iwencai_search` | A-share | `VIBE_TRADING_IWENCAI_KEY` |++Notes:+- `get_financial_statements` reads A-share, US, and HK statements via the+ Eastmoney datacenter report API (per-market F10 report names) — an IP-throttled+ client, not the OHLCV loader of the same name.+- `get_stock_news` routes A-share (SH/SZ/BJ) to an Eastmoney news client and+ US (.US) / HK (.HK) to a Yahoo search client; a failure on one upstream is+ returned as an error envelope, never raised, so a single bad symbol never+ aborts a batch.## Decision Tree-### Backtest Scenario (writing config.json)--Use `source: "auto"` — the runner automatically routes by symbol pattern and falls back to alternative sources if the primary one is unavailable.--You do NOT need to specify a concrete data source in config.json unless the user explicitly asks for one.+### Backtest scenario (writing config.json)-### Analysis / Research Scenario (writing Python scripts)+Use `source: "auto"` — the runner routes by symbol pattern and falls back across+same-market sources automatically. Only set a concrete source when the user asks.-1. Identify the market type from the user's request-2. Pick the source by priority:+### Analysis / research scenario-**A-shares**: tushare (if TUSHARE_TOKEN is set) > akshare (free fallback)-**US stocks**: yfinance > akshare-**HK stocks**: yfinance > akshare-**Crypto**: okx (single exchange) > ccxt (multi-exchange)-**Futures**: tushare > akshare-**Macro / economics**: akshare > tushare-**Forex**: akshare > yfinance+1. Identify the data need, then read the Capability table for the tool + env key.+2. If the need is plain OHLCV, call `get_market_data` and let source fallback run.+3. Set any required env key before calling a key-gated tool; if it is missing,+ report the missing key rather than failing silently.-3. Load the corresponding skill for API details: `load_skill("akshare")`+### Source priority (for OHLCV by market)-### Availability Check--- **tushare**: check if `TUSHARE_TOKEN` environment variable exists-- **yfinance / okx / ccxt / akshare**: free but may have network restrictions-- If the user reports "connection timeout" or "cannot access", switch to the same-market fallback+- **A-shares**: tencent / mootdx (never banned) > tushare (`TUSHARE_TOKEN`) >+ baostock / akshare > eastmoney (throttled).+- **US stocks**: stooq / yahoo > tiingo / finnhub / fmp / alphavantage (key-gated) >+ sina / eastmoney (throttled) > yfinance.+- **HK stocks**: tencent > eastmoney / yahoo > yfinance.+- **Crypto**: okx (single exchange) > ccxt (multi-exchange).+- **Futures / macro / forex**: tushare > akshare.## Symbol Format Reference| Market | Format | Examples |-|--------|--------|---------|-| A-shares | `NNNNNN.SZ/SH/BJ` | 000001.SZ, 600000.SH |+|--------|--------|----------|+| A-shares | `NNNNNN.SZ/SH/BJ` | 000001.SZ, 600000.SH, 430139.BJ || US stocks | `TICKER.US` | AAPL.US, MSFT.US |-| HK stocks | `NNN(N).HK` | 700.HK, 9988.HK |+| HK stocks | `NNNNN.HK` | 00700.HK, 09988.HK || Crypto | `SYMBOL-USDT` | BTC-USDT, ETH-USDT || Futures | `XXNNNN.EXCHANGE` | CU2406.SHFE || Forex | `XXX/YYY` | USD/CNY, EUR/USD |-## Fallback Chain (Runner Layer)--The backtest runner implements automatic fallback at the market level:--```-User requests 000001.SZ (A-share)- -> detect market: a_share- -> try tushare: TUSHARE_TOKEN missing -> skip- -> try akshare: available -> use akshare- -> success (zero config required)-```--This is transparent to the user — they just see results.+## Ban-Risk & Fallback Notes++- **Prefer never-banned sources**: `tencent` and `mootdx` have no observed IP ban;+ reach for them first for A-share OHLCV when no token is set.+- **Eastmoney rate-limits by IP and must be throttled.** Every Eastmoney-backed+ tool/loader routes through the shared per-host throttle; do not hammer it. On a+ throttle/timeout, fall back to the same-market source above (tencent/baostock).+- **Sina / Yahoo also throttle by IP** — same per-host wrapper, same fallback rule.+- **Key-gated sources need their env key** (`FINNHUB_API_KEY`,+ `ALPHAVANTAGE_API_KEY`, `TIINGO_API_KEY`, `FMP_API_KEY`, `FRED_API_KEY`,+ `VIBE_TRADING_IWENCAI_KEY`, `TUSHARE_TOKEN`). If the key is absent the tool/loader+ is unavailable — route to a free same-market source instead of erroring out.+- A single failing symbol or transient HTTP error is reported inside the envelope;+ it never aborts the surrounding batch.diff --git a/agent/src/skills/eastmoney/SKILL.md b/agent/src/skills/eastmoney/SKILL.mdnew file mode 100644index 000000000..b6e9c29ea--- /dev/null+++ b/agent/src/skills/eastmoney/SKILL.md@@ -0,0 +1,98 @@+---+name: eastmoney+category: data-source+description: 东方财富(Eastmoney)免费免鉴权数据接口,覆盖资金流向、龙虎榜、融资融券、大宗交易、股东户数、限售解禁、行业概念板块、券商研报、财经新闻、美股/港股三大报表+主要指标、全市场选股与代码搜索。所有请求经共享 IP 限速层节流(东财按源 IP 限流并临时封禁突发请求),通过 Vibe-Trading 工具直接调用,无需 token。+---+# Eastmoney(东方财富)++## 概述++东方财富对外开放了一批免费、免鉴权的行情与披露接口(push2 / push2his / datacenter-web / reportapi / search-api)。这些接口由 Vibe-Trading 内置工具封装,统一返回 `{"ok": true/false, ...}` JSON 信封,覆盖 A 股 / 港股 / 美股的资金面、披露面、舆情面与基本面数据。本技能是上述接口的**索引页**:每个接口的端点 URL、入参、返回字段写在 `references/` 下;调用范例写在 `scripts/` 下。++> **限速红线**:东方财富按**源 IP** 限流,并会临时封禁突发请求。所有工具内部已经过共享 per-host 节流层(`backtest.loaders._http`),切勿绕过工具直接对端点发起裸 HTTP 突发请求。可用环境变量 `VIBE_TRADING_EASTMONEY_MIN_INTERVAL` 调整最小请求间隔(默认 1.0 秒)。++## 快速上手++这些接口已注册为 Vibe-Trading 工具,直接以工具名调用即可,无需安装 SDK、无需 token:++```python+from src.tools.fund_flow_tool import FundFlowTool++# 主力 / 超大单 / 大单 / 中单 / 小单 净流入(近 30 日)+print(FundFlowTool().execute(codes=["600519.SH", "00700.HK"], period="daily", days=30))+```++底层共享客户端 `backtest.loaders.eastmoney_client` 负责 `secid` 解析与限速 GET:++```python+from backtest.loaders.eastmoney_client import resolve_secid, get_json++resolve_secid("600519.SH") # -> "1.600519"+resolve_secid("00700.HK") # -> "116.00700"+resolve_secid("AAPL.US") # -> "105.AAPL"(经 suggest 端点解析并进程内缓存)+```++## 参数格式说明++- **代码(symbol)**:`<code>.<exchange>` 形式,交易所后缀大写。A 股 `600519.SH` / `000001.SZ` / `830799.BJ`,港股 `00700.HK`(零填充至 5 位),美股 `AAPL.US`。+- **secid**:东财内部寻址 `<market>.<code>`。SH=1,SZ/BJ=0,HK=116,美股 NASDAQ=105 / NYSE=106 / AMEX=107(美股 market 前缀由 suggest 端点解析)。+- **日期**:datacenter `filter` 用 `YYYY-MM-DD`;kline `beg`/`end` 用 `YYYYMMDD`。+- **返回**:统一 JSON 字符串信封,成功 `{"ok": true, "market", "source": "eastmoney", "data": {...}}`,失败 `{"ok": false, "error": ...}`。单个失败 symbol 以 per-symbol error 上报,不中断批次。++> 链接约定:本文档内所有指向 `references/` 的链接均以**技能名前缀** `eastmoney/references/...` 书写。`read_file` 工具以 `skills/` 为根解析路径,省略前缀会读取失败。++## python 脚本示例++- [资金流向 + 板块联动研究](eastmoney/scripts/fund_flow_example.py)+- [龙虎榜 + 大宗交易 + 融资融券披露面研究](eastmoney/scripts/disclosure_example.py)+- [研报舆情 + 美股/港股财报基本面研究](eastmoney/scripts/fundamentals_example.py)+- [代码搜索 + 全市场选股](eastmoney/scripts/screen_search_example.py)++## 接口列表++### 资金面++| 工具 | 标题(详细文档) | 市场 | 描述 |+| ---- | -------------- | ---- | ---- |+| `get_fund_flow` | [资金流向](eastmoney/references/资金面/资金流向.md) | A股/港股/美股 | 主力/超大单/大单/中单/小单净流入,日线历史或当日分钟线 |++### 龙虎榜++| 工具 | 标题(详细文档) | 市场 | 描述 |+| ---- | -------------- | ---- | ---- |+| `get_dragon_tiger` | [龙虎榜](eastmoney/references/龙虎榜/龙虎榜.md) | A股 | 某交易日全市场上榜个股 + 指定个股的买卖席位排名 |++### 参考数据(披露面)++| 工具 | 标题(详细文档) | 市场 | 描述 |+| ---- | -------------- | ---- | ---- |+| `get_margin_trading` | [融资融券](eastmoney/references/参考数据/融资融券.md) | A股 | 个股每日融资余额/融资买入/融券余额/RZRQ 合计 |+| `get_block_trades` | [大宗交易](eastmoney/references/参考数据/大宗交易.md) | A股 | 逐笔成交价/量/额、相对收盘折溢价、买卖营业部 |+| `get_shareholder_count` | [股东户数](eastmoney/references/参考数据/股东户数.md) | A股 | 各报告期股东户数、环比变动、户均持股 |+| `get_lockup_expiry` | [限售解禁](eastmoney/references/参考数据/限售解禁.md) | A股 | 个股全历史解禁表,或全市场未来 N 日解禁日历 |++### 板块++| 工具 | 标题(详细文档) | 市场 | 描述 |+| ---- | -------------- | ---- | ---- |+| `get_sector_info` | [行业概念板块](eastmoney/references/板块/行业概念板块.md) | A股 | 个股所属行业/概念板块(membership)或行业板块按涨幅排名(ranking) |++### 研报舆情++| 工具 | 标题(详细文档) | 市场 | 描述 |+| ---- | -------------- | ---- | ---- |+| `get_research_reports` | [券商研报](eastmoney/references/研报舆情/券商研报.md) | A股 | 券商研报列表(标题/机构/分析师/评级/EPS·PE 预测)+ 同花顺一致预期 EPS |+| `get_stock_news` | [财经新闻](eastmoney/references/研报舆情/财经新闻.md) | A股/港股/美股 | 个股新闻或全市场财经快讯(A 股走东财,美/港走 Yahoo) |++### 财务报表(美股 / 港股)++| 工具 | 标题(详细文档) | 市场 | 描述 |+| ---- | -------------- | ---- | ---- |+| `get_financial_statements` | [三大报表与主要指标](eastmoney/references/财务报表/三大报表与主要指标.md) | 美股/港股(东财)·A股(新浪) | 资产负债表/利润表/现金流量表/主要指标(GMAININDICATOR) |++### 选股检索++| 工具 | 标题(详细文档) | 市场 | 描述 |+| ---- | -------------- | ---- | ---- |+| `screen_market` | [全市场选股](eastmoney/references/选股检索/全市场选股.md) | A股/美股/港股 | 全市场按涨跌幅/成交量/成交额/换手率排名取 top N |+| `search_symbol` | [代码搜索](eastmoney/references/选股检索/代码搜索.md) | 多市场 | 名称/代码片段解析为候选 symbol + 市场(东财 suggest + Yahoo + SEC CIK) |diff --git "a/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\345\244\247\345\256\227\344\272\244\346\230\223.md" "b/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\345\244\247\345\256\227\344\272\244\346\230\223.md"new file mode 100644index 000000000..1248ec2c7--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\345\244\247\345\256\227\344\272\244\346\230\223.md"@@ -0,0 +1,62 @@+## 大宗交易(Block Trades)++工具:`get_block_trades`(`src.tools.block_trades_tool.BlockTradesTool`)+描述:东财通过免费免鉴权 datacenter 报表接口(`RPT_DATA_BLOCKTRADE`)发布每笔 A 股大宗交易——相对收盘价折溢价成交的场外协议成交。每条记录含成交价、量、相对当日收盘的折溢价,以及挂单的买/卖营业部("席位")。大宗交易流向是机构吸筹/派发的观察信号。只读。+市场:A 股(.SH / .SZ / .BJ),港股/美股不在此报表内。+限速:经共享 `eastmoney` per-host 节流层;东财按源 IP 限流。++<br>++**端点**++`https://datacenter-web.eastmoney.com/api/data/v1/get`,reportName = `RPT_DATA_BLOCKTRADE`。++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+code | str | Y | 带后缀的 A 股 symbol,如 `600519.SH` / `000001.SZ` / `830799.BJ`。先经 `resolve_secid` 校验,仅接受 market 0/1(SZ/BJ/SH)。+days | int | N | 以今天为止的回溯日历天数窗口,clamp 至 [1, 365],默认 30。++<br>++**端点查询参数**++名称 | 取值 | 描述+---- | ---- | ----+reportName | `RPT_DATA_BLOCKTRADE` | 报表名+columns | `TRADE_DATE,SECURITY_CODE,SECURITY_NAME_ABBR,CLOSE_PRICE,DEAL_PRICE,PREMIUM_RATIO,DEAL_VOLUME,DEAL_AMT,BUYER_NAME,SELLER_NAME` | 请求列+filter | `(SECURITY_CODE="<code>")(TRADE_DATE>='start')(TRADE_DATE<='end')` | 个股 + 日期窗口+sortColumns / sortTypes | `TRADE_DATE` / `-1` | 按日期降序+pageNumber / pageSize | `1` / `200` | 单页上限 200 条+source / client | `WEB` / `WEB` | 来源标识++<br>++**返回字段**(源字段 → 输出键)++源字段 | 输出键 | 类型 | 描述+---- | ---- | ---- | ----+TRADE_DATE | trade_date | str | 成交日+SECURITY_NAME_ABBR | name | str | 简称+CLOSE_PRICE | close_price | float | 当日收盘价+DEAL_PRICE | deal_price | float | 大宗成交价+PREMIUM_RATIO | premium_ratio | float | 相对收盘折溢价率+DEAL_VOLUME | deal_volume | float | 成交量+DEAL_AMT | deal_amount | float | 成交额+BUYER_NAME | buyer_seat | str | 买方营业部+SELLER_NAME | seller_seat | str | 卖方营业部++信封:`{"ok": true, "market": "china_a", "source": "eastmoney", "data": {"code","days","count","records":[...]}}`。++<br>++**调用范例**++```python+from src.tools.block_trades_tool import BlockTradesTool++print(BlockTradesTool().execute(code="600519.SH", days=30))+```diff --git "a/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\350\202\241\344\270\234\346\210\267\346\225\260.md" "b/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\350\202\241\344\270\234\346\210\267\346\225\260.md"new file mode 100644index 000000000..0415b32e6--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\350\202\241\344\270\234\346\210\267\346\225\260.md"@@ -0,0 +1,60 @@+## 股东户数(Shareholder Count)++工具:`get_shareholder_count`(`src.tools.shareholder_count_tool.ShareholderCountTool`)+描述:东财 datacenter 报表接口发布的 A 股周期性"股东户数"(注册股东数)披露:各报告期户数、环比变动(绝对值与百分比)、户均持股(股数与市值)。+市场:仅 A 股(.SH / .SZ / .BJ),其他市场返回 error 信封。+限速:经共享 `eastmoney` per-host 节流层;东财按源 IP 限流。++<br>++**端点**++`https://datacenter-web.eastmoney.com/api/data/v1/get`,reportName = `RPT_HOLDERNUMLATEST`,按 `SECUCODE`(带后缀,如 `600519.SH`)过滤。++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+code | str | Y | `<code>.<exchange>` 形式,后缀 SH / SZ / BJ(如 `600519.SH`、`000001.SZ`、`830799.BJ`)。+max_periods | int | N | 返回最近报告期数上限(1–24,默认 24)。++<br>++**端点查询参数**++名称 | 取值 | 描述+---- | ---- | ----+reportName | `RPT_HOLDERNUMLATEST` | 报表名+columns | `SECUCODE,SECURITY_CODE,END_DATE,HOLDER_NUM,HOLDER_NUM_CHANGE,HOLDER_NUM_RATIO,AVG_HOLD_AMT,AVG_HOLD_NUM,TOTAL_MARKET_CAP` | 请求列+filter | `(SECUCODE="<code>")` | 个股过滤+sortColumns / sortTypes | `END_DATE` / `-1` | 按报告期降序+pageNumber / pageSize | `1` / `<max_periods>` | 分页+source / client | `WEB` / `WEB` | 来源标识++<br>++**返回字段**(源字段 → 输出键)++源字段 | 输出键 | 类型 | 描述+---- | ---- | ---- | ----+END_DATE | end_date | str | 报告期(取 `YYYY-MM-DD`)+HOLDER_NUM | holder_count | float | 股东户数+HOLDER_NUM_CHANGE | holder_count_change | float | 户数环比变动(绝对)+HOLDER_NUM_RATIO | holder_count_change_pct | float | 户数环比变动(%)+AVG_HOLD_NUM | avg_hold_shares | float | 户均持股(股)+AVG_HOLD_AMT | avg_hold_amount | float | 户均持股市值+TOTAL_MARKET_CAP | total_market_cap | float | 总市值++end_date 与 holder_count 同时缺失的行被丢弃。信封:`{"ok": true, "market": "CN", "source": "eastmoney", "data": {"code", "periods": [...]}}`(最新在前)。++<br>++**调用范例**++```python+from src.tools.shareholder_count_tool import ShareholderCountTool++print(ShareholderCountTool().execute(code="600519.SH"))+```diff --git "a/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\350\236\215\350\265\204\350\236\215\345\210\270.md" "b/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\350\236\215\350\265\204\350\236\215\345\210\270.md"new file mode 100644index 000000000..97be2c198--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\350\236\215\350\265\204\350\236\215\345\210\270.md"@@ -0,0 +1,60 @@+## 融资融券(Margin Trading / RZRQ)++工具:`get_margin_trading`(`src.tools.margin_trading_tool.MarginTradingTool`)+描述:东财公开 datacenter 暴露交易所发布的个股每日融资融券(融资融券)数据:融资余额、融资买入额、融券余额、RZRQ 合计余额,每个交易日一行。可回答"这只股票杠杆有多高?"。只读、免凭证。+市场:A 股(SH / SZ),融资融券仅覆盖 A 股。+限速:经共享 `eastmoney` per-host 节流层;东财按源 IP 限流。++<br>++**端点**++`https://datacenter-web.eastmoney.com/api/data/v1/get`,reportName = `RPTA_WEB_RZRQ_GGMX`(个股每日融资融券明细),按 `SCODE`(裸代码)过滤。++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+code | str | Y | A 股代码。接受裸六位(`600519`)、带后缀(`600519.SH` / `000001.SZ`)、交易所前缀(`sh600519`)。仅 A 股。+days | int | N | 返回最近 N 个交易日,默认 30,上限 250。++<br>++**端点查询参数**++名称 | 取值 | 描述+---- | ---- | ----+reportName | `RPTA_WEB_RZRQ_GGMX` | 报表名+columns | `ALL` | 返回全列+filter | `(SCODE="<code>")` | 个股过滤+sortColumns / sortTypes | `DATE` / `-1` | 按日期降序+pageNumber / pageSize | `1` / `<days>` | 分页+source | `WEB` | 来源标识++<br>++**返回字段**(源字段 → 输出键)++源字段 | 输出键 | 类型 | 描述+---- | ---- | ---- | ----+DATE | trade_date | str | 交易日(取前 10 位 `YYYY-MM-DD`)+RZYE | financing_balance | float | 融资余额+RZMRE | financing_buy | float | 融资买入额+RZCHE | financing_repay | float | 融资偿还额+RQYE | short_balance | float | 融券余额+RQYL | short_volume | float | 融券余量+RZRQYE | margin_total_balance | float | 融资融券合计余额++信封:`{"ok": true, "market": "a_share", "source": "eastmoney", "data": {"code", "rows": [...]}}`(最新在前)。++<br>++**调用范例**++```python+from src.tools.margin_trading_tool import MarginTradingTool++print(MarginTradingTool().execute(code="600519.SH", days=30))+```diff --git "a/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\351\231\220\345\224\256\350\247\243\347\246\201.md" "b/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\351\231\220\345\224\256\350\247\243\347\246\201.md"new file mode 100644index 000000000..d49196043--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\351\231\220\345\224\256\350\247\243\347\246\201.md"@@ -0,0 +1,67 @@+## 限售解禁(Lockup Expiry / Restricted-Share Unlock)++工具:`get_lockup_expiry`(`src.tools.lockup_expiry_tool.LockupExpiryTool`)+描述:A 股限售股在排定日期解禁;大额临近解禁会因新增可流通供给压制股价。工具返回个股的全历史解禁表,或全市场未来窗口(默认 90 日)的解禁日历。+市场:A 股。+限速:经共享 `eastmoney` per-host 节流层;东财按源 IP 限流。++<br>++**端点**++`https://datacenter-web.eastmoney.com/api/data/v1/get`,reportName = `RPT_LIFT_STOCK`。++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+code | str | N | A 股 6 位代码,可带后缀(`600519` / `600519.SH` / `000001.SZ`)。给定 → 该股全历史解禁表;省略 → 全市场未来 N 日解禁日历。+horizon_days | int | N | 全市场日历的未来窗口天数,clamp 至 [1, 365],默认 90。给定 code 时忽略(返回全历史)。++注:该工具 `repeatable = True`。++<br>++**端点查询参数**++名称 | 取值 | 描述+---- | ---- | ----+reportName | `RPT_LIFT_STOCK` | 报表名+columns | `SECURITY_CODE,SECURITY_NAME_ABBR,FREE_DATE,FREE_SHARES_TYPE,FREE_SHARES,CURRENT_FREE_SHARES,ABLE_FREE_SHARES,LIFT_MARKET_CAP,FREE_RATIO,TOTAL_RATIO` | 请求列+filter | 个股=`(SECURITY_CODE="<code>")`;全市场=`(FREE_DATE>='start')(FREE_DATE<='end')` | 过滤谓词+sortColumns / sortTypes | `FREE_DATE` / 个股 `-1`(最新在前)、全市场 `1`(最近解禁在前) | 排序+pageNumber / pageSize | `1` / `200` | 分页+source / client | `WEB` / `WEB` | 来源标识++<br>++**返回字段**(源字段 → 输出键)++源字段 | 输出键 | 类型 | 描述+---- | ---- | ---- | ----+SECURITY_CODE | code | str | 代码+SECURITY_NAME_ABBR | name | str | 简称+FREE_DATE | free_date | str | 解禁日(取 `YYYY-MM-DD`)+FREE_SHARES_TYPE | share_type | str | 解禁股份类型+FREE_SHARES | free_shares | float | 解禁股数+ABLE_FREE_SHARES | able_free_shares | float | 实际可流通股数+LIFT_MARKET_CAP | lift_market_cap | float | 解禁市值+FREE_RATIO | free_ratio | float | 占流通股比+TOTAL_RATIO | total_ratio | float | 占总股本比++无 code 或 free_date 的行被丢弃;记录上限 200。信封:`{"ok": true, "market": "a_share", "source": "eastmoney", "data": {"scope": "single_code"|"market_calendar", "count", "records":[...], ("code") | ("horizon_days","as_of"), ("truncated")}}`。++<br>++**调用范例**++```python+from src.tools.lockup_expiry_tool import LockupExpiryTool++# 个股全历史解禁+print(LockupExpiryTool().execute(code="600519.SH"))+# 全市场未来 30 日解禁日历+print(LockupExpiryTool().execute(horizon_days=30))+```diff --git "a/agent/src/skills/eastmoney/references/\346\235\277\345\235\227/\350\241\214\344\270\232\346\246\202\345\277\265\346\235\277\345\235\227.md" "b/agent/src/skills/eastmoney/references/\346\235\277\345\235\227/\350\241\214\344\270\232\346\246\202\345\277\265\346\235\277\345\235\227.md"new file mode 100644index 000000000..8edfc31a6--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\346\235\277\345\235\227/\350\241\214\344\270\232\346\246\202\345\277\265\346\235\277\345\235\227.md"@@ -0,0 +1,72 @@+## 行业概念板块(Sector / Concept Boards)++工具:`get_sector_info`(`src.tools.sector_tool.SectorInfoTool`)+描述:东财免费免鉴权板块分类,把 A 股归入行业板块(行业板块)与主题概念板块(概念板块)。两种只读视图:+- **membership** —— 给定个股 `code`,列出它所属的行业/概念板块(push2 `slist` 端点,按 secid 寻址)。+- **ranking** —— `mode="ranking"`,把行业板块本身按盘中涨跌幅排名(push2 `clist` 端点,行业板块全集 `fs=m:90+t:2`)。+市场:membership 覆盖 A 股(.SH / .SZ / .BJ);ranking 为 A 股板块全集。+限速:经共享 `eastmoney` per-host 节流层;东财按源 IP 限流。++<br>++**端点**++| 模式 | 端点 URL |+| ---- | -------- |+| membership | `https://push2.eastmoney.com/api/qt/slist/get` |+| ranking | `https://push2.eastmoney.com/api/qt/clist/get` |++字段选择器:f12=板块/证券代码,f14=名称,f3=涨跌幅,f2=最新价/指数,f104/f105=上涨/下跌成分数(ranking),f140=领涨股(ranking)。++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+mode | str | N | `"membership"`(默认,列个股所属板块,需 `code`)或 `"ranking"`(行业板块按当日涨幅排名,忽略 `code`)。+code | str | membership 必选 | A 股 symbol 带后缀,如 `600519.SH` / `000001.SZ` / `430139.BJ`。+limit | int | N | ranking 时返回 top 板块数(1–100,默认 30);membership 忽略。++<br>++**端点查询参数**++membership(slist):`secid=<secid>`、`spt=3`、`pi=0`、`pz=100`、`fields=f12,f13,f14,f3,f2`、`fltt=2`、`po=1`。+ranking(clist):`fs=m:90+t:2`、`fields=f12,f14,f3,f2,f104,f105,f128,f140`、`pn=1`、`pz=<limit>`、`po=1`、`fid=f3`、`fltt=2`。++<br>++**返回字段**++membership(每行一个板块):++字段 | 类型 | 描述+---- | ---- | ----+board_code | str | 板块代码(f12)+board_name | str | 板块名称(f14)+change_pct | float | 涨跌幅(f3)+price | float | 最新价(f2)++ranking(每行一个行业板块):++字段 | 类型 | 描述+---- | ---- | ----+board_code / board_name | str | 板块代码 / 名称+change_pct | float | 涨跌幅(f3)+index | float | 板块指数(f2)+up_count / down_count | float | 上涨 / 下跌成分数(f104 / f105)+leader | str | 领涨股(f140;`-` → None)++信封:`{"ok": true, "market": "stock", "source": "eastmoney", "mode": <mode>, "data": {...}}`。`-`/空映射为 None。++<br>++**调用范例**++```python+from src.tools.sector_tool import SectorInfoTool++print(SectorInfoTool().execute(code="600519.SH")) # membership+print(SectorInfoTool().execute(mode="ranking", limit=20)) # 行业板块涨幅榜+```diff --git "a/agent/src/skills/eastmoney/references/\347\240\224\346\212\245\350\210\206\346\203\205/\345\210\270\345\225\206\347\240\224\346\212\245.md" "b/agent/src/skills/eastmoney/references/\347\240\224\346\212\245\350\210\206\346\203\205/\345\210\270\345\225\206\347\240\224\346\212\245.md"new file mode 100644index 000000000..a28a79616--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\347\240\224\346\212\245\350\210\206\346\203\205/\345\210\270\345\225\206\347\240\224\346\212\245.md"@@ -0,0 +1,68 @@+## 券商研报 + 一致预期 EPS(Research Reports)++工具:`get_research_reports`(`src.tools.research_reports_tool.ResearchReportsTool`)+描述:两路免费免鉴权披露拼成一个信封:+- **东财 reportapi** —— A 股滚动券商研报列表:标题、发布机构、分析师、发布日、机构评级标签、该机构的分年度 EPS / PE 预测。主源,驱动 `reports` 块。+- **同花顺(THS, `basic.10jqka.com.cn`)** —— 市场*一致预期* EPS(分析师估计均值),按前瞻财年。THS 拒绝裸 requests UA,故调用带桌面 UA + Referer,走独立 `ths` host bucket 节流。该块为 best-effort:THS 失败时 `consensus_eps` 降级为空列表,不中断研报抓取。+市场:仅 A 股(.SH / .SZ / .BJ)。+限速:东财经 `eastmoney` bucket、THS 经 `ths` bucket,均 per-host 节流。++<br>++**端点**++| 块 | 端点 URL |+| ---- | -------- |+| reports(东财) | `https://reportapi.eastmoney.com/report/list` |+| consensus_eps(THS) | `https://basic.10jqka.com.cn/api/stock/profit_forecast/` |++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+code | str | Y | `<code>.<exchange>`,后缀 SH / SZ / BJ(如 `600519.SH`)。+limit | int | N | 返回最近研报数上限(1–50,默认 20)。++<br>++**端点查询参数**++reportapi:`code=<裸代码>`、`qType=0`(个股研报)、`pageSize=<limit>`、`pageNo=1`。+THS:`code=<裸代码>`;headers 带 `User-Agent`(桌面 UA)+ `Referer: https://basic.10jqka.com.cn/`。++<br>++**返回字段**++reports(源字段 → 输出键):++源字段 | 输出键 | 描述+---- | ---- | ----+title | title | 研报标题+orgSName / orgName | brokerage | 发布机构(简称优先)+researcher | analyst | 分析师+publishDate | publish_date | 发布日(取 `YYYY-MM-DD`)+emRatingName / sRatingName | rating | 机构评级+predictThisYearEps / predictNextYearEps | eps_forecast.this_year / .next_year | 分年度 EPS 预测+predictThisYearPe / predictNextYearPe | pe_forecast.this_year / .next_year | 分年度 PE 预测++consensus_eps(THS,字段名多变,按 alias 探测):++输出键 | 来源 alias | 描述+---- | ---- | ----+fiscal_year | year / fiscal_year / report_year | 前瞻财年+consensus_eps | eps / avg_eps / predict_eps / forecast_eps | 一致预期 EPS(均值)++无 title 且无 publish_date 的研报行被丢弃。信封:`{"ok": true, "market": "CN", "source": "eastmoney+ths", "data": {"code","reports":[...],"consensus_eps":[...]}}`。++<br>++**调用范例**++```python+from src.tools.research_reports_tool import ResearchReportsTool++print(ResearchReportsTool().execute(code="600519.SH", limit=10))+```diff --git "a/agent/src/skills/eastmoney/references/\347\240\224\346\212\245\350\210\206\346\203\205/\350\264\242\347\273\217\346\226\260\351\227\273.md" "b/agent/src/skills/eastmoney/references/\347\240\224\346\212\245\350\210\206\346\203\205/\350\264\242\347\273\217\346\226\260\351\227\273.md"new file mode 100644index 000000000..545cd59e1--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\347\240\224\346\212\245\350\210\206\346\203\205/\350\264\242\347\273\217\346\226\260\351\227\273.md"@@ -0,0 +1,68 @@+## 财经新闻(Stock / Global News)++工具:`get_stock_news`(`src.tools.stock_news_tool.StockNewsTool`)+描述:两路公开免鉴权新闻面封在同一 BaseTool 下:+- **A 股(及一般中国市场财经)头条** —— 东财免费 `search-api` 新闻列表端点。按源 IP 限流,故走 `eastmoney` 节流客户端。+- **美 / 港头条** —— Yahoo Finance 公开 search 端点(`backtest.loaders.yahoo_client.search`,自身 per-host 节流),返回相关标的匹配。+两种 scope:`stock`(默认,单只证券,需 `code`)、`global`(宽口径市场头条,无需 `code`)。+市场:A 股(.SH/.SZ/.BJ → 东财)、美股(.US)/港股(.HK → Yahoo)。+限速:东财经 `eastmoney` bucket、Yahoo 经其 host bucket。++<br>++**端点**++| 上游 | 端点 URL |+| ---- | -------- |+| 东财新闻 | `https://search-api-web.eastmoney.com/search/jsonp` |+| Yahoo search | 经 `backtest.loaders.yahoo_client.search()` |++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+scope | str | N | `"stock"`(默认,单只证券,需 `code`)或 `"global"`(宽口径中国市场财经,默认查询词 `财经`)。+code | str | scope=stock 必选 | symbol,如 `600519.SH` / `AAPL.US` / `00700.HK`。后缀选上游:SH/SZ/BJ → 东财;US/HK → Yahoo。+limit | int | N | 返回头条数上限(1–50,默认 20)。++<br>++**端点查询参数(东财)**++`cb=`、`_=0`、`param=<JSON 字符串>`。其中 `param` 体:`{"uid":"","keyword":<查询词>,"type":["cmsArticleWebOld"],"client":"web","clientType":"web","param":{"cmsArticleWebOld":{"searchScope":"default","sort":"default","pageIndex":1,"pageSize":<limit>}}}`。响应可能为 JSONP(`callback(...)`),工具自动剥壳。++<br>++**返回字段**++东财文章(`result.cmsArticleWebOld[]`,源字段 → 输出键):++源字段 | 输出键 | 描述+---- | ---- | ----+title | title | 标题+url | url | 链接+mediaName | source | 媒体名+date | published | 发布时间+content | snippet | 正文(裁剪至 280 字符)++Yahoo 匹配(相关标的):++字段 | 描述+---- | ----+title | shortname/longname/symbol 之一+symbol / exchange / quote_type | 标的代码 / 交易所 / 类型++信封:`{"ok": true, "market": <market>, "source": "eastmoney"|"yahoo", "data": {"scope", ("code"), "articles":[...]}}`。market 为 `a_share`/`us`/`hk`/`global`。++<br>++**调用范例**++```python+from src.tools.stock_news_tool import StockNewsTool++print(StockNewsTool().execute(code="600519.SH", scope="stock", limit=10))+print(StockNewsTool().execute(scope="global", limit=15))+```diff --git "a/agent/src/skills/eastmoney/references/\350\264\242\345\212\241\346\212\245\350\241\250/\344\270\211\345\244\247\346\212\245\350\241\250\344\270\216\344\270\273\350\246\201\346\214\207\346\240\207.md" "b/agent/src/skills/eastmoney/references/\350\264\242\345\212\241\346\212\245\350\241\250/\344\270\211\345\244\247\346\212\245\350\241\250\344\270\216\344\270\273\350\246\201\346\214\207\346\240\207.md"new file mode 100644index 000000000..b2252de8c--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\350\264\242\345\212\241\346\212\245\350\241\250/\344\270\211\345\244\247\346\212\245\350\241\250\344\270\216\344\270\273\350\246\201\346\214\207\346\240\207.md"@@ -0,0 +1,69 @@+## 三大报表与主要指标(Financial Statements + GMAININDICATOR)++工具:`get_financial_statements`(`src.tools.financial_statements_tool.FinancialStatementsTool`)+描述:取单只股票的资产负债表 / 利润表 / 现金流量表 / 主要指标,按 symbol 后缀选上游:+- **美股(.US)与港股(.HK)** —— 东财 datacenter 报表接口;三大报表来自分市场财报数据集,`indicators` 读主要指标数据集(GMAININDICATOR)。+- **A 股(.SH / .SZ / .BJ)** —— 新浪 `quotes.sina.cn` 公司财务 openapi(`sina` host bucket 节流)。+报表以"最新在前"的扁平逐期行返回。+市场:美股/港股(东财)、A 股(新浪)。+限速:东财经 `eastmoney`、新浪经 `sina`,均 per-host 节流。++<br>++**端点**++| 市场 | 端点 |+| ---- | ---- |+| 美股/港股 | `https://datacenter.eastmoney.com/securities/api/data/v1/get` |+| A 股 | `https://quotes.sina.cn/cn/api/openapi.php/CompanyFinanceService.<method>` |++**东财 reportName(market_group → statement → reportName)**++statement | us(105/106/107) | hk(116)+---- | ---- | ----+balance | `RPT_USF10_FN_BALANCE` | `RPT_HKF10_FN_BALANCE`+income | `RPT_USF10_FN_INCOME` | `RPT_HKF10_FN_INCOME`+cashflow | `RPT_USF10_FN_CASHFLOW` | `RPT_HKF10_FN_CASHFLOW`+indicators | `RPT_USF10_FN_GMAININDICATOR` | `RPT_HKF10_FN_GMAININDICATOR`++**新浪 method(A 股)**:balance=`getBalanceSheet`、income=`getProfitStatement`、cashflow=`getCashFlow`、indicators=`getFinanceIndex`。++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+code | str | Y | 单只带后缀 symbol,如 `600519.SH` / `000001.SZ` / `AAPL.US` / `00700.HK`。+statement | str | N | `balance` / `income` / `cashflow` / `indicators`(默认 `indicators`)。+period | str | N | `annual`(年报)或 `quarter`(季报),默认 `annual`。++<br>++**端点查询参数**++东财:`reportName=<上表>`、`columns=ALL`、`filter=(SECURITY_CODE="<bare>")(REPORT_TYPE="0"|"1")`(annual=0 / quarter=1)、`sortColumns=REPORT_DATE`、`sortTypes=-1`、`pageNumber=1`、`pageSize=40`、`source=F10`、`client=PC`。+新浪:`symbol=<sh/sz/bj+code>`、`paperType=1`(年)|`2`(季)、`num=40`;headers 带 `Referer: https://quotes.sina.cn/`。++<br>++**返回字段**++报表逐期行为扁平 `字段名 → 值` 的原始 provider 字段(东财用 SECURITY_CODE/REPORT_DATE/REPORT_TYPE 等英文键,新浪用其 openapi 键),工具**不重命名透传**。防爆上限:每只股票最多 40 期,每期最多 200 个字段。++信封:`{"ok": true, "market": "a_share"|"us"|"hk", "source": "sina"|"eastmoney", "statement": <statement>, "period": <period>, "data": {code: {"periods": [...]} | {"error": ...}}}`。单只 symbol 失败以 per-symbol `error` 上报,不抛异常。++<br>++**调用范例**++```python+from src.tools.financial_statements_tool import FinancialStatementsTool++# 美股利润表(年报)+print(FinancialStatementsTool().execute(code="AAPL.US", statement="income", period="annual"))+# 港股主要指标(GMAININDICATOR)+print(FinancialStatementsTool().execute(code="00700.HK", statement="indicators"))+# A 股资产负债表(新浪)+print(FinancialStatementsTool().execute(code="600519.SH", statement="balance"))+```diff --git "a/agent/src/skills/eastmoney/references/\350\265\204\351\207\221\351\235\242/\350\265\204\351\207\221\346\265\201\345\220\221.md" "b/agent/src/skills/eastmoney/references/\350\265\204\351\207\221\351\235\242/\350\265\204\351\207\221\346\265\201\345\220\221.md"new file mode 100644index 000000000..abf050093--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\350\265\204\351\207\221\351\235\242/\350\265\204\351\207\221\346\265\201\345\220\221.md"@@ -0,0 +1,67 @@+## 资金流向(Fund Flow / 主力净流入)++工具:`get_fund_flow`(`src.tools.fund_flow_tool.FundFlowTool`)+描述:东方财富免费免鉴权资金流向序列,把每根 bar 的净流入拆成 主力/超大单/大单/中单/小单 五档("主力/超大单/大单/中单/小单"分解),可取日线历史或当日分钟线。+市场:A 股(.SH / .SZ / .BJ)、港股(.HK)、美股(.US)。+限速:经共享 `eastmoney` per-host 节流层;东财按源 IP 限流。++<br>++**端点**++| 周期 | 端点 URL |+| ---- | -------- |+| daily(日线历史) | `https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get` |+| min(当日分钟) | `https://push2.eastmoney.com/api/qt/stock/fflow/kline/get` |++二者均以 `secid`(`resolve_secid(symbol)` 得到)寻址。++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+codes | list[str] | Y | 带后缀的 symbol 列表,如 `["600519.SH", "00700.HK", "AAPL.US"]`。单个不可解析 symbol 按 per-symbol error 上报,不中断批次。+period | str | N | `"daily"`(默认,日线净流入历史)或 `"min"`(当日分钟线)。+days | int | N | period='daily' 时保留最近 N 根日线(1–250,默认 30);period='min' 忽略。++<br>++**端点查询参数**++名称 | 取值 | 描述+---- | ---- | ----+secid | `<market>.<code>` | 由 symbol 解析+fields1 | `f1,f2,f3,f7` | 请求级 meta 选择器+fields2 | daily=`f51..f65` / min=`f51..f56` | 逐 bar 字段选择器+klt | daily=`101` / min=`1` | 周期代码+lmt | `0` | 不限条数++<br>++**返回字段**++每根 bar 行以逗号拼接,首列为时间戳,其后 5 列依次为五档净流入(单位:人民币元):++字段 | 类型 | 描述+---- | ---- | ----+timestamp | str | daily 为 `YYYY-MM-DD`;min 为 `YYYY-MM-DD HH:MM`+main | float | 主力净流入(主力净额)+small | float | 小单净流入+medium | float | 中单净流入+large | float | 大单净流入+super_large | float | 超大单净流入++信封:`{"ok": true, "market": "stock", "source": "eastmoney", "period": <period>, "buckets": ["main","small","medium","large","super_large"], "data": {symbol: {"symbol","secid","rows":[...]}}}`。++<br>++**调用范例**++```python+from src.tools.fund_flow_tool import FundFlowTool++out = FundFlowTool().execute(codes=["600519.SH"], period="daily", days=30)+print(out) # {"ok": true, ... "data": {"600519.SH": {"rows": [{"timestamp": "...", "main": ...}]}}}+```diff --git "a/agent/src/skills/eastmoney/references/\351\200\211\350\202\241\346\243\200\347\264\242/\344\273\243\347\240\201\346\220\234\347\264\242.md" "b/agent/src/skills/eastmoney/references/\351\200\211\350\202\241\346\243\200\347\264\242/\344\273\243\347\240\201\346\220\234\347\264\242.md"new file mode 100644index 000000000..70b5c4d5c--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\351\200\211\350\202\241\346\243\200\347\264\242/\344\273\243\347\240\201\346\220\234\347\264\242.md"@@ -0,0 +1,60 @@+## 代码搜索(Symbol Search)++工具:`search_symbol`(`src.tools.symbol_search_tool.SymbolSearchTool`)+描述:把公司名/代码片段解析为带市场的候选 symbol(项目代码约定:A 股 `600519.SH`、港股 `00700.HK`、美股 `AAPL.US`,外加 Yahoo 的 crypto/index/FX)。在三路冻结、IP 节流的公开 API 客户端上扇出,归一为统一候选行,按 symbol 去重并裁剪。单源失败不影响其他源——其错误记入 `sources`,存活候选照常返回。+- **东财 suggest** —— 中/英文名与代码,跨 A 股/港股/美股,每条带 `<market>.<code>` 形式的 `QuoteID`。+- **Yahoo v1 search** —— 全球代码/公司名(US、HK、crypto、indices、FX…)。+- **SEC EDGAR company-tickers** —— 为解析出的美股权益代码补 0 填充的 CIK。+市场:多市场。+限速:东财经 `eastmoney` bucket,Yahoo / SEC 各自 host bucket。++<br>++**端点**++| 源 | 端点 |+| ---- | ---- |+| 东财 suggest | `https://searchapi.eastmoney.com/api/suggest/get`(`input=<query>`、`type=14`、`count=25`) |+| Yahoo search | 经 `backtest.loaders.yahoo_client.search()` |+| SEC CIK | 经 `backtest.loaders.sec_edgar_client.cik_for()` |++**东财 market 号 → 后缀**:1→SH,0→SZ(深/北共用 0 前缀),116→HK,105/106/107→US。++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+query | str | Y | 公司名或代码片段,如 `apple` / `贵州茅台` / `茅台` / `AAPL` / `00700`。中英文均可。+limit | int | N | 合并后候选数上限(1–25,默认 10)。++<br>++**返回字段**++每个候选行:++字段 | 描述+---- | ----+symbol | 项目约定 symbol(HK 零填充至 5 位)+name | 名称+market | 粗粒度市场:cn / hk / us / global+type | 证券类型(东财 SecurityTypeName / Yahoo quoteType)+exchange | 交易所(Yahoo 候选)+source | 命中源:`eastmoney` / `yahoo`+also_from | 去重时第二个命中源(可选)+cik | 美股权益补充的 SEC CIK(可选)++信封:`{"ok": true, "market": "multi", "source": "symbol_search", "data": {"query","count","candidates":[...],"sources": {<name>: "ok"|<error>}}}`。仅当 query 本身非法时返回 `{"ok": false, "error": ...}`。++<br>++**调用范例**++```python+from src.tools.symbol_search_tool import SymbolSearchTool++print(SymbolSearchTool().execute(query="apple", limit=5))+print(SymbolSearchTool().execute(query="茅台"))+```diff --git "a/agent/src/skills/eastmoney/references/\351\200\211\350\202\241\346\243\200\347\264\242/\345\205\250\345\270\202\345\234\272\351\200\211\350\202\241.md" "b/agent/src/skills/eastmoney/references/\351\200\211\350\202\241\346\243\200\347\264\242/\345\205\250\345\270\202\345\234\272\351\200\211\350\202\241.md"new file mode 100644index 000000000..842e521c8--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\351\200\211\350\202\241\346\243\200\347\264\242/\345\205\250\345\270\202\345\234\272\351\200\211\350\202\241.md"@@ -0,0 +1,65 @@+## 全市场选股(Market Screener)++工具:`screen_market`(`src.tools.market_screener_tool.MarketScreenerTool`)+描述:东财免费免鉴权全市场行情列表(push2 `clist`)。给定市场全集选择器(`fs`),每只上市标的返回一行:最新价 + 常用排名指标(涨跌幅、成交量、成交额、换手率),并由服务端按所选字段(`fid`)预排序。用于回答"今天最大的涨跌/最活跃名单",无需逐 symbol 抓取。+市场:A 股、美股、港股。+限速:经共享 `eastmoney` per-host 节流层;东财按源 IP 限流。结果有上限,全市场列表不会撑爆上下文。++<br>++**端点**++`https://push2.eastmoney.com/api/qt/clist/get`++**市场全集选择器(fs)**++market | fs+---- | ----+a(A 股,SH/SZ/主板+创业板+北交所) | `m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048`+us(NASDAQ/NYSE/AMEX) | `m:105,m:106,m:107`+hk(主板 + 创业板等) | `m:116,m:113,m:114,m:115,m:128`++**排序字段(sort_by → fid)**:change_pct=`f3`、volume=`f5`、amount=`f6`、turnover=`f8`。++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+market | str | Y | `a`(A 股)/ `us`(美股)/ `hk`(港股)。+sort_by | str | N | `change_pct`(涨跌幅,默认)/ `volume`(成交量)/ `amount`(成交额)/ `turnover`(换手率),降序。+top_n | int | N | 返回 top N(1–100,默认 30)。++<br>++**端点查询参数**++`pn=1`、`pz=<top_n>`、`po=1`(降序)、`fid=<排序字段>`、`fs=<市场全集>`、`fields=f2,f3,f4,f5,f6,f8,f12,f14`。++<br>++**返回字段**(field id → 输出键)++field id | 输出键 | 描述+---- | ---- | ----+f12 | code | 代码+f14 | name | 名称+f2 | price | 最新价+f3 | change_pct | 涨跌幅+f4 | change | 涨跌额+f5 | volume | 成交量(手)+f6 | amount | 成交额(货币)+f8 | turnover_rate | 换手率(%)++`-` 等哨兵值映射为 None。信封:`{"ok": true, "market": <market>, "source": "eastmoney", "sort_by": <sort_by>, "data": [...]}`。++<br>++**调用范例**++```python+from src.tools.market_screener_tool import MarketScreenerTool++print(MarketScreenerTool().execute(market="a", sort_by="change_pct", top_n=20))+```diff --git "a/agent/src/skills/eastmoney/references/\351\276\231\350\231\216\346\246\234/\351\276\231\350\231\216\346\246\234.md" "b/agent/src/skills/eastmoney/references/\351\276\231\350\231\216\346\246\234/\351\276\231\350\231\216\346\246\234.md"new file mode 100644index 000000000..d43023067--- /dev/null+++ "b/agent/src/skills/eastmoney/references/\351\276\231\350\231\216\346\246\234/\351\276\231\350\231\216\346\246\234.md"@@ -0,0 +1,82 @@+## 龙虎榜(Dragon-Tiger Board)++工具:`get_dragon_tiger`(`src.tools.dragon_tiger_tool.DragonTigerTool`)+描述:沪深交易所每日发布的"龙虎榜"披露——列出当日触发异动披露的每只 A 股,以及驱动最大买卖的券商席位。东财通过免费免鉴权 `datacenter-web` JSON 接口转发该披露。只读、无 auth。+市场:A 股(SH / SZ)。+限速:经共享 `eastmoney` per-host 节流层;东财按源 IP 限流。++<br>++**端点**++`https://datacenter-web.eastmoney.com/api/data/v1/get`++用两个 reportName:++- `RPT_DAILYBILLBOARD_DETAILS` —— 当日上榜个股明细(appearances)+- `RPT_BILLBOARD_TRADEDETAIL` —— 指定个股的买卖席位明细(seats)++<br>++**输入参数(工具入参)**++名称 | 类型 | 必选 | 描述+---- | ---- | ---- | ----+date | str | Y | 交易日,`YYYY-MM-DD`(如 `2024-01-02`;亦接受紧凑 `20240102`)。+code | str | N | A 股 symbol 或裸代码(`600519.SH` / `600519`)。省略则返回当日全市场上榜列表;给定则附带该个股的买卖席位明细。++<br>++**端点查询参数**++名称 | 取值 | 描述+---- | ---- | ----+reportName | 上述两个之一 | 报表名+columns | `ALL` | 返回全列+filter | `(TRADE_DATE='YYYY-MM-DD')` 可附 `(SECURITY_CODE="<code>")` | 过滤谓词+sortColumns | appearances=`BILLBOARD_NET_AMT` / seats=`NET` | 排序列+sortTypes | `-1` | 降序+pageNumber / pageSize | `1` / `500` | 分页+source / client | `WEB` / `WEB` | 来源标识++<br>++**返回字段**++appearances(每行一只上榜个股,源字段 → 输出键):++源字段 | 输出键 | 描述+---- | ---- | ----+SECURITY_CODE | code | 代码+SECURITY_NAME_ABBR | name | 简称+CLOSE_PRICE | close | 收盘价+CHANGE_RATE | change_pct | 涨跌幅+BILLBOARD_NET_AMT | net_buy | 龙虎榜净买入额+BILLBOARD_BUY_AMT | buy_amount | 龙虎榜买入额+BILLBOARD_SELL_AMT | sell_amount | 龙虎榜卖出额+ACCUM_AMOUNT | turnover | 成交额+EXPLANATION | reason | 上榜原因++seats(给定 code 时,每行一个券商席位):++源字段 | 输出键 | 描述+---- | ---- | ----+OPERATEDEPT_NAME | seat | 营业部名+SIDE | side | 买/卖方向+BUY / SELL / NET | buy / sell / net | 买入 / 卖出 / 净额+RANK | rank | 席位排名++信封:`{"ok": true, "market": "a_share", "source": "eastmoney", "data": {"date","count","appearances":[...], ("code","seats":[...])}}`。appearances 上限 200,seats 上限 30。++<br>++**调用范例**++```python+from src.tools.dragon_tiger_tool import DragonTigerTool++# 当日全市场上榜列表+print(DragonTigerTool().execute(date="2024-01-02"))+# 指定个股 + 买卖席位+print(DragonTigerTool().execute(date="2024-01-02", code="600519.SH"))+```diff --git a/agent/src/skills/eastmoney/scripts/disclosure_example.py b/agent/src/skills/eastmoney/scripts/disclosure_example.pynew file mode 100644index 000000000..67cea4c5e--- /dev/null+++ b/agent/src/skills/eastmoney/scripts/disclosure_example.py@@ -0,0 +1,68 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""龙虎榜 + 大宗交易 + 融资融券披露面研究示例。++运行前提:在 agent/ 目录下执行(导入根为 agent/)。无需 token。+所有请求经东方财富共享 IP 限速层节流(按源 IP 限流)。+"""++import json++from src.tools.block_trades_tool import BlockTradesTool+from src.tools.dragon_tiger_tool import DragonTigerTool+from src.tools.margin_trading_tool import MarginTradingTool+++def dragon_tiger_seats(date: str, code: str) -> None:+ """打印指定个股在某交易日的龙虎榜买卖席位排名。"""+ envelope = json.loads(DragonTigerTool().execute(date=date, code=code))+ if not envelope.get("ok"):+ print(f"龙虎榜获取失败:{envelope.get('error')}")+ return+ seats = envelope["data"].get("seats", [])+ print(f"{code} {date} 龙虎榜席位(前 3):")+ for seat in seats[:3]:+ print(f" {seat['seat']} 净额={seat['net']} 方向={seat['side']}")+++def recent_block_trades(code: str, days: int = 30) -> None:+ """打印近 N 日大宗交易的折溢价与买卖营业部。"""+ envelope = json.loads(BlockTradesTool().execute(code=code, days=days))+ if not envelope.get("ok"):+ print(f"大宗交易获取失败:{envelope.get('error')}")+ return+ records = envelope["data"].get("records", [])+ print(f"{code} 近 {days} 日大宗交易 {len(records)} 笔:")+ for rec in records[:3]:+ print(+ f" {rec['trade_date']} 价={rec['deal_price']} "+ f"折溢价={rec['premium_ratio']} 买方={rec['buyer_seat']}"+ )+++def margin_balance_trend(code: str, days: int = 30) -> None:+ """打印融资余额趋势(最新一日)。"""+ envelope = json.loads(MarginTradingTool().execute(code=code, days=days))+ if not envelope.get("ok"):+ print(f"融资融券获取失败:{envelope.get('error')}")+ return+ rows = envelope["data"].get("rows", [])+ if rows:+ latest = rows[0]+ print(+ f"{code} {latest['trade_date']} 融资余额={latest['financing_balance']} "+ f"融券余额={latest['short_balance']}"+ )+++def main() -> None:+ """主流程:三路披露面交叉验证机构动向。"""+ print("===== Eastmoney 披露面研究(龙虎榜/大宗/两融) =====")+ code = "600519.SH"+ dragon_tiger_seats("2024-01-02", code)+ recent_block_trades(code, days=30)+ margin_balance_trend(code, days=30)+++if __name__ == "__main__":+ main()diff --git a/agent/src/skills/eastmoney/scripts/fund_flow_example.py b/agent/src/skills/eastmoney/scripts/fund_flow_example.pynew file mode 100644index 000000000..44815430e--- /dev/null+++ b/agent/src/skills/eastmoney/scripts/fund_flow_example.py@@ -0,0 +1,59 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""资金流向 + 板块联动研究示例。++运行前提:在 agent/ 目录下执行(导入根为 agent/)。无需 token,+所有请求经东方财富共享 IP 限速层节流。+"""++import json++from src.tools.fund_flow_tool import FundFlowTool+from src.tools.sector_tool import SectorInfoTool+++def study_main_force(code: str, days: int = 30) -> dict | None:+ """读取一只股票近 N 日的主力净流入序列。++ Args:+ code: 带后缀 symbol,如 "600519.SH"。+ days: 保留最近 N 根日线。++ Returns:+ 该 symbol 的资金流向结果 dict,失败返回 None。+ """+ envelope = json.loads(+ FundFlowTool().execute(codes=[code], period="daily", days=days)+ )+ if not envelope.get("ok"):+ print(f"资金流向获取失败:{envelope.get('error')}")+ return None+ result = envelope["data"].get(code)+ rows = result.get("rows", []) if result else []+ print(f"{code} 近 {len(rows)} 日资金流向(最后一行):{rows[-1] if rows else '无'}")+ return result+++def study_sectors(code: str) -> None:+ """列出该股票所属行业/概念板块,并打印今日行业涨幅榜前 5。"""+ membership = json.loads(SectorInfoTool().execute(code=code))+ if membership.get("ok"):+ boards = membership["data"].get("boards", [])+ print(f"{code} 所属板块:{[b['board_name'] for b in boards]}")++ ranking = json.loads(SectorInfoTool().execute(mode="ranking", limit=5))+ if ranking.get("ok"):+ for board in ranking["data"]["boards"]:+ print(f" {board['board_name']}: {board['change_pct']}%")+++def main() -> None:+ """主流程:资金流向 + 板块联动。"""+ print("===== Eastmoney 资金流向 + 板块研究 =====")+ code = "600519.SH"+ study_main_force(code, days=30)+ study_sectors(code)+++if __name__ == "__main__":+ main()diff --git a/agent/src/skills/eastmoney/scripts/fundamentals_example.py b/agent/src/skills/eastmoney/scripts/fundamentals_example.pynew file mode 100644index 000000000..374815855--- /dev/null+++ b/agent/src/skills/eastmoney/scripts/fundamentals_example.py@@ -0,0 +1,66 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""研报舆情 + 美股/港股财报基本面研究示例。++运行前提:在 agent/ 目录下执行(导入根为 agent/)。无需 token。+研报/财报经东方财富(及新浪/同花顺)共享 IP 限速层节流。+"""++import json++from src.tools.financial_statements_tool import FinancialStatementsTool+from src.tools.research_reports_tool import ResearchReportsTool+from src.tools.shareholder_count_tool import ShareholderCountTool+++def broker_consensus(code: str, limit: int = 10) -> None:+ """打印券商研报评级分布与一致预期 EPS。"""+ envelope = json.loads(ResearchReportsTool().execute(code=code, limit=limit))+ if not envelope.get("ok"):+ print(f"研报获取失败:{envelope.get('error')}")+ return+ data = envelope["data"]+ ratings = [r["rating"] for r in data["reports"] if r.get("rating")]+ print(f"{code} 近 {limit} 篇研报评级:{ratings}")+ print(f" 一致预期 EPS:{data.get('consensus_eps')}")+++def us_hk_indicators(code: str) -> None:+ """打印美股/港股主要指标(GMAININDICATOR)的最新报告期。"""+ envelope = json.loads(+ FinancialStatementsTool().execute(+ code=code, statement="indicators", period="annual"+ )+ )+ if not envelope.get("ok"):+ print(f"财报获取失败:{envelope.get('error')}")+ return+ result = envelope["data"].get(code, {})+ periods = result.get("periods", [])+ print(f"{code} 主要指标报告期数:{len(periods)}(来源 {envelope['source']})")+++def holder_trend(code: str) -> None:+ """打印 A 股股东户数环比趋势(最新两期)。"""+ envelope = json.loads(ShareholderCountTool().execute(code=code))+ if not envelope.get("ok"):+ print(f"股东户数获取失败:{envelope.get('error')}")+ return+ for period in envelope["data"]["periods"][:2]:+ print(+ f" {period['end_date']} 户数={period['holder_count']} "+ f"环比={period['holder_count_change_pct']}%"+ )+++def main() -> None:+ """主流程:基本面 + 舆情交叉。"""+ print("===== Eastmoney 基本面 + 研报研究 =====")+ broker_consensus("600519.SH", limit=10)+ holder_trend("600519.SH")+ us_hk_indicators("AAPL.US")+ us_hk_indicators("00700.HK")+++if __name__ == "__main__":+ main()diff --git a/agent/src/skills/eastmoney/scripts/screen_search_example.py b/agent/src/skills/eastmoney/scripts/screen_search_example.pynew file mode 100644index 000000000..2ef265db6--- /dev/null+++ b/agent/src/skills/eastmoney/scripts/screen_search_example.py@@ -0,0 +1,54 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""代码搜索 + 全市场选股研究示例。++运行前提:在 agent/ 目录下执行(导入根为 agent/)。无需 token。+所有请求经东方财富共享 IP 限速层节流(按源 IP 限流)。+"""++import json++from src.tools.market_screener_tool import MarketScreenerTool+from src.tools.symbol_search_tool import SymbolSearchTool+++def resolve_symbol(query: str, limit: int = 5) -> str | None:+ """把名称/片段解析为最佳候选 symbol。++ Args:+ query: 公司名或代码片段,如 "茅台" / "apple"。+ limit: 候选数上限。++ Returns:+ 第一个候选 symbol,无候选返回 None。+ """+ envelope = json.loads(SymbolSearchTool().execute(query=query, limit=limit))+ candidates = envelope.get("data", {}).get("candidates", [])+ print(f"'{query}' 候选:{[c['symbol'] for c in candidates]}")+ return candidates[0]["symbol"] if candidates else None+++def top_movers(market: str, top_n: int = 10) -> None:+ """打印某市场今日涨幅榜前 N。"""+ envelope = json.loads(+ MarketScreenerTool().execute(market=market, sort_by="change_pct", top_n=top_n)+ )+ if not envelope.get("ok"):+ print(f"选股失败:{envelope.get('error')}")+ return+ print(f"{market} 今日涨幅榜:")+ for row in envelope["data"][:5]:+ print(f" {row['code']} {row['name']} {row['change_pct']}%")+++def main() -> None:+ """主流程:先搜代码再看市场动向。"""+ print("===== Eastmoney 代码搜索 + 全市场选股 =====")+ symbol = resolve_symbol("贵州茅台")+ print(f"解析得到:{symbol}")+ top_movers("a", top_n=10)+ top_movers("us", top_n=10)+++if __name__ == "__main__":+ main()diff --git a/agent/src/skills/okx-market/SKILL.md b/agent/src/skills/okx-market/SKILL.mdindex ecf6aceeb..2eb887588 100644--- a/agent/src/skills/okx-market/SKILL.md+++ b/agent/src/skills/okx-market/SKILL.md@@ -46,25 +46,27 @@ print(f"BTC last price: {data['last']} 24h change: {float(data['last'])/float(d- **Timestamp**: millisecond Unix timestamp (for example `1773763200000`)- **Response format**: JSON. `code=0` indicates success, and data is returned in the `data` field+> Link convention: every link to `references/` in this document is written with the **skill-name prefix** (for example `okx-market/references/...`). The `read_file` tool resolves paths rooted at `skills/`, so omitting the prefix makes the read fail. When adding new skill docs, always use the `<skill-name>/references/...` form.+## Python Script Examples-- [Market data retrieval example](scripts/market_data_example.py)-- [Candlestick data retrieval example](scripts/candle_data_example.py)+- [Market data retrieval example](okx-market/scripts/market_data_example.py)+- [Candlestick data retrieval example](okx-market/scripts/candle_data_example.py)## Market Data Endpoint List| ID | Endpoint Path | Title (Detailed Documentation) | Category | Description || ---: | :--- | :--- | :--- | :--- |-| 1 | /market/ticker | [Single Ticker](references/现货行情/单个行情.md) | Spot Market | Retrieve the latest market data for a single trading instrument, including last price, bid/ask, 24h volume, and more |-| 2 | /market/tickers | [Batch Tickers](references/现货行情/批量行情.md) | Spot Market | Retrieve all market data for a given instrument class (`SPOT`/`SWAP`/`FUTURES`/`OPTION`) in batch |-| 3 | /market/candles | [Candlestick Data](references/现货行情/K线数据.md) | Spot Market | Retrieve candlestick (OHLCV) data with multiple supported intervals |-| 4 | /market/trades | [Recent Trades](references/现货行情/最近成交.md) | Spot Market | Retrieve recent trade-level details |-| 5 | /public/instruments | [Instrument List](references/现货行情/交易产品列表.md) | Spot Market | Retrieve metadata for all tradable instruments, including minimum order size and price precision |-| 6 | /market/books | [Order Book Depth](references/现货行情/深度数据.md) | Spot Market | Retrieve bid/ask order book depth data |-| 7 | /public/funding-rate | [Funding Rate](references/合约行情/资金费率.md) | Derivatives Market | Retrieve current and historical funding rates for perpetual contracts |-| 8 | /public/funding-rate-history | [Historical Funding Rate](references/合约行情/历史资金费率.md) | Derivatives Market | Retrieve historical funding-rate data for perpetual contracts |-| 9 | /public/mark-price | [Mark Price](references/合约行情/标记价格.md) | Derivatives Market | Retrieve mark prices for derivatives, used for PnL and liquidation calculations |-| 10 | /public/open-interest | [Open Interest](references/合约行情/持仓量.md) | Derivatives Market | Retrieve open-interest data for derivatives |-| 11 | /public/price-limit | [Price Limit](references/合约行情/限价.md) | Derivatives Market | Retrieve the current maximum and minimum price limits for derivatives |-| 12 | /market/index-tickers | [Index Tickers](references/指数行情/指数行情.md) | Index Market | Retrieve index price market data |-| 13 | /market/index-candles | [Index Candles](references/指数行情/指数K线.md) | Index Market | Retrieve index candlestick data |+| 1 | /market/ticker | [Single Ticker](okx-market/references/现货行情/单个行情.md) | Spot Market | Retrieve the latest market data for a single trading instrument, including last price, bid/ask, 24h volume, and more |+| 2 | /market/tickers | [Batch Tickers](okx-market/references/现货行情/批量行情.md) | Spot Market | Retrieve all market data for a given instrument class (`SPOT`/`SWAP`/`FUTURES`/`OPTION`) in batch |+| 3 | /market/candles | [Candlestick Data](okx-market/references/现货行情/K线数据.md) | Spot Market | Retrieve candlestick (OHLCV) data with multiple supported intervals |+| 4 | /market/trades | [Recent Trades](okx-market/references/现货行情/最近成交.md) | Spot Market | Retrieve recent trade-level details |+| 5 | /public/instruments | [Instrument List](okx-market/references/现货行情/交易产品列表.md) | Spot Market | Retrieve metadata for all tradable instruments, including minimum order size and price precision |+| 6 | /market/books | [Order Book Depth](okx-market/references/现货行情/深度数据.md) | Spot Market | Retrieve bid/ask order book depth data |+| 7 | /public/funding-rate | [Funding Rate](okx-market/references/合约行情/资金费率.md) | Derivatives Market | Retrieve current and historical funding rates for perpetual contracts |+| 8 | /public/funding-rate-history | [Historical Funding Rate](okx-market/references/合约行情/历史资金费率.md) | Derivatives Market | Retrieve historical funding-rate data for perpetual contracts |+| 9 | /public/mark-price | [Mark Price](okx-market/references/合约行情/标记价格.md) | Derivatives Market | Retrieve mark prices for derivatives, used for PnL and liquidation calculations |+| 10 | /public/open-interest | [Open Interest](okx-market/references/合约行情/持仓量.md) | Derivatives Market | Retrieve open-interest data for derivatives |+| 11 | /public/price-limit | [Price Limit](okx-market/references/合约行情/限价.md) | Derivatives Market | Retrieve the current maximum and minimum price limits for derivatives |+| 12 | /market/index-tickers | [Index Tickers](okx-market/references/指数行情/指数行情.md) | Index Market | Retrieve index price market data |+| 13 | /market/index-candles | [Index Candles](okx-market/references/指数行情/指数K线.md) | Index Market | Retrieve index candlestick data |diff --git a/agent/src/skills/sec-edgar/SKILL.md b/agent/src/skills/sec-edgar/SKILL.mdnew file mode 100644index 000000000..6ec1cf626--- /dev/null+++ b/agent/src/skills/sec-edgar/SKILL.md@@ -0,0 +1,71 @@+---+name: sec-edgar+description: U.S. SEC EDGAR fetch interface — resolve a ticker to its CIK, list recent filings (10-K / 10-Q / 8-K and friends) with primary-document URLs, and pull XBRL companyfacts financial series. Free, no API key; rate-limited by IP so every request is throttled and carries a contact User-Agent. United States only.+category: data-source+---+# SEC EDGAR++## Overview++The U.S. Securities and Exchange Commission (SEC) publishes free, no-auth JSON endpoints for every reporting company on its EDGAR system: a ticker-to-CIK directory, a recent-filings index, and the full set of XBRL ("companyfacts") financial concepts a company has reported. This skill documents how Vibe-Trading fetches that data through the bundled `sec_edgar_client` transport and the `get_sec_filings` agent tool.++This is the **fetch** skill — it covers how to get filing-index rows, document URLs, and us-gaap metric series out of EDGAR. The separate `edgar-sec-filings` skill is the **methodology** layer (how to read a 10-K, score insider activity, interpret 8-K items); for any actual data retrieval it delegates here.++Scope is the United States only. EDGAR has no coverage of A-shares, HK, or other non-U.S. markets — route those through `tushare` / `yfinance` / `akshare` instead.++> Link convention: every link below that points into `references/` is written with the **skill-name prefix** (`sec-edgar/references/...`). The `read_file` tool resolves paths with `skills/` as the root; dropping the prefix breaks the read. Keep the `<skill-name>/references/...` form when adding new docs.++## Quick Start++Preferred path — the `get_sec_filings` tool (read-only, throttled, returns strict JSON):++```json+{ "ticker": "AAPL", "form": "10-K", "limit": 5 }+```++```json+{ "ticker": "MSFT", "metric": "Revenues", "limit": 8 }+```++The tool resolves the ticker to a CIK, fetches the filing index (optionally filtered by `form`), and — when `metric` is set — also pulls the XBRL series for that us-gaap concept. See `sec-edgar/references/get_sec_filings_tool.md` for the full parameter and envelope contract.++Script path — call the `sec_edgar_client` transport directly when you need raw JSON the tool does not surface (e.g. company address, all units of a concept):++```python+from backtest.loaders.sec_edgar_client import cik_for, get_submissions, get_company_facts++cik = cik_for("AAPL") # "0000320193", or None if not in the SEC table+submissions = get_submissions(cik) # recent-filings index + company metadata+facts = get_company_facts(cik) # all reported XBRL concepts+```++A runnable end-to-end example lives at `sec-edgar/scripts/sec_filings_example.py`.++## Parameter & Format Notes++- **Ticker**: U.S. equity symbol, case-insensitive (`AAPL`, `msft`). Resolved to a CIK via the SEC company-tickers table; an unlisted ticker returns an error envelope (tool) or `None` (`cik_for`).+- **CIK**: the SEC Central Index Key, normalized to a **zero-padded 10-digit** string (`320193` → `"0000320193"`). The submissions and companyfacts endpoints require the padded form; document URLs use the un-padded form.+- **Form**: SEC form type, case-insensitive (`10-K`, `10-Q`, `8-K`, `DEF 14A`, `4`). Omit to return all recent forms.+- **Metric**: an XBRL `us-gaap` concept name (`Revenues`, `NetIncomeLoss`, `Assets`, `StockholdersEquity`). Case-sensitive — these are exact taxonomy element names.+- **Dates**: SEC returns ISO `YYYY-MM-DD` strings (e.g. `2023-09-30`).+- **Return shape**: the tool returns a JSON-string envelope; the client returns decoded JSON (`dict`).++## Reference Docs++- [sec_edgar_client transport](sec-edgar/references/sec_edgar_client.md) — `cik_for`, `get_submissions`, `get_company_facts`, CIK padding, throttle bucket, contact User-Agent.+- [get_sec_filings tool](sec-edgar/references/get_sec_filings_tool.md) — parameters, success/error envelope, `filings[]` and `metric` field shapes.+- [Endpoints & rate limits](sec-edgar/references/endpoints_and_limits.md) — the three public endpoints, secid/CIK rules, fair-access policy, env overrides.+- [Common forms & XBRL concepts](sec-edgar/references/forms_and_concepts.md) — frequently used form types and us-gaap concept names.++## Scripts++- [End-to-end fetch example](sec-edgar/scripts/sec_filings_example.py) — ticker → CIK → recent 10-Ks → a metric series, using the bundled client.++## Notes++- **Free, no API key**: EDGAR is public. The only requirement is a descriptive `User-Agent` carrying a contact address; the client ships a compliant default and honors the `VIBE_TRADING_SEC_UA` override.+- **Rate-limited by IP**: the SEC throttles per source IP and temporarily blocks clients that burst without a contact UA. Every request routes through the shared `backtest.loaders._http` throttle under the `"sec"` host bucket (≈0.12s spacing floor, overridable via `VIBE_TRADING_SEC_MIN_INTERVAL`). Do not bypass the client with raw `requests` loops.+- **United States only**: a non-U.S. symbol will not resolve to a CIK.+- **Transport, not a backtest loader**: `sec_edgar_client` is a thin REST client, not a `DataLoaderProtocol`. There is no `source: "sec_edgar"` backtest mode — EDGAR feeds the `get_sec_filings` tool, not the bar-loading layer.+- **Reporting lag**: filings appear after the company submits; XBRL companyfacts trail the filing. Insider (Form 4) and 13F latency caveats are covered in the `edgar-sec-filings` methodology skill.+- **Research only**: this data supports research and does not constitute investment advice.diff --git a/agent/src/skills/sec-edgar/references/endpoints_and_limits.md b/agent/src/skills/sec-edgar/references/endpoints_and_limits.mdnew file mode 100644index 000000000..5a5705f6f--- /dev/null+++ b/agent/src/skills/sec-edgar/references/endpoints_and_limits.md@@ -0,0 +1,46 @@+# EDGAR endpoints, identifiers & rate limits++All public, free, no-auth JSON. Source of truth for the URLs and rules the `sec_edgar_client` is built on.++## Endpoints++| Purpose | URL | Keyed by |+|---------|-----|----------|+| Ticker → CIK directory | `https://www.sec.gov/files/company_tickers.json` | — (full table) |+| Filing index (submissions) | `https://data.sec.gov/submissions/CIK{cik}.json` | padded 10-digit CIK |+| XBRL company facts | `https://data.sec.gov/api/xbrl/companyfacts/CIK{cik}.json` | padded 10-digit CIK |++Primary-document URLs are assembled, not fetched as JSON:++```+https://www.sec.gov/Archives/edgar/data/{cik_unpadded}/{accession_no_dashes}/{primary_document}+```++`accession_no_dashes` is the accession number with its hyphens removed (`0000320193-23-000106` → `000032019323000106`).++## Identifiers++- **CIK (Central Index Key)**: the SEC's per-filer numeric id. The submissions and companyfacts endpoints require it **zero-padded to 10 digits** (`320193` → `0000320193`). Document URLs use the **un-padded** form (`320193`).+- **Ticker**: case-insensitive; resolved to a CIK through `company_tickers.json`. A `company_tickers.json` row looks like `{"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."}`.+- **Accession number**: per-filing id, dashed form `0000320193-23-000106`.++## Rate limits & fair access++The SEC rate-limits **by source IP** and asks every client to send a descriptive `User-Agent` that carries a contact address. The documented ceiling is ~10 requests/second; bursting without a contact UA earns a temporary block.++The client therefore:++- routes every request through the shared `backtest.loaders._http` throttle under the `"sec"` host bucket, enforcing a ~0.12s per-request spacing floor;+- sends a compliant contact `User-Agent` by default.++### Environment overrides++| Variable | Effect | Default |+|----------|--------|---------|+| `VIBE_TRADING_SEC_UA` | Replace the contact User-Agent (use your own address) | a Vibe-Trading contact string |+| `VIBE_TRADING_SEC_MIN_INTERVAL` | Raise per-request spacing; never drops below the 0.12s floor | `0.12` |++## Coverage & lag++- **United States only.** EDGAR has no non-U.S. coverage; non-U.S. symbols will not resolve to a CIK.+- Filings appear after submission; XBRL companyfacts trail the filing itself. Reporting-lag nuances for Form 4 (insider) and 13F live in the `edgar-sec-filings` methodology skill.diff --git a/agent/src/skills/sec-edgar/references/forms_and_concepts.md b/agent/src/skills/sec-edgar/references/forms_and_concepts.mdnew file mode 100644index 000000000..f63c7ac9d--- /dev/null+++ b/agent/src/skills/sec-edgar/references/forms_and_concepts.md@@ -0,0 +1,68 @@+# Common SEC forms & XBRL us-gaap concepts++Reference values for the `form` and `metric` parameters of `get_sec_filings`.++## Frequently used form types++Pass to the tool's `form` parameter (case-insensitive).++| Form | What it is | Cadence |+|------|------------|---------|+| `10-K` | Annual report — full-year financials, risk factors, MD&A | Annual |+| `10-Q` | Quarterly report — interim financials and MD&A | Quarterly |+| `8-K` | Current report — material events (M&A, exec change, guidance, restatement) | Event-driven |+| `DEF 14A` | Definitive proxy statement — exec comp, board, shareholder proposals | Annual |+| `4` | Insider transaction (Section 16) — insider buys/sells | Within ~2 business days |+| `13F-HR` | Institutional holdings (>$100M AUM) | Quarterly |+| `SC 13D` | >5% activist/strategic ownership stake | Event-driven |+| `SC 13G` | >5% passive ownership stake | Event-driven |+| `S-1` | Registration statement (IPO) | One-time |+| `424B` | Prospectus | As filed |+| `20-F` | Annual report for foreign private issuers | Annual |+| `6-K` | Foreign-issuer current report | Event-driven |++Omit `form` to return all recent forms newest-first.++## Frequently used us-gaap concepts++Pass to the tool's `metric` parameter. These are **exact, case-sensitive** XBRL taxonomy element names. A company reports only the concepts relevant to it, so a given name may be absent (the tool then returns an empty `points` list).++### Income statement++| Concept | Meaning |+|---------|---------|+| `Revenues` | Total revenue (some filers use `RevenueFromContractWithCustomerExcludingAssessedTax`) |+| `CostOfRevenue` | Cost of revenue / COGS |+| `GrossProfit` | Gross profit |+| `OperatingIncomeLoss` | Operating income |+| `NetIncomeLoss` | Net income |+| `EarningsPerShareBasic` | Basic EPS |+| `EarningsPerShareDiluted` | Diluted EPS |+| `ResearchAndDevelopmentExpense` | R&D expense |++### Balance sheet++| Concept | Meaning |+|---------|---------|+| `Assets` | Total assets |+| `Liabilities` | Total liabilities |+| `StockholdersEquity` | Shareholders' equity |+| `CashAndCashEquivalentsAtCarryingValue` | Cash & equivalents |+| `LongTermDebtNoncurrent` | Long-term debt (noncurrent) |+| `Goodwill` | Goodwill |++### Cash flow++| Concept | Meaning |+|---------|---------|+| `NetCashProvidedByUsedInOperatingActivities` | Operating cash flow |+| `NetCashProvidedByUsedInInvestingActivities` | Investing cash flow |+| `NetCashProvidedByUsedInFinancingActivities` | Financing cash flow |+| `PaymentsToAcquirePropertyPlantAndEquipment` | CapEx |+| `PaymentsForRepurchaseOfCommonStock` | Share buybacks |++## Notes++- Concept naming varies by filer and over time; if `Revenues` returns empty, try `RevenueFromContractWithCustomerExcludingAssessedTax`.+- Each metric point carries `end`, `val`, `fiscal_year`, `fiscal_period`, `form`, `accession`, and `frame`; use `fiscal_period` (`FY`, `Q1`–`Q4`) to separate annual from quarterly observations.+- The tool reports the unit bucket with the most rows (usually `USD` for monetary concepts, `USD/shares` for per-share concepts).diff --git a/agent/src/skills/sec-edgar/references/get_sec_filings_tool.md b/agent/src/skills/sec-edgar/references/get_sec_filings_tool.mdnew file mode 100644index 000000000..44a78b1c4--- /dev/null+++ b/agent/src/skills/sec-edgar/references/get_sec_filings_tool.md@@ -0,0 +1,89 @@+# get_sec_filings — agent tool++Tool name: `get_sec_filings` (class `SecFilingsTool`, module `src.tools.sec_filings_tool`)++Read-only tool that wraps the `sec_edgar_client` transport behind the project's `BaseTool` contract. One call answers two questions: a list of recent filings, and (optionally) the reported XBRL us-gaap series for one financial concept. Auto-discovered via the tool registry; the agent never touches `sec.gov` un-throttled.++Markets: United States only.++## Parameters++| Name | Type | Required | Default | Description |+|------|------|----------|---------|-------------|+| `ticker` | string | yes | — | U.S. equity ticker, case-insensitive (`AAPL`, `msft`). Resolved to a CIK via the SEC company-tickers table. |+| `form` | string | no | all forms | SEC form type filter, case-insensitive (`10-K`, `10-Q`, `8-K`). Omit to return every recent form. |+| `metric` | string | no | — | XBRL `us-gaap` concept name (`Revenues`, `NetIncomeLoss`, `Assets`). When set, the response also carries that concept's reported series. Case-sensitive. |+| `limit` | integer | no | `20` | Max number of most-recent filings and metric points to return. Clamped to `1..40`. |++## Success envelope++```json+{+ "ok": true,+ "market": "US",+ "source": "sec_edgar",+ "data": {+ "ticker": "AAPL",+ "cik": "0000320193",+ "filings": [+ {+ "form": "10-K",+ "accession_number": "0000320193-23-000106",+ "filing_date": "2023-11-03",+ "report_date": "2023-09-30",+ "primary_document": "aapl-20230930.htm",+ "description": "10-K",+ "document_url": "https://www.sec.gov/Archives/edgar/data/320193/000032019323000106/aapl-20230930.htm"+ }+ ],+ "metric": {+ "concept": "Revenues",+ "unit": "USD",+ "label": "Revenues",+ "points": [+ {+ "end": "2023-09-30",+ "val": 383285000000.0,+ "fiscal_year": 2023,+ "fiscal_period": "FY",+ "form": "10-K",+ "accession": "0000320193-23-000106",+ "frame": "CY2023"+ }+ ]+ }+ }+}+```++- `source` is the literal `"sec_edgar"` — it tags the data origin in the envelope; it is **not** a backtest `source` value (EDGAR is not a bar loader).+- `filings` is newest-first (as the SEC returns it), filtered to `form` when given, capped at 40.+- `metric` is present only when the `metric` parameter is supplied. The tool picks the unit bucket with the most rows; `points` is the most-recent `limit` entries. `unit` / `points` are empty when the concept is absent or carries no data.+- `document_url` is `null` when the SEC row lacks an accession number or primary-document filename.++## Error envelope++```json+{ "ok": false, "error": "ticker 'XYZ' not found in the SEC company table (US only)" }+```++Returned for: missing/blank `ticker`; a ticker absent from the SEC table; or any underlying fetch failure (ticker lookup, submissions, or companyfacts). A single failing fetch yields an error envelope rather than raising.++## Examples++```json+{ "ticker": "AAPL", "form": "10-K", "limit": 5 }+```++```json+{ "ticker": "NVDA", "metric": "NetIncomeLoss", "limit": 12 }+```++```json+{ "ticker": "TSLA", "form": "8-K", "limit": 10 }+```++## Notes++- `get_sec_filings` is an agent + CLI tool. For deeper interpretation (reading MD&A, scoring insider/8-K signals), pair it with the `edgar-sec-filings` methodology skill, which delegates here for fetching.+- The tool surfaces a compact subset; for raw fields (company address, every unit of a concept) call the `sec_edgar_client` functions directly.diff --git a/agent/src/skills/sec-edgar/references/sec_edgar_client.md b/agent/src/skills/sec-edgar/references/sec_edgar_client.mdnew file mode 100644index 000000000..d3bb489fc--- /dev/null+++ b/agent/src/skills/sec-edgar/references/sec_edgar_client.md@@ -0,0 +1,65 @@+# sec_edgar_client — SEC EDGAR transport++Module: `backtest.loaders.sec_edgar_client`++A thin, IP-throttled REST client over the SEC's free JSON endpoints. It returns raw decoded JSON for downstream loaders/tools to shape; it is **not** a `DataLoaderProtocol` implementation and is not registered as a backtest `source`. Use it directly only when you need data the `get_sec_filings` tool does not already surface.++## Public functions++### `cik_for(ticker: str) -> Optional[str]`++Resolve a U.S. ticker to its zero-padded 10-digit CIK.++- **Args**: `ticker` — a U.S. equity ticker, case-insensitive (`"AAPL"`, `"msft"`).+- **Returns**: the padded CIK string (`"0000320193"`), or `None` when the ticker is empty or absent from the SEC table.+- **Raises**: `requests.RequestException` if the one-time tickers fetch fails.++The ticker→CIK table is fetched once per process from `company_tickers.json` and memoized (thread-safe). Lookups after the first are in-memory.++```python+from backtest.loaders.sec_edgar_client import cik_for++cik = cik_for("AAPL") # "0000320193"+missing = cik_for("NOT_A_TICKER") # None+```++### `get_submissions(cik: str | int) -> Dict[str, Any]`++Fetch the filing-index ("submissions") document for a CIK.++- **Args**: `cik` — int or string; padded to 10 digits internally (a `"CIK"` prefix or leading zeros are tolerated).+- **Returns**: the decoded submissions document — company metadata plus the recent-filings block at `filings.recent` (parallel arrays: `form`, `accessionNumber`, `filingDate`, `reportDate`, `primaryDocument`, `primaryDocDescription`, ...).+- **Raises**: `ValueError` if `cik` contains no digits; `requests.RequestException` on a non-2xx status or undecodable body.++### `get_company_facts(cik: str | int) -> Dict[str, Any]`++Fetch the XBRL `companyfacts` document for a CIK.++- **Args**: `cik` — int or string; padded internally.+- **Returns**: the decoded companyfacts document. Concepts nest as `facts.us-gaap.<Concept>.units.<Unit>` → a list of points (`{end, val, fy, fp, form, accn, frame?}`).+- **Raises**: `ValueError` if `cik` contains no digits; `requests.RequestException` on a non-2xx status or undecodable body.++## CIK padding++The SEC's submissions and companyfacts endpoints key on the **zero-padded 10-digit** CIK. The client normalizes any input — int, padded string, or `"CIK"`-prefixed — by keeping the digits and left-zero-filling to width 10. Primary-document URLs, by contrast, use the **un-padded** CIK (leading zeros stripped).++| Input | Padded (endpoints) | Un-padded (doc URLs) |+|-------|--------------------|----------------------|+| `320193` | `0000320193` | `320193` |+| `"0000320193"` | `0000320193` | `320193` |+| `"CIK0000320193"` | `0000320193` | `320193` |++## Throttling & User-Agent++Every request goes through `backtest.loaders._http` under the `"sec"` host bucket, enforcing a per-request spacing floor of ~0.12s (well under the SEC's ~10 req/s ceiling). The client also sends a descriptive contact `User-Agent`, which the SEC fair-access policy requires; bursting without one earns a temporary IP block.++Environment overrides:++| Variable | Effect | Default |+|----------|--------|---------|+| `VIBE_TRADING_SEC_UA` | Replace the contact User-Agent with your own address | a Vibe-Trading contact string |+| `VIBE_TRADING_SEC_MIN_INTERVAL` | Raise the per-request spacing (never goes below the 0.12s floor) | `0.12` |++## Error handling++Network/HTTP failures propagate as `requests.RequestException` for the caller to classify (the `get_sec_filings` tool catches these and renders an error envelope). A bad CIK (no digits) raises `ValueError`. A malformed row inside the tickers payload is skipped rather than aborting the whole map.diff --git a/agent/src/skills/sec-edgar/scripts/sec_filings_example.py b/agent/src/skills/sec-edgar/scripts/sec_filings_example.pynew file mode 100644index 000000000..436c9b349--- /dev/null+++ b/agent/src/skills/sec-edgar/scripts/sec_filings_example.py@@ -0,0 +1,161 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""End-to-end SEC EDGAR fetch example.++Resolves a ticker to its CIK, lists recent 10-K filings with their primary+document URLs, and prints a single XBRL us-gaap metric series — all through the+bundled, IP-throttled ``sec_edgar_client`` transport (no API key required).++Run from the ``agent/`` directory so that ``backtest`` resolves on the path::++ python -m src.skills.sec-edgar.scripts.sec_filings_example+ # or+ python src/skills/sec-edgar/scripts/sec_filings_example.py+"""++from typing import Any, Dict, List, Optional++from backtest.loaders.sec_edgar_client import (+ cik_for,+ get_company_facts,+ get_submissions,+)++_DOC_BASE = "https://www.sec.gov/Archives/edgar/data"+++def resolve_cik(ticker: str) -> Optional[str]:+ """Resolve a U.S. ticker to its zero-padded 10-digit CIK.++ Args:+ ticker: A U.S. equity ticker, case-insensitive (e.g. ``"AAPL"``).++ Returns:+ The padded CIK string, or ``None`` when the ticker is not in the SEC+ company table.+ """+ try:+ cik = cik_for(ticker)+ except Exception as exc: # noqa: BLE001 - example: report and continue+ print(f"CIK lookup failed for {ticker}: {exc}")+ return None+ if cik is None:+ print(f"Ticker not found in the SEC table (US only): {ticker}")+ return cik+++def recent_filings(cik: str, form: str, limit: int) -> List[Dict[str, Any]]:+ """List recent filings of one form type for a CIK, newest first.++ Args:+ cik: A padded or un-padded CIK.+ form: SEC form type to keep (e.g. ``"10-K"``), case-insensitive.+ limit: Maximum number of filings to return.++ Returns:+ A list of normalized filing dicts; empty on fetch failure or no match.+ """+ try:+ submissions = get_submissions(cik)+ except Exception as exc: # noqa: BLE001 - example: report and continue+ print(f"submissions fetch failed for CIK {cik}: {exc}")+ return []++ recent = (submissions.get("filings") or {}).get("recent") or {}+ forms = recent.get("form") or []+ accessions = recent.get("accessionNumber") or []+ filing_dates = recent.get("filingDate") or []+ primary_docs = recent.get("primaryDocument") or []++ want = form.strip().upper()+ cik_unpadded = str(cik).lstrip("0") or "0"+ out: List[Dict[str, Any]] = []+ for idx, raw_form in enumerate(forms):+ if str(raw_form).strip().upper() != want:+ continue+ accession = accessions[idx] if idx < len(accessions) else None+ doc = primary_docs[idx] if idx < len(primary_docs) else None+ url = None+ if accession and doc:+ url = f"{_DOC_BASE}/{cik_unpadded}/{str(accession).replace('-', '')}/{doc}"+ out.append(+ {+ "form": str(raw_form).strip(),+ "accession_number": accession,+ "filing_date": filing_dates[idx] if idx < len(filing_dates) else None,+ "document_url": url,+ }+ )+ if len(out) >= limit:+ break+ return out+++def metric_series(cik: str, concept: str, limit: int) -> List[Dict[str, Any]]:+ """Pull the most-recent points of one us-gaap concept for a CIK.++ Args:+ cik: A padded or un-padded CIK.+ concept: An XBRL ``us-gaap`` concept name (e.g. ``"Revenues"``).+ limit: Maximum number of most-recent points to return.++ Returns:+ A list of ``{end, val, fiscal_year, fiscal_period}`` points; empty when+ the concept is absent or the fetch fails.+ """+ try:+ facts = get_company_facts(cik)+ except Exception as exc: # noqa: BLE001 - example: report and continue+ print(f"companyfacts fetch failed for CIK {cik}: {exc}")+ return []++ concept_block = ((facts.get("facts") or {}).get("us-gaap") or {}).get(concept)+ if not isinstance(concept_block, dict):+ print(f"concept not reported: {concept}")+ return []++ units = concept_block.get("units") or {}+ # Pick the unit bucket with the most rows (usually USD for monetary concepts).+ rows: List[Any] = []+ for candidate in units.values():+ if isinstance(candidate, list) and len(candidate) >= len(rows):+ rows = candidate++ points = [+ {+ "end": r.get("end"),+ "val": r.get("val"),+ "fiscal_year": r.get("fy"),+ "fiscal_period": r.get("fp"),+ }+ for r in rows+ if isinstance(r, dict)+ ]+ return points[-limit:] if limit > 0 else points+++def main() -> None:+ """Run the example for a single ticker."""+ ticker = "AAPL"+ print(f"===== SEC EDGAR fetch example: {ticker} =====")++ cik = resolve_cik(ticker)+ if cik is None:+ return+ print(f"CIK: {cik}")++ print("\nRecent 10-K filings:")+ for filing in recent_filings(cik, form="10-K", limit=3):+ print(f" {filing['filing_date']} {filing['accession_number']}")+ print(f" {filing['document_url']}")++ print("\nRevenues (most recent points):")+ for point in metric_series(cik, concept="Revenues", limit=5):+ print(+ f" {point['end']} {point['val']} "+ f"FY{point['fiscal_year']} {point['fiscal_period']}"+ )+++if __name__ == "__main__":+ main()diff --git a/agent/src/skills/tushare/SKILL.md b/agent/src/skills/tushare/SKILL.mdindex 1a7e741a7..752f17f84 100644--- a/agent/src/skills/tushare/SKILL.md+++ b/agent/src/skills/tushare/SKILL.md@@ -47,242 +47,244 @@ print(df)- 股票代码:ts_code 格式(如 000001.SZ, 600000.SH)- 返回格式:pandas DataFrame+> 链接约定:本文档内所有指向 `references/` 的链接均以 **技能名前缀** 书写(如 `tushare/references/...`)。`read_file` 工具以 `skills/` 为根解析路径,省略前缀会导致读取失败。新增技能文档时务必沿用 `<技能名>/references/...` 形式。+## python脚本示例-- [股票数据获取示例](scripts/stock_data_example.py)-- [基金数据获取示例](scripts/fund_data_example.py)+- [股票数据获取示例](tushare/scripts/stock_data_example.py)+- [基金数据获取示例](tushare/scripts/fund_data_example.py)## 数据接口列表| ID | 接口名 | 标题(详细文档) | 分类 | 描述 || ----: | :------------------- | :--------------------------------------------------------------------------------------------------------- | :---------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| 416 | rt_min | [ETF实时分钟](references/ETF专题/ETF实时分钟.md) | ETF专题 | 获取ETF实时分钟数据,包括1~60min |-| 400 | rt_etf_k | [ETF实时日线](references/ETF专题/ETF实时日线.md) | ETF专题 | 获取ETF实时日k线行情,支持按ETF代码或代码通配符一次性提取全部ETF实时日k线行情 |-| 387 | stk_mins | [ETF历史分钟](references/ETF专题/ETF历史分钟.md) | ETF专题 | 获取ETF分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式 |-| 386 | etf_index | [ETF基准指数](references/ETF专题/ETF基准指数.md) | ETF专题 | 获取ETF基准指数列表信息 |-| 385 | etf_basic | [ETF基本信息](references/ETF专题/ETF基本信息.md) | ETF专题 | 获取国内ETF基础信息,包括了QDII。数据来源与沪深交易所公开披露信息。 |-| 199 | fund_adj | [ETF复权因子](references/ETF专题/ETF复权因子.md) | ETF专题 | 获取基金复权因子,用于计算基金复权行情 |-| 127 | fund_daily | [ETF日线行情](references/ETF专题/ETF日线行情.md) | ETF专题 | 获取ETF行情每日收盘后成交数据,历史超过10年 |-| 408 | etf_share_size | [ETF份额规模](references/ETF专题/ETF份额规模.md) | ETF专题 | 获取沪深ETF每日份额和规模数据,能体现规模份额的变化,掌握ETF资金动向,同时提供每日净值和收盘价;数据指标是分批入库,建议在每日19点后提取;另外,涉及海外的ETF数据更新会晚一些属于正常情况。 |-| 322 | bc_otcqt | [柜台流通式债券报价](references/债券专题/柜台流通式债券报价.md) | 债券专题 | 柜台流通式债券报价 |-| 305 | cb_rate | [可转债票面利率](references/债券专题/可转债票面利率.md) | 债券专题 | 获取可转债票面利率 |-| 272 | bond_blk_detail | [大宗交易明细](references/债券专题/大宗交易明细.md) | 债券专题 | 获取沪深交易所债券大宗交易数据,可以通过[**数据工具**](https://tushare.pro/webclient/)调试和查看数据。 |-| 271 | bond_blk | [大宗交易](references/债券专题/大宗交易.md) | 债券专题 | 获取沪深交易所债券大宗交易数据,可以通过[**数据工具**](https://tushare.pro/webclient/)调试和查看数据。 |-| 269 | cb_call | [可转债赎回信息](references/债券专题/可转债赎回信息.md) | 债券专题 | 获取可转债到期赎回、强制赎回等信息。数据来源于公开披露渠道,供个人和机构研究使用,请不要用于数据商业目的。 |-| 256 | repo_daily | [债券回购日行情](references/债券专题/债券回购日行情.md) | 债券专题 | 债券回购日行情 |-| 323 | bc_bestotcqt | [柜台流通式债券最优报价](references/债券专题/柜台流通式债券最优报价.md) | 债券专题 | 柜台流通式债券最优报价 |-| 392 | cb_factor_pro | [可转债技术面因子(专业版)](references/债券专题/可转债技术面因子(专业版).md) | 债券专题 | 获取可转债每日技术面因子数据,用于跟踪可转债当前走势情况,数据由Tushare社区自产,覆盖全历史;输出参数_bfq表示不复权,_qfq表示前复权 _hfq表示后复权,描述中说明了因子的默认传参,如需要特殊参数或者更多因子可以联系管理员评估 |-| 246 | cb_price_chg | [可转债转股价变动](references/债券专题/可转债转股价变动.md) | 债券专题 | 获取可转债转股价变动 |-| 233 | eco_cal | [全球财经事件](references/债券专题/全球财经事件.md) | 债券专题 | 获取全球财经日历、包括经济事件数据更新 |-| 201 | yc_cb | [国债收益率曲线](references/债券专题/国债收益率曲线.md) | 债券专题 | 获取中债收益率曲线,目前可获取中债国债收益率曲线即期和到期收益率曲线数据 |-| 187 | cb_daily | [可转债行情](references/债券专题/可转债行情.md) | 债券专题 | 获取可转债行情 |-| 186 | cb_issue | [可转债发行](references/债券专题/可转债发行.md) | 债券专题 | 获取可转债发行数据 |-| 185 | cb_basic | [可转债基础信息](references/债券专题/可转债基础信息.md) | 债券专题 | 获取可转债基本信息 |-| 247 | cb_share | [可转债转股结果](references/债券专题/可转债转股结果.md) | 债券专题 | 获取可转债转股结果 |-| 208 | fund_manager | [基金经理](references/公募基金/基金经理.md) | 公募基金 | 获取公募基金经理数据,包括基金经理简历等数据 |-| 207 | fund_share | [基金规模](references/公募基金/基金规模.md) | 公募基金 | 获取基金规模数据,包含上海和深圳ETF基金 |-| 121 | fund_portfolio | [基金持仓](references/公募基金/基金持仓.md) | 公募基金 | 获取公募基金持仓数据,季度更新 |-| 120 | fund_div | [基金分红](references/公募基金/基金分红.md) | 公募基金 | 获取公募基金分红数据 |-| 119 | fund_nav | [基金净值](references/公募基金/基金净值.md) | 公募基金 | 获取公募基金净值数据 |-| 118 | fund_company | [基金管理人](references/公募基金/基金管理人.md) | 公募基金 | 获取公募基金管理人列表 |-| 19 | fund_basic | [基金列表](references/公募基金/基金列表.md) | 公募基金 | 获取公募基金数据列表,包括场内和场外基金 |-| 359 | fund_factor_pro | [基金技术面因子(专业版)](references/公募基金/基金技术面因子(专业版).md) | 公募基金 | 获取场内基金每日技术面因子数据,用于跟踪场内基金当前走势情况,数据由Tushare社区自产,覆盖全历史;输出参数_bfq表示不复权,描述中说明了因子的默认传参,如需要特殊参数或者更多因子可以联系管理员评估 |-| 178 | fx_obasic | [外汇基础信息(海外)](references/外汇数据/外汇基础信息(海外).md) | 外汇数据 | 获取海外外汇基础信息,目前只有FXCM交易商的数据 |-| 179 | fx_daily | [外汇日线行情](references/外汇数据/外汇日线行情.md) | 外汇数据 | 获取外汇日线行情 |-| 415 | research_report | [券商研究报告](references/大模型语料专题数据/券商研究报告.md) | 大模型语料专题数据 | 获取券商研究报告-个股、行业等,历史数据从20170101开始提供,增量每天两次更新 |-| 143 | news | [新闻快讯(短讯)](references/大模型语料专题数据/新闻快讯(短讯).md) | 大模型语料专题数据 | 获取主流新闻网站的快讯新闻数据,提供超过6年以上历史新闻。 |-| 154 | cctv_news | [新闻联播文字稿](references/大模型语料专题数据/新闻联播文字稿.md) | 大模型语料专题数据 | 获取新闻联播文字稿数据,数据开始于2017年。 |-| 176 | anns_d | [上市公司公告](references/大模型语料专题数据/上市公司公告.md) | 大模型语料专题数据 | 获取全量公告数据,提供pdf下载URL |-| 367 | irm_qa_sz | [深证易互动问答](references/大模型语料专题数据/深证易互动问答.md) | 大模型语料专题数据 | |-| 366 | irm_qa_sh | [上证e互动问答](references/大模型语料专题数据/上证e互动问答.md) | 大模型语料专题数据 | |-| 195 | major_news | [新闻通讯(长篇)](references/大模型语料专题数据/新闻通讯(长篇).md) | 大模型语料专题数据 | 获取长篇通讯信息,覆盖主要新闻资讯网站,提供超过8年历史新闻。 |-| 406 | npr | [国家政策库](references/大模型语料专题数据/国家政策库.md) | 大模型语料专题数据 | 获取国家行政机关公开披露的各类法规、条例政策、批复、通知等文本数据。 |-| 245 | cn_ppi | [工业生产者出厂价格指数(PPI)](references/宏观经济/国内宏观/价格指数/工业生产者出厂价格指数(PPI).md) | 宏观经济,国内宏观,价格指数 | 获取PPI工业生产者出厂价格指数数据 |-| 228 | cn_cpi | [居民消费价格指数(CPI)](references/宏观经济/国内宏观/价格指数/居民消费价格指数(CPI).md) | 宏观经济,国内宏观,价格指数 | 获取CPI居民消费价格数据,包括全国、城市和农村的数据 |-| 149 | shibor | [Shibor利率](references/宏观经济/国内宏观/利率数据/Shibor利率.md) | 宏观经济,国内宏观,利率数据 | shibor利率 |-| 151 | shibor_lpr | [LPR贷款基础利率](references/宏观经济/国内宏观/利率数据/LPR贷款基础利率.md) | 宏观经济,国内宏观,利率数据 | LPR贷款基础利率 |-| 152 | libor | [Libor利率](references/宏观经济/国内宏观/利率数据/Libor利率.md) | 宏观经济,国内宏观,利率数据 | Libor拆借利率 |-| 150 | shibor_quote | [Shibor报价数据](references/宏观经济/国内宏观/利率数据/Shibor报价数据.md) | 宏观经济,国内宏观,利率数据 | Shibor报价数据 |-| 173 | wz_index | [温州民间借贷利率](references/宏观经济/国内宏观/利率数据/温州民间借贷利率.md) | 宏观经济,国内宏观,利率数据 | 温州民间借贷利率,即温州指数 |-| 153 | hibor | [Hibor利率](references/宏观经济/国内宏观/利率数据/Hibor利率.md) | 宏观经济,国内宏观,利率数据 | Hibor利率 |-| 174 | gz_index | [广州民间借贷利率](references/宏观经济/国内宏观/利率数据/广州民间借贷利率.md) | 宏观经济,国内宏观,利率数据 | 广州民间借贷利率 |-| 227 | cn_gdp | [国内生产总值(GDP)](references/宏观经济/国内宏观/国民经济/国内生产总值(GDP).md) | 宏观经济,国内宏观,国民经济 | 获取国民经济之GDP数据 |-| 325 | cn_pmi | [采购经理指数(PMI)](references/宏观经济/国内宏观/景气度/采购经理指数(PMI).md) | 宏观经济,国内宏观,景气度 | 采购经理人指数 |-| 310 | sf_month | [社融增量(月度)](references/宏观经济/国内宏观/金融/社会融资/社融增量(月度).md) | 宏观经济,国内宏观,金融,社会融资 | 获取月度社会融资数据 |-| 242 | cn_m | [货币供应量(月)](references/宏观经济/国内宏观/金融/货币供应量/货币供应量(月).md) | 宏观经济,国内宏观,金融,货币供应量 | 获取货币供应量之月度数据 |-| 221 | us_tbr | [短期国债利率](references/宏观经济/国际宏观/美国利率/短期国债利率.md) | 宏观经济,国际宏观,美国利率 | 获取美国短期国债利率数据 |-| 220 | us_trycr | [国债实际收益率曲线利率](references/宏观经济/国际宏观/美国利率/国债实际收益率曲线利率.md) | 宏观经济,国际宏观,美国利率 | 国债实际收益率曲线利率 |-| 222 | us_tltr | [国债长期利率](references/宏观经济/国际宏观/美国利率/国债长期利率.md) | 宏观经济,国际宏观,美国利率 | 国债长期利率 |-| 223 | us_trltr | [国债长期利率平均值](references/宏观经济/国际宏观/美国利率/国债长期利率平均值.md) | 宏观经济,国际宏观,美国利率 | 国债实际长期利率平均值 |-| 219 | us_tycr | [国债收益率曲线利率](references/宏观经济/国际宏观/美国利率/国债收益率曲线利率.md) | 宏观经济,国际宏观,美国利率 | 获取美国每日国债收益率曲线利率 |-| 420 | rt_idx_min | [指数实时分钟](references/指数专题/指数实时分钟.md) | 指数专题 | 获取交易所指数实时分钟数据,包括1~60min |-| 419 | idx_mins | [指数历史分钟](references/指数专题/指数历史分钟.md) | 指数专题 | 获取交易所指数分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式 |-| 215 | daily_info | [沪深市场每日交易统计](references/指数专题/沪深市场每日交易统计.md) | 指数专题 | 获取交易所股票交易统计,包括各板块明细 |-| 211 | index_global | [国际主要指数](references/指数专题/国际主要指数.md) | 指数专题 | 获取国际主要指数日线行情 |-| 181 | index_classify | [申万行业分类](references/指数专题/申万行业分类.md) | 指数专题 | 获取申万行业分类,可以获取申万2014年版本(28个一级分类,104个二级分类,227个三级分类)和2021年本版(31个一级分类,134个二级分类,346个三级分类)列表信息 |-| 268 | sz_daily_info | [深圳市场每日交易情况](references/指数专题/深圳市场每日交易情况.md) | 指数专题 | 获取深圳市场每日交易概况 |-| 128 | index_dailybasic | [大盘指数每日指标](references/指数专题/大盘指数每日指标.md) | 指数专题 | 目前只提供上证综指,深证成指,上证50,中证500,中小板指,创业板指的每日指标数据 |-| 403 | rt_idx_k | [指数实时日线](references/指数专题/指数实时日线.md) | 指数专题 | 获取交易所指数实时日线行情,支持按代码或代码通配符一次性提取全部交易所指数实时日k线行情 |-| 96 | index_weight | [指数成分和权重](references/指数专题/指数成分和权重.md) | 指数专题 | 获取各类指数成分和权重,**月度数据** ,建议输入参数里开始日期和结束日分别输入当月第一天和最后一天的日期。 |-| 373 | ci_index_member | [中信行业成分](references/指数专题/中信行业成分.md) | 指数专题 | 按三级分类提取中信行业成分,可提供某个分类的所有成分,也可按股票代码提取所属分类,参数灵活 |-| 358 | idx_factor_pro | [指数技术面因子(专业版)](references/指数专题/指数技术面因子(专业版).md) | 指数专题 | 获取指数每日技术面因子数据,用于跟踪指数当前走势情况,数据由Tushare社区自产,覆盖全历史;输出参数_bfq表示不复权描述中说明了因子的默认传参,如需要特殊参数或者更多因子可以联系管理员评估,指数包括大盘指数 申万行业指数 中信指数 |-| 335 | index_member_all | [申万行业成分(分级)](references/指数专题/申万行业成分(分级).md) | 指数专题 | 按三级分类提取申万行业成分,可提供某个分类的所有成分,也可按股票代码提取所属分类,参数灵活 |-| 417 | rt_sw_k | [申万实时行情](references/指数专题/申万实时行情.md) | 指数专题 | 获取申万行业指数的最新截面数据 |-| 172 | index_monthly | [指数月线行情](references/指数专题/指数月线行情.md) | 指数专题 | 获取指数月线行情,每月更新一次 |-| 308 | ci_daily | [中信行业指数日行情](references/指数专题/中信行业指数日行情.md) | 指数专题 | 获取中信行业指数日线行情 |-| 171 | index_weekly | [指数周线行情](references/指数专题/指数周线行情.md) | 指数专题 | 获取指数周线行情 |-| 327 | sw_daily | [申万行业指数日行情](references/指数专题/申万行业指数日行情.md) | 指数专题 | 获取申万行业日线行情(默认是申万2021版行情) |-| 95 | index_daily | [指数日线行情](references/指数专题/指数日线行情.md) | 指数专题 | 获取指数每日行情,还可以通过bar接口获取。由于服务器压力,目前规则是单次调取最多取8000行记录,可以设置start和end日期补全。指数行情也可以通过[**通用行情接口**](https://tushare.pro/document/2?doc_id=109)获取数据. |-| 94 | index_basic | [指数基本信息](references/指数专题/指数基本信息.md) | 指数专题 | 获取指数基础信息。 |-| 341 | opt_mins | [期权分钟行情](references/期权数据/期权分钟行情.md) | 期权数据 | 获取全市场期权合约分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式。 |-| 159 | opt_daily | [期权日线行情](references/期权数据/期权日线行情.md) | 期权数据 | 获取期权日线行情 |-| 158 | opt_basic | [期权合约信息](references/期权数据/期权合约信息.md) | 期权数据 | 获取期权合约信息 |-| 216 | fut_weekly_detail | [期货主要品种交易周报](references/期货数据/期货主要品种交易周报.md) | 期货数据 | 获取期货交易所主要品种每周交易统计信息,数据从2010年3月开始 |-| 368 | ft_limit | [期货合约涨跌停价格](references/期货数据/期货合约涨跌停价格.md) | 期货数据 | 获取所有期货合约每天的涨跌停价格及最低保证金率,数据开始于2005年。 |-| 340 | rt_fut_min | [实时分钟行情](references/期货数据/实时分钟行情.md) | 期货数据 | 获取全市场期货合约实时分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK、 http Restful API和websocket三种方式,如果需要主力合约分钟,请先通过主力[mapping](https://tushare.pro/document/2?doc_id=189)接口获取对应的合约代码后提取分钟。 |-| 135 | fut_basic | [合约信息](references/期货数据/合约信息.md) | 期货数据 | 获取期货合约列表数据 |-| 137 | trade_cal | [交易日历](references/期货数据/交易日历.md) | 期货数据 | 获取各大期货交易所交易日历数据 |-| 138 | fut_daily | [日线行情](references/期货数据/日线行情.md) | 期货数据 | 期货日线行情数据 |-| 139 | fut_holding | [每日持仓排名](references/期货数据/每日持仓排名.md) | 期货数据 | 获取每日成交持仓排名数据 |-| 140 | fut_wsr | [仓单日报](references/期货数据/仓单日报.md) | 期货数据 | 获取仓单日报数据,了解各仓库/厂库的仓单变化 |-| 141 | fut_settle | [每日结算参数](references/期货数据/每日结算参数.md) | 期货数据 | 获取每日结算参数数据,包括交易和交割费率等 |-| 155 | index_daily | [南华期货指数行情](references/期货数据/南华期货指数行情.md) | 期货数据 | 获取南华指数每日行情,指数行情也可以通过[**通用行情接口**](https://tushare.pro/document/2?doc_id=109)获取数据. |-| 189 | fut_mapping | [期货主力与连续合约](references/期货数据/期货主力与连续合约.md) | 期货数据 | 获取期货主力(或连续)合约与月合约映射数据 |-| 313 | ft_mins | [历史分钟行情](references/期货数据/历史分钟行情.md) | 期货数据 | 获取全市场期货合约分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式,如果需要主力合约分钟,请先通过主力[mapping](https://tushare.pro/document/2?doc_id=189)接口获取对应的合约代码后提取分钟。 |-| 337 | fut_weekly_monthly | [期货周月线行情(每日更新)](references/期货数据/期货周月线行情(每日更新).md) | 期货数据 | 期货周/月线行情(每日更新) |-| 391 | hk_cashflow | [港股现金流量表](references/港股数据/港股现金流量表.md) | 港股数据 | 获取港股上市公司现金流量表数据 |-| 390 | hk_balancesheet | [港股资产负债表](references/港股数据/港股资产负债表.md) | 港股数据 | 获取港股上市公司资产负债表 |-| 389 | hk_income | [港股利润表](references/港股数据/港股利润表.md) | 港股数据 | 获取港股上市公司财务利润表数据 |-| 388 | hk_fina_indicator | [港股财务指标数据](references/港股数据/港股财务指标数据.md) | 港股数据 | 获取港股上市公司财务指标数据,为避免服务器压力,现阶段每次请求最多返回200条记录,可通过设置日期多次请求获取更多数据。 |-| 401 | hk_adjfactor | [港股复权因子](references/港股数据/港股复权因子.md) | 港股数据 | 获取港股每日复权因子数据,每天滚动刷新 |-| 339 | hk_daily_adj | [港股复权行情](references/港股数据/港股复权行情.md) | 港股数据 | 获取港股复权行情,提供股票股本、市值和成交及换手多个数据指标 |-| 383 | rt_hk_k | [港股实时日线](references/港股数据/港股实时日线.md) | 港股数据 | 获取港股实时日k线行情,支持按股票代码及股票代码通配符一次性提取全部股票实时日k线行情 |-| 191 | hk_basic | [港股基础信息](references/港股数据/港股基础信息.md) | 港股数据 | 获取港股列表信息 |-| 192 | hk_daily | [港股日线行情](references/港股数据/港股日线行情.md) | 港股数据 | 获取港股每日增量和历史行情,每日18点左右更新当日数据 |-| 304 | hk_mins | [港股分钟行情](references/港股数据/港股分钟行情.md) | 港股数据 | 港股分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式 |-| 250 | hk_tradecal | [港股交易日历](references/港股数据/港股交易日历.md) | 港股数据 | 获取交易日历 |-| 285 | sge_daily | [上海黄金现货日行情](references/现货数据/上海黄金现货日行情.md) | 现货数据 | 获取上海黄金交易所现货合约日线行情 |-| 284 | sge_basic | [上海黄金基础信息](references/现货数据/上海黄金基础信息.md) | 现货数据 | 获取上海黄金交易所现货合约基础信息 |-| 393 | us_fina_indicator | [美股财务指标数据](references/美股数据/美股财务指标数据.md) | 美股数据 | 获取美股上市公司财务指标数据,目前只覆盖主要美股和中概股。为避免服务器压力,现阶段每次请求最多返回200条记录,可通过设置日期多次请求获取更多数据。 |-| 402 | us_adjfactor | [美股复权因子](references/美股数据/美股复权因子.md) | 美股数据 | 获取美股每日复权因子数据,在每天美股收盘后滚动刷新 |-| 396 | us_cashflow | [美股现金流量表](references/美股数据/美股现金流量表.md) | 美股数据 | 获取美股上市公司现金流量表数据(目前只覆盖主要美股和中概股) |-| 395 | us_balancesheet | [美股资产负债表](references/美股数据/美股资产负债表.md) | 美股数据 | 获取美股上市公司资产负债表(目前只覆盖主要美股和中概股) |-| 394 | us_income | [美股利润表](references/美股数据/美股利润表.md) | 美股数据 | 获取美股上市公司财务利润表数据(目前只覆盖主要美股和中概股) |-| 254 | us_daily | [美股日线行情](references/美股数据/美股日线行情.md) | 美股数据 | 获取美股行情(未复权),包括全部股票全历史行情,以及重要的市场和估值指标 |-| 253 | us_tradecal | [美股交易日历](references/美股数据/美股交易日历.md) | 美股数据 | 获取美股交易日历信息 |-| 252 | us_basic | [美股基础信息](references/美股数据/美股基础信息.md) | 美股数据 | 获取美股列表信息 |-| 338 | us_daily_adj | [美股复权行情](references/美股数据/美股复权行情.md) | 美股数据 | 获取美股复权行情,支持美股全市场股票,提供股本、市值、复权因子和成交信息等多个数据指标 |-| 326 | margin_secs | [融资融券标的(盘前)](references/股票数据/两融及转融通/融资融券标的(盘前).md) | 股票数据,两融及转融通 | 获取沪深京三大交易所融资融券标的(包括ETF),每天盘前更新 |-| 331 | slb_len | [转融资交易汇总](references/股票数据/两融及转融通/转融资交易汇总.md) | 股票数据,两融及转融通 | 转融通融资汇总 |-| 332 | slb_sec | [转融券交易汇总(停)](references/股票数据/两融及转融通/转融券交易汇总(停).md) | 股票数据,两融及转融通 | 转融通转融券交易汇总 |-| 333 | slb_sec_detail | [转融券交易明细(停)](references/股票数据/两融及转融通/转融券交易明细(停).md) | 股票数据,两融及转融通 | 转融券交易明细 |-| 59 | margin_detail | [融资融券交易明细](references/股票数据/两融及转融通/融资融券交易明细.md) | 股票数据,两融及转融通 | 获取沪深两市每日融资融券明细 |-| 58 | margin | [融资融券交易汇总](references/股票数据/两融及转融通/融资融券交易汇总.md) | 股票数据,两融及转融通 | 获取融资融券每日交易汇总数据 |-| 334 | slb_len_mm | [做市借券交易汇总(停)](references/股票数据/两融及转融通/做市借券交易汇总(停).md) | 股票数据,两融及转融通 | 做市借券交易汇总 |-| 124 | repurchase | [股票回购](references/股票数据/参考数据/股票回购.md) | 股票数据,参考数据 | 获取上市公司回购股票数据 |-| 110 | pledge_stat | [股权质押统计数据](references/股票数据/参考数据/股权质押统计数据.md) | 股票数据,参考数据 | 获取股票质押统计数据 |-| 160 | share_float | [限售股解禁](references/股票数据/参考数据/限售股解禁.md) | 股票数据,参考数据 | 获取限售股解禁 |-| 161 | block_trade | [大宗交易](references/股票数据/参考数据/大宗交易.md) | 股票数据,参考数据 | 大宗交易 |-| 164 | stk_account | [股票开户数据(停)](references/股票数据/参考数据/股票开户数据(停).md) | 股票数据,参考数据 | 获取股票账户开户数据,统计周期为一周 |-| 165 | stk_account_old | [股票开户数据(旧)](references/股票数据/参考数据/股票开户数据(旧).md) | 股票数据,参考数据 | 获取股票账户开户数据旧版格式数据,数据从2008年1月开始,到2015年5月29,新数据请通过[股票开户数据](https://tushare.pro/document/2?doc_id=164)获取。 |-| 166 | stk_holdernumber | [股东人数](references/股票数据/参考数据/股东人数.md) | 股票数据,参考数据 | 获取上市公司股东户数数据,数据不定期公布 |-| 175 | stk_holdertrade | [股东增减持](references/股票数据/参考数据/股东增减持.md) | 股票数据,参考数据 | 获取上市公司增减持数据,了解重要股东近期及历史上的股份增减变化 |-| 61 | top10_holders | [前十大股东](references/股票数据/参考数据/前十大股东.md) | 股票数据,参考数据 | 获取上市公司前十大股东数据,包括持有数量和比例等信息 |-| 111 | pledge_detail | [股权质押明细数据](references/股票数据/参考数据/股权质押明细数据.md) | 股票数据,参考数据 | 获取股票质押明细数据 |-| 62 | top10_floatholders | [前十大流通股东](references/股票数据/参考数据/前十大流通股东.md) | 股票数据,参考数据 | 获取上市公司前十大流通股东数据 |-| 423 | st | [ST风险警示板股票](references/股票数据/基础数据/ST风险警示板股票.md) | 股票数据,基础数据 | ST风险警示板股票列表 |-| 398 | stock_hsgt | [沪深港通股票列表](references/股票数据/基础数据/沪深港通股票列表.md) | 股票数据,基础数据 | 获取沪深港通股票列表 |-| 397 | stock_st | [ST股票列表](references/股票数据/基础数据/ST股票列表.md) | 股票数据,基础数据 | 获取ST股票列表,可根据交易日期获取历史上每天的ST列表 |-| 375 | bse_mapping | [北交所新旧代码对照](references/股票数据/基础数据/北交所新旧代码对照.md) | 股票数据,基础数据 | 获取北交所股票代码变更后新旧代码映射表数据 |-| 329 | stk_premarket | [每日股本(盘前)](references/股票数据/基础数据/每日股本(盘前).md) | 股票数据,基础数据 | 每日开盘前获取当日股票的股本情况,包括总股本和流通股本,涨跌停价格等。 |-| 123 | new_share | [IPO新股上市](references/股票数据/基础数据/IPO新股上市.md) | 股票数据,基础数据 | 获取新股上市列表数据 |-| 194 | stk_rewards | [管理层薪酬和持股](references/股票数据/基础数据/管理层薪酬和持股.md) | 股票数据,基础数据 | 获取上市公司管理层薪酬和持股 |-| 193 | stk_managers | [上市公司管理层](references/股票数据/基础数据/上市公司管理层.md) | 股票数据,基础数据 | 获取上市公司管理层 |-| 112 | stock_company | [上市公司基本信息](references/股票数据/基础数据/上市公司基本信息.md) | 股票数据,基础数据 | 获取上市公司基础信息,单次提取4500条,可以根据交易所分批提取 |-| 100 | namechange | [股票曾用名](references/股票数据/基础数据/股票曾用名.md) | 股票数据,基础数据 | 历史名称变更记录 |-| 26 | trade_cal | [交易日历](references/股票数据/基础数据/交易日历.md) | 股票数据,基础数据 | 获取各大交易所交易日历数据,默认提取的是上交所 |-| 25 | stock_basic | [股票列表](references/股票数据/基础数据/股票列表.md) | 股票数据,基础数据 | 获取基础信息数据,包括股票代码、名称、上市日期、退市日期等 |-| 262 | bak_basic | [股票历史列表](references/股票数据/基础数据/股票历史列表.md) | 股票数据,基础数据 | 获取备用基础列表,数据从2016年开始 |-| 382 | dc_daily | [东财概念和行业指数行情](references/股票数据/打板专题数据/东财概念和行业指数行情.md) | 股票数据,打板专题数据 | 获取东财概念板块、行业指数板块、地域板块行情数据,历史数据开始于2020年 |-| 321 | dc_hot | [东方财富App热榜](references/股票数据/打板专题数据/东方财富App热榜.md) | 股票数据,打板专题数据 | 获取东方财富App热榜数据,包括A股市场、ETF基金、港股市场、美股市场等等,每日盘中提取4次,收盘后4次,最晚22点提取一次。 |-| 298 | limit_list_d | [涨跌停和炸板数据](references/股票数据/打板专题数据/涨跌停和炸板数据.md) | 股票数据,打板专题数据 | 获取A股每日涨跌停、炸板数据情况,数据从2020年开始(不提供ST股票的统计) |-| 311 | hm_list | [市场游资最全名录](references/股票数据/打板专题数据/市场游资最全名录.md) | 股票数据,打板专题数据 | 获取游资分类名录信息 |-| 347 | kpl_list | [榜单数据(开盘啦)](references/股票数据/打板专题数据/榜单数据(开盘啦).md) | 股票数据,打板专题数据 | 获取开盘啦涨停、跌停、炸板等榜单数据 |-| 261 | ths_member | [同花顺行业概念成分](references/股票数据/打板专题数据/同花顺行业概念成分.md) | 股票数据,打板专题数据 | 获取同花顺概念板块成分列表注:数据版权归属同花顺,如做商业用途,请主动联系同花顺。 |-| 260 | ths_daily | [同花顺概念和行业指数行情](references/股票数据/打板专题数据/同花顺概念和行业指数行情.md) | 股票数据,打板专题数据 | 获取同花顺板块指数行情。注:数据版权归属同花顺,如做商业用途,请主动联系同花顺,如需帮助请联系微信:waditu_a |-| 259 | ths_index | [同花顺行业概念板块](references/股票数据/打板专题数据/同花顺行业概念板块.md) | 股票数据,打板专题数据 | 获取同花顺板块指数。注:数据版权归属同花顺,如做商业用途,请主动联系同花顺,如需帮助请联系微信:waditu_a |-| 107 | top_inst | [龙虎榜机构交易单](references/股票数据/打板专题数据/龙虎榜机构交易单.md) | 股票数据,打板专题数据 | 龙虎榜机构成交明细 |-| 351 | kpl_concept_cons | [题材成分(开盘啦)](references/股票数据/打板专题数据/题材成分(开盘啦).md) | 股票数据,打板专题数据 | 获取开盘啦概念题材的成分股 |-| 355 | limit_list_ths | [同花顺涨跌停榜单](references/股票数据/打板专题数据/同花顺涨跌停榜单.md) | 股票数据,打板专题数据 | 获取同花顺每日涨跌停榜单数据,历史数据从20231101开始提供,增量每天16点左右更新 |-| 356 | limit_step | [涨停股票连板天梯](references/股票数据/打板专题数据/涨停股票连板天梯.md) | 股票数据,打板专题数据 | 获取每天连板个数晋级的股票,可以分析出每天连续涨停进阶个数,判断强势热度 |-| 357 | limit_cpt_list | [涨停最强板块统计](references/股票数据/打板专题数据/涨停最强板块统计.md) | 股票数据,打板专题数据 | 获取每天涨停股票最多最强的概念板块,可以分析强势板块的轮动,判断资金动向 |-| 362 | dc_index | [东方财富概念板块](references/股票数据/打板专题数据/东方财富概念板块.md) | 股票数据,打板专题数据 | 获取东方财富每个交易日的概念板块数据,支持按日期查询 |-| 363 | dc_member | [东方财富概念成分](references/股票数据/打板专题数据/东方财富概念成分.md) | 股票数据,打板专题数据 | 获取东方财富板块每日成分数据,可以根据概念板块代码和交易日期,获取历史成分 |-| 369 | stk_auction | [开盘竞价成交(当日)](references/股票数据/打板专题数据/开盘竞价成交(当日).md) | 股票数据,打板专题数据 | 获取当日个股和ETF的集合竞价成交情况,每天9点25~29分之间可以获取当日的集合竞价成交数据 |-| 376 | tdx_index | [通达信板块信息](references/股票数据/打板专题数据/通达信板块信息.md) | 股票数据,打板专题数据 | 获取通达信板块基础信息,包括概念板块、行业、风格、地域等 |-| 106 | top_list | [龙虎榜每日统计单](references/股票数据/打板专题数据/龙虎榜每日统计单.md) | 股票数据,打板专题数据 | 龙虎榜每日交易明细 |-| 377 | tdx_member | [通达信板块成分](references/股票数据/打板专题数据/通达信板块成分.md) | 股票数据,打板专题数据 | 获取通达信各板块成分股信息 |-| 378 | tdx_daily | [通达信板块行情](references/股票数据/打板专题数据/通达信板块行情.md) | 股票数据,打板专题数据 | 获取通达信各板块行情,包括成交和估值等数据 |-| 312 | hm_detail | [游资交易每日明细](references/股票数据/打板专题数据/游资交易每日明细.md) | 股票数据,打板专题数据 | 获取每日游资交易明细,数据开始于2022年8。游资分类名录,请点击<a href="https://tushare.pro/document/2?doc_id=311">游资名录</a> |-| 320 | ths_hot | [同花顺App热榜数](references/股票数据/打板专题数据/同花顺App热榜数.md) | 股票数据,打板专题数据 | 获取同花顺App热榜数据,包括热股、概念板块、ETF、可转债、港美股等等,每日盘中提取4次,收盘后4次,最晚22点提取一次。 |-| 364 | stk_nineturn | [神奇九转指标](references/股票数据/特色数据/神奇九转指标.md) | 股票数据,特色数据 | 神奇九转(又称“九转序列”)是一种基于技术分析的股票趋势反转指标,其思想来源于技术分析大师汤姆·迪马克(Tom DeMark)的TD序列。该指标的核心功能是通过识别股价在上涨或下跌过程中连续9天的特定走势,来判断股价的潜在反转点,从而帮助投资者提高抄底和逃顶的成功率,日线级别配合60min的九转效果更好,数据从20230101开始。 |-| 188 | hk_hold | [沪深股通持股明细](references/股票数据/特色数据/沪深股通持股明细.md) | 股票数据,特色数据 | 获取沪深港股通持股明细,数据来源港交所。 |-| 267 | broker_recommend | [券商月度金股](references/股票数据/特色数据/券商月度金股.md) | 股票数据,特色数据 | 获取券商月度金股,一般1日~3日内更新当月数据 |-| 274 | ccass_hold_detail | [中央结算系统持股明细](references/股票数据/特色数据/中央结算系统持股明细.md) | 股票数据,特色数据 | 获取中央结算系统机构席位持股明细,数据覆盖**全历史**,根据交易所披露时间,当日数据在下一交易日早上9点前完成 |-| 275 | stk_surv | [机构调研数据](references/股票数据/特色数据/机构调研数据.md) | 股票数据,特色数据 | 获取上市公司机构调研记录数据 |-| 292 | report_rc | [券商盈利预测数据](references/股票数据/特色数据/券商盈利预测数据.md) | 股票数据,特色数据 | 获取券商(卖方)每天研报的盈利预测数据,数据从2010年开始,每晚19~22点更新当日数据 |-| 293 | cyq_perf | [每日筹码及胜率](references/股票数据/特色数据/每日筹码及胜率.md) | 股票数据,特色数据 | 获取A股每日筹码平均成本和胜率情况,每天18~19点左右更新,数据从2018年开始 |-| 294 | cyq_chips | [每日筹码分布](references/股票数据/特色数据/每日筹码分布.md) | 股票数据,特色数据 | 获取A股每日的筹码分布情况,提供各价位占比,数据从2018年开始,每天18~19点之间更新当日数据 |-| 295 | ccass_hold | [中央结算系统持股统计](references/股票数据/特色数据/中央结算系统持股统计.md) | 股票数据,特色数据 | 获取中央结算系统持股汇总数据,覆盖全部历史数据,根据交易所披露时间,当日数据在下一交易日早上9点前完成入库 |-| 353 | stk_auction_o | [股票开盘集合竞价数据](references/股票数据/特色数据/股票开盘集合竞价数据.md) | 股票数据,特色数据 | 股票开盘9:30集合竞价数据,每天盘后更新 |-| 354 | stk_auction_c | [股票收盘集合竞价数据](references/股票数据/特色数据/股票收盘集合竞价数据.md) | 股票数据,特色数据 | 股票收盘15:00集合竞价数据,每天盘后更新 |-| 399 | stk_ah_comparison | [AH股比价](references/股票数据/特色数据/AH股比价.md) | 股票数据,特色数据 | AH股比价数据,可根据交易日期获取历史 |-| 328 | stk_factor_pro | [股票技术面因子(专业版)](references/股票数据/特色数据/股票技术面因子(专业版).md) | 股票数据,特色数据 | 获取股票每日技术面因子数据,用于跟踪股票当前走势情况,数据由Tushare社区自产,覆盖全历史;输出参数_bfq表示不复权,_qfq表示前复权 _hfq表示后复权,描述中说明了因子的默认传参,如需要特殊参数或者更多因子可以联系管理员评估 |-| 27 | daily | [历史日线](references/股票数据/行情数据/历史日线.md) | 股票数据,行情数据 | 获取股票行情数据,或通过[**通用行情接口**](https://tushare.pro/document/2?doc_id=109)获取数据,包含了前后复权数据 |-| 146 | pro_bar | [复权行情](references/股票数据/行情数据/复权行情.md) | 股票数据,行情数据 | |-| 145 | monthly | [月线行情](references/股票数据/行情数据/月线行情.md) | 股票数据,行情数据 | 获取A股月线数据 |-| 374 | rt_min | [实时分钟](references/股票数据/行情数据/实时分钟.md) | 股票数据,行情数据 | 获取全A股票实时分钟数据,包括1~60min |-| 372 | rt_k | [实时日线](references/股票数据/行情数据/实时日线.md) | 股票数据,行情数据 | 获取实时日k线行情,支持按股票代码及股票代码通配符一次性提取全部股票实时日k线行情 |-| 370 | stk_mins | [历史分钟](references/股票数据/行情数据/历史分钟.md) | 股票数据,行情数据 | 获取A股分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式 |-| 365 | stk_week_month_adj | [周月线复权行情(每日更新)](references/股票数据/行情数据/周月线复权行情(每日更新).md) | 股票数据,行情数据 | 股票周/月线行情(复权--每日更新) |-| 336 | stk_weekly_monthly | [周月线行情(每日更新)](references/股票数据/行情数据/周月线行情(每日更新).md) | 股票数据,行情数据 | 股票周/月线行情(每日更新) |-| 255 | bak_daily | [备用行情](references/股票数据/行情数据/备用行情.md) | 股票数据,行情数据 | 获取备用行情,包括特定的行情指标(数据从2017年中左右开始,早期有几天数据缺失,近期正常) |-| 144 | weekly | [周线行情](references/股票数据/行情数据/周线行情.md) | 股票数据,行情数据 | 获取A股周线行情,本接口每周最后一个交易日更新,如需要使用每天更新的周线数据,请使用[日度更新的周线行情接口](https://tushare.pro/document/2?doc_id=336)。 |-| 214 | suspend_d | [每日停复牌信息](references/股票数据/行情数据/每日停复牌信息.md) | 股票数据,行情数据 | 按日期方式获取股票每日停复牌信息 |-| 196 | ggt_daily | [港股通每日成交统计](references/股票数据/行情数据/港股通每日成交统计.md) | 股票数据,行情数据 | 获取港股通每日成交信息,数据从2014年开始 |-| 183 | stk_limit | [每日涨跌停价格](references/股票数据/行情数据/每日涨跌停价格.md) | 股票数据,行情数据 | 获取全市场(包含A/B股和基金)每日涨跌停价格,包括涨停价格,跌停价格等,每个交易日8点40左右更新当日股票涨跌停价格。 |-| 109 | pro_bar | [通用行情接口](references/股票数据/行情数据/通用行情接口.md) | 股票数据,行情数据 | |-| 49 | ggt_top10 | [港股通十大成交股](references/股票数据/行情数据/港股通十大成交股.md) | 股票数据,行情数据 | 获取港股通每日成交数据,其中包括沪市、深市详细数据,每天18~20点之间完成当日更新 |-| 48 | hsgt_top10 | [沪深股通十大成交股](references/股票数据/行情数据/沪深股通十大成交股.md) | 股票数据,行情数据 | 获取沪股通、深股通每日前十大成交详细数据,每天18~20点之间完成当日更新 |-| 32 | daily_basic | [每日指标](references/股票数据/行情数据/每日指标.md) | 股票数据,行情数据 | 获取全部股票每日重要的基本面指标,可用于选股分析、报表展示等。单次请求最大返回6000条数据,可按日线循环提取全部历史。 |-| 28 | adj_factor | [复权因子](references/股票数据/行情数据/复权因子.md) | 股票数据,行情数据 | 本接口由Tushare自行生产,获取股票复权因子,可提取单只股票全部历史复权因子,也可以提取单日全部股票的复权因子。 |-| 197 | ggt_monthly | [港股通每月成交统计](references/股票数据/行情数据/港股通每月成交统计.md) | 股票数据,行情数据 | 港股通每月成交信息,数据从2014年开始 |-| 33 | income | [利润表](references/股票数据/财务数据/利润表.md) | 股票数据,财务数据 | 获取上市公司财务利润表数据 |-| 44 | cashflow | [现金流量表](references/股票数据/财务数据/现金流量表.md) | 股票数据,财务数据 | 获取上市公司现金流量表 |-| 36 | balancesheet | [资产负债表](references/股票数据/财务数据/资产负债表.md) | 股票数据,财务数据 | 获取上市公司资产负债表 |-| 46 | express | [业绩快报](references/股票数据/财务数据/业绩快报.md) | 股票数据,财务数据 | 获取上市公司业绩快报 |-| 79 | fina_indicator | [财务指标数据](references/股票数据/财务数据/财务指标数据.md) | 股票数据,财务数据 | 获取上市公司财务指标数据,为避免服务器压力,现阶段每次请求最多返回100条记录,可通过设置日期多次请求获取更多数据。 |-| 81 | fina_mainbz | [主营业务构成](references/股票数据/财务数据/主营业务构成.md) | 股票数据,财务数据 | 获得上市公司主营业务构成,分地区和产品两种方式 |-| 103 | dividend | [分红送股数据](references/股票数据/财务数据/分红送股数据.md) | 股票数据,财务数据 | 分红送股数据 |-| 162 | disclosure_date | [财报披露日期表](references/股票数据/财务数据/财报披露日期表.md) | 股票数据,财务数据 | 获取财报披露计划日期 |-| 45 | forecast | [业绩预告](references/股票数据/财务数据/业绩预告.md) | 股票数据,财务数据 | 获取业绩预告数据 |-| 80 | fina_audit | [财务审计意见](references/股票数据/财务数据/财务审计意见.md) | 股票数据,财务数据 | 获取上市公司定期财务审计意见数据 |-| 47 | moneyflow_hsgt | [沪深港通资金流向](references/股票数据/资金流向数据/沪深港通资金流向.md) | 股票数据,资金流向数据 | 获取沪股通、深股通、港股通每日资金流向数据,每次最多返回300条记录,总量不限制。 |-| 170 | moneyflow | [个股资金流向](references/股票数据/资金流向数据/个股资金流向.md) | 股票数据,资金流向数据 | 获取沪深A股票资金流向数据,分析大单小单成交情况,用于判别资金动向,数据开始于2010年。 |-| 343 | moneyflow_ind_ths | [行业资金流向(THS)](references/股票数据/资金流向数据/行业资金流向(THS).md) | 股票数据,资金流向数据 | 获取同花顺行业资金流向,每日盘后更新 |-| 344 | moneyflow_ind_dc | [板块资金流向(DC)](references/股票数据/资金流向数据/板块资金流向(DC).md) | 股票数据,资金流向数据 | 获取东方财富板块资金流向,每天盘后更新 |-| 345 | moneyflow_mkt_dc | [大盘资金流向(DC)](references/股票数据/资金流向数据/大盘资金流向(DC).md) | 股票数据,资金流向数据 | 获取东方财富大盘资金流向数据,每日盘后更新 |-| 348 | moneyflow_ths | [个股资金流向(THS)](references/股票数据/资金流向数据/个股资金流向(THS).md) | 股票数据,资金流向数据 | 获取同花顺个股资金流向数据,每日盘后更新 |-| 349 | moneyflow_dc | [个股资金流向(DC)](references/股票数据/资金流向数据/个股资金流向(DC).md) | 股票数据,资金流向数据 | 获取东方财富个股资金流向数据,每日盘后更新,数据开始于20230911 |-| 371 | moneyflow_cnt_ths | [板块资金流向(THS)](references/股票数据/资金流向数据/板块资金流向(THS).md) | 股票数据,资金流向数据 | 获取同花顺概念板块每日资金流向 |-| 156 | film_record | [全国电影剧本备案数据](references/行业经济/TMT行业/全国电影剧本备案数据.md) | 行业经济,TMT行业 | 获取全国电影剧本备案的公示数据 |-| 180 | teleplay_record | [全国电视剧备案公示数据](references/行业经济/TMT行业/全国电视剧备案公示数据.md) | 行业经济,TMT行业 | 获取2009年以来全国拍摄制作电视剧备案公示数据 |-| 87 | tmt_twincomedetail | [台湾电子产业月营收明细](references/行业经济/TMT行业/台湾电子产业月营收明细.md) | 行业经济,TMT行业 | 获取台湾TMT行业上市公司各类产品月度营收情况。 |-| 88 | tmt_twincome | [台湾电子产业月营收](references/行业经济/TMT行业/台湾电子产业月营收.md) | 行业经济,TMT行业 | 获取台湾TMT电子产业领域各类产品月度营收数据。 |-| 113 | bo_monthly | [电影月度票房](references/行业经济/TMT行业/电影月度票房.md) | 行业经济,TMT行业 | 获取电影月度票房数据 |-| 115 | bo_daily | [电影日度票房](references/行业经济/TMT行业/电影日度票房.md) | 行业经济,TMT行业 | 获取电影日度票房 |-| 116 | bo_cinema | [影院日度票房](references/行业经济/TMT行业/影院日度票房.md) | 行业经济,TMT行业 | 获取每日各影院的票房数据 |-| 114 | bo_weekly | [电影周度票房](references/行业经济/TMT行业/电影周度票房.md) | 行业经济,TMT行业 | 获取周度票房数据 |-| 265 | fund_sales_ratio | [各渠道公募基金销售保有规模占比](references/财富管理/基金销售行业数据/各渠道公募基金销售保有规模占比.md) | 财富管理,基金销售行业数据 | 获取各渠道公募基金销售保有规模占比数据,年度更新 |-| 266 | fund_sales_vol | [销售机构公募基金销售保有规模](references/财富管理/基金销售行业数据/销售机构公募基金销售保有规模.md) | 财富管理,基金销售行业数据 | 获取销售机构公募基金销售保有规模数据,本数据从2021年Q1开始公布,季度更新 |+| 416 | rt_min | [ETF实时分钟](tushare/references/ETF专题/ETF实时分钟.md) | ETF专题 | 获取ETF实时分钟数据,包括1~60min |+| 400 | rt_etf_k | [ETF实时日线](tushare/references/ETF专题/ETF实时日线.md) | ETF专题 | 获取ETF实时日k线行情,支持按ETF代码或代码通配符一次性提取全部ETF实时日k线行情 |+| 387 | stk_mins | [ETF历史分钟](tushare/references/ETF专题/ETF历史分钟.md) | ETF专题 | 获取ETF分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式 |+| 386 | etf_index | [ETF基准指数](tushare/references/ETF专题/ETF基准指数.md) | ETF专题 | 获取ETF基准指数列表信息 |+| 385 | etf_basic | [ETF基本信息](tushare/references/ETF专题/ETF基本信息.md) | ETF专题 | 获取国内ETF基础信息,包括了QDII。数据来源与沪深交易所公开披露信息。 |+| 199 | fund_adj | [ETF复权因子](tushare/references/ETF专题/ETF复权因子.md) | ETF专题 | 获取基金复权因子,用于计算基金复权行情 |+| 127 | fund_daily | [ETF日线行情](tushare/references/ETF专题/ETF日线行情.md) | ETF专题 | 获取ETF行情每日收盘后成交数据,历史超过10年 |+| 408 | etf_share_size | [ETF份额规模](tushare/references/ETF专题/ETF份额规模.md) | ETF专题 | 获取沪深ETF每日份额和规模数据,能体现规模份额的变化,掌握ETF资金动向,同时提供每日净值和收盘价;数据指标是分批入库,建议在每日19点后提取;另外,涉及海外的ETF数据更新会晚一些属于正常情况。 |+| 322 | bc_otcqt | [柜台流通式债券报价](tushare/references/债券专题/柜台流通式债券报价.md) | 债券专题 | 柜台流通式债券报价 |+| 305 | cb_rate | [可转债票面利率](tushare/references/债券专题/可转债票面利率.md) | 债券专题 | 获取可转债票面利率 |+| 272 | bond_blk_detail | [大宗交易明细](tushare/references/债券专题/大宗交易明细.md) | 债券专题 | 获取沪深交易所债券大宗交易数据,可以通过[**数据工具**](https://tushare.pro/webclient/)调试和查看数据。 |+| 271 | bond_blk | [大宗交易](tushare/references/债券专题/大宗交易.md) | 债券专题 | 获取沪深交易所债券大宗交易数据,可以通过[**数据工具**](https://tushare.pro/webclient/)调试和查看数据。 |+| 269 | cb_call | [可转债赎回信息](tushare/references/债券专题/可转债赎回信息.md) | 债券专题 | 获取可转债到期赎回、强制赎回等信息。数据来源于公开披露渠道,供个人和机构研究使用,请不要用于数据商业目的。 |+| 256 | repo_daily | [债券回购日行情](tushare/references/债券专题/债券回购日行情.md) | 债券专题 | 债券回购日行情 |+| 323 | bc_bestotcqt | [柜台流通式债券最优报价](tushare/references/债券专题/柜台流通式债券最优报价.md) | 债券专题 | 柜台流通式债券最优报价 |+| 392 | cb_factor_pro | [可转债技术面因子(专业版)](tushare/references/债券专题/可转债技术面因子(专业版).md) | 债券专题 | 获取可转债每日技术面因子数据,用于跟踪可转债当前走势情况,数据由Tushare社区自产,覆盖全历史;输出参数_bfq表示不复权,_qfq表示前复权 _hfq表示后复权,描述中说明了因子的默认传参,如需要特殊参数或者更多因子可以联系管理员评估 |+| 246 | cb_price_chg | [可转债转股价变动](tushare/references/债券专题/可转债转股价变动.md) | 债券专题 | 获取可转债转股价变动 |+| 233 | eco_cal | [全球财经事件](tushare/references/债券专题/全球财经事件.md) | 债券专题 | 获取全球财经日历、包括经济事件数据更新 |+| 201 | yc_cb | [国债收益率曲线](tushare/references/债券专题/国债收益率曲线.md) | 债券专题 | 获取中债收益率曲线,目前可获取中债国债收益率曲线即期和到期收益率曲线数据 |+| 187 | cb_daily | [可转债行情](tushare/references/债券专题/可转债行情.md) | 债券专题 | 获取可转债行情 |+| 186 | cb_issue | [可转债发行](tushare/references/债券专题/可转债发行.md) | 债券专题 | 获取可转债发行数据 |+| 185 | cb_basic | [可转债基础信息](tushare/references/债券专题/可转债基础信息.md) | 债券专题 | 获取可转债基本信息 |+| 247 | cb_share | [可转债转股结果](tushare/references/债券专题/可转债转股结果.md) | 债券专题 | 获取可转债转股结果 |+| 208 | fund_manager | [基金经理](tushare/references/公募基金/基金经理.md) | 公募基金 | 获取公募基金经理数据,包括基金经理简历等数据 |+| 207 | fund_share | [基金规模](tushare/references/公募基金/基金规模.md) | 公募基金 | 获取基金规模数据,包含上海和深圳ETF基金 |+| 121 | fund_portfolio | [基金持仓](tushare/references/公募基金/基金持仓.md) | 公募基金 | 获取公募基金持仓数据,季度更新 |+| 120 | fund_div | [基金分红](tushare/references/公募基金/基金分红.md) | 公募基金 | 获取公募基金分红数据 |+| 119 | fund_nav | [基金净值](tushare/references/公募基金/基金净值.md) | 公募基金 | 获取公募基金净值数据 |+| 118 | fund_company | [基金管理人](tushare/references/公募基金/基金管理人.md) | 公募基金 | 获取公募基金管理人列表 |+| 19 | fund_basic | [基金列表](tushare/references/公募基金/基金列表.md) | 公募基金 | 获取公募基金数据列表,包括场内和场外基金 |+| 359 | fund_factor_pro | [基金技术面因子(专业版)](tushare/references/公募基金/基金技术面因子(专业版).md) | 公募基金 | 获取场内基金每日技术面因子数据,用于跟踪场内基金当前走势情况,数据由Tushare社区自产,覆盖全历史;输出参数_bfq表示不复权,描述中说明了因子的默认传参,如需要特殊参数或者更多因子可以联系管理员评估 |+| 178 | fx_obasic | [外汇基础信息(海外)](tushare/references/外汇数据/外汇基础信息(海外).md) | 外汇数据 | 获取海外外汇基础信息,目前只有FXCM交易商的数据 |+| 179 | fx_daily | [外汇日线行情](tushare/references/外汇数据/外汇日线行情.md) | 外汇数据 | 获取外汇日线行情 |+| 415 | research_report | [券商研究报告](tushare/references/大模型语料专题数据/券商研究报告.md) | 大模型语料专题数据 | 获取券商研究报告-个股、行业等,历史数据从20170101开始提供,增量每天两次更新 |+| 143 | news | [新闻快讯(短讯)](tushare/references/大模型语料专题数据/新闻快讯(短讯).md) | 大模型语料专题数据 | 获取主流新闻网站的快讯新闻数据,提供超过6年以上历史新闻。 |+| 154 | cctv_news | [新闻联播文字稿](tushare/references/大模型语料专题数据/新闻联播文字稿.md) | 大模型语料专题数据 | 获取新闻联播文字稿数据,数据开始于2017年。 |+| 176 | anns_d | [上市公司公告](tushare/references/大模型语料专题数据/上市公司公告.md) | 大模型语料专题数据 | 获取全量公告数据,提供pdf下载URL |+| 367 | irm_qa_sz | [深证易互动问答](tushare/references/大模型语料专题数据/深证易互动问答.md) | 大模型语料专题数据 | |+| 366 | irm_qa_sh | [上证e互动问答](tushare/references/大模型语料专题数据/上证e互动问答.md) | 大模型语料专题数据 | |+| 195 | major_news | [新闻通讯(长篇)](tushare/references/大模型语料专题数据/新闻通讯(长篇).md) | 大模型语料专题数据 | 获取长篇通讯信息,覆盖主要新闻资讯网站,提供超过8年历史新闻。 |+| 406 | npr | [国家政策库](tushare/references/大模型语料专题数据/国家政策库.md) | 大模型语料专题数据 | 获取国家行政机关公开披露的各类法规、条例政策、批复、通知等文本数据。 |+| 245 | cn_ppi | [工业生产者出厂价格指数(PPI)](tushare/references/宏观经济/国内宏观/价格指数/工业生产者出厂价格指数(PPI).md) | 宏观经济,国内宏观,价格指数 | 获取PPI工业生产者出厂价格指数数据 |+| 228 | cn_cpi | [居民消费价格指数(CPI)](tushare/references/宏观经济/国内宏观/价格指数/居民消费价格指数(CPI).md) | 宏观经济,国内宏观,价格指数 | 获取CPI居民消费价格数据,包括全国、城市和农村的数据 |+| 149 | shibor | [Shibor利率](tushare/references/宏观经济/国内宏观/利率数据/Shibor利率.md) | 宏观经济,国内宏观,利率数据 | shibor利率 |+| 151 | shibor_lpr | [LPR贷款基础利率](tushare/references/宏观经济/国内宏观/利率数据/LPR贷款基础利率.md) | 宏观经济,国内宏观,利率数据 | LPR贷款基础利率 |+| 152 | libor | [Libor利率](tushare/references/宏观经济/国内宏观/利率数据/Libor利率.md) | 宏观经济,国内宏观,利率数据 | Libor拆借利率 |+| 150 | shibor_quote | [Shibor报价数据](tushare/references/宏观经济/国内宏观/利率数据/Shibor报价数据.md) | 宏观经济,国内宏观,利率数据 | Shibor报价数据 |+| 173 | wz_index | [温州民间借贷利率](tushare/references/宏观经济/国内宏观/利率数据/温州民间借贷利率.md) | 宏观经济,国内宏观,利率数据 | 温州民间借贷利率,即温州指数 |+| 153 | hibor | [Hibor利率](tushare/references/宏观经济/国内宏观/利率数据/Hibor利率.md) | 宏观经济,国内宏观,利率数据 | Hibor利率 |+| 174 | gz_index | [广州民间借贷利率](tushare/references/宏观经济/国内宏观/利率数据/广州民间借贷利率.md) | 宏观经济,国内宏观,利率数据 | 广州民间借贷利率 |+| 227 | cn_gdp | [国内生产总值(GDP)](tushare/references/宏观经济/国内宏观/国民经济/国内生产总值(GDP).md) | 宏观经济,国内宏观,国民经济 | 获取国民经济之GDP数据 |+| 325 | cn_pmi | [采购经理指数(PMI)](tushare/references/宏观经济/国内宏观/景气度/采购经理指数(PMI).md) | 宏观经济,国内宏观,景气度 | 采购经理人指数 |+| 310 | sf_month | [社融增量(月度)](tushare/references/宏观经济/国内宏观/金融/社会融资/社融增量(月度).md) | 宏观经济,国内宏观,金融,社会融资 | 获取月度社会融资数据 |+| 242 | cn_m | [货币供应量(月)](tushare/references/宏观经济/国内宏观/金融/货币供应量/货币供应量(月).md) | 宏观经济,国内宏观,金融,货币供应量 | 获取货币供应量之月度数据 |+| 221 | us_tbr | [短期国债利率](tushare/references/宏观经济/国际宏观/美国利率/短期国债利率.md) | 宏观经济,国际宏观,美国利率 | 获取美国短期国债利率数据 |+| 220 | us_trycr | [国债实际收益率曲线利率](tushare/references/宏观经济/国际宏观/美国利率/国债实际收益率曲线利率.md) | 宏观经济,国际宏观,美国利率 | 国债实际收益率曲线利率 |+| 222 | us_tltr | [国债长期利率](tushare/references/宏观经济/国际宏观/美国利率/国债长期利率.md) | 宏观经济,国际宏观,美国利率 | 国债长期利率 |+| 223 | us_trltr | [国债长期利率平均值](tushare/references/宏观经济/国际宏观/美国利率/国债长期利率平均值.md) | 宏观经济,国际宏观,美国利率 | 国债实际长期利率平均值 |+| 219 | us_tycr | [国债收益率曲线利率](tushare/references/宏观经济/国际宏观/美国利率/国债收益率曲线利率.md) | 宏观经济,国际宏观,美国利率 | 获取美国每日国债收益率曲线利率 |+| 420 | rt_idx_min | [指数实时分钟](tushare/references/指数专题/指数实时分钟.md) | 指数专题 | 获取交易所指数实时分钟数据,包括1~60min |+| 419 | idx_mins | [指数历史分钟](tushare/references/指数专题/指数历史分钟.md) | 指数专题 | 获取交易所指数分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式 |+| 215 | daily_info | [沪深市场每日交易统计](tushare/references/指数专题/沪深市场每日交易统计.md) | 指数专题 | 获取交易所股票交易统计,包括各板块明细 |+| 211 | index_global | [国际主要指数](tushare/references/指数专题/国际主要指数.md) | 指数专题 | 获取国际主要指数日线行情 |+| 181 | index_classify | [申万行业分类](tushare/references/指数专题/申万行业分类.md) | 指数专题 | 获取申万行业分类,可以获取申万2014年版本(28个一级分类,104个二级分类,227个三级分类)和2021年本版(31个一级分类,134个二级分类,346个三级分类)列表信息 |+| 268 | sz_daily_info | [深圳市场每日交易情况](tushare/references/指数专题/深圳市场每日交易情况.md) | 指数专题 | 获取深圳市场每日交易概况 |+| 128 | index_dailybasic | [大盘指数每日指标](tushare/references/指数专题/大盘指数每日指标.md) | 指数专题 | 目前只提供上证综指,深证成指,上证50,中证500,中小板指,创业板指的每日指标数据 |+| 403 | rt_idx_k | [指数实时日线](tushare/references/指数专题/指数实时日线.md) | 指数专题 | 获取交易所指数实时日线行情,支持按代码或代码通配符一次性提取全部交易所指数实时日k线行情 |+| 96 | index_weight | [指数成分和权重](tushare/references/指数专题/指数成分和权重.md) | 指数专题 | 获取各类指数成分和权重,**月度数据** ,建议输入参数里开始日期和结束日分别输入当月第一天和最后一天的日期。 |+| 373 | ci_index_member | [中信行业成分](tushare/references/指数专题/中信行业成分.md) | 指数专题 | 按三级分类提取中信行业成分,可提供某个分类的所有成分,也可按股票代码提取所属分类,参数灵活 |+| 358 | idx_factor_pro | [指数技术面因子(专业版)](tushare/references/指数专题/指数技术面因子(专业版).md) | 指数专题 | 获取指数每日技术面因子数据,用于跟踪指数当前走势情况,数据由Tushare社区自产,覆盖全历史;输出参数_bfq表示不复权描述中说明了因子的默认传参,如需要特殊参数或者更多因子可以联系管理员评估,指数包括大盘指数 申万行业指数 中信指数 |+| 335 | index_member_all | [申万行业成分(分级)](tushare/references/指数专题/申万行业成分(分级).md) | 指数专题 | 按三级分类提取申万行业成分,可提供某个分类的所有成分,也可按股票代码提取所属分类,参数灵活 |+| 417 | rt_sw_k | [申万实时行情](tushare/references/指数专题/申万实时行情.md) | 指数专题 | 获取申万行业指数的最新截面数据 |+| 172 | index_monthly | [指数月线行情](tushare/references/指数专题/指数月线行情.md) | 指数专题 | 获取指数月线行情,每月更新一次 |+| 308 | ci_daily | [中信行业指数日行情](tushare/references/指数专题/中信行业指数日行情.md) | 指数专题 | 获取中信行业指数日线行情 |+| 171 | index_weekly | [指数周线行情](tushare/references/指数专题/指数周线行情.md) | 指数专题 | 获取指数周线行情 |+| 327 | sw_daily | [申万行业指数日行情](tushare/references/指数专题/申万行业指数日行情.md) | 指数专题 | 获取申万行业日线行情(默认是申万2021版行情) |+| 95 | index_daily | [指数日线行情](tushare/references/指数专题/指数日线行情.md) | 指数专题 | 获取指数每日行情,还可以通过bar接口获取。由于服务器压力,目前规则是单次调取最多取8000行记录,可以设置start和end日期补全。指数行情也可以通过[**通用行情接口**](https://tushare.pro/document/2?doc_id=109)获取数据. |+| 94 | index_basic | [指数基本信息](tushare/references/指数专题/指数基本信息.md) | 指数专题 | 获取指数基础信息。 |+| 341 | opt_mins | [期权分钟行情](tushare/references/期权数据/期权分钟行情.md) | 期权数据 | 获取全市场期权合约分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式。 |+| 159 | opt_daily | [期权日线行情](tushare/references/期权数据/期权日线行情.md) | 期权数据 | 获取期权日线行情 |+| 158 | opt_basic | [期权合约信息](tushare/references/期权数据/期权合约信息.md) | 期权数据 | 获取期权合约信息 |+| 216 | fut_weekly_detail | [期货主要品种交易周报](tushare/references/期货数据/期货主要品种交易周报.md) | 期货数据 | 获取期货交易所主要品种每周交易统计信息,数据从2010年3月开始 |+| 368 | ft_limit | [期货合约涨跌停价格](tushare/references/期货数据/期货合约涨跌停价格.md) | 期货数据 | 获取所有期货合约每天的涨跌停价格及最低保证金率,数据开始于2005年。 |+| 340 | rt_fut_min | [实时分钟行情](tushare/references/期货数据/实时分钟行情.md) | 期货数据 | 获取全市场期货合约实时分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK、 http Restful API和websocket三种方式,如果需要主力合约分钟,请先通过主力[mapping](https://tushare.pro/document/2?doc_id=189)接口获取对应的合约代码后提取分钟。 |+| 135 | fut_basic | [合约信息](tushare/references/期货数据/合约信息.md) | 期货数据 | 获取期货合约列表数据 |+| 137 | trade_cal | [交易日历](tushare/references/期货数据/交易日历.md) | 期货数据 | 获取各大期货交易所交易日历数据 |+| 138 | fut_daily | [日线行情](tushare/references/期货数据/日线行情.md) | 期货数据 | 期货日线行情数据 |+| 139 | fut_holding | [每日持仓排名](tushare/references/期货数据/每日持仓排名.md) | 期货数据 | 获取每日成交持仓排名数据 |+| 140 | fut_wsr | [仓单日报](tushare/references/期货数据/仓单日报.md) | 期货数据 | 获取仓单日报数据,了解各仓库/厂库的仓单变化 |+| 141 | fut_settle | [每日结算参数](tushare/references/期货数据/每日结算参数.md) | 期货数据 | 获取每日结算参数数据,包括交易和交割费率等 |+| 155 | index_daily | [南华期货指数行情](tushare/references/期货数据/南华期货指数行情.md) | 期货数据 | 获取南华指数每日行情,指数行情也可以通过[**通用行情接口**](https://tushare.pro/document/2?doc_id=109)获取数据. |+| 189 | fut_mapping | [期货主力与连续合约](tushare/references/期货数据/期货主力与连续合约.md) | 期货数据 | 获取期货主力(或连续)合约与月合约映射数据 |+| 313 | ft_mins | [历史分钟行情](tushare/references/期货数据/历史分钟行情.md) | 期货数据 | 获取全市场期货合约分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式,如果需要主力合约分钟,请先通过主力[mapping](https://tushare.pro/document/2?doc_id=189)接口获取对应的合约代码后提取分钟。 |+| 337 | fut_weekly_monthly | [期货周月线行情(每日更新)](tushare/references/期货数据/期货周月线行情(每日更新).md) | 期货数据 | 期货周/月线行情(每日更新) |+| 391 | hk_cashflow | [港股现金流量表](tushare/references/港股数据/港股现金流量表.md) | 港股数据 | 获取港股上市公司现金流量表数据 |+| 390 | hk_balancesheet | [港股资产负债表](tushare/references/港股数据/港股资产负债表.md) | 港股数据 | 获取港股上市公司资产负债表 |+| 389 | hk_income | [港股利润表](tushare/references/港股数据/港股利润表.md) | 港股数据 | 获取港股上市公司财务利润表数据 |+| 388 | hk_fina_indicator | [港股财务指标数据](tushare/references/港股数据/港股财务指标数据.md) | 港股数据 | 获取港股上市公司财务指标数据,为避免服务器压力,现阶段每次请求最多返回200条记录,可通过设置日期多次请求获取更多数据。 |+| 401 | hk_adjfactor | [港股复权因子](tushare/references/港股数据/港股复权因子.md) | 港股数据 | 获取港股每日复权因子数据,每天滚动刷新 |+| 339 | hk_daily_adj | [港股复权行情](tushare/references/港股数据/港股复权行情.md) | 港股数据 | 获取港股复权行情,提供股票股本、市值和成交及换手多个数据指标 |+| 383 | rt_hk_k | [港股实时日线](tushare/references/港股数据/港股实时日线.md) | 港股数据 | 获取港股实时日k线行情,支持按股票代码及股票代码通配符一次性提取全部股票实时日k线行情 |+| 191 | hk_basic | [港股基础信息](tushare/references/港股数据/港股基础信息.md) | 港股数据 | 获取港股列表信息 |+| 192 | hk_daily | [港股日线行情](tushare/references/港股数据/港股日线行情.md) | 港股数据 | 获取港股每日增量和历史行情,每日18点左右更新当日数据 |+| 304 | hk_mins | [港股分钟行情](tushare/references/港股数据/港股分钟行情.md) | 港股数据 | 港股分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式 |+| 250 | hk_tradecal | [港股交易日历](tushare/references/港股数据/港股交易日历.md) | 港股数据 | 获取交易日历 |+| 285 | sge_daily | [上海黄金现货日行情](tushare/references/现货数据/上海黄金现货日行情.md) | 现货数据 | 获取上海黄金交易所现货合约日线行情 |+| 284 | sge_basic | [上海黄金基础信息](tushare/references/现货数据/上海黄金基础信息.md) | 现货数据 | 获取上海黄金交易所现货合约基础信息 |+| 393 | us_fina_indicator | [美股财务指标数据](tushare/references/美股数据/美股财务指标数据.md) | 美股数据 | 获取美股上市公司财务指标数据,目前只覆盖主要美股和中概股。为避免服务器压力,现阶段每次请求最多返回200条记录,可通过设置日期多次请求获取更多数据。 |+| 402 | us_adjfactor | [美股复权因子](tushare/references/美股数据/美股复权因子.md) | 美股数据 | 获取美股每日复权因子数据,在每天美股收盘后滚动刷新 |+| 396 | us_cashflow | [美股现金流量表](tushare/references/美股数据/美股现金流量表.md) | 美股数据 | 获取美股上市公司现金流量表数据(目前只覆盖主要美股和中概股) |+| 395 | us_balancesheet | [美股资产负债表](tushare/references/美股数据/美股资产负债表.md) | 美股数据 | 获取美股上市公司资产负债表(目前只覆盖主要美股和中概股) |+| 394 | us_income | [美股利润表](tushare/references/美股数据/美股利润表.md) | 美股数据 | 获取美股上市公司财务利润表数据(目前只覆盖主要美股和中概股) |+| 254 | us_daily | [美股日线行情](tushare/references/美股数据/美股日线行情.md) | 美股数据 | 获取美股行情(未复权),包括全部股票全历史行情,以及重要的市场和估值指标 |+| 253 | us_tradecal | [美股交易日历](tushare/references/美股数据/美股交易日历.md) | 美股数据 | 获取美股交易日历信息 |+| 252 | us_basic | [美股基础信息](tushare/references/美股数据/美股基础信息.md) | 美股数据 | 获取美股列表信息 |+| 338 | us_daily_adj | [美股复权行情](tushare/references/美股数据/美股复权行情.md) | 美股数据 | 获取美股复权行情,支持美股全市场股票,提供股本、市值、复权因子和成交信息等多个数据指标 |+| 326 | margin_secs | [融资融券标的(盘前)](tushare/references/股票数据/两融及转融通/融资融券标的(盘前).md) | 股票数据,两融及转融通 | 获取沪深京三大交易所融资融券标的(包括ETF),每天盘前更新 |+| 331 | slb_len | [转融资交易汇总](tushare/references/股票数据/两融及转融通/转融资交易汇总.md) | 股票数据,两融及转融通 | 转融通融资汇总 |+| 332 | slb_sec | [转融券交易汇总(停)](tushare/references/股票数据/两融及转融通/转融券交易汇总(停).md) | 股票数据,两融及转融通 | 转融通转融券交易汇总 |+| 333 | slb_sec_detail | [转融券交易明细(停)](tushare/references/股票数据/两融及转融通/转融券交易明细(停).md) | 股票数据,两融及转融通 | 转融券交易明细 |+| 59 | margin_detail | [融资融券交易明细](tushare/references/股票数据/两融及转融通/融资融券交易明细.md) | 股票数据,两融及转融通 | 获取沪深两市每日融资融券明细 |+| 58 | margin | [融资融券交易汇总](tushare/references/股票数据/两融及转融通/融资融券交易汇总.md) | 股票数据,两融及转融通 | 获取融资融券每日交易汇总数据 |+| 334 | slb_len_mm | [做市借券交易汇总(停)](tushare/references/股票数据/两融及转融通/做市借券交易汇总(停).md) | 股票数据,两融及转融通 | 做市借券交易汇总 |+| 124 | repurchase | [股票回购](tushare/references/股票数据/参考数据/股票回购.md) | 股票数据,参考数据 | 获取上市公司回购股票数据 |+| 110 | pledge_stat | [股权质押统计数据](tushare/references/股票数据/参考数据/股权质押统计数据.md) | 股票数据,参考数据 | 获取股票质押统计数据 |+| 160 | share_float | [限售股解禁](tushare/references/股票数据/参考数据/限售股解禁.md) | 股票数据,参考数据 | 获取限售股解禁 |+| 161 | block_trade | [大宗交易](tushare/references/股票数据/参考数据/大宗交易.md) | 股票数据,参考数据 | 大宗交易 |+| 164 | stk_account | [股票开户数据(停)](tushare/references/股票数据/参考数据/股票开户数据(停).md) | 股票数据,参考数据 | 获取股票账户开户数据,统计周期为一周 |+| 165 | stk_account_old | [股票开户数据(旧)](tushare/references/股票数据/参考数据/股票开户数据(旧).md) | 股票数据,参考数据 | 获取股票账户开户数据旧版格式数据,数据从2008年1月开始,到2015年5月29,新数据请通过[股票开户数据](https://tushare.pro/document/2?doc_id=164)获取。 |+| 166 | stk_holdernumber | [股东人数](tushare/references/股票数据/参考数据/股东人数.md) | 股票数据,参考数据 | 获取上市公司股东户数数据,数据不定期公布 |+| 175 | stk_holdertrade | [股东增减持](tushare/references/股票数据/参考数据/股东增减持.md) | 股票数据,参考数据 | 获取上市公司增减持数据,了解重要股东近期及历史上的股份增减变化 |+| 61 | top10_holders | [前十大股东](tushare/references/股票数据/参考数据/前十大股东.md) | 股票数据,参考数据 | 获取上市公司前十大股东数据,包括持有数量和比例等信息 |+| 111 | pledge_detail | [股权质押明细数据](tushare/references/股票数据/参考数据/股权质押明细数据.md) | 股票数据,参考数据 | 获取股票质押明细数据 |+| 62 | top10_floatholders | [前十大流通股东](tushare/references/股票数据/参考数据/前十大流通股东.md) | 股票数据,参考数据 | 获取上市公司前十大流通股东数据 |+| 423 | st | [ST风险警示板股票](tushare/references/股票数据/基础数据/ST风险警示板股票.md) | 股票数据,基础数据 | ST风险警示板股票列表 |+| 398 | stock_hsgt | [沪深港通股票列表](tushare/references/股票数据/基础数据/沪深港通股票列表.md) | 股票数据,基础数据 | 获取沪深港通股票列表 |+| 397 | stock_st | [ST股票列表](tushare/references/股票数据/基础数据/ST股票列表.md) | 股票数据,基础数据 | 获取ST股票列表,可根据交易日期获取历史上每天的ST列表 |+| 375 | bse_mapping | [北交所新旧代码对照](tushare/references/股票数据/基础数据/北交所新旧代码对照.md) | 股票数据,基础数据 | 获取北交所股票代码变更后新旧代码映射表数据 |+| 329 | stk_premarket | [每日股本(盘前)](tushare/references/股票数据/基础数据/每日股本(盘前).md) | 股票数据,基础数据 | 每日开盘前获取当日股票的股本情况,包括总股本和流通股本,涨跌停价格等。 |+| 123 | new_share | [IPO新股上市](tushare/references/股票数据/基础数据/IPO新股上市.md) | 股票数据,基础数据 | 获取新股上市列表数据 |+| 194 | stk_rewards | [管理层薪酬和持股](tushare/references/股票数据/基础数据/管理层薪酬和持股.md) | 股票数据,基础数据 | 获取上市公司管理层薪酬和持股 |+| 193 | stk_managers | [上市公司管理层](tushare/references/股票数据/基础数据/上市公司管理层.md) | 股票数据,基础数据 | 获取上市公司管理层 |+| 112 | stock_company | [上市公司基本信息](tushare/references/股票数据/基础数据/上市公司基本信息.md) | 股票数据,基础数据 | 获取上市公司基础信息,单次提取4500条,可以根据交易所分批提取 |+| 100 | namechange | [股票曾用名](tushare/references/股票数据/基础数据/股票曾用名.md) | 股票数据,基础数据 | 历史名称变更记录 |+| 26 | trade_cal | [交易日历](tushare/references/股票数据/基础数据/交易日历.md) | 股票数据,基础数据 | 获取各大交易所交易日历数据,默认提取的是上交所 |+| 25 | stock_basic | [股票列表](tushare/references/股票数据/基础数据/股票列表.md) | 股票数据,基础数据 | 获取基础信息数据,包括股票代码、名称、上市日期、退市日期等 |+| 262 | bak_basic | [股票历史列表](tushare/references/股票数据/基础数据/股票历史列表.md) | 股票数据,基础数据 | 获取备用基础列表,数据从2016年开始 |+| 382 | dc_daily | [东财概念和行业指数行情](tushare/references/股票数据/打板专题数据/东财概念和行业指数行情.md) | 股票数据,打板专题数据 | 获取东财概念板块、行业指数板块、地域板块行情数据,历史数据开始于2020年 |+| 321 | dc_hot | [东方财富App热榜](tushare/references/股票数据/打板专题数据/东方财富App热榜.md) | 股票数据,打板专题数据 | 获取东方财富App热榜数据,包括A股市场、ETF基金、港股市场、美股市场等等,每日盘中提取4次,收盘后4次,最晚22点提取一次。 |+| 298 | limit_list_d | [涨跌停和炸板数据](tushare/references/股票数据/打板专题数据/涨跌停和炸板数据.md) | 股票数据,打板专题数据 | 获取A股每日涨跌停、炸板数据情况,数据从2020年开始(不提供ST股票的统计) |+| 311 | hm_list | [市场游资最全名录](tushare/references/股票数据/打板专题数据/市场游资最全名录.md) | 股票数据,打板专题数据 | 获取游资分类名录信息 |+| 347 | kpl_list | [榜单数据(开盘啦)](tushare/references/股票数据/打板专题数据/榜单数据(开盘啦).md) | 股票数据,打板专题数据 | 获取开盘啦涨停、跌停、炸板等榜单数据 |+| 261 | ths_member | [同花顺行业概念成分](tushare/references/股票数据/打板专题数据/同花顺行业概念成分.md) | 股票数据,打板专题数据 | 获取同花顺概念板块成分列表注:数据版权归属同花顺,如做商业用途,请主动联系同花顺。 |+| 260 | ths_daily | [同花顺概念和行业指数行情](tushare/references/股票数据/打板专题数据/同花顺概念和行业指数行情.md) | 股票数据,打板专题数据 | 获取同花顺板块指数行情。注:数据版权归属同花顺,如做商业用途,请主动联系同花顺,如需帮助请联系微信:waditu_a |+| 259 | ths_index | [同花顺行业概念板块](tushare/references/股票数据/打板专题数据/同花顺行业概念板块.md) | 股票数据,打板专题数据 | 获取同花顺板块指数。注:数据版权归属同花顺,如做商业用途,请主动联系同花顺,如需帮助请联系微信:waditu_a |+| 107 | top_inst | [龙虎榜机构交易单](tushare/references/股票数据/打板专题数据/龙虎榜机构交易单.md) | 股票数据,打板专题数据 | 龙虎榜机构成交明细 |+| 351 | kpl_concept_cons | [题材成分(开盘啦)](tushare/references/股票数据/打板专题数据/题材成分(开盘啦).md) | 股票数据,打板专题数据 | 获取开盘啦概念题材的成分股 |+| 355 | limit_list_ths | [同花顺涨跌停榜单](tushare/references/股票数据/打板专题数据/同花顺涨跌停榜单.md) | 股票数据,打板专题数据 | 获取同花顺每日涨跌停榜单数据,历史数据从20231101开始提供,增量每天16点左右更新 |+| 356 | limit_step | [涨停股票连板天梯](tushare/references/股票数据/打板专题数据/涨停股票连板天梯.md) | 股票数据,打板专题数据 | 获取每天连板个数晋级的股票,可以分析出每天连续涨停进阶个数,判断强势热度 |+| 357 | limit_cpt_list | [涨停最强板块统计](tushare/references/股票数据/打板专题数据/涨停最强板块统计.md) | 股票数据,打板专题数据 | 获取每天涨停股票最多最强的概念板块,可以分析强势板块的轮动,判断资金动向 |+| 362 | dc_index | [东方财富概念板块](tushare/references/股票数据/打板专题数据/东方财富概念板块.md) | 股票数据,打板专题数据 | 获取东方财富每个交易日的概念板块数据,支持按日期查询 |+| 363 | dc_member | [东方财富概念成分](tushare/references/股票数据/打板专题数据/东方财富概念成分.md) | 股票数据,打板专题数据 | 获取东方财富板块每日成分数据,可以根据概念板块代码和交易日期,获取历史成分 |+| 369 | stk_auction | [开盘竞价成交(当日)](tushare/references/股票数据/打板专题数据/开盘竞价成交(当日).md) | 股票数据,打板专题数据 | 获取当日个股和ETF的集合竞价成交情况,每天9点25~29分之间可以获取当日的集合竞价成交数据 |+| 376 | tdx_index | [通达信板块信息](tushare/references/股票数据/打板专题数据/通达信板块信息.md) | 股票数据,打板专题数据 | 获取通达信板块基础信息,包括概念板块、行业、风格、地域等 |+| 106 | top_list | [龙虎榜每日统计单](tushare/references/股票数据/打板专题数据/龙虎榜每日统计单.md) | 股票数据,打板专题数据 | 龙虎榜每日交易明细 |+| 377 | tdx_member | [通达信板块成分](tushare/references/股票数据/打板专题数据/通达信板块成分.md) | 股票数据,打板专题数据 | 获取通达信各板块成分股信息 |+| 378 | tdx_daily | [通达信板块行情](tushare/references/股票数据/打板专题数据/通达信板块行情.md) | 股票数据,打板专题数据 | 获取通达信各板块行情,包括成交和估值等数据 |+| 312 | hm_detail | [游资交易每日明细](tushare/references/股票数据/打板专题数据/游资交易每日明细.md) | 股票数据,打板专题数据 | 获取每日游资交易明细,数据开始于2022年8。游资分类名录,请点击<a href="https://tushare.pro/document/2?doc_id=311">游资名录</a> |+| 320 | ths_hot | [同花顺App热榜数](tushare/references/股票数据/打板专题数据/同花顺App热榜数.md) | 股票数据,打板专题数据 | 获取同花顺App热榜数据,包括热股、概念板块、ETF、可转债、港美股等等,每日盘中提取4次,收盘后4次,最晚22点提取一次。 |+| 364 | stk_nineturn | [神奇九转指标](tushare/references/股票数据/特色数据/神奇九转指标.md) | 股票数据,特色数据 | 神奇九转(又称“九转序列”)是一种基于技术分析的股票趋势反转指标,其思想来源于技术分析大师汤姆·迪马克(Tom DeMark)的TD序列。该指标的核心功能是通过识别股价在上涨或下跌过程中连续9天的特定走势,来判断股价的潜在反转点,从而帮助投资者提高抄底和逃顶的成功率,日线级别配合60min的九转效果更好,数据从20230101开始。 |+| 188 | hk_hold | [沪深股通持股明细](tushare/references/股票数据/特色数据/沪深股通持股明细.md) | 股票数据,特色数据 | 获取沪深港股通持股明细,数据来源港交所。 |+| 267 | broker_recommend | [券商月度金股](tushare/references/股票数据/特色数据/券商月度金股.md) | 股票数据,特色数据 | 获取券商月度金股,一般1日~3日内更新当月数据 |+| 274 | ccass_hold_detail | [中央结算系统持股明细](tushare/references/股票数据/特色数据/中央结算系统持股明细.md) | 股票数据,特色数据 | 获取中央结算系统机构席位持股明细,数据覆盖**全历史**,根据交易所披露时间,当日数据在下一交易日早上9点前完成 |+| 275 | stk_surv | [机构调研数据](tushare/references/股票数据/特色数据/机构调研数据.md) | 股票数据,特色数据 | 获取上市公司机构调研记录数据 |+| 292 | report_rc | [券商盈利预测数据](tushare/references/股票数据/特色数据/券商盈利预测数据.md) | 股票数据,特色数据 | 获取券商(卖方)每天研报的盈利预测数据,数据从2010年开始,每晚19~22点更新当日数据 |+| 293 | cyq_perf | [每日筹码及胜率](tushare/references/股票数据/特色数据/每日筹码及胜率.md) | 股票数据,特色数据 | 获取A股每日筹码平均成本和胜率情况,每天18~19点左右更新,数据从2018年开始 |+| 294 | cyq_chips | [每日筹码分布](tushare/references/股票数据/特色数据/每日筹码分布.md) | 股票数据,特色数据 | 获取A股每日的筹码分布情况,提供各价位占比,数据从2018年开始,每天18~19点之间更新当日数据 |+| 295 | ccass_hold | [中央结算系统持股统计](tushare/references/股票数据/特色数据/中央结算系统持股统计.md) | 股票数据,特色数据 | 获取中央结算系统持股汇总数据,覆盖全部历史数据,根据交易所披露时间,当日数据在下一交易日早上9点前完成入库 |+| 353 | stk_auction_o | [股票开盘集合竞价数据](tushare/references/股票数据/特色数据/股票开盘集合竞价数据.md) | 股票数据,特色数据 | 股票开盘9:30集合竞价数据,每天盘后更新 |+| 354 | stk_auction_c | [股票收盘集合竞价数据](tushare/references/股票数据/特色数据/股票收盘集合竞价数据.md) | 股票数据,特色数据 | 股票收盘15:00集合竞价数据,每天盘后更新 |+| 399 | stk_ah_comparison | [AH股比价](tushare/references/股票数据/特色数据/AH股比价.md) | 股票数据,特色数据 | AH股比价数据,可根据交易日期获取历史 |+| 328 | stk_factor_pro | [股票技术面因子(专业版)](tushare/references/股票数据/特色数据/股票技术面因子(专业版).md) | 股票数据,特色数据 | 获取股票每日技术面因子数据,用于跟踪股票当前走势情况,数据由Tushare社区自产,覆盖全历史;输出参数_bfq表示不复权,_qfq表示前复权 _hfq表示后复权,描述中说明了因子的默认传参,如需要特殊参数或者更多因子可以联系管理员评估 |+| 27 | daily | [历史日线](tushare/references/股票数据/行情数据/历史日线.md) | 股票数据,行情数据 | 获取股票行情数据,或通过[**通用行情接口**](https://tushare.pro/document/2?doc_id=109)获取数据,包含了前后复权数据 |+| 146 | pro_bar | [复权行情](tushare/references/股票数据/行情数据/复权行情.md) | 股票数据,行情数据 | |+| 145 | monthly | [月线行情](tushare/references/股票数据/行情数据/月线行情.md) | 股票数据,行情数据 | 获取A股月线数据 |+| 374 | rt_min | [实时分钟](tushare/references/股票数据/行情数据/实时分钟.md) | 股票数据,行情数据 | 获取全A股票实时分钟数据,包括1~60min |+| 372 | rt_k | [实时日线](tushare/references/股票数据/行情数据/实时日线.md) | 股票数据,行情数据 | 获取实时日k线行情,支持按股票代码及股票代码通配符一次性提取全部股票实时日k线行情 |+| 370 | stk_mins | [历史分钟](tushare/references/股票数据/行情数据/历史分钟.md) | 股票数据,行情数据 | 获取A股分钟数据,支持1min/5min/15min/30min/60min行情,提供Python SDK和 http Restful API两种方式 |+| 365 | stk_week_month_adj | [周月线复权行情(每日更新)](tushare/references/股票数据/行情数据/周月线复权行情(每日更新).md) | 股票数据,行情数据 | 股票周/月线行情(复权--每日更新) |+| 336 | stk_weekly_monthly | [周月线行情(每日更新)](tushare/references/股票数据/行情数据/周月线行情(每日更新).md) | 股票数据,行情数据 | 股票周/月线行情(每日更新) |+| 255 | bak_daily | [备用行情](tushare/references/股票数据/行情数据/备用行情.md) | 股票数据,行情数据 | 获取备用行情,包括特定的行情指标(数据从2017年中左右开始,早期有几天数据缺失,近期正常) |+| 144 | weekly | [周线行情](tushare/references/股票数据/行情数据/周线行情.md) | 股票数据,行情数据 | 获取A股周线行情,本接口每周最后一个交易日更新,如需要使用每天更新的周线数据,请使用[日度更新的周线行情接口](https://tushare.pro/document/2?doc_id=336)。 |+| 214 | suspend_d | [每日停复牌信息](tushare/references/股票数据/行情数据/每日停复牌信息.md) | 股票数据,行情数据 | 按日期方式获取股票每日停复牌信息 |+| 196 | ggt_daily | [港股通每日成交统计](tushare/references/股票数据/行情数据/港股通每日成交统计.md) | 股票数据,行情数据 | 获取港股通每日成交信息,数据从2014年开始 |+| 183 | stk_limit | [每日涨跌停价格](tushare/references/股票数据/行情数据/每日涨跌停价格.md) | 股票数据,行情数据 | 获取全市场(包含A/B股和基金)每日涨跌停价格,包括涨停价格,跌停价格等,每个交易日8点40左右更新当日股票涨跌停价格。 |+| 109 | pro_bar | [通用行情接口](tushare/references/股票数据/行情数据/通用行情接口.md) | 股票数据,行情数据 | |+| 49 | ggt_top10 | [港股通十大成交股](tushare/references/股票数据/行情数据/港股通十大成交股.md) | 股票数据,行情数据 | 获取港股通每日成交数据,其中包括沪市、深市详细数据,每天18~20点之间完成当日更新 |+| 48 | hsgt_top10 | [沪深股通十大成交股](tushare/references/股票数据/行情数据/沪深股通十大成交股.md) | 股票数据,行情数据 | 获取沪股通、深股通每日前十大成交详细数据,每天18~20点之间完成当日更新 |+| 32 | daily_basic | [每日指标](tushare/references/股票数据/行情数据/每日指标.md) | 股票数据,行情数据 | 获取全部股票每日重要的基本面指标,可用于选股分析、报表展示等。单次请求最大返回6000条数据,可按日线循环提取全部历史。 |+| 28 | adj_factor | [复权因子](tushare/references/股票数据/行情数据/复权因子.md) | 股票数据,行情数据 | 本接口由Tushare自行生产,获取股票复权因子,可提取单只股票全部历史复权因子,也可以提取单日全部股票的复权因子。 |+| 197 | ggt_monthly | [港股通每月成交统计](tushare/references/股票数据/行情数据/港股通每月成交统计.md) | 股票数据,行情数据 | 港股通每月成交信息,数据从2014年开始 |+| 33 | income | [利润表](tushare/references/股票数据/财务数据/利润表.md) | 股票数据,财务数据 | 获取上市公司财务利润表数据 |+| 44 | cashflow | [现金流量表](tushare/references/股票数据/财务数据/现金流量表.md) | 股票数据,财务数据 | 获取上市公司现金流量表 |+| 36 | balancesheet | [资产负债表](tushare/references/股票数据/财务数据/资产负债表.md) | 股票数据,财务数据 | 获取上市公司资产负债表 |+| 46 | express | [业绩快报](tushare/references/股票数据/财务数据/业绩快报.md) | 股票数据,财务数据 | 获取上市公司业绩快报 |+| 79 | fina_indicator | [财务指标数据](tushare/references/股票数据/财务数据/财务指标数据.md) | 股票数据,财务数据 | 获取上市公司财务指标数据,为避免服务器压力,现阶段每次请求最多返回100条记录,可通过设置日期多次请求获取更多数据。 |+| 81 | fina_mainbz | [主营业务构成](tushare/references/股票数据/财务数据/主营业务构成.md) | 股票数据,财务数据 | 获得上市公司主营业务构成,分地区和产品两种方式 |+| 103 | dividend | [分红送股数据](tushare/references/股票数据/财务数据/分红送股数据.md) | 股票数据,财务数据 | 分红送股数据 |+| 162 | disclosure_date | [财报披露日期表](tushare/references/股票数据/财务数据/财报披露日期表.md) | 股票数据,财务数据 | 获取财报披露计划日期 |+| 45 | forecast | [业绩预告](tushare/references/股票数据/财务数据/业绩预告.md) | 股票数据,财务数据 | 获取业绩预告数据 |+| 80 | fina_audit | [财务审计意见](tushare/references/股票数据/财务数据/财务审计意见.md) | 股票数据,财务数据 | 获取上市公司定期财务审计意见数据 |+| 47 | moneyflow_hsgt | [沪深港通资金流向](tushare/references/股票数据/资金流向数据/沪深港通资金流向.md) | 股票数据,资金流向数据 | 获取沪股通、深股通、港股通每日资金流向数据,每次最多返回300条记录,总量不限制。 |+| 170 | moneyflow | [个股资金流向](tushare/references/股票数据/资金流向数据/个股资金流向.md) | 股票数据,资金流向数据 | 获取沪深A股票资金流向数据,分析大单小单成交情况,用于判别资金动向,数据开始于2010年。 |+| 343 | moneyflow_ind_ths | [行业资金流向(THS)](tushare/references/股票数据/资金流向数据/行业资金流向(THS).md) | 股票数据,资金流向数据 | 获取同花顺行业资金流向,每日盘后更新 |+| 344 | moneyflow_ind_dc | [板块资金流向(DC)](tushare/references/股票数据/资金流向数据/板块资金流向(DC).md) | 股票数据,资金流向数据 | 获取东方财富板块资金流向,每天盘后更新 |+| 345 | moneyflow_mkt_dc | [大盘资金流向(DC)](tushare/references/股票数据/资金流向数据/大盘资金流向(DC).md) | 股票数据,资金流向数据 | 获取东方财富大盘资金流向数据,每日盘后更新 |+| 348 | moneyflow_ths | [个股资金流向(THS)](tushare/references/股票数据/资金流向数据/个股资金流向(THS).md) | 股票数据,资金流向数据 | 获取同花顺个股资金流向数据,每日盘后更新 |+| 349 | moneyflow_dc | [个股资金流向(DC)](tushare/references/股票数据/资金流向数据/个股资金流向(DC).md) | 股票数据,资金流向数据 | 获取东方财富个股资金流向数据,每日盘后更新,数据开始于20230911 |+| 371 | moneyflow_cnt_ths | [板块资金流向(THS)](tushare/references/股票数据/资金流向数据/板块资金流向(THS).md) | 股票数据,资金流向数据 | 获取同花顺概念板块每日资金流向 |+| 156 | film_record | [全国电影剧本备案数据](tushare/references/行业经济/TMT行业/全国电影剧本备案数据.md) | 行业经济,TMT行业 | 获取全国电影剧本备案的公示数据 |+| 180 | teleplay_record | [全国电视剧备案公示数据](tushare/references/行业经济/TMT行业/全国电视剧备案公示数据.md) | 行业经济,TMT行业 | 获取2009年以来全国拍摄制作电视剧备案公示数据 |+| 87 | tmt_twincomedetail | [台湾电子产业月营收明细](tushare/references/行业经济/TMT行业/台湾电子产业月营收明细.md) | 行业经济,TMT行业 | 获取台湾TMT行业上市公司各类产品月度营收情况。 |+| 88 | tmt_twincome | [台湾电子产业月营收](tushare/references/行业经济/TMT行业/台湾电子产业月营收.md) | 行业经济,TMT行业 | 获取台湾TMT电子产业领域各类产品月度营收数据。 |+| 113 | bo_monthly | [电影月度票房](tushare/references/行业经济/TMT行业/电影月度票房.md) | 行业经济,TMT行业 | 获取电影月度票房数据 |+| 115 | bo_daily | [电影日度票房](tushare/references/行业经济/TMT行业/电影日度票房.md) | 行业经济,TMT行业 | 获取电影日度票房 |+| 116 | bo_cinema | [影院日度票房](tushare/references/行业经济/TMT行业/影院日度票房.md) | 行业经济,TMT行业 | 获取每日各影院的票房数据 |+| 114 | bo_weekly | [电影周度票房](tushare/references/行业经济/TMT行业/电影周度票房.md) | 行业经济,TMT行业 | 获取周度票房数据 |+| 265 | fund_sales_ratio | [各渠道公募基金销售保有规模占比](tushare/references/财富管理/基金销售行业数据/各渠道公募基金销售保有规模占比.md) | 财富管理,基金销售行业数据 | 获取各渠道公募基金销售保有规模占比数据,年度更新 |+| 266 | fund_sales_vol | [销售机构公募基金销售保有规模](tushare/references/财富管理/基金销售行业数据/销售机构公募基金销售保有规模.md) | 财富管理,基金销售行业数据 | 获取销售机构公募基金销售保有规模数据,本数据从2021年Q1开始公布,季度更新 |diff --git a/agent/src/skills/yfinance/SKILL.md b/agent/src/skills/yfinance/SKILL.mdindex 5e5e1827a..7fc5230f2 100644--- a/agent/src/skills/yfinance/SKILL.md+++ b/agent/src/skills/yfinance/SKILL.md@@ -13,6 +13,34 @@ The project has a built-in yfinance DataLoader (`backtest/loaders/yfinance_loadeFor OHLCV bars in agent/swarm work, prefer the `get_market_data` tool when it is available. It routes through the project loader layer, normalizes symbols, removes malformed OHLC rows, and returns strict JSON. Use direct `yfinance` calls mainly for data outside OHLCV coverage such as company info, financial statements, options, holders, and insider transactions.+## Deep Yahoo Interfaces (references/)++Beyond the `yfinance` package, the project ships a built-in **Yahoo public-API+client** (`backtest.loaders.yahoo_client`) and two read-only agent tools that+sit on top of it. These reach Yahoo's own unauthenticated JSON endpoints+directly via `requests` (no `yfinance` install needed), share one throttled+HTTP gate (Yahoo rate-limits by source IP), and handle the cookie+crumb+handshake automatically. Each interface has its own reference doc — read the+one you need rather than loading them all:++| Doc | Covers |+|-----|--------|+| [yahoo_client.get_chart](yfinance/references/yahoo_client_get_chart.md) | Direct v8 OHLCV bars (range or epoch window) |+| [yahoo_client.get_quote_summary](yfinance/references/yahoo_client_get_quote_summary.md) | v10 quoteSummary modules (key stats, financials, ownership) |+| [yahoo_client.get_options](yfinance/references/yahoo_client_get_options.md) | v7 option chain (expirations + calls/puts) |+| [yahoo_client.search](yfinance/references/yahoo_client_search.md) | v1 instrument search by ticker/name |+| [get_options_chain tool](yfinance/references/tool_get_options_chain.md) | Agent tool: US options ladder envelope |+| [get_stock_profile tool](yfinance/references/tool_get_stock_profile.md) | Agent tool: company profile/estimates/ownership envelope |++> Path convention: `read_file` resolves paths with `skills/` as the root, so+> every link above is written with the **skill-name prefix** (`yfinance/references/...`).+> Omitting the prefix makes the read fail. Reuse this `yfinance/references/...`+> form for any new reference docs.++The Yahoo client uses the project ticker convention (`AAPL.US` → `AAPL`,+`00700.HK` → `0700.HK`); see the [Ticker Format Conversion](#ticker-format-conversion)+table below — the same rules apply across all of the interfaces above.+## Quick StartPreferred OHLCV tool call:@@ -183,56 +211,6 @@ usdhkd = yf.download("HKD=X", start="2025-01-01", end="2026-01-01", progress=Faleurusd = yf.download("EURUSD=X", start="2025-01-01", end="2026-01-01", progress=False)```-## Popular Ticker Reference--### US Stocks--| Ticker | Company |-|--------|---------|-| AAPL | Apple |-| MSFT | Microsoft |-| GOOGL | Alphabet (Google) |-| AMZN | Amazon |-| NVDA | NVIDIA |-| META | Meta Platforms |-| TSLA | Tesla |-| BRK-B | Berkshire Hathaway |--### HK Stocks--| Project Format | yfinance Format | Company |-|---------------|----------------|---------|-| 700.HK | 0700.HK | Tencent |-| 9988.HK | 9988.HK | Alibaba |-| 9618.HK | 9618.HK | JD.com |-| 3690.HK | 3690.HK | Meituan |-| 1810.HK | 1810.HK | Xiaomi |-| 2318.HK | 2318.HK | Ping An |--### Major Indices--| Ticker | Index |-|--------|-------|-| ^GSPC | S&P 500 |-| ^DJI | Dow Jones Industrial Average |-| ^IXIC | NASDAQ Composite |-| ^HSI | Hang Seng Index |-| ^N225 | Nikkei 225 |-| ^FTSE | FTSE 100 |--### Sector ETFs--| Ticker | Sector |-|--------|--------|-| XLK | Technology |-| XLF | Financials |-| XLE | Energy |-| XLV | Healthcare |-| XLY | Consumer Discretionary |-| XLP | Consumer Staples |-| XLI | Industrials |-| XLU | Utilities |-## Backtest Usage### config.json Examplediff --git a/agent/src/skills/yfinance/references/tool_get_options_chain.md b/agent/src/skills/yfinance/references/tool_get_options_chain.mdnew file mode 100644index 000000000..4afac752c--- /dev/null+++ b/agent/src/skills/yfinance/references/tool_get_options_chain.md@@ -0,0 +1,97 @@+## get_options_chain (agent tool)++----++Tool: `get_options_chain`+Backed by: `backtest.loaders.yahoo_client.get_options`+Description: Read-only agent/CLI tool that returns the US-listed options ladder+(calls and puts) for a single expiration, plus the list of available+expirations. Use it for an options snapshot — strike, bid/ask, last price,+volume, open interest, implied volatility, and the in/out-of-money flag. For+raw chain payloads call `yahoo_client.get_options` directly.++Each side is capped at 60 contracts so a deep chain cannot blow up the model+payload.++<br>+<br>++**Input parameters**++Name | Type | Required | Description+---- | ---- | -------- | -----------+ticker | str | Y | US underlying, `AAPL` or `AAPL.US` (the `.US` suffix is stripped).+expiration | int | N | Expiration as Unix epoch seconds (a value from the returned `expirations`). Omit for the nearest expiration.++<br>+<br>++**Output**++A JSON-string envelope.++On success:++```json+{"ok": true, "market": "us", "source": "yahoo", "data": {...}}+```++`data` fields:++Field | Type | Description+----- | ---- | -----------+ticker | str | Echoed input ticker.+expiration | int | The returned expiration as Unix epoch seconds.+expirations | list[int] | All available expirations as Unix epoch seconds.+calls_count | int | Number of call rows returned (≤ 60).+puts_count | int | Number of put rows returned (≤ 60).+calls | list[dict] | Call contracts (see fields below).+puts | list[dict] | Put contracts (same shape).++Per-contract fields (snake_case): `contract_symbol`, `strike`, `last_price`,+`bid`, `ask`, `volume`, `open_interest`, `implied_volatility`, `in_the_money`,+`expiration`.++On failure:++```json+{"ok": false, "error": "<message>"}+```++Failures are returned as an envelope (never raised) — e.g. a missing/blank+`ticker`, a non-integer `expiration`, or an upstream Yahoo request error.++<br>+<br>++**Example**++```text+get_options_chain(ticker="AAPL")+get_options_chain(ticker="AAPL.US", expiration=1718236800)+```++<br>+<br>++**Data example**++```json+{+ "ok": true, "market": "us", "source": "yahoo",+ "data": {+ "ticker": "AAPL",+ "expiration": 1718236800,+ "expirations": [1718236800, 1718841600],+ "calls_count": 2, "puts_count": 2,+ "calls": [{"contract_symbol": "AAPL240613C00190000", "strike": 190.0,+ "last_price": 4.05, "bid": 3.95, "ask": 4.10, "volume": 1203,+ "open_interest": 8821, "implied_volatility": 0.224,+ "in_the_money": true, "expiration": 1718236800}],+ "puts": [{"contract_symbol": "AAPL240613P00190000", "strike": 190.0,+ "last_price": 1.85, "bid": 1.80, "ask": 1.90, "volume": 642,+ "open_interest": 5104, "implied_volatility": 0.231,+ "in_the_money": false, "expiration": 1718236800}]+ }+}+```diff --git a/agent/src/skills/yfinance/references/tool_get_stock_profile.md b/agent/src/skills/yfinance/references/tool_get_stock_profile.mdnew file mode 100644index 000000000..58f7abf30--- /dev/null+++ b/agent/src/skills/yfinance/references/tool_get_stock_profile.md@@ -0,0 +1,97 @@+## get_stock_profile (agent tool)++----++Tool: `get_stock_profile`+Backed by: `backtest.loaders.yahoo_client.get_quote_summary`+Description: Read-only agent/CLI tool that returns a compact company profile for+a US or Hong Kong listing — valuation key statistics, analyst price targets and+earnings/revenue estimates, institutional and insider ownership, and the+analyst recommendation trend. Use it for fundamentals and consensus context,+not for OHLCV price bars (use `get_market_data` for prices).++The tool selects the right Yahoo quoteSummary modules, unwraps Yahoo+`{"raw","fmt"}` cells to their numeric `raw` value, caps each list section at+25 rows, and wraps the result in the project envelope.++<br>+<br>++**Input parameters**++Name | Type | Required | Description+---- | ---- | -------- | -----------+ticker | str | Y | US (`AAPL` or `AAPL.US`) or HK (`00700.HK`, zero-padded) symbol.+sections | list[str] | N | Which sections to return (one or more of the section names below). Defaults to all sections. Unknown names return an error envelope.++Section name → underlying Yahoo module:++Section | Yahoo module | Contents+------- | ------------ | --------+key_stats | defaultKeyStatistics | Enterprise value, forward PE, EPS, PEG, price-to-book, profit margin, beta, shares outstanding, float, insider/institution held %.+financials | financialData | Current price, analyst target prices, recommendation key, analyst count, revenue/growth/margins, ROE, cash, debt.+earnings_trend | earningsTrend | Per-period EPS/revenue estimates (avg/low/high), growth, analyst count.+institution_ownership | institutionOwnership | Top institutional holders (organization, report date, pct held, position, value).+insider_holders | insiderHolders | Insider holders (name, relation, latest transaction date, position).+recommendation_trend | recommendationTrend | Strong-buy / buy / hold / sell / strong-sell counts per period.++<br>+<br>++**Output**++A JSON-string envelope.++On success:++```json+{"ok": true, "market": "us|hk", "source": "yahoo",+ "data": {"ticker": "<input>", "sections": {"<name>": <shaped>}}}+```++`market` is `hk` when the ticker ends `.HK`, else `us`. Scalar sections+(`key_stats`, `financials`) shape to a flat dict; list sections+(`earnings_trend`, `institution_ownership`, `insider_holders`,+`recommendation_trend`) shape to a list of rows (≤ 25).++On failure:++```json+{"ok": false, "error": "<message>"}+```++Failures are returned as an envelope (never raised) — e.g. a missing/blank+`ticker`, an unknown section name, or an upstream Yahoo request error.++<br>+<br>++**Example**++```text+get_stock_profile(ticker="AAPL.US")+get_stock_profile(ticker="AAPL", sections=["key_stats", "financials"])+get_stock_profile(ticker="00700.HK", sections=["key_stats"])+```++<br>+<br>++**Data example**++```json+{+ "ok": true, "market": "us", "source": "yahoo",+ "data": {+ "ticker": "AAPL.US",+ "sections": {+ "key_stats": {"enterpriseValue": 2980000000000, "forwardPE": 27.4,+ "trailingEps": 6.43, "priceToBook": 45.1, "beta": 1.28,+ "heldPercentInstitutions": 0.612},+ "financials": {"currentPrice": 192.2, "targetMeanPrice": 205.0,+ "recommendationKey": "buy", "numberOfAnalystOpinions": 41,+ "returnOnEquity": 1.47}+ }+ }+}+```diff --git a/agent/src/skills/yfinance/references/yahoo_client_get_chart.md b/agent/src/skills/yfinance/references/yahoo_client_get_chart.mdnew file mode 100644index 000000000..16c99c908--- /dev/null+++ b/agent/src/skills/yfinance/references/yahoo_client_get_chart.md@@ -0,0 +1,87 @@+## yahoo_client.get_chart++----++Interface: `backtest.loaders.yahoo_client.get_chart`+Endpoint: `GET https://query1.finance.yahoo.com/v8/finance/chart/{symbol}`+Description: Fetch OHLCV bars directly from Yahoo's v8 chart endpoint as+ascending row dicts. This is the lowest-level price call — for normal backtest+or agent OHLCV work prefer the `get_market_data` tool or the yfinance loader,+which already routes through this client and normalizes the frame. Use+`get_chart` directly only when you need raw bars with a custom interval/window+and want to map them yourself.++Auth: none (unauthenticated public endpoint). All traffic passes through the+shared throttle (`backtest.loaders._http`) because Yahoo rate-limits by source+IP; spacing is enforced process-wide across every Yahoo call.++<br>+<br>++**Input parameters**++Name | Type | Required | Description+---- | ---- | -------- | -----------+symbol | str | Y | Project-side symbol (`AAPL.US`, `00700.HK`, `BTC-USD`, `^GSPC`). Mapped to Yahoo form via `map_symbol`.+interval | str | N | Bar size accepted by Yahoo: `1m`, `2m`, `5m`, `15m`, `30m`, `60m`, `90m`, `1h`, `1d`, `5d`, `1wk`, `1mo`, `3mo`. Default `1d`.+period1 | int | N | Inclusive start as Unix epoch seconds. Ignored when `range_` is given.+period2 | int | N | Exclusive end as Unix epoch seconds. Ignored when `range_` is given.+range_ | str | N | Relative range string (`1d`, `5d`, `1mo`, `6mo`, `1y`, `5y`, `max`). Takes precedence over `period1`/`period2` when both are supplied.++Supply either `range_` or a `period1`/`period2` window. Minute-bar history is+limited by Yahoo (1m ≈ 7 days; 2m–90m ≈ 60 days; 1h ≈ 730 days; daily+ is+unbounded).++<br>+<br>++**Output**++Returns a `list[dict]` of ascending bars. Each row:++Field | Type | Description+----- | ---- | -----------+trade_date | int | Bar timestamp as Unix epoch seconds.+open | float | Open price.+high | float | High price.+low | float | Low price.+close | float | Close price.+volume | float | Traded volume.++Bars whose OHLC is `null` (non-trading slots Yahoo pads in) are dropped. An+empty list is returned when Yahoo reports no data for the symbol/window.++Raises `requests.RequestException` on a network/HTTP failure and `ValueError`+when Yahoo reports a per-symbol error or the payload is structurally unusable.++<br>+<br>++**Example**++```python+from backtest.loaders import yahoo_client++# Relative range+bars = yahoo_client.get_chart("AAPL.US", interval="1d", range_="1mo")++# Explicit epoch window+import time+end = int(time.time())+start = end - 7 * 24 * 3600+intraday = yahoo_client.get_chart(+ "AAPL.US", interval="5m", period1=start, period2=end+)+for row in bars[:3]:+ print(row)+```++<br>+<br>++**Data example**++```text+{'trade_date': 1717075800, 'open': 191.5, 'high': 192.6, 'low': 190.9, 'close': 192.2, 'volume': 48211000.0}+{'trade_date': 1717162200, 'open': 192.9, 'high': 194.0, 'low': 192.1, 'close': 193.5, 'volume': 51122300.0}+```diff --git a/agent/src/skills/yfinance/references/yahoo_client_get_options.md b/agent/src/skills/yfinance/references/yahoo_client_get_options.mdnew file mode 100644index 000000000..cf636b541--- /dev/null+++ b/agent/src/skills/yfinance/references/yahoo_client_get_options.md@@ -0,0 +1,88 @@+## yahoo_client.get_options++----++Interface: `backtest.loaders.yahoo_client.get_options`+Endpoint: `GET https://query2.finance.yahoo.com/v7/finance/options/{symbol}`+Description: Fetch the Yahoo v7 option chain for an underlying — the list of+available expirations plus the calls/puts ladder for one expiration. This is+the data source behind the `get_options_chain` tool; call the tool for a+capped, snake_case envelope, and call this function directly when you need the+raw chain (e.g. all contract fields, strikes array, or quote block).++Auth: none (unauthenticated public endpoint). Routed through the shared+throttle because Yahoo rate-limits by source IP.++<br>+<br>++**Input parameters**++Name | Type | Required | Description+---- | ---- | -------- | -----------+symbol | str | Y | Project-side underlying symbol (`AAPL.US`). Mapped to Yahoo form via `map_symbol`.+expiration | int | N | Expiration as Unix epoch seconds (one of `expirationDates`). Omit for the nearest expiration.++<br>+<br>++**Output**++Returns the `optionChain.result[0]` mapping, or `{}` when Yahoo has no chain.+Key members:++Field | Type | Description+----- | ---- | -----------+underlyingSymbol | str | The resolved Yahoo underlying ticker.+expirationDates | list[int] | All available expirations as Unix epoch seconds.+strikes | list[float] | All strike prices for the returned expiration.+options | list[dict] | One block for the chosen expiration with `expirationDate`, `calls`, `puts`.++Each entry in `calls` / `puts` is a contract dict with (among others)+`contractSymbol`, `strike`, `lastPrice`, `bid`, `ask`, `volume`,+`openInterest`, `impliedVolatility`, `inTheMoney`, and `expiration`.++Raises `requests.RequestException` on a network/HTTP failure and `ValueError`+when Yahoo reports a per-symbol error.++<br>+<br>++**Example**++```python+from backtest.loaders import yahoo_client++# Nearest expiration+chain = yahoo_client.get_options("AAPL.US")+expirations = chain.get("expirationDates", [])+block = (chain.get("options") or [{}])[0]+print(len(block.get("calls", [])), "calls")++# A specific later expiration+if len(expirations) > 1:+ later = yahoo_client.get_options("AAPL.US", expiration=expirations[1])+```++<br>+<br>++**Data example**++```text+{+ "underlyingSymbol": "AAPL",+ "expirationDates": [1718236800, 1718841600, 1719446400],+ "options": [{+ "expirationDate": 1718236800,+ "calls": [{"contractSymbol": "AAPL240613C00190000", "strike": 190.0,+ "lastPrice": 4.05, "bid": 3.95, "ask": 4.10, "volume": 1203,+ "openInterest": 8821, "impliedVolatility": 0.224,+ "inTheMoney": true}],+ "puts": [{"contractSymbol": "AAPL240613P00190000", "strike": 190.0,+ "lastPrice": 1.85, "bid": 1.80, "ask": 1.90, "volume": 642,+ "openInterest": 5104, "impliedVolatility": 0.231,+ "inTheMoney": false}]+ }]+}+```diff --git a/agent/src/skills/yfinance/references/yahoo_client_get_quote_summary.md b/agent/src/skills/yfinance/references/yahoo_client_get_quote_summary.mdnew file mode 100644index 000000000..30151fc86--- /dev/null+++ b/agent/src/skills/yfinance/references/yahoo_client_get_quote_summary.md@@ -0,0 +1,85 @@+## yahoo_client.get_quote_summary++----++Interface: `backtest.loaders.yahoo_client.get_quote_summary`+Endpoint: `GET https://query2.finance.yahoo.com/v10/finance/quoteSummary/{symbol}`+Description: Fetch one or more Yahoo quoteSummary **modules** for a symbol —+valuation key statistics, analyst financials/estimates, ownership, and similar+fundamentals. This is the data source behind the `get_stock_profile` tool; call+the tool when you want a compact, projected envelope, and call this function+directly when you need raw module payloads or a module the tool does not expose.++Auth: the v10 quoteSummary endpoint requires a session **cookie** plus a+matching **crumb** token. The client performs this handshake lazily on first+use and refreshes it once on a `401` (the documented "crumb expired /+unauthorized" signal), so callers never manage cookies or crumbs. All requests+route through the shared throttle because Yahoo rate-limits by source IP.++<br>+<br>++**Input parameters**++Name | Type | Required | Description+---- | ---- | -------- | -----------+symbol | str | Y | Project-side symbol (`AAPL.US`, `00700.HK`). Mapped to Yahoo form via `map_symbol`.+modules | list[str] | Y | Yahoo module names to request, joined as the `modules` query param.++Commonly used module names:++Module | Contents+------ | --------+price | Current price, exchange, currency, market state.+summaryDetail | Day range, 52-week range, volume, dividend yield, market cap.+defaultKeyStatistics | Enterprise value, forward PE, EPS, PEG, price-to-book, shares outstanding, insider/institution held %.+financialData | Current price, analyst target prices, recommendation key, revenue/margins, cash/debt, ROE.+earningsTrend | Per-period EPS and revenue estimates with growth and analyst counts.+institutionOwnership | Top institutional holders (organization, report date, pct held, position, value).+insiderHolders | Insider holders (name, relation, latest transaction date, position).+recommendationTrend | Strong-buy / buy / hold / sell / strong-sell counts per period.+assetProfile | Sector, industry, business summary, officers, employee count.++<br>+<br>++**Output**++Returns the `quoteSummary.result[0]` mapping: a dict keyed by the requested+module names, each value the verbose Yahoo module payload. Returns `{}` when+Yahoo returns no result for the symbol.++Many scalar cells arrive as Yahoo `{"raw": <number>, "fmt": <string>}` wrappers+— take the `raw` member for the numeric value (the `get_stock_profile` tool's+`_raw` helper does exactly this).++Raises `requests.RequestException` on a non-401 HTTP failure or a second+consecutive `401`, and `ValueError` when Yahoo reports a per-symbol error.++<br>+<br>++**Example**++```python+from backtest.loaders.yahoo_client import get_quote_summary++summary = get_quote_summary("AAPL.US", ["price", "defaultKeyStatistics"])+price = summary.get("price", {})+stats = summary.get("defaultKeyStatistics", {})+print(price.get("regularMarketPrice", {}).get("raw"))+print(stats.get("forwardPE", {}).get("raw"))+```++<br>+<br>++**Data example**++```text+{+ "price": {"regularMarketPrice": {"raw": 192.2, "fmt": "192.20"}, "currency": "USD"},+ "defaultKeyStatistics": {"forwardPE": {"raw": 27.4, "fmt": "27.40"},+ "priceToBook": {"raw": 45.1, "fmt": "45.10"}}+}+```diff --git a/agent/src/skills/yfinance/references/yahoo_client_search.md b/agent/src/skills/yfinance/references/yahoo_client_search.mdnew file mode 100644index 000000000..a1ba0c927--- /dev/null+++ b/agent/src/skills/yfinance/references/yahoo_client_search.md@@ -0,0 +1,63 @@+## yahoo_client.search++----++Interface: `backtest.loaders.yahoo_client.search`+Endpoint: `GET https://query2.finance.yahoo.com/v1/finance/search`+Description: Resolve a free-text query (ticker fragment or company name) to+matching Yahoo instruments. Useful for symbol discovery before calling+`get_chart`, `get_quote_summary`, or `get_options`.++Auth: none (unauthenticated public endpoint). Routed through the shared+throttle because Yahoo rate-limits by source IP.++<br>+<br>++**Input parameters**++Name | Type | Required | Description+---- | ---- | -------- | -----------+query | str | Y | Free-text query — a ticker fragment (`AAPL`) or company name (`Apple`), sent as the `q` query param.++<br>+<br>++**Output**++Returns the `quotes` list (non-dict entries filtered out), or `[]` when nothing+matches. Each quote dict typically carries:++Field | Type | Description+----- | ---- | -----------+symbol | str | Yahoo ticker (use as-is for the other client calls, or map back to project form).+shortname | str | Short instrument name.+longname | str | Full instrument name (when available).+exchange | str | Exchange code.+quoteType | str | Instrument type (`EQUITY`, `ETF`, `INDEX`, `CRYPTOCURRENCY`, ...).++Raises `requests.RequestException` on a network/HTTP failure.++<br>+<br>++**Example**++```python+from backtest.loaders import yahoo_client++matches = yahoo_client.search("Apple")+for quote in matches[:3]:+ print(quote.get("symbol"), quote.get("shortname"), quote.get("quoteType"))+```++<br>+<br>++**Data example**++```text+AAPL Apple Inc. EQUITY+APLE Apple Hospitality REIT EQUITY+AAPL.MX Apple Inc. EQUITY+```diff --git a/agent/src/tools/block_trades_tool.py b/agent/src/tools/block_trades_tool.pynew file mode 100644index 000000000..6150f3b99--- /dev/null+++ b/agent/src/tools/block_trades_tool.py@@ -0,0 +1,277 @@+"""Block-trade (大宗交易) lookup tool backed by the Eastmoney datacenter.++Eastmoney publishes every A-share block trade — negotiated off-book deals struck+at a premium or discount to the close — through its free, no-auth datacenter+report API (``RPT_DATA_BLOCKTRADE``). Each record carries the deal price and+volume, the discount/premium versus that session's close, and the buyer/seller+营业部 ("seats") that booked the trade. Block-trade flow is a watched signal for+institutional accumulation or distribution, so this read-only tool surfaces the+recent record list for a single A-share symbol.++Every request routes through the shared, throttled Eastmoney client+(:func:`backtest.loaders.eastmoney_client.get_json`) because Eastmoney+rate-limits by source IP; this tool never opens its own HTTP session.+"""++from __future__ import annotations++import json+import logging+from datetime import date, datetime, timedelta+from typing import Any++from backtest.loaders.eastmoney_client import get_json, resolve_secid+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney datacenter report endpoint + the block-trade report name.+_DATACENTER_URL = "https://datacenter-web.eastmoney.com/api/data/v1/get"+_REPORT_NAME = "RPT_DATA_BLOCKTRADE"++# Report columns we request, mapped to our envelope keys. The report exposes the+# Chinese-named fields below; we never rename them in transit, only on output.+_FIELDS = (+ "TRADE_DATE,SECURITY_CODE,SECURITY_NAME_ABBR,CLOSE_PRICE,DEAL_PRICE,"+ "PREMIUM_RATIO,DEAL_VOLUME,DEAL_AMT,BUYER_NAME,SELLER_NAME"+)++# Bound the request and the returned payload so a wide window cannot blow up the+# context window. Eastmoney paginates; we pull one bounded page.+_MAX_RECORDS = 200+_MAX_DAYS = 365+_DEFAULT_DAYS = 30+++def _resolve_code(symbol: str) -> str | None:+ """Validate an A-share symbol and extract its bare 6-digit code.++ The datacenter report filters by the plain ``SECURITY_CODE`` (no market+ prefix), but we route through :func:`resolve_secid` first so only genuine+ A-share symbols (``.SH`` / ``.SZ`` / ``.BJ``) are accepted; block trades do+ not exist for HK/US listings here.++ Args:+ symbol: Symbol such as ``"600519.SH"`` or ``"000001.SZ"``.++ Returns:+ The bare 6-digit code (e.g. ``"600519"``), or ``None`` when the symbol+ is not a resolvable A-share.+ """+ secid = resolve_secid(symbol)+ if not secid or "." not in secid:+ return None+ market = secid.split(".", 1)[0]+ if market not in ("0", "1"): # 0=SZ/BJ, 1=SH; HK/US are not A-share blocks.+ return None+ code = symbol.rpartition(".")[0].strip().upper()+ return code or None+++def _clamp_days(days: Any) -> int:+ """Coerce the ``days`` argument into the supported ``[1, _MAX_DAYS]`` range.++ Args:+ days: Caller-supplied lookback window; may be missing or malformed.++ Returns:+ A bounded integer day count, defaulting to ``_DEFAULT_DAYS``.+ """+ try:+ value = int(days)+ except (TypeError, ValueError):+ return _DEFAULT_DAYS+ if value < 1:+ return 1+ if value > _MAX_DAYS:+ return _MAX_DAYS+ return value+++def _date_filter(code: str, start: date, end: date) -> str:+ """Build the report ``filter`` clause for one code over a date window.++ Args:+ code: Bare 6-digit security code.+ start: Inclusive lower bound.+ end: Inclusive upper bound.++ Returns:+ An Eastmoney report filter expression string.+ """+ return (+ f"(SECURITY_CODE=\"{code}\")"+ f"(TRADE_DATE>='{start.isoformat()}')"+ f"(TRADE_DATE<='{end.isoformat()}')"+ )+++def _to_float(value: Any) -> float | None:+ """Best-effort float coercion that maps blanks/None to ``None``.++ Args:+ value: Raw report cell value.++ Returns:+ The float value, or ``None`` when the cell is empty or non-numeric.+ """+ if value is None or value == "":+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _normalize_record(raw: dict[str, Any]) -> dict[str, Any]:+ """Project one raw report row onto our stable, English-keyed shape.++ Args:+ raw: One ``result.data`` element from the datacenter response.++ Returns:+ A normalized record: trade date, deal price/volume/amount, the+ premium-vs-close ratio, and the buyer/seller seat names.+ """+ return {+ "trade_date": raw.get("TRADE_DATE"),+ "name": raw.get("SECURITY_NAME_ABBR"),+ "close_price": _to_float(raw.get("CLOSE_PRICE")),+ "deal_price": _to_float(raw.get("DEAL_PRICE")),+ "premium_ratio": _to_float(raw.get("PREMIUM_RATIO")),+ "deal_volume": _to_float(raw.get("DEAL_VOLUME")),+ "deal_amount": _to_float(raw.get("DEAL_AMT")),+ "buyer_seat": raw.get("BUYER_NAME"),+ "seller_seat": raw.get("SELLER_NAME"),+ }+++def _extract_rows(payload: Any) -> list[dict[str, Any]]:+ """Pull the data rows out of a datacenter ``result`` envelope.++ Args:+ payload: Decoded JSON from the datacenter endpoint.++ Returns:+ The list of raw row dicts, or an empty list when the payload carries+ no data (an empty window is a valid, non-error result).+ """+ if not isinstance(payload, dict):+ return []+ result = payload.get("result")+ if not isinstance(result, dict):+ return []+ data = result.get("data")+ if not isinstance(data, list):+ return []+ return [row for row in data if isinstance(row, dict)]+++class BlockTradesTool(BaseTool):+ """Recent A-share block trades (大宗交易): price, premium, volume, seats."""++ name = "get_block_trades"+ description = (+ "Fetch recent A-share block trades (大宗交易) for one symbol from the "+ "Eastmoney datacenter: per-deal price, volume, amount, the "+ "premium/discount versus that day's close, and the buyer/seller broker "+ "seats (营业部). Markets: China A-share only (.SH/.SZ/.BJ). Read-only. "+ 'Example: get_block_trades(code="600519.SH", days=30).'+ )+ parameters = {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": (+ "A-share symbol with exchange suffix, e.g. '600519.SH', "+ "'000001.SZ', or '830799.BJ'."+ ),+ },+ "days": {+ "type": "integer",+ "description": (+ "Lookback window in calendar days ending today; clamped to "+ f"[1, {_MAX_DAYS}]."+ ),+ "default": _DEFAULT_DAYS,+ },+ },+ "required": ["code"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Look up block trades for one symbol and return a JSON envelope.++ Args:+ **kwargs: ``code`` (required A-share symbol) and optional ``days``+ lookback window.++ Returns:+ A JSON string. On success:+ ``{"ok": true, "market": "china_a", "source": "eastmoney",+ "data": {"code", "days", "count", "records": [...]}}``. On failure:+ ``{"ok": false, "error": str}``.+ """+ symbol = str(kwargs.get("code") or "").strip()+ if not symbol:+ return json.dumps(+ {"ok": False, "error": "code is required"}, ensure_ascii=False+ )++ code = _resolve_code(symbol)+ if code is None:+ return json.dumps(+ {+ "ok": False,+ "error": (+ f"{symbol!r} is not a resolvable A-share symbol "+ "(use .SH/.SZ/.BJ)"+ ),+ },+ ensure_ascii=False,+ )++ days = _clamp_days(kwargs.get("days", _DEFAULT_DAYS))+ end = datetime.now().date()+ start = end - timedelta(days=days - 1)++ try:+ payload = get_json(+ _DATACENTER_URL,+ params={+ "reportName": _REPORT_NAME,+ "columns": _FIELDS,+ "filter": _date_filter(code, start, end),+ "sortColumns": "TRADE_DATE",+ "sortTypes": "-1",+ "pageNumber": "1",+ "pageSize": str(_MAX_RECORDS),+ "source": "WEB",+ "client": "WEB",+ },+ )+ except Exception as exc: # noqa: BLE001 - surface upstream failure as envelope+ logger.warning("block-trade lookup failed for %s: %s", symbol, exc)+ return json.dumps(+ {"ok": False, "error": f"eastmoney request failed: {exc}"},+ ensure_ascii=False,+ )++ rows = _extract_rows(payload)+ records = [_normalize_record(row) for row in rows[:_MAX_RECORDS]]++ return json.dumps(+ {+ "ok": True,+ "market": "china_a",+ "source": "eastmoney",+ "data": {+ "code": symbol,+ "days": days,+ "count": len(records),+ "records": records,+ },+ },+ ensure_ascii=False,+ )diff --git a/agent/src/tools/dragon_tiger_tool.py b/agent/src/tools/dragon_tiger_tool.pynew file mode 100644index 000000000..158d2d9e4--- /dev/null+++ b/agent/src/tools/dragon_tiger_tool.py@@ -0,0 +1,266 @@+"""Dragon-Tiger (龙虎榜) board tool backed by the Eastmoney datacenter API.++The Shanghai/Shenzhen exchanges publish a daily "dragon-tiger" (龙虎榜) board+listing every A-share that triggered an abnormal-trading disclosure, together+with the brokerage seats that drove the largest buys and sells. Eastmoney+re-serves this disclosure through its free, no-auth ``datacenter-web`` JSON+endpoint, which it rate-limits by source IP, so every request here routes+through the shared throttled Eastmoney client.++This tool is read-only: it returns the day's board appearances (optionally+narrowed to one A-share ``code``) and, for a specific security, the ranked+top buy/sell brokerage seats.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from backtest.loaders import eastmoney_client+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney datacenter report endpoint and the two report names this tool reads.+_DATACENTER_URL = "https://datacenter-web.eastmoney.com/api/data/v1/get"+_APPEARANCE_REPORT = "RPT_DAILYBILLBOARD_DETAILS"+_SEAT_REPORT = "RPT_BILLBOARD_TRADEDETAIL"++# Per-symbol caps so a wide market day never returns an unbounded payload.+_MAX_APPEARANCES = 200+_MAX_SEATS = 30+++def _compact_date(date: str) -> str:+ """Normalize a ``YYYY-MM-DD`` (or already-compact) date for the API filter.++ Args:+ date: A trade date such as ``"2024-01-02"`` or ``"20240102"``.++ Returns:+ The date in dashed ``YYYY-MM-DD`` form expected by the datacenter+ ``TRADE_DATE`` filter.++ Raises:+ ValueError: The string is not a recognizable 8-digit / dashed date.+ """+ cleaned = date.strip()+ digits = cleaned.replace("-", "")+ if len(digits) != 8 or not digits.isdigit():+ raise ValueError(f"invalid date: {date!r}; expected YYYY-MM-DD")+ return f"{digits[:4]}-{digits[4:6]}-{digits[6:]}"+++def _bare_code(code: str) -> str:+ """Strip any exchange suffix to the bare numeric A-share code.++ Args:+ code: A symbol such as ``"600519.SH"``, ``"000001.SZ"`` or ``"600519"``.++ Returns:+ The leading numeric code (e.g. ``"600519"``).+ """+ return code.strip().upper().split(".", 1)[0]+++def _fetch_report(+ report_name: str, *, filter_expr: str, sort_columns: str, sort_types: str+) -> list[dict[str, Any]]:+ """Pull one page of datacenter rows for a report, tolerating empty results.++ Args:+ report_name: Eastmoney ``reportName`` (e.g. ``RPT_DAILYBILLBOARD_DETAILS``).+ filter_expr: The datacenter ``filter`` predicate string.+ sort_columns: Column name to sort by.+ sort_types: Sort direction (``"1"`` ascending, ``"-1"`` descending).++ Returns:+ The list of row dicts under ``result.data``; empty when none.++ Raises:+ requests.RequestException: Network failure, propagated to the caller.+ requests.HTTPError: Non-2xx response status.+ ValueError: Body is not valid JSON.+ """+ payload = eastmoney_client.get_json(+ _DATACENTER_URL,+ params={+ "reportName": report_name,+ "columns": "ALL",+ "filter": filter_expr,+ "sortColumns": sort_columns,+ "sortTypes": sort_types,+ "pageNumber": "1",+ "pageSize": "500",+ "source": "WEB",+ "client": "WEB",+ },+ )+ if not isinstance(payload, dict):+ return []+ result = payload.get("result")+ if not isinstance(result, dict):+ return []+ data = result.get("data")+ if not isinstance(data, list):+ return []+ return [row for row in data if isinstance(row, dict)]+++def _appearance_row(raw: dict[str, Any]) -> dict[str, Any]:+ """Project a raw appearance row to a compact, named record.++ Args:+ raw: One ``RPT_DAILYBILLBOARD_DETAILS`` row.++ Returns:+ A flat dict of the fields a research caller cares about.+ """+ return {+ "code": raw.get("SECURITY_CODE"),+ "name": raw.get("SECURITY_NAME_ABBR"),+ "close": raw.get("CLOSE_PRICE"),+ "change_pct": raw.get("CHANGE_RATE"),+ "net_buy": raw.get("BILLBOARD_NET_AMT"),+ "buy_amount": raw.get("BILLBOARD_BUY_AMT"),+ "sell_amount": raw.get("BILLBOARD_SELL_AMT"),+ "turnover": raw.get("ACCUM_AMOUNT"),+ "reason": raw.get("EXPLANATION"),+ }+++def _seat_row(raw: dict[str, Any]) -> dict[str, Any]:+ """Project a raw seat row to a compact, named record.++ Args:+ raw: One ``RPT_BILLBOARD_TRADEDETAIL`` row.++ Returns:+ A flat dict describing one brokerage seat's buy/sell footprint.+ """+ return {+ "seat": raw.get("OPERATEDEPT_NAME"),+ "side": raw.get("SIDE"),+ "buy": raw.get("BUY"),+ "sell": raw.get("SELL"),+ "net": raw.get("NET"),+ "rank": raw.get("RANK"),+ }+++class DragonTigerTool(BaseTool):+ """Query the Eastmoney A-share dragon-tiger (龙虎榜) disclosure board."""++ name = "get_dragon_tiger"+ description = (+ "Fetch the A-share dragon-tiger board (龙虎榜) for a given trade date from "+ "Eastmoney's free datacenter API. Markets: China A-share (SH/SZ). Omit "+ "'code' for the full-market list of every security that appeared on the "+ "board that day; supply 'code' to also get that security's ranked top "+ "buy/sell brokerage seats. Read-only, no auth. "+ 'Example: {"date": "2024-01-02", "code": "600519.SH"}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "date": {+ "type": "string",+ "description": "Trade date in YYYY-MM-DD format (e.g. 2024-01-02).",+ },+ "code": {+ "type": "string",+ "description": (+ "Optional A-share symbol or bare code (e.g. '600519.SH' or "+ "'600519'). Omit to list the entire market's board for the "+ "date; supply it to also fetch that security's seat detail."+ ),+ },+ },+ "required": ["date"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Fetch dragon-tiger appearances (and seats when ``code`` is given).++ Args:+ **kwargs: ``date`` (required, YYYY-MM-DD) and optional ``code``.++ Returns:+ A JSON string envelope. On success:+ ``{"ok": true, "market": "a_share", "source": "eastmoney",+ "data": {...}}``. On failure: ``{"ok": false, "error": "..."}``.+ """+ date_arg = kwargs.get("date")+ if not isinstance(date_arg, str) or not date_arg.strip():+ return self._error("missing required parameter: date")++ try:+ trade_date = _compact_date(date_arg)+ except ValueError as exc:+ return self._error(str(exc))++ code_arg = kwargs.get("code")+ code = _bare_code(code_arg) if isinstance(code_arg, str) and code_arg.strip() else None++ try:+ data = self._collect(trade_date, code)+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as an envelope+ logger.warning("dragon-tiger fetch failed for %s/%s: %s", trade_date, code, exc)+ return self._error(f"eastmoney dragon-tiger fetch failed: {exc}")++ return json.dumps(+ {"ok": True, "market": "a_share", "source": "eastmoney", "data": data},+ ensure_ascii=False,+ )++ def _collect(self, trade_date: str, code: str | None) -> dict[str, Any]:+ """Assemble the appearances and (optionally) seat detail payload.++ Args:+ trade_date: Dashed ``YYYY-MM-DD`` trade date.+ code: Bare A-share code, or ``None`` for the full-market list.++ Returns:+ A dict with ``date``, capped ``appearances`` and, when ``code`` is+ given, capped ``seats`` plus the seat ``code``.+ """+ appear_filter = f"(TRADE_DATE='{trade_date}')"+ if code:+ appear_filter += f"(SECURITY_CODE=\"{code}\")"+ appearances_raw = _fetch_report(+ _APPEARANCE_REPORT,+ filter_expr=appear_filter,+ sort_columns="BILLBOARD_NET_AMT",+ sort_types="-1",+ )+ appearances = [_appearance_row(r) for r in appearances_raw[:_MAX_APPEARANCES]]++ data: dict[str, Any] = {+ "date": trade_date,+ "count": len(appearances_raw),+ "appearances": appearances,+ }+ if code:+ data["code"] = code+ seats_raw = _fetch_report(+ _SEAT_REPORT,+ filter_expr=f"(TRADE_DATE='{trade_date}')(SECURITY_CODE=\"{code}\")",+ sort_columns="NET",+ sort_types="-1",+ )+ data["seats"] = [_seat_row(r) for r in seats_raw[:_MAX_SEATS]]+ return data++ @staticmethod+ def _error(message: str) -> str:+ """Render a failure envelope as a JSON string.++ Args:+ message: Human-readable error text.++ Returns:+ ``{"ok": false, "error": message}`` as a JSON string.+ """+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)diff --git a/agent/src/tools/financial_statements_tool.py b/agent/src/tools/financial_statements_tool.pynew file mode 100644index 000000000..9aa98a404--- /dev/null+++ b/agent/src/tools/financial_statements_tool.py@@ -0,0 +1,378 @@+"""Read-only financial-statements tool: three statements + key indicators.++Pulls a single stock's balance sheet, income statement, cash-flow statement, or+key per-period indicators from Eastmoney's free, no-auth datacenter report API,+picking the per-market report dataset from the symbol's market suffix:++* **A-share** (``.SH`` / ``.SZ`` / ``.BJ``) — Eastmoney's A-share F10 report+ datasets (``RPT_F10_FINANCE_*``), filtered on the dotted ``SECUCODE`` (e.g.+ ``600519.SH``). The legacy Sina ``quotes.sina.cn`` company-finance openapi+ returned a graceful-empty masking an upstream failure, so the A-share path now+ shares the Eastmoney transport with US/HK.+* **US** (``.US``) and **Hong Kong** (``.HK``) — Eastmoney's per-market F10+ financial-report datasets, filtered on the bare ``SECURITY_CODE``; ``indicators``+ reads the main-indicator dataset.++All requests go through :func:`backtest.loaders.eastmoney_client.get_json`+(Eastmoney bans bursting clients, so every call is throttled under+``host_key="eastmoney"``).++The tool is read-only and self-contained: ``execute`` returns a JSON-string+envelope and never raises for a recoverable per-request failure — a bad symbol+or a transient HTTP error is reported inside the envelope.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from backtest.loaders.eastmoney_client import get_json, resolve_secid+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# --- Eastmoney datacenter report API --------------------------------------++# Eastmoney datacenter report API. The three statements and the main-indicator+# dataset are addressed by report name, which differs by market (A / US / HK).+_EM_REPORT_URL = "https://datacenter.eastmoney.com/securities/api/data/v1/get"++# (market_prefix_group, statement) -> Eastmoney report name. ``a`` covers the+# mainland exchanges (markets 0/1); ``us`` covers 105/106/107; ``hk`` covers 116.+_EM_REPORT_NAME: dict[str, dict[str, str]] = {+ "a": {+ "balance": "RPT_F10_FINANCE_GBALANCE",+ "income": "RPT_F10_FINANCE_GINCOME",+ "cashflow": "RPT_F10_FINANCE_GCASHFLOW",+ "indicators": "RPT_F10_FINANCE_MAINFINADATA",+ },+ "us": {+ "balance": "RPT_USF10_FN_BALANCE",+ "income": "RPT_USF10_FN_INCOME",+ "cashflow": "RPT_USF10_FN_CASHFLOW",+ "indicators": "RPT_USF10_FN_GMAININDICATOR",+ },+ "hk": {+ "balance": "RPT_HKF10_FN_BALANCE",+ "income": "RPT_HKF10_FN_INCOME",+ "cashflow": "RPT_HKF10_FN_CASHFLOW",+ "indicators": "RPT_HKF10_FN_GMAININDICATOR",+ },+}++# Eastmoney mainland A-share markets (SZ/BJ = 0, SH = 1), US markets+# (NASDAQ / NYSE / AMEX), and the HK market.+_EM_A_MARKETS = ("0", "1")+_EM_US_MARKETS = ("105", "106", "107")+_EM_HK_MARKET = "116"++# --- Shared limits / validation ------------------------------------------++_VALID_STATEMENTS = ("balance", "income", "cashflow", "indicators")+_VALID_PERIODS = ("annual", "quarter")++# Defensive caps so a payload can never blow up the LLM context.+_MAX_PERIODS = 40+_MAX_FIELDS_PER_PERIOD = 200+++def _error(message: str) -> str:+ """Build the failure envelope as a JSON string.++ Args:+ message: Human-readable error description.++ Returns:+ A ``{"ok": false, "error": ...}`` JSON string.+ """+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)+++def _truncate_period(record: dict[str, Any]) -> dict[str, Any]:+ """Cap one period's field count so a single record stays context-safe.++ Args:+ record: A flat period dict (field name -> value).++ Returns:+ A new dict with at most :data:`_MAX_FIELDS_PER_PERIOD` items, preserving+ insertion order. The original is never mutated.+ """+ items = list(record.items())+ if len(items) <= _MAX_FIELDS_PER_PERIOD:+ return dict(items)+ return dict(items[:_MAX_FIELDS_PER_PERIOD])+++def _cap_periods(periods: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Keep the most recent periods, each truncated to a safe field count.++ Args:+ periods: Period records as returned by the provider parser.++ Returns:+ A new list of at most :data:`_MAX_PERIODS` field-capped records.+ """+ capped = periods[:_MAX_PERIODS]+ return [_truncate_period(record) for record in capped]+++def _eastmoney_market_group(secid: str) -> str | None:+ """Classify an Eastmoney secid into the ``a``, ``us``, or ``hk`` report group.++ Args:+ secid: Eastmoney secid (e.g. ``"1.600519"``, ``"105.AAPL"`` or+ ``"116.00700"``).++ Returns:+ ``"a"``, ``"us"``, ``"hk"``, or ``None`` when the market prefix is+ unrecognized.+ """+ market = secid.split(".", 1)[0]+ if market in _EM_A_MARKETS:+ return "a"+ if market in _EM_US_MARKETS:+ return "us"+ if market == _EM_HK_MARKET:+ return "hk"+ return None+++def _parse_eastmoney_periods(payload: Any) -> list[dict[str, Any]]:+ """Extract period records from an Eastmoney datacenter report payload.++ Eastmoney nests report rows under ``result.data`` as a list of flat dicts.+ Any other shape yields an empty list rather than raising.++ Args:+ payload: Decoded JSON from the datacenter report API.++ Returns:+ A list of flat period dicts (possibly empty).+ """+ if not isinstance(payload, dict):+ return []+ result = payload.get("result")+ data = result.get("data") if isinstance(result, dict) else None+ if not isinstance(data, list):+ return []+ return [row for row in data if isinstance(row, dict)]+++def _eastmoney_filter(group: str, code: str, secid: str) -> str:+ """Build the datacenter ``filter`` clause for one market group.++ The A-share F10 datasets key on the dotted ``SECUCODE`` (e.g.+ ``600519.SH``), whereas the US/HK datasets key on the bare ``SECURITY_CODE``+ carried in the secid (e.g. ``AAPL`` / ``00700``). No ``REPORT_TYPE`` clause+ is emitted: Eastmoney stores ``REPORT_TYPE`` as locale text (年报 / 一季报)+ or a ``2026/Q1`` string that differs by market and report, so a numeric+ filter matched zero rows. Period selection is done client-side instead+ (see :func:`_filter_by_period`).++ Args:+ group: Market group from :func:`_eastmoney_market_group`.+ code: Original Vibe-Trading symbol (e.g. ``"600519.SH"``).+ secid: Resolved Eastmoney secid (e.g. ``"1.600519"``).++ Returns:+ The Eastmoney ``filter`` query-parameter string.+ """+ if group == "a":+ return f'(SECUCODE="{code.upper()}")'+ bare_code = secid.split(".", 1)[1]+ return f'(SECURITY_CODE="{bare_code}")'+++def _filter_by_period(+ periods: list[dict[str, Any]], period: str+) -> list[dict[str, Any]]:+ """Best-effort client-side period selection by report date.++ Eastmoney returns a mixed newest-first series (annual + interim reports).+ For ``annual`` we keep only fiscal-year-end rows (``REPORT_DATE`` ending+ ``-12-31``); if none match — e.g. a US issuer whose fiscal year does not end+ in December — we fall back to the full series rather than drop all data.+ ``quarter`` returns the full newest-first series unchanged.++ Args:+ periods: Period records (newest-first) from the report parser.+ period: ``"annual"`` or ``"quarter"``.++ Returns:+ The filtered list; never empty when ``periods`` is non-empty.+ """+ if period != "annual":+ return periods+ annual = [+ row+ for row in periods+ if str(row.get("REPORT_DATE", ""))[:10].endswith("-12-31")+ ]+ return annual or periods+++def _fetch_eastmoney_statement(+ code: str, *, statement: str, period: str+) -> dict[str, Any]:+ """Fetch one A-share/US/HK statement from Eastmoney, shaped into a result dict.++ Args:+ code: Symbol (e.g. ``"600519.SH"``, ``"AAPL.US"`` or ``"00700.HK"``).+ statement: One of :data:`_VALID_STATEMENTS`.+ period: ``"annual"`` or ``"quarter"``.++ Returns:+ ``{"periods": [...]}`` on success or ``{"error": ...}`` on failure;+ never raises.+ """+ secid = resolve_secid(code)+ if secid is None:+ return {"error": "unresolvable symbol"}++ group = _eastmoney_market_group(secid)+ if group is None:+ return {"error": "symbol is not an A-share, US, or Hong Kong instrument"}++ params = {+ "reportName": _EM_REPORT_NAME[group][statement],+ "columns": "ALL",+ "filter": _eastmoney_filter(group, code, secid),+ "sortColumns": "REPORT_DATE",+ "sortTypes": "-1",+ "pageNumber": "1",+ "pageSize": str(_MAX_PERIODS),+ "source": "F10",+ "client": "PC",+ }+ try:+ payload = get_json(_EM_REPORT_URL, params=params)+ except Exception as exc: # noqa: BLE001 - one bad fetch must not kill the call+ logger.warning("eastmoney statement fetch failed for %s: %s", code, exc)+ return {"error": str(exc)}++ periods = _filter_by_period(_parse_eastmoney_periods(payload), period)+ return {"periods": _cap_periods(periods)}+++def _classify_market(code: str) -> str | None:+ """Classify a symbol's suffix into ``a_share``, ``us``, ``hk``, or ``None``.++ Args:+ code: Symbol with a market suffix (e.g. ``"600519.SH"``, ``"AAPL.US"``).++ Returns:+ The market label, or ``None`` when the suffix is unrecognized.+ """+ suffix = code.rpartition(".")[2].strip().upper()+ if suffix in ("SH", "SZ", "BJ"):+ return "a_share"+ if suffix == "US":+ return "us"+ if suffix == "HK":+ return "hk"+ return None+++class FinancialStatementsTool(BaseTool):+ """Fetch a stock's three financial statements or key per-period indicators."""++ name = "get_financial_statements"+ description = (+ "Fetch a single stock's financial statements: balance sheet, income "+ "statement, cash-flow statement, or key per-period indicators (margins, "+ "ROE, EPS, etc.). Markets: A-share (.SH/.SZ/.BJ), US (.US) and "+ "Hong Kong (.HK), all via Eastmoney. Reports come back newest-first as flat "+ "per-period rows. Use this to read fundamentals before building a "+ 'valuation or screen. Example: {"code": "600519.SH", "statement": '+ '"income", "period": "annual"}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": (+ "Single symbol with a market suffix, e.g. '600519.SH', "+ "'000001.SZ', 'AAPL.US', or '00700.HK'."+ ),+ },+ "statement": {+ "type": "string",+ "enum": list(_VALID_STATEMENTS),+ "description": (+ "Which report to fetch: 'balance' (balance sheet), 'income' "+ "(income statement), 'cashflow' (cash-flow statement), or "+ "'indicators' (key per-period indicators)."+ ),+ "default": "indicators",+ },+ "period": {+ "type": "string",+ "enum": list(_VALID_PERIODS),+ "description": (+ "Reporting cadence: 'annual' (annual reports) or 'quarter' "+ "(quarterly reports)."+ ),+ "default": "annual",+ },+ },+ "required": ["code"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Validate inputs, dispatch by market, and return a JSON envelope.++ Args:+ **kwargs: ``code`` (str, required), ``statement`` (one of balance|+ income|cashflow|indicators, default 'indicators'), ``period``+ (annual|quarter, default 'annual').++ Returns:+ A JSON string ``{"ok": true, "market": str, "source": str,+ "statement": str, "period": str, "data": {...}}`` when the fetch+ yields data, ``{"ok": false, "error": ...}`` when validation fails,+ or the same envelope with ``ok: false`` plus a top-level ``error``+ when the per-market fetch failed for every requested code (so a+ nested fetch error is never masked by a top-level ``ok: true``).+ """+ code = kwargs.get("code")+ if not isinstance(code, str) or not code.strip():+ return _error("code must be a non-empty symbol string")+ code = code.strip()++ statement = kwargs.get("statement", "indicators")+ if statement not in _VALID_STATEMENTS:+ return _error(f"statement must be one of {list(_VALID_STATEMENTS)}")++ period = kwargs.get("period", "annual")+ if period not in _VALID_PERIODS:+ return _error(f"period must be one of {list(_VALID_PERIODS)}")++ market = _classify_market(code)+ if market is None:+ return _error(+ "code must carry a supported suffix: .SH/.SZ/.BJ, .US, or .HK"+ )++ result = _fetch_eastmoney_statement(+ code, statement=statement, period=period+ )++ # The fetch failed for every requested code (here, the single ``code``)+ # iff its result carries an ``error``. Surface that as a top-level+ # ``ok: false`` so a nested failure is never masked by ``ok: true``.+ all_failed = "error" in result+ envelope: dict[str, Any] = {+ "ok": not all_failed,+ "market": market,+ "source": "eastmoney",+ "statement": statement,+ "period": period,+ "data": {code: result},+ }+ if all_failed:+ envelope["error"] = result["error"]+ return json.dumps(envelope, ensure_ascii=False)diff --git a/agent/src/tools/fred_macro_tool.py b/agent/src/tools/fred_macro_tool.pynew file mode 100644index 000000000..724dcc66d--- /dev/null+++ b/agent/src/tools/fred_macro_tool.py@@ -0,0 +1,259 @@+"""Read-only tool: FRED macroeconomic time series (St. Louis Fed).++The Federal Reserve Bank of St. Louis publishes hundreds of thousands of+economic time series — CPI, unemployment, GDP, federal funds rate, Treasury+yields, money supply and the like — through its FRED REST API. Each series is+addressed by a short uppercase ``series_id`` (e.g. ``CPIAUCSL`` for headline+CPI, ``UNRATE`` for the unemployment rate, ``DGS10`` for the 10-year Treasury+yield).++This tool fetches the observations of a single series over an optional date+window and returns them as a normalized envelope. The FRED API requires a free+``api_key``; the tool reads it from the ``FRED_API_KEY`` environment variable+and is silently excluded from the registry when that key is absent, so the+agent never sees a tool it cannot call. Every outbound GET routes through the+project's IP-throttled HTTP layer under the ``fred`` host bucket so the API is+never hit un-throttled.+"""++from __future__ import annotations++import json+import logging+import os+from typing import Any++from backtest.loaders._http import resolve_min_interval, throttled_get_json+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# FRED series-observations endpoint. The response carries an ``observations``+# array of ``{date, value}`` records (value is a string; "." marks a gap).+_OBSERVATIONS_URL = "https://api.stlouisfed.org/fred/series/observations"++_FRED_HOST_KEY = "fred"+_FRED_MIN_INTERVAL_ENV = "VIBE_TRADING_FRED_MIN_INTERVAL"+_FRED_DEFAULT_MIN_INTERVAL = 0.6+_FRED_TIMEOUT_S = 15.0++# Hard cap on returned observations so a long daily series cannot bloat the+# payload. The most recent observations are kept when the cap is exceeded.+_DEFAULT_LIMIT = 2000+_MAX_LIMIT = 5000++# FRED's sentinel for a missing value within an otherwise valid series.+_MISSING_VALUE = "."+++class FredMacroTool(BaseTool):+ """Fetch a single FRED macroeconomic time series from the St. Louis Fed."""++ name = "get_macro_series"+ description = (+ "Fetch a FRED macroeconomic time series from the St. Louis Fed: dated "+ "observations of indicators such as CPI (CPIAUCSL), unemployment "+ "(UNRATE), real GDP (GDPC1), the federal funds rate (FEDFUNDS), or the "+ "10-year Treasury yield (DGS10). Markets: US / global macroeconomic "+ "data. Requires a free FRED API key (FRED_API_KEY). "+ 'Example: {"series_id": "CPIAUCSL", "start_date": "2020-01-01", '+ '"end_date": "2024-12-31"}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "series_id": {+ "type": "string",+ "description": (+ "FRED series identifier, a short uppercase code such as "+ "'CPIAUCSL', 'UNRATE', 'GDPC1', 'FEDFUNDS' or 'DGS10'."+ ),+ },+ "start_date": {+ "type": "string",+ "description": (+ "Inclusive start of the observation window, YYYY-MM-DD. "+ "Omit for the full available history."+ ),+ },+ "end_date": {+ "type": "string",+ "description": (+ "Inclusive end of the observation window, YYYY-MM-DD. "+ "Omit for observations through the latest available date."+ ),+ },+ "limit": {+ "type": "integer",+ "description": (+ "Maximum number of most-recent observations to return "+ f"(1-{_MAX_LIMIT}). Defaults to {_DEFAULT_LIMIT}."+ ),+ "default": _DEFAULT_LIMIT,+ },+ },+ "required": ["series_id"],+ }++ @classmethod+ def check_available(cls) -> bool:+ """Available only when a FRED API key is configured.++ Returns:+ ``True`` when ``FRED_API_KEY`` is set in the environment, otherwise+ ``False`` so the tool is silently excluded from the registry.+ """+ return bool(os.getenv("FRED_API_KEY"))++ def execute(self, **kwargs: Any) -> str:+ """Fetch one FRED series and return a JSON envelope.++ Args:+ **kwargs: ``series_id`` (required FRED code), optional ``start_date``+ / ``end_date`` (inclusive YYYY-MM-DD bounds) and optional+ ``limit`` (observation count cap).++ Returns:+ A JSON string envelope. On success:+ ``{"ok": true, "market": "US", "source": "fred",+ "data": {"series_id", "observations": [{"date", "value"}, ...],+ "count"}}``. On failure: ``{"ok": false, "error": str}``.+ """+ api_key = os.getenv("FRED_API_KEY")+ if not api_key:+ return _error("FRED_API_KEY is not configured")++ series_id = kwargs.get("series_id")+ if not isinstance(series_id, str) or not series_id.strip():+ return _error("'series_id' is required and must be a non-empty string")+ series_id = series_id.strip().upper()++ params: dict[str, str] = {+ "series_id": series_id,+ "api_key": api_key,+ "file_type": "json",+ }+ start_date = _clean_date(kwargs.get("start_date"))+ if start_date is not None:+ params["observation_start"] = start_date+ end_date = _clean_date(kwargs.get("end_date"))+ if end_date is not None:+ params["observation_end"] = end_date++ try:+ payload = throttled_get_json(+ _OBSERVATIONS_URL,+ host_key=_FRED_HOST_KEY,+ min_interval=resolve_min_interval(+ _FRED_MIN_INTERVAL_ENV, _FRED_DEFAULT_MIN_INTERVAL+ ),+ params=params,+ timeout=_FRED_TIMEOUT_S,+ )+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelope+ return _error(f"fred observations request failed: {exc}")++ observations = _parse_observations(payload)+ if not observations:+ return _error(f"no observations found for series '{series_id}'")++ limit = _clamp_limit(kwargs.get("limit", _DEFAULT_LIMIT))+ # Keep the most recent observations when the cap is exceeded; FRED serves+ # oldest-first, so the tail holds the newest records.+ capped = observations[-limit:]++ return json.dumps(+ {+ "ok": True,+ "market": "US",+ "source": "fred",+ "data": {+ "series_id": series_id,+ "observations": capped,+ "count": len(capped),+ },+ },+ ensure_ascii=False,+ )+++def _parse_observations(payload: Any) -> list[dict]:+ """Extract dated observations from a FRED observations payload.++ Args:+ payload: Decoded FRED JSON; rows live under the ``observations`` array,+ each a ``{date, value}`` record where ``value`` is a string and a+ lone ``"."`` marks a missing reading.++ Returns:+ A list of ``{date, value}`` dicts in served (oldest-first) order, with+ ``value`` coerced to ``float`` or ``None`` for gaps. Empty when the+ payload carries no usable rows.+ """+ if not isinstance(payload, dict):+ return []+ rows = payload.get("observations")+ if not isinstance(rows, list):+ return []++ out: list[dict] = []+ for row in rows:+ record = _normalize_observation(row)+ if record is not None:+ out.append(record)+ return out+++def _normalize_observation(row: Any) -> dict | None:+ """Map one raw FRED observation row to our record, or ``None`` if unusable.++ A row with no date carries no anchor and is dropped; a single bad row never+ aborts the batch.++ Args:+ row: One element of the FRED ``observations`` array.++ Returns:+ ``{"date": str, "value": float | None}`` or ``None``.+ """+ if not isinstance(row, dict):+ return None+ date = _clean_date(row.get("date"))+ if date is None:+ return None+ return {"date": date, "value": _to_number(row.get("value"))}+++def _clamp_limit(value: Any) -> int:+ """Coerce a requested observation count into the supported range."""+ try:+ n = int(value)+ except (TypeError, ValueError):+ return _DEFAULT_LIMIT+ return max(1, min(n, _MAX_LIMIT))+++def _clean_date(value: Any) -> str | None:+ """Trim a date cell to its ``YYYY-MM-DD`` form, or ``None`` when absent/blank."""+ if not isinstance(value, str) or not value.strip():+ return None+ return value.strip().split(" ", 1)[0]+++def _to_number(value: Any) -> float | None:+ """Coerce a FRED value cell to ``float``, or ``None`` for gaps / non-numerics.++ FRED encodes a missing reading as the string ``"."``; that and any other+ non-numeric cell map to ``None`` so downstream consumers see an explicit gap.+ """+ if value is None or value == "" or value == _MISSING_VALUE:+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _error(message: str) -> str:+ """Render a failure envelope as a JSON string."""+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)diff --git a/agent/src/tools/fund_flow_tool.py b/agent/src/tools/fund_flow_tool.pynew file mode 100644index 000000000..33ee19b0b--- /dev/null+++ b/agent/src/tools/fund_flow_tool.py@@ -0,0 +1,227 @@+"""Read-only fund-flow (capital-flow) tool backed by the Eastmoney client.++Eastmoney publishes a free, no-auth capital-flow series that splits each bar's+net inflow into main / large / medium / small-order buckets (the+"主力/超大单/大单/中单/小单" decomposition). Two ``fflow`` endpoints serve it:+a daily history line and an intraday (minute) line. Both are addressed by the+same ``secid`` scheme used for klines, so symbol resolution and HTTP throttling+are delegated to :mod:`backtest.loaders.eastmoney_client` (every request routes+through the shared per-host throttle — Eastmoney rate-limits by IP and bans+bursting clients).++Markets: A-share (``.SH`` / ``.SZ`` / ``.BJ``), Hong Kong (``.HK``) and US+(``.US``). One unresolvable or failing symbol never aborts the batch.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from backtest.loaders.eastmoney_client import get_json, resolve_secid+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney capital-flow endpoints. ``daykline`` is the daily history line;+# ``kline`` is the intraday (per-minute) line for the current session.+_DAILY_URL = "https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get"+_MINUTE_URL = "https://push2.eastmoney.com/api/qt/stock/fflow/kline/get"++# Per-bar field selectors. The daily line carries date + the five net-inflow+# buckets; the minute line carries time + the same five buckets (no leading+# date, since all bars share the current trading day).+_DAILY_FIELDS = "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63,f64,f65"+_MINUTE_FIELDS = "f51,f52,f53,f54,f55,f56"++# Bucket labels in the order Eastmoney emits them after the leading timestamp:+# main (主力净额), small, medium, large, super-large net inflow in CNY.+_BUCKETS = ("main", "small", "medium", "large", "super_large")++# Defensive caps so a payload can never blow up the LLM context.+_MAX_DAYS = 250+_MAX_ROWS_PER_SYMBOL = 250+_VALID_PERIODS = ("min", "daily")+++def _error(message: str) -> str:+ """Build the failure envelope as a JSON string.++ Args:+ message: Human-readable error description.++ Returns:+ A ``{"ok": false, "error": ...}`` JSON string.+ """+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)+++def _parse_flow_row(raw: str) -> dict[str, Any] | None:+ """Parse one comma-joined fflow row into a labelled net-inflow dict.++ Daily rows lead with a ``YYYY-MM-DD`` date; minute rows lead with a+ ``YYYY-MM-DD HH:MM`` timestamp. Either way the next five columns are the+ main / small / medium / large / super-large net inflow values in CNY.++ Args:+ raw: One row string from ``data.klines``.++ Returns:+ A dict ``{timestamp, main, small, medium, large, super_large}``, or+ ``None`` when the row is too short or carries non-numeric buckets.+ """+ parts = raw.split(",")+ if len(parts) < 1 + len(_BUCKETS):+ return None+ timestamp = parts[0]+ try:+ values = [float(parts[i + 1]) for i in range(len(_BUCKETS))]+ except (ValueError, TypeError):+ return None+ row: dict[str, Any] = {"timestamp": timestamp}+ row.update(dict(zip(_BUCKETS, values)))+ return row+++def _fetch_symbol_flow(symbol: str, *, period: str, days: int) -> dict[str, Any]:+ """Fetch one symbol's capital-flow series and shape it into a result dict.++ Args:+ symbol: Vibe-Trading symbol (e.g. ``"600519.SH"``, ``"AAPL.US"``).+ period: ``"daily"`` or ``"min"``.+ days: Number of most-recent daily bars to keep (ignored for ``"min"``).++ Returns:+ A per-symbol result dict carrying either ``rows`` on success or an+ ``error`` string on failure. Never raises for a single symbol.+ """+ secid = resolve_secid(symbol)+ if secid is None:+ return {"symbol": symbol, "error": "unresolvable symbol"}++ is_daily = period == "daily"+ url = _DAILY_URL if is_daily else _MINUTE_URL+ params = {+ "secid": secid,+ "fields1": "f1,f2,f3,f7",+ "fields2": _DAILY_FIELDS if is_daily else _MINUTE_FIELDS,+ "klt": "101" if is_daily else "1",+ "lmt": "0" if is_daily else "0",+ }+ try:+ payload = get_json(url, params=params)+ except Exception as exc: # noqa: BLE001 - one bad symbol must not kill the batch+ logger.warning("fund flow fetch failed for %s: %s", symbol, exc)+ return {"symbol": symbol, "error": str(exc)}++ data = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(data, dict):+ return {"symbol": symbol, "secid": secid, "rows": []}+ klines = data.get("klines")+ if not isinstance(klines, list):+ return {"symbol": symbol, "secid": secid, "rows": []}++ rows: list[dict[str, Any]] = []+ for raw in klines:+ if not isinstance(raw, str):+ continue+ parsed = _parse_flow_row(raw)+ if parsed is not None:+ rows.append(parsed)++ if is_daily and days < len(rows):+ rows = rows[-days:]+ if len(rows) > _MAX_ROWS_PER_SYMBOL:+ rows = rows[-_MAX_ROWS_PER_SYMBOL:]++ return {"symbol": symbol, "secid": secid, "rows": rows}+++class FundFlowTool(BaseTool):+ """Fetch order-bucket net capital inflow (main/large/medium/small) for stocks."""++ name = "get_fund_flow"+ description = (+ "PER-STOCK order-level net inflow for a GIVEN symbol: for each requested "+ "ticker, the main / super-large / large / medium / small-order net inflow "+ "(in CNY), as daily history or the current session's per-minute line. Use "+ "this for one or more named stocks to gauge whether large/main-force money "+ "is flowing into or out of that specific symbol. NOT market-wide aggregate "+ "flow (for Stock-Connect 北向 use get_northbound_flow). Markets: A-share "+ "(.SH/.SZ/.BJ), Hong Kong (.HK) and US (.US). Example: "+ '{"codes": ["600519.SH", "00700.HK"], "period": "daily", "days": 30}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "codes": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ 'Symbols with market suffix, e.g. ["600519.SH", "000001.SZ", '+ '"00700.HK", "AAPL.US"]. One unresolvable symbol is reported '+ "per-symbol and does not abort the batch."+ ),+ },+ "period": {+ "type": "string",+ "enum": ["min", "daily"],+ "description": (+ 'Series granularity. "daily" = daily net-inflow history; '+ '"min" = the current trading session per-minute line.'+ ),+ "default": "daily",+ },+ "days": {+ "type": "integer",+ "description": (+ "For period='daily', number of most-recent daily bars to keep "+ f"(1-{_MAX_DAYS}). Ignored for period='min'."+ ),+ "default": 30,+ },+ },+ "required": ["codes"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Resolve symbols, fetch fund flow per symbol, return a JSON envelope.++ Args:+ **kwargs: ``codes`` (list[str], required), ``period`` ("min"|"daily",+ default "daily"), ``days`` (int, default 30).++ Returns:+ A JSON string ``{"ok": true, "market": "stock", "source":+ "eastmoney", "data": {...}}`` on success, or ``{"ok": false,+ "error": ...}`` on a request-level failure.+ """+ codes = kwargs.get("codes")+ if not isinstance(codes, list) or not codes:+ return _error("codes must be a non-empty list of symbols")+ if any(not isinstance(c, str) or not c.strip() for c in codes):+ return _error("every code must be a non-empty string")++ period = kwargs.get("period", "daily")+ if period not in _VALID_PERIODS:+ return _error(f"period must be one of {list(_VALID_PERIODS)}")++ days = kwargs.get("days", 30)+ if not isinstance(days, int) or isinstance(days, bool) or days < 1:+ return _error("days must be a positive integer")+ days = min(days, _MAX_DAYS)++ results = {+ symbol: _fetch_symbol_flow(symbol, period=period, days=days)+ for symbol in (c.strip() for c in codes)+ }+ envelope = {+ "ok": True,+ "market": "stock",+ "source": "eastmoney",+ "period": period,+ "buckets": list(_BUCKETS),+ "data": results,+ }+ return json.dumps(envelope, ensure_ascii=False)diff --git a/agent/src/tools/iwencai_tool.py b/agent/src/tools/iwencai_tool.pynew file mode 100644index 000000000..1a3b0d704--- /dev/null+++ b/agent/src/tools/iwencai_tool.py@@ -0,0 +1,254 @@+"""iWenCai (问财) natural-language A-share research search tool.++iWenCai is a Chinese-market natural-language stock screener: a research caller+phrases a question in plain language ("low-PE banks with rising net profit") and+the service returns the matching A-share securities with the metric columns its+parser extracted from the question. This tool wraps that semantic-search+endpoint read-only.++The endpoint is rate-limited per source IP and requires a caller-supplied access+key, so every request routes through :mod:`backtest.loaders._http` for per-host+throttling and session reuse, and carries a ``Bearer`` authorization header built+from ``VIBE_TRADING_IWENCAI_KEY``. The tool is silently excluded from the registry+when that key is absent, so a key-less install never advertises a search it cannot+perform.+"""++from __future__ import annotations++import json+import logging+import os+from typing import Any++from backtest.loaders._http import resolve_min_interval, throttled_get_json+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Endpoint + throttle bucket. All iWenCai calls share one host key so the shared+# HTTP layer spaces and pools them independently of other providers.+_SEARCH_URL = "https://www.iwencai.com/customized/chart/get-robot-data"+_HOST_KEY = "iwencai"+_MIN_INTERVAL_ENV = "VIBE_TRADING_IWENCAI_MIN_INTERVAL"+_DEFAULT_MIN_INTERVAL = 1.5++# Access key env var. Absent -> tool excluded by check_available().+_KEY_ENV = "VIBE_TRADING_IWENCAI_KEY"++# Result caps so a broad query never returns an unbounded payload.+_DEFAULT_LIMIT = 20+_MAX_LIMIT = 100+# Hard ceiling on per-row columns retained, keeping the envelope compact even+# when the service tags a row with dozens of derived metrics.+_MAX_COLUMNS = 40+++def _min_interval() -> float:+ """Resolve the per-call minimum iWenCai request spacing in seconds."""+ return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL)+++def _coerce_limit(value: Any) -> int:+ """Clamp a requested row limit into the supported range.++ Args:+ value: Raw ``limit`` argument (may be missing, a string, or a number).++ Returns:+ An int in ``[1, _MAX_LIMIT]``, defaulting to ``_DEFAULT_LIMIT`` when the+ value is missing or not parseable.+ """+ try:+ limit = int(value)+ except (TypeError, ValueError):+ return _DEFAULT_LIMIT+ if limit < 1:+ return _DEFAULT_LIMIT+ return min(limit, _MAX_LIMIT)+++def _extract_rows(payload: Any) -> list[dict[str, Any]]:+ """Pull the answer rows out of the iWenCai robot-data response.++ The service nests the structured result several levels deep under+ ``data.answer[].txt[].content.components[].data.datas``; any level may be+ absent on an empty or unparseable answer, so each hop is defensive and a+ missing branch yields an empty list rather than raising.++ Args:+ payload: Decoded JSON response body.++ Returns:+ The list of per-security row dicts, possibly empty.+ """+ if not isinstance(payload, dict):+ return []+ data = payload.get("data")+ if not isinstance(data, dict):+ return []+ for answer in data.get("answer", []) if isinstance(data.get("answer"), list) else []:+ if not isinstance(answer, dict):+ continue+ for txt in answer.get("txt", []) if isinstance(answer.get("txt"), list) else []:+ rows = _rows_from_txt(txt)+ if rows:+ return rows+ return []+++def _rows_from_txt(txt: Any) -> list[dict[str, Any]]:+ """Extract the ``datas`` rows from one ``txt`` block, if present.++ Args:+ txt: One entry of an answer's ``txt`` list.++ Returns:+ The row dicts under the first component carrying ``data.datas``; empty+ when this block holds no tabular result.+ """+ if not isinstance(txt, dict):+ return []+ content = txt.get("content")+ if not isinstance(content, dict):+ return []+ components = content.get("components")+ if not isinstance(components, list):+ return []+ for component in components:+ if not isinstance(component, dict):+ continue+ comp_data = component.get("data")+ if not isinstance(comp_data, dict):+ continue+ datas = comp_data.get("datas")+ if isinstance(datas, list):+ return [row for row in datas if isinstance(row, dict)]+ return []+++def _project_row(raw: dict[str, Any]) -> dict[str, Any]:+ """Trim one raw answer row to a compact, column-capped record.++ iWenCai returns a wide, query-dependent column set keyed by Chinese metric+ names; rather than hardcode column names (they vary per question) we pass the+ columns through verbatim but cap their count so the payload stays bounded.++ Args:+ raw: One row dict from the answer's ``datas`` list.++ Returns:+ A dict with at most ``_MAX_COLUMNS`` of the row's key/value pairs.+ """+ items = list(raw.items())[:_MAX_COLUMNS]+ return {str(key): value for key, value in items}+++class IWenCaiSearchTool(BaseTool):+ """Run an iWenCai (问财) natural-language A-share research query."""++ name = "iwencai_search"++ @classmethod+ def check_available(cls) -> bool:+ """Available only when an iWenCai access key is configured.++ Returns:+ ``True`` when ``VIBE_TRADING_IWENCAI_KEY`` is set to a non-empty+ value; ``False`` otherwise, which silently excludes the tool from+ the registry. Never raises.+ """+ return bool(os.getenv(_KEY_ENV))++ description = (+ "Run a natural-language A-share research query against iWenCai (问财), a "+ "Chinese-market semantic stock screener. Phrase the question in plain "+ "language (Chinese works best) and get back the matching China A-share "+ "(SH/SZ) securities with the metric columns iWenCai parsed from the "+ "question. Read-only; requires the VIBE_TRADING_IWENCAI_KEY access key. "+ 'Example: {"query": "市盈率低于15的银行股", "limit": 10}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": (+ "Natural-language research question, e.g. "+ "'市盈率低于15且净利润增长的银行股' or 'low-PE banks with "+ "rising net profit'. Chinese phrasing yields the best parse."+ ),+ },+ "limit": {+ "type": "integer",+ "description": (+ "Maximum securities to return. Default 20, max 100; values "+ "outside the range are clamped."+ ),+ "default": _DEFAULT_LIMIT,+ },+ },+ "required": ["query"],+ }+ repeatable = True++ def execute(self, **kwargs: Any) -> str:+ """Execute an iWenCai semantic search and return a JSON envelope.++ Args:+ **kwargs: ``query`` (required, str) and optional ``limit`` (int).++ Returns:+ A JSON string envelope. On success:+ ``{"ok": true, "market": "a_share", "source": "iwencai",+ "data": {"query": ..., "count": int, "results": [...]}}``. On+ failure: ``{"ok": false, "error": "..."}``.+ """+ key = os.getenv(_KEY_ENV)+ if not key:+ return self._error(+ f"iWenCai access key not configured; set {_KEY_ENV} to enable this tool"+ )++ query_arg = kwargs.get("query")+ if not isinstance(query_arg, str) or not query_arg.strip():+ return self._error("missing required parameter: query")+ query = query_arg.strip()+ limit = _coerce_limit(kwargs.get("limit"))++ try:+ payload = throttled_get_json(+ _SEARCH_URL,+ host_key=_HOST_KEY,+ min_interval=_min_interval(),+ params={+ "question": query,+ "perpage": str(limit),+ "page": "1",+ "source": "Ths_iwencai_Xuangu",+ },+ headers={"Authorization": f"Bearer {key}"},+ )+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as an envelope+ logger.warning("iwencai search failed for %r: %s", query, exc)+ return self._error(f"iwencai search failed: {exc}")++ rows = _extract_rows(payload)+ results = [_project_row(row) for row in rows[:limit]]+ data = {"query": query, "count": len(results), "results": results}+ return json.dumps(+ {"ok": True, "market": "a_share", "source": "iwencai", "data": data},+ ensure_ascii=False,+ )++ @staticmethod+ def _error(message: str) -> str:+ """Render a failure envelope as a JSON string.++ Args:+ message: Human-readable error text.++ Returns:+ ``{"ok": false, "error": message}`` as a JSON string.+ """+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)diff --git a/agent/src/tools/lockup_expiry_tool.py b/agent/src/tools/lockup_expiry_tool.pynew file mode 100644index 000000000..fac5c07db--- /dev/null+++ b/agent/src/tools/lockup_expiry_tool.py@@ -0,0 +1,324 @@+"""Lockup-expiry (限售解禁) tool backed by the Eastmoney datacenter API.++Chinese A-share restricted shares come off lockup on scheduled dates; a large+upcoming unlock can pressure a stock as newly tradable supply hits the market.+This tool surfaces both the historical unlock schedule and the upcoming window+(default 90 days) for a single A-share code, or a market-wide upcoming-unlock+calendar when no code is given.++All requests reuse the shared, per-host-throttled Eastmoney client+(:mod:`backtest.loaders.eastmoney_client`); Eastmoney rate-limits by source IP+and temporarily bans bursting callers, so this module never issues an+un-throttled GET. It only knows Eastmoney's ``RPT_LIFT_STOCK`` report layout,+not any loader's DataFrame conventions.+"""++from __future__ import annotations++import json+import logging+from datetime import date, datetime, timedelta+from typing import Any++from backtest.loaders import eastmoney_client+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney datacenter report endpoint + the restricted-share unlock report.+_DATACENTER_URL = "https://datacenter-web.eastmoney.com/api/data/v1/get"+_REPORT_NAME = "RPT_LIFT_STOCK"++# Per-bar columns requested from the report, in our display order.+_COLUMNS = (+ "SECURITY_CODE,SECURITY_NAME_ABBR,FREE_DATE,FREE_SHARES_TYPE,"+ "FREE_SHARES,CURRENT_FREE_SHARES,ABLE_FREE_SHARES,LIFT_MARKET_CAP,"+ "FREE_RATIO,TOTAL_RATIO"+)++# Defaults / hard caps. Eastmoney's pageSize is generous, but we cap the+# returned payload so a market-wide query can never flood the agent context.+_DEFAULT_HORIZON_DAYS = 90+_MAX_HORIZON_DAYS = 365+_MAX_RECORDS = 200+_PAGE_SIZE = 200+++def _today() -> date:+ """Return today's date (indirection kept for test monkeypatching)."""+ return datetime.now().date()+++def _compact(d: date) -> str:+ """Format a date as Eastmoney's ``YYYY-MM-DD`` filter literal."""+ return d.strftime("%Y-%m-%d")+++def _clamp_horizon(horizon_days: Any) -> int:+ """Coerce a caller horizon into ``[1, _MAX_HORIZON_DAYS]`` days.++ Args:+ horizon_days: Caller-supplied value of any type.++ Returns:+ A valid integer horizon, falling back to the default on bad input.+ """+ try:+ value = int(horizon_days)+ except (TypeError, ValueError):+ return _DEFAULT_HORIZON_DAYS+ if value < 1:+ return 1+ return min(value, _MAX_HORIZON_DAYS)+++def _normalize_code(code: str) -> str | None:+ """Reduce a Vibe-Trading symbol to its bare 6-digit A-share code.++ Accepts ``"600519"``, ``"600519.SH"``, ``"000001.SZ"`` and similar; the+ Eastmoney report keys on the bare numeric code regardless of exchange.++ Args:+ code: Caller-supplied symbol.++ Returns:+ The bare 6-digit code, or ``None`` when it is not a 6-digit A-share code.+ """+ bare = code.strip().split(".", 1)[0]+ if len(bare) == 6 and bare.isdigit():+ return bare+ return None+++def _build_filter(code: str | None, start: date, end: date) -> str:+ """Compose the Eastmoney ``filter`` clause for the query.++ Args:+ code: Bare 6-digit code, or ``None`` for a market-wide calendar.+ start: Inclusive earliest unlock date for the upcoming window.+ end: Inclusive latest unlock date for the upcoming window.++ Returns:+ The Eastmoney filter expression string.+ """+ if code is not None:+ # Whole history for one code: no date bound, report sorts by date.+ return f'(SECURITY_CODE="{code}")'+ return f"(FREE_DATE>='{_compact(start)}')(FREE_DATE<='{_compact(end)}')"+++def _select_sort(code: str | None) -> tuple[str, str]:+ """Pick sort column + direction for the query.++ Single-code history reads newest-first; the market calendar reads+ soonest-first so the nearest unlocks lead.+ """+ if code is not None:+ return "FREE_DATE", "-1"+ return "FREE_DATE", "1"+++def _to_float(value: Any) -> float | None:+ """Best-effort float coercion; ``None`` for missing/garbage values."""+ if value is None:+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _shape_record(raw: Any) -> dict[str, Any] | None:+ """Project one Eastmoney report row into our compact record shape.++ Args:+ raw: One element of ``result.data``.++ Returns:+ A normalized record dict, or ``None`` when the row is unusable.+ """+ if not isinstance(raw, dict):+ return None+ code = raw.get("SECURITY_CODE")+ free_date = raw.get("FREE_DATE")+ if not code or not free_date:+ return None+ return {+ "code": str(code),+ "name": raw.get("SECURITY_NAME_ABBR"),+ "free_date": str(free_date)[:10],+ "share_type": raw.get("FREE_SHARES_TYPE"),+ "free_shares": _to_float(raw.get("FREE_SHARES")),+ "able_free_shares": _to_float(raw.get("ABLE_FREE_SHARES")),+ "lift_market_cap": _to_float(raw.get("LIFT_MARKET_CAP")),+ "free_ratio": _to_float(raw.get("FREE_RATIO")),+ "total_ratio": _to_float(raw.get("TOTAL_RATIO")),+ }+++def _extract_rows(payload: Any) -> list[dict]:+ """Pull the ``result.data`` list out of a datacenter payload.++ Args:+ payload: Decoded JSON from the datacenter endpoint.++ Returns:+ The raw record list, or an empty list when absent.+ """+ if not isinstance(payload, dict):+ return []+ result = payload.get("result")+ if not isinstance(result, dict):+ return []+ data = result.get("data")+ return data if isinstance(data, list) else []+++def _fetch_lockups(code: str | None, horizon_days: int) -> list[dict]:+ """Fetch and normalize lockup-expiry records from Eastmoney.++ Args:+ code: Bare 6-digit code, or ``None`` for a market-wide calendar.+ horizon_days: Upcoming-window length in days (used only when ``code``+ is ``None``).++ Returns:+ Normalized records (capped at :data:`_MAX_RECORDS`).++ Raises:+ requests.RequestException: Network failure from the shared client.+ requests.HTTPError: Non-2xx response status.+ ValueError: Body is not valid JSON.+ """+ start = _today()+ end = start + timedelta(days=horizon_days)+ sort_column, sort_type = _select_sort(code)++ payload = eastmoney_client.get_json(+ _DATACENTER_URL,+ params={+ "reportName": _REPORT_NAME,+ "columns": _COLUMNS,+ "filter": _build_filter(code, start, end),+ "sortColumns": sort_column,+ "sortTypes": sort_type,+ "pageNumber": "1",+ "pageSize": str(_PAGE_SIZE),+ "source": "WEB",+ "client": "WEB",+ },+ )++ records: list[dict] = []+ for raw in _extract_rows(payload):+ shaped = _shape_record(raw)+ if shaped is not None:+ records.append(shaped)+ if len(records) >= _MAX_RECORDS:+ break+ return records+++def get_lockup_expiry(code: str | None, horizon_days: int) -> str:+ """Query A-share lockup-expiry (限售解禁) data from Eastmoney.++ Args:+ code: A-share symbol (``"600519"`` or ``"600519.SH"``); ``None`` or+ empty yields a market-wide upcoming-unlock calendar.+ horizon_days: Upcoming-window length in days for the market calendar,+ clamped to ``[1, 365]``.++ Returns:+ A JSON-string envelope ``{"ok": true, "market": "a_share",+ "source": "eastmoney", "data": {...}}`` on success, or+ ``{"ok": false, "error": str}`` on failure.+ """+ horizon = _clamp_horizon(horizon_days)+ bare_code: str | None = None+ if code and code.strip():+ bare_code = _normalize_code(code)+ if bare_code is None:+ return json.dumps(+ {+ "ok": False,+ "error": (+ f"unrecognized A-share code {code!r}; expected a 6-digit "+ "code such as '600519' or '600519.SH'"+ ),+ },+ ensure_ascii=False,+ )++ try:+ records = _fetch_lockups(bare_code, horizon)+ except Exception as exc: # noqa: BLE001 - surface any upstream failure cleanly+ logger.warning("get_lockup_expiry failed (code=%s): %s", bare_code, exc)+ return json.dumps(+ {"ok": False, "error": f"eastmoney lockup query failed: {exc}"},+ ensure_ascii=False,+ )++ scope = "single_code" if bare_code is not None else "market_calendar"+ data: dict[str, Any] = {+ "scope": scope,+ "count": len(records),+ "records": records,+ }+ if bare_code is not None:+ data["code"] = bare_code+ else:+ data["horizon_days"] = horizon+ data["as_of"] = _compact(_today())+ if len(records) >= _MAX_RECORDS:+ data["truncated"] = True++ return json.dumps(+ {"ok": True, "market": "a_share", "source": "eastmoney", "data": data},+ ensure_ascii=False,+ )+++class LockupExpiryTool(BaseTool):+ """Surface Chinese A-share restricted-share unlock (限售解禁) schedules."""++ name = "get_lockup_expiry"+ description = (+ "Fetch Chinese A-share lockup-expiry (restricted-share unlock, 限售解禁) "+ "data from Eastmoney. Pass a 6-digit A-share code (e.g. '600519' or "+ "'600519.SH') to get that stock's full historical unlock schedule, or "+ "omit the code to get a market-wide calendar of upcoming unlocks within "+ "the next horizon_days. A large near-term unlock adds tradable supply "+ "and often pressures the stock. Example: "+ '{"code": "600519.SH"} or {"horizon_days": 30}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": (+ "A-share symbol: 6-digit code, optionally suffixed "+ "(e.g. '600519', '600519.SH', '000001.SZ'). Omit for a "+ "market-wide upcoming-unlock calendar."+ ),+ },+ "horizon_days": {+ "type": "integer",+ "description": (+ "Length of the upcoming-unlock window in days for the "+ "market-wide calendar; clamped to [1, 365]. Ignored when "+ "code is given (full history is returned instead)."+ ),+ "default": _DEFAULT_HORIZON_DAYS,+ },+ },+ "required": [],+ }+ repeatable = True++ def execute(self, **kwargs: Any) -> str:+ """Execute the lockup-expiry query and return a JSON envelope."""+ return get_lockup_expiry(+ kwargs.get("code"),+ kwargs.get("horizon_days", _DEFAULT_HORIZON_DAYS),+ )diff --git a/agent/src/tools/margin_trading_tool.py b/agent/src/tools/margin_trading_tool.pynew file mode 100644index 000000000..1c9ca798d--- /dev/null+++ b/agent/src/tools/margin_trading_tool.py@@ -0,0 +1,217 @@+"""Read-only margin-trading (融资融券) balance tool backed by Eastmoney.++Eastmoney's public datacenter exposes the daily exchange-published+margin-financing / securities-lending (融资融券) figures for individual A-share+stocks: outstanding financing balance, financing buy amount, securities-lending+balance, and the combined RZRQ balance, one row per trading day. This tool reads+those rows through the shared throttled Eastmoney client so the agent can answer+"how leveraged is this stock?" without writing a raw scraping script.++The datacenter is rate-limited by source IP, so every request routes through+:func:`backtest.loaders.eastmoney_client.get_json` (per-host throttle + session+reuse). No credentials are required; the endpoint is read-only public data.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from backtest.loaders import eastmoney_client+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney datacenter report API. RPTA_WEB_RZRQ_GGMX is the per-stock daily+# margin-trading detail report (个股明细), filterable by SCODE (bare code).+_DATACENTER_URL = "https://datacenter-web.eastmoney.com/api/data/v1/get"+_REPORT_NAME = "RPTA_WEB_RZRQ_GGMX"++# Per-bar columns we surface, mapped from the report's raw field names. The+# datacenter returns more columns than this; we keep the headline balances.+_FIELD_MAP: dict[str, str] = {+ "DATE": "trade_date",+ "RZYE": "financing_balance",+ "RZMRE": "financing_buy",+ "RZCHE": "financing_repay",+ "RQYE": "short_balance",+ "RQYL": "short_volume",+ "RZRQYE": "margin_total_balance",+}++# Hard caps so a pathological response can never blow up the LLM context.+_MAX_DAYS = 250+_DEFAULT_DAYS = 30+++def _extract_code(symbol: str) -> str | None:+ """Reduce a user-supplied symbol to the bare A-share numeric code.++ Accepts ``"600519"``, ``"600519.SH"``, ``"sh600519"`` or ``"000001.SZ"`` and+ returns the six-digit code Eastmoney's ``SCODE`` filter expects. Margin+ trading is an A-share-only dataset, so non-A symbols return ``None``.++ Args:+ symbol: Caller-supplied stock identifier.++ Returns:+ The six-digit code, or ``None`` when no A-share code can be derived.+ """+ if not symbol:+ return None+ token = symbol.strip().upper()+ if "." in token:+ token = token.rpartition(".")[0]+ for prefix in ("SH", "SZ", "BJ"):+ if token.startswith(prefix):+ token = token[len(prefix) :]+ token = token.strip()+ if len(token) == 6 and token.isdigit():+ return token+ return None+++def _clamp_days(days: Any) -> int:+ """Coerce the requested ``days`` to a sane integer within bounds.++ Args:+ days: Raw value from kwargs (may be ``None``, str, or int).++ Returns:+ An int in ``[1, _MAX_DAYS]``; falls back to ``_DEFAULT_DAYS`` on junk.+ """+ try:+ value = int(days)+ except (TypeError, ValueError):+ return _DEFAULT_DAYS+ if value <= 0:+ return _DEFAULT_DAYS+ return min(value, _MAX_DAYS)+++def _to_float(value: Any) -> float | None:+ """Convert a raw cell to ``float``, returning ``None`` on missing/garbage."""+ if value is None or value == "":+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _normalize_row(raw: dict[str, Any]) -> dict[str, Any]:+ """Project one datacenter row onto our headline-balance schema.++ Args:+ raw: One element of the report's ``result.data`` list.++ Returns:+ A dict keyed by our field names; numeric cells become ``float`` or+ ``None``, the date is kept as the provider's ``YYYY-MM-DD`` string.+ """+ row: dict[str, Any] = {}+ for source_key, out_key in _FIELD_MAP.items():+ value = raw.get(source_key)+ if out_key == "trade_date":+ row[out_key] = str(value)[:10] if value else None+ else:+ row[out_key] = _to_float(value)+ return row+++def _err(message: str) -> str:+ """Serialize a failure envelope."""+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)+++class MarginTradingTool(BaseTool):+ """Fetch daily A-share margin-financing / short-selling balances."""++ name = "get_margin_trading"+ description = (+ "Fetch an A-share stock's daily margin-trading (融资融券) balances from "+ "Eastmoney's public datacenter: outstanding financing balance, financing "+ "buy amount, securities-lending balance, and combined RZRQ balance, one "+ "row per trading day (most recent first). Read-only, no credentials, "+ "Mainland China A-shares only (SH/SZ). "+ 'Example: get_margin_trading(code="600519.SH", days=30).'+ )+ parameters = {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": (+ "A-share stock code. Accepts a bare six-digit code "+ '("600519"), a suffixed symbol ("600519.SH", "000001.SZ"), '+ 'or an exchange-prefixed form ("sh600519"). A-shares only.'+ ),+ },+ "days": {+ "type": "integer",+ "description": (+ "Number of most-recent trading days to return. "+ f"Default {_DEFAULT_DAYS}, capped at {_MAX_DAYS}."+ ),+ "default": _DEFAULT_DAYS,+ },+ },+ "required": ["code"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Fetch margin-trading rows and return a JSON envelope string.++ Args:+ **kwargs: ``code`` (required, str) and ``days`` (optional int).++ Returns:+ A JSON string. On success:+ ``{"ok": true, "market": "a_share", "source": "eastmoney",+ "data": {"code": str, "rows": [...]}}``. On failure:+ ``{"ok": false, "error": str}``.+ """+ code = _extract_code(kwargs.get("code", ""))+ if code is None:+ return _err(+ "Unsupported symbol: margin trading covers A-shares only "+ "(e.g. 600519.SH or 000001.SZ)."+ )+ days = _clamp_days(kwargs.get("days", _DEFAULT_DAYS))++ try:+ payload = eastmoney_client.get_json(+ _DATACENTER_URL,+ params={+ "reportName": _REPORT_NAME,+ "columns": "ALL",+ "source": "WEB",+ "filter": f'(SCODE="{code}")',+ "sortColumns": "DATE",+ "sortTypes": "-1",+ "pageNumber": "1",+ "pageSize": str(days),+ },+ )+ except Exception as exc: # noqa: BLE001 - surface any provider failure as envelope+ logger.warning("eastmoney margin fetch failed for %s: %s", code, exc)+ return _err(f"Eastmoney margin request failed: {exc}")++ result = payload.get("result") if isinstance(payload, dict) else None+ data = result.get("data") if isinstance(result, dict) else None+ if not isinstance(data, list) or not data:+ return _err(f"No margin-trading data returned for {code}.")++ rows = [_normalize_row(item) for item in data if isinstance(item, dict)]+ rows = rows[:days]++ return json.dumps(+ {+ "ok": True,+ "market": "a_share",+ "source": "eastmoney",+ "data": {"code": code, "rows": rows},+ },+ ensure_ascii=False,+ )diff --git a/agent/src/tools/market_data_tool.py b/agent/src/tools/market_data_tool.pyindex 73a8a157c..62611ed6c 100644--- a/agent/src/tools/market_data_tool.py+++ b/agent/src/tools/market_data_tool.py@@ -35,7 +35,32 @@ class MarketDataTool(BaseTool):},"source": {"type": "string",- "description": "Data source: auto, yfinance, okx, tushare, baostock, tencent, akshare, or ccxt.",+ "enum": [+ "auto",+ "yfinance",+ "yahoo",+ "okx",+ "ccxt",+ "tushare",+ "baostock",+ "tencent",+ "akshare",+ "mootdx",+ "eastmoney",+ "sina",+ "stooq",+ "finnhub",+ "alphavantage",+ "tiingo",+ "fmp",+ ],+ "description": (+ "Data source. 'auto' detects from symbol format with fallback. "+ "Free, no key: yfinance/yahoo (US/HK equities), okx/ccxt "+ "(crypto), baostock/tencent/eastmoney/sina/akshare/mootdx "+ "(China A-shares), stooq (global EOD). Key-gated REST: tushare "+ "(China A-shares), finnhub/alphavantage/tiingo/fmp (US/global)."+ ),"default": "auto",},"interval": {diff --git a/agent/src/tools/market_screener_tool.py b/agent/src/tools/market_screener_tool.pynew file mode 100644index 000000000..c1adc42f5--- /dev/null+++ b/agent/src/tools/market_screener_tool.py@@ -0,0 +1,255 @@+"""Read-only full-market screener backed by the Eastmoney client.++Eastmoney publishes a free, no-auth full-market quote list via the push2+``clist`` endpoint. Given a market universe selector (``fs``) it returns one row+per listed instrument with the latest price plus the common ranking metrics —+percent change, traded volume, turnover value (amount) and turnover rate — and+serves them already sorted server-side by a chosen field (``fid``). This tool+wraps that endpoint to answer "what are today's biggest movers / most-traded+names" questions across A-share, US and Hong Kong markets without writing raw+provider scripts.++Every request routes through :mod:`backtest.loaders.eastmoney_client` so it+goes through the shared per-host throttle (Eastmoney rate-limits by IP and+temporarily bans bursting clients). The result payload is capped so a full+market list can never blow up the LLM context.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from backtest.loaders.eastmoney_client import get_json+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney push2 full-market quote list endpoint.+_CLIST_URL = "https://push2.eastmoney.com/api/qt/clist/get"++# Per-market universe selectors (``fs``). A-share covers the SH/SZ main+ChiNext+# boards plus the Beijing exchange; US covers NASDAQ/NYSE/AMEX; HK covers the+# main-board and GEM equity markets.+_MARKET_FS: dict[str, str] = {+ "a": "m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048",+ "us": "m:105,m:106,m:107",+ "hk": "m:116,m:113,m:114,m:115,m:128",+}++# Sort-key -> Eastmoney field id. f3 = change percent, f5 = traded volume (lots),+# f6 = turnover value / amount (currency), f8 = turnover rate (percent).+_SORT_FID: dict[str, str] = {+ "change_pct": "f3",+ "volume": "f5",+ "amount": "f6",+ "turnover": "f8",+}++# Column selectors requested from the endpoint, in no particular order; values+# are read out by name from each row dict below.+_FIELDS = "f2,f3,f4,f5,f6,f8,f12,f14"++# Defensive caps so a full-market response can never blow up the LLM context.+_MAX_TOP_N = 100+_DEFAULT_TOP_N = 30+++def _error(message: str) -> str:+ """Build the failure envelope as a JSON string.++ Args:+ message: Human-readable error description.++ Returns:+ A ``{"ok": false, "error": ...}`` JSON string.+ """+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)+++def _num(value: Any) -> float | None:+ """Coerce one Eastmoney numeric cell to ``float``.++ Eastmoney sends ``"-"`` (or sometimes ``-`` as an int sentinel) for cells+ with no value (e.g. a halted name's turnover rate). Those become ``None``+ rather than a misleading zero.++ Args:+ value: Raw cell value from the row dict.++ Returns:+ The value as a float, or ``None`` when it is a sentinel / unparseable.+ """+ if value is None or value == "-":+ return None+ try:+ return float(value)+ except (ValueError, TypeError):+ return None+++def _shape_row(raw: Any) -> dict[str, Any] | None:+ """Shape one clist row dict into a normalized screener record.++ Args:+ raw: One element of ``data.diff`` (a per-instrument dict keyed by the+ Eastmoney field ids requested in :data:`_FIELDS`).++ Returns:+ A dict ``{code, name, price, change_pct, change, volume, amount,+ turnover_rate}``, or ``None`` when the row carries no usable code.+ """+ if not isinstance(raw, dict):+ return None+ code = raw.get("f12")+ if not code:+ return None+ return {+ "code": str(code),+ "name": str(raw.get("f14", "")),+ "price": _num(raw.get("f2")),+ "change_pct": _num(raw.get("f3")),+ "change": _num(raw.get("f4")),+ "volume": _num(raw.get("f5")),+ "amount": _num(raw.get("f6")),+ "turnover_rate": _num(raw.get("f8")),+ }+++def _screen_market(market: str, *, sort_by: str, top_n: int) -> list[dict[str, Any]]:+ """Fetch the ``top_n`` instruments of ``market`` ranked by ``sort_by``.++ Args:+ market: One of :data:`_MARKET_FS` keys (``a`` / ``us`` / ``hk``).+ sort_by: One of :data:`_SORT_FID` keys.+ top_n: Number of rows to request (already validated/capped).++ Returns:+ A list of shaped row dicts (already server-side sorted descending),+ possibly empty when the payload carries no rows.++ Raises:+ requests.RequestException: Network failure, propagated to the caller.+ requests.HTTPError: Non-2xx response status.+ ValueError: Body is not valid JSON.+ """+ payload = get_json(+ _CLIST_URL,+ params={+ "pn": "1",+ "pz": str(top_n),+ "po": "1", # descending+ "fid": _SORT_FID[sort_by],+ "fs": _MARKET_FS[market],+ "fields": _FIELDS,+ },+ )+ data = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(data, dict):+ return []+ diff = data.get("diff")+ # push2 clist returns ``diff`` either as a list or, on some hosts, a dict+ # keyed by index; normalize both to a list of row dicts.+ if isinstance(diff, dict):+ diff = list(diff.values())+ if not isinstance(diff, list):+ return []++ rows: list[dict[str, Any]] = []+ for raw in diff:+ shaped = _shape_row(raw)+ if shaped is not None:+ rows.append(shaped)+ return rows[:top_n]+++class MarketScreenerTool(BaseTool):+ """Rank a full market's listed instruments by change%, volume or turnover."""++ name = "screen_market"+ description = (+ "Screen a whole market's listed instruments and return the top names "+ "ranked by a chosen metric: percent change, traded volume, turnover "+ "value (amount) or turnover rate. Use this to find today's biggest "+ "movers or most-actively-traded names without fetching every symbol. "+ "Markets: A-share ('a'), US ('us'), Hong Kong ('hk'). "+ 'Example: {"market": "a", "sort_by": "change_pct", "top_n": 20}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "market": {+ "type": "string",+ "enum": ["a", "us", "hk"],+ "description": (+ "Market universe to screen: 'a' = China A-share "+ "(SH/SZ/ChiNext/Beijing), 'us' = US (NASDAQ/NYSE/AMEX), "+ "'hk' = Hong Kong."+ ),+ },+ "sort_by": {+ "type": "string",+ "enum": ["change_pct", "volume", "amount", "turnover"],+ "description": (+ "Ranking metric, sorted descending: 'change_pct' = percent "+ "change, 'volume' = traded volume, 'amount' = turnover value "+ "in currency, 'turnover' = turnover rate (percent)."+ ),+ "default": "change_pct",+ },+ "top_n": {+ "type": "integer",+ "description": (+ f"Number of top-ranked instruments to return (1-{_MAX_TOP_N})."+ ),+ "default": _DEFAULT_TOP_N,+ },+ },+ "required": ["market"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Validate inputs, screen the market, and return a JSON envelope.++ Args:+ **kwargs: ``market`` (str, required, one of a/us/hk), ``sort_by``+ (str, default "change_pct"), ``top_n`` (int, default 30).++ Returns:+ A JSON string ``{"ok": true, "market": <market>, "source":+ "eastmoney", "data": {"market": <market>, "sort_by": <sort_by>,+ "rows": [...]}}`` on success, or ``{"ok": false, "error": ...}`` on+ a validation or request failure. The row list nests under ``data``+ so the envelope matches every other tool's ``data:{...}`` shape.+ """+ market = kwargs.get("market")+ if not isinstance(market, str) or market not in _MARKET_FS:+ return _error(f"market must be one of {list(_MARKET_FS)}")++ sort_by = kwargs.get("sort_by", "change_pct")+ if sort_by not in _SORT_FID:+ return _error(f"sort_by must be one of {list(_SORT_FID)}")++ top_n = kwargs.get("top_n", _DEFAULT_TOP_N)+ if not isinstance(top_n, int) or isinstance(top_n, bool) or top_n < 1:+ return _error("top_n must be a positive integer")+ top_n = min(top_n, _MAX_TOP_N)++ try:+ rows = _screen_market(market, sort_by=sort_by, top_n=top_n)+ except Exception as exc: # noqa: BLE001 - surface as the error envelope+ logger.warning("market screen failed for %s/%s: %s", market, sort_by, exc)+ return _error(str(exc))++ envelope = {+ "ok": True,+ "market": market,+ "source": "eastmoney",+ "data": {+ "market": market,+ "sort_by": sort_by,+ "rows": rows,+ },+ }+ return json.dumps(envelope, ensure_ascii=False)diff --git a/agent/src/tools/northbound_tool.py b/agent/src/tools/northbound_tool.pynew file mode 100644index 000000000..f1f6dba87--- /dev/null+++ b/agent/src/tools/northbound_tool.py@@ -0,0 +1,249 @@+"""Northbound (Stock-Connect) net-flow tool backed by Eastmoney push2his.++Northbound flow is the net capital moving from Hong Kong into mainland China+A-shares through the Shanghai/Shenzhen Stock-Connect channels ("沪股通" and+"深股通"). Eastmoney publishes this as a free, no-auth time series through its+``push2his`` ``kamt`` (kapital-amount) endpoints. Every request routes through+the shared throttled Eastmoney client so we honor Eastmoney's per-IP rate limit+and never burst the host into a temporary ban.++This tool is read-only: it fetches the latest realtime net inflow plus a short+recent-daily history and returns them in the standard JSON envelope. It performs+no order placement and reaches no live trading endpoint.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from backtest.loaders.eastmoney_client import get_json+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney kamt (Stock-Connect capital) endpoints. ``kamt/get`` carries the+# realtime snapshot for both connect channels; ``kamt.kline/get`` carries the+# daily net-inflow history.+_REALTIME_URL = "https://push2.eastmoney.com/api/qt/kamt/get"+_HISTORY_URL = "https://push2his.eastmoney.com/api/qt/kamt.kline/get"++# Default and ceiling for the recent-daily window. The history endpoint returns+# at most a few years of daily points; we cap to keep the payload bounded.+_DEFAULT_LOOKBACK_DAYS = 30+_MAX_LOOKBACK_DAYS = 250++# Realtime snapshot field selectors. Eastmoney's kamt realtime payload nests the+# two channels under ``data`` with ``s2n`` (south-to-north net inflow) figures+# per channel: ``hk2sh`` (Shanghai-Connect) and ``hk2sz`` (Shenzhen-Connect).+_REALTIME_FIELDS = "f1,f2,f3,f4,f51,f52,f54,f56"++# History field selectors: f51 date, f52 Shanghai net inflow, f54 Shenzhen net+# inflow (units: 10k CNY as published by Eastmoney).+_HISTORY_FIELDS1 = "f1,f3"+_HISTORY_FIELDS2 = "f51,f52,f54"+++def _coerce_float(value: Any) -> float | None:+ """Coerce a raw Eastmoney numeric cell to ``float`` or ``None``.++ Args:+ value: Raw value from the payload (number, numeric string, or sentinel).++ Returns:+ The parsed float, or ``None`` when the cell is missing or not numeric+ (Eastmoney uses ``"-"`` for an absent figure).+ """+ if value in (None, "", "-"):+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _parse_realtime(payload: Any) -> dict[str, float | None]:+ """Extract per-channel realtime net inflow from a kamt realtime payload.++ Args:+ payload: Decoded JSON from :data:`_REALTIME_URL`.++ Returns:+ Mapping with ``shanghai_connect``, ``shenzhen_connect`` and ``total``+ net inflow (10k CNY); each value is ``None`` when unavailable.+ """+ data = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(data, dict):+ return {"shanghai_connect": None, "shenzhen_connect": None, "total": None}++ sh_block = data.get("hk2sh") if isinstance(data.get("hk2sh"), dict) else {}+ sz_block = data.get("hk2sz") if isinstance(data.get("hk2sz"), dict) else {}++ shanghai = _coerce_float(sh_block.get("netBuyAmt"))+ shenzhen = _coerce_float(sz_block.get("netBuyAmt"))+ total: float | None+ if shanghai is None and shenzhen is None:+ total = None+ else:+ total = (shanghai or 0.0) + (shenzhen or 0.0)++ return {+ "shanghai_connect": shanghai,+ "shenzhen_connect": shenzhen,+ "total": total,+ }+++def _parse_history_row(raw: str) -> dict[str, Any] | None:+ """Parse one ``kamt.kline`` history row into a daily net-inflow dict.++ Column order follows :data:`_HISTORY_FIELDS2`: date, Shanghai net inflow,+ Shenzhen net inflow.++ Args:+ raw: One comma-joined row string from ``data.klines``.++ Returns:+ A dict ``{trade_date, shanghai_connect, shenzhen_connect, total}``, or+ ``None`` when the row is malformed.+ """+ parts = raw.split(",")+ if len(parts) < 3:+ return None+ shanghai = _coerce_float(parts[1])+ shenzhen = _coerce_float(parts[2])+ if shanghai is None and shenzhen is None:+ total: float | None = None+ else:+ total = (shanghai or 0.0) + (shenzhen or 0.0)+ return {+ "trade_date": parts[0],+ "shanghai_connect": shanghai,+ "shenzhen_connect": shenzhen,+ "total": total,+ }+++def _parse_history(payload: Any, lookback_days: int) -> list[dict[str, Any]]:+ """Extract the most recent ``lookback_days`` daily net-inflow rows.++ Args:+ payload: Decoded JSON from :data:`_HISTORY_URL`.+ lookback_days: Number of trailing daily rows to keep.++ Returns:+ Ascending list of daily net-inflow dicts (empty when no rows).+ """+ data = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(data, dict):+ return []+ klines = data.get("klines")+ if not isinstance(klines, list):+ return []++ rows: list[dict[str, Any]] = []+ for raw in klines:+ if not isinstance(raw, str):+ continue+ parsed = _parse_history_row(raw)+ if parsed is not None:+ rows.append(parsed)+ return rows[-lookback_days:]+++def _clamp_lookback(value: Any) -> int:+ """Clamp a requested lookback to ``[1, _MAX_LOOKBACK_DAYS]``.++ Args:+ value: Raw ``lookback_days`` argument (any type the caller supplied).++ Returns:+ A valid lookback day count, defaulting on unparseable input.+ """+ try:+ days = int(value)+ except (TypeError, ValueError):+ return _DEFAULT_LOOKBACK_DAYS+ if days < 1:+ return 1+ if days > _MAX_LOOKBACK_DAYS:+ return _MAX_LOOKBACK_DAYS+ return days+++class NorthboundFlowTool(BaseTool):+ """Fetch Northbound (Stock-Connect) net capital flow from Eastmoney."""++ name = "get_northbound_flow"+ description = (+ "MARKET-WIDE Northbound (Stock-Connect / 北向) net capital flow for the "+ "whole mainland China A-share market: the aggregate net inflow from Hong "+ "Kong, split into Shanghai-Connect (沪股通) and Shenzhen-Connect (深股通) "+ "channels (units: 10k CNY), as the latest realtime figure plus a recent "+ "daily history. This is a market-level total, NOT per-stock flow (for a "+ "given symbol's order-bucket inflow use get_fund_flow). Read-only; China "+ "A-share market only. Example: get_northbound_flow(lookback_days=10)."+ )+ parameters = {+ "type": "object",+ "properties": {+ "lookback_days": {+ "type": "integer",+ "description": (+ "Number of trailing trading days of daily net-inflow history "+ f"to return, clamped to 1..{_MAX_LOOKBACK_DAYS}."+ ),+ "default": _DEFAULT_LOOKBACK_DAYS,+ },+ },+ "required": [],+ }++ def execute(self, **kwargs: Any) -> str:+ """Fetch realtime + recent-daily Northbound net flow as a JSON envelope.++ Args:+ **kwargs: Accepts ``lookback_days`` (int, default+ :data:`_DEFAULT_LOOKBACK_DAYS`).++ Returns:+ A JSON string envelope ``{"ok": true, "market": "China A",+ "source": "eastmoney", "data": {...}}`` on success, or+ ``{"ok": false, "error": str}`` on failure.+ """+ lookback_days = _clamp_lookback(kwargs.get("lookback_days", _DEFAULT_LOOKBACK_DAYS))++ try:+ realtime_payload = get_json(+ _REALTIME_URL,+ params={"fields": _REALTIME_FIELDS},+ )+ history_payload = get_json(+ _HISTORY_URL,+ params={+ "fields1": _HISTORY_FIELDS1,+ "fields2": _HISTORY_FIELDS2,+ "klt": "101",+ "lmt": str(_MAX_LOOKBACK_DAYS),+ },+ )+ except Exception as exc: # noqa: BLE001 - surface as error envelope+ logger.warning("northbound flow fetch failed: %s", exc)+ return json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False)++ realtime = _parse_realtime(realtime_payload)+ history = _parse_history(history_payload, lookback_days)++ envelope = {+ "ok": True,+ "market": "China A",+ "source": "eastmoney",+ "data": {+ "unit": "10k CNY",+ "lookback_days": lookback_days,+ "realtime": realtime,+ "history": history,+ },+ }+ return json.dumps(envelope, ensure_ascii=False)diff --git a/agent/src/tools/options_chain_tool.py b/agent/src/tools/options_chain_tool.pynew file mode 100644index 000000000..031f61ade--- /dev/null+++ b/agent/src/tools/options_chain_tool.py@@ -0,0 +1,155 @@+"""Read-only options-chain tool backed by the shared Yahoo Finance client.++Surfaces the calls/puts ladder for a US-listed underlying (strike, bid/ask,+last price, volume, open interest, implied volatility, and the in/out-of-money+flag) for a single expiration. All HTTP routes through+:func:`backtest.loaders.yahoo_client.get_options`, which throttles per host and+reuses one session, so the agent never hits Yahoo un-spaced.+"""++from __future__ import annotations++import json+from typing import Any, Dict, List, Optional++from backtest.loaders import yahoo_client+from src.agent.tools import BaseTool++# Upper bound on contracts emitted per side so a deep chain cannot blow up the+# tool payload handed back to the model.+_MAX_CONTRACTS_PER_SIDE = 60++# Yahoo contract fields we surface, mapped to our snake_case envelope keys.+_CONTRACT_FIELDS = (+ ("contractSymbol", "contract_symbol"),+ ("strike", "strike"),+ ("lastPrice", "last_price"),+ ("bid", "bid"),+ ("ask", "ask"),+ ("volume", "volume"),+ ("openInterest", "open_interest"),+ ("impliedVolatility", "implied_volatility"),+ ("inTheMoney", "in_the_money"),+ ("expiration", "expiration"),+)+++class OptionsChainTool(BaseTool):+ """Fetch a US equity option chain (calls + puts) with greeks-grade fields."""++ name = "get_options_chain"+ description = (+ "Fetch the US-listed options chain (calls and puts) for one expiration "+ "via Yahoo Finance: per-contract strike, bid/ask, last price, volume, "+ "open interest, implied volatility, and in-the-money flag, plus the list "+ "of available expirations (epoch seconds). Read-only US options data. "+ 'Example: get_options_chain(ticker="AAPL").'+ )+ parameters = {+ "type": "object",+ "properties": {+ "ticker": {+ "type": "string",+ "description": (+ "US underlying symbol, e.g. 'AAPL' or 'AAPL.US' (the .US "+ "suffix is stripped). Required."+ ),+ },+ "expiration": {+ "type": "integer",+ "description": (+ "Optional expiration as Unix epoch seconds (one of the "+ "values from the returned expirations list). Omit for the "+ "nearest expiration."+ ),+ },+ },+ "required": ["ticker"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Return a JSON-string envelope with the calls/puts chain.++ Args:+ **kwargs: ``ticker`` (str, required) and optional ``expiration``+ (int epoch seconds).++ Returns:+ A JSON string. On success:+ ``{"ok": true, "market": "us", "source": "yahoo", "data": {...}}``+ where ``data`` carries ``ticker``, ``expirations``, ``expiration``,+ ``calls``, ``puts``, and per-side counts. On failure:+ ``{"ok": false, "error": str}``.+ """+ ticker = str(kwargs.get("ticker") or "").strip()+ if not ticker:+ return _error("ticker is required")++ expiration = kwargs.get("expiration")+ normalized_expiration = _coerce_expiration(expiration)+ if expiration is not None and normalized_expiration is None:+ return _error("expiration must be Unix epoch seconds (integer)")++ try:+ result = yahoo_client.get_options(+ ticker, expiration=normalized_expiration+ )+ except Exception as exc: # noqa: BLE001 - surface as error envelope+ return _error(f"yahoo options request failed: {exc}")++ return _success(ticker, result)+++def _coerce_expiration(value: Any) -> Optional[int]:+ """Coerce an epoch-second expiration to ``int``; ``None`` when absent/bad."""+ if value is None:+ return None+ try:+ return int(value)+ except (TypeError, ValueError):+ return None+++def _success(ticker: str, result: Dict[str, Any]) -> str:+ """Build the success envelope from a quote-chain ``result[0]`` mapping."""+ expirations = [+ epoch for epoch in (result.get("expirationDates") or []) if epoch is not None+ ]+ options = result.get("options") or []+ block = options[0] if options else {}++ calls = _contracts(block.get("calls"))+ puts = _contracts(block.get("puts"))++ data = {+ "ticker": ticker,+ "expiration": block.get("expirationDate"),+ "expirations": expirations,+ "calls_count": len(calls),+ "puts_count": len(puts),+ "calls": calls,+ "puts": puts,+ }+ return json.dumps(+ {"ok": True, "market": "us", "source": "yahoo", "data": data},+ ensure_ascii=False,+ )+++def _contracts(raw: Any) -> List[Dict[str, Any]]:+ """Normalize a Yahoo calls/puts array into capped snake_case rows."""+ if not isinstance(raw, list):+ return []+ rows: List[Dict[str, Any]] = []+ for entry in raw[:_MAX_CONTRACTS_PER_SIDE]:+ if not isinstance(entry, dict):+ continue+ rows.append(+ {our_key: entry.get(yahoo_key) for yahoo_key, our_key in _CONTRACT_FIELDS}+ )+ return rows+++def _error(message: str) -> str:+ """Render a failure envelope as a JSON string."""+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)diff --git a/agent/src/tools/research_reports_tool.py b/agent/src/tools/research_reports_tool.pynew file mode 100644index 000000000..d893f88a8--- /dev/null+++ b/agent/src/tools/research_reports_tool.py@@ -0,0 +1,332 @@+"""Read-only tool: sell-side research reports + consensus EPS for A-shares.++Two free, no-auth disclosure feeds are stitched into one envelope:++* **Eastmoney reportapi** publishes the rolling list of broker research reports+ for a mainland A-share: report title, issuing brokerage, analyst, publish+ date, the broker's rating label, and that broker's per-year EPS / PE+ forecasts. This is the primary feed and drives the ``reports`` block.+* **THS** (同花顺, ``basic.10jqka.com.cn``) publishes a market *consensus* EPS+ forecast (the mean of analyst estimates) per forward fiscal year. THS rejects+ the bare requests User-Agent, so the call carries a desktop UA and a Referer+ and routes through the frozen IP-throttled HTTP layer under its own ``ths``+ host bucket. The consensus feed is best-effort: a THS failure degrades the+ ``consensus_eps`` block to an empty list and never aborts the report fetch.++Both feeds cover mainland A-shares only (``.SH`` / ``.SZ`` / ``.BJ``); any other+market returns an error envelope. Every outbound GET goes through the project's+throttled clients so the tool never hits a host un-throttled and never+re-implements provider plumbing.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from backtest.loaders._http import (+ DEFAULT_USER_AGENT,+ resolve_min_interval,+ throttled_get,+)+from backtest.loaders.eastmoney_client import get_json, resolve_secid+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney research-report list endpoint. qType=0 selects individual-stock+# reports; the response carries a ``data`` array of one row per report.+_REPORT_LIST_URL = "https://reportapi.eastmoney.com/report/list"++# THS consensus-forecast endpoint. Returns per-forward-year mean analyst EPS.+_THS_CONSENSUS_URL = "https://basic.10jqka.com.cn/api/stock/profit_forecast/"+_THS_HOST_KEY = "ths"+_THS_MIN_INTERVAL_ENV = "VIBE_TRADING_THS_MIN_INTERVAL"+_THS_DEFAULT_MIN_INTERVAL = 1.0+_THS_TIMEOUT_S = 15.0++# A-share exchange suffixes these disclosures cover.+_A_SHARE_SUFFIXES = ("SH", "SZ", "BJ")++# Hard caps so a long history cannot bloat the payload.+_DEFAULT_LIMIT = 20+_MAX_LIMIT = 50+++class ResearchReportsTool(BaseTool):+ """Fetch A-share sell-side research reports plus market consensus EPS."""++ name = "get_research_reports"+ description = (+ "Fetch mainland A-share sell-side research coverage: recent broker "+ "research reports (title, brokerage, analyst, publish date, rating) with "+ "each broker's per-year EPS and PE forecasts from Eastmoney, plus the "+ "market consensus (mean) EPS forecast per forward fiscal year from THS "+ "(同花顺). Markets: China A-shares only (.SH / .SZ / .BJ). "+ 'Example: {"code": "600519.SH", "limit": 10}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": (+ "A-share symbol in <code>.<exchange> form, exchange suffix one "+ "of SH / SZ / BJ (e.g. '600519.SH', '000001.SZ', '830799.BJ')."+ ),+ },+ "limit": {+ "type": "integer",+ "description": (+ "Maximum number of most-recent research reports to return "+ f"(1-{_MAX_LIMIT}). Defaults to {_DEFAULT_LIMIT}."+ ),+ "default": _DEFAULT_LIMIT,+ },+ },+ "required": ["code"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Resolve the symbol, fetch reports + consensus, return a JSON envelope.++ Args:+ **kwargs: ``code`` (required A-share symbol) and optional ``limit``+ (report count cap).++ Returns:+ A JSON string envelope. On success:+ ``{"ok": true, "market": "CN", "source": "eastmoney+ths",+ "data": {"code", "reports": [...], "consensus_eps": [...]}}``.+ On failure: ``{"ok": false, "error": str}``.+ """+ code = kwargs.get("code")+ if not isinstance(code, str) or not code.strip():+ return _error("'code' is required and must be a non-empty A-share symbol")+ code = code.strip().upper()++ suffix = code.rpartition(".")[2]+ if suffix not in _A_SHARE_SUFFIXES:+ return _error(+ f"research reports are China A-share only (.SH/.SZ/.BJ); got '{code}'"+ )+ if resolve_secid(code) is None:+ return _error(f"could not resolve A-share symbol '{code}'")++ limit = _clamp_limit(kwargs.get("limit", _DEFAULT_LIMIT))++ try:+ payload = get_json(+ _REPORT_LIST_URL,+ params={+ "code": _bare_code(code),+ "qType": "0",+ "pageSize": str(limit),+ "pageNo": "1",+ },+ )+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelope+ return _error(f"eastmoney report list request failed: {exc}")++ reports = _parse_reports(payload)++ # Consensus EPS is best-effort: a THS outage must not sink the reports.+ consensus_eps = _fetch_consensus_eps(code)++ if not reports and not consensus_eps:+ return _error(f"no research coverage found for '{code}'")++ return json.dumps(+ {+ "ok": True,+ "market": "CN",+ "source": "eastmoney+ths",+ "data": {+ "code": code,+ "reports": reports[:limit],+ "consensus_eps": consensus_eps,+ },+ },+ ensure_ascii=False,+ )+++def _bare_code(code: str) -> str:+ """Return the numeric stock code without its exchange suffix."""+ return code.rpartition(".")[0]+++def _clamp_limit(value: Any) -> int:+ """Coerce a requested report count into the supported ``1.._MAX_LIMIT`` range."""+ try:+ n = int(value)+ except (TypeError, ValueError):+ return _DEFAULT_LIMIT+ return max(1, min(n, _MAX_LIMIT))+++def _parse_reports(payload: Any) -> list[dict]:+ """Extract per-report records from an Eastmoney reportapi payload.++ Args:+ payload: Decoded reportapi JSON; rows live under the ``data`` array.++ Returns:+ A list of normalized report dicts (newest first as served), empty when+ the payload carries no usable rows.+ """+ if not isinstance(payload, dict):+ return []+ rows = payload.get("data")+ if not isinstance(rows, list):+ return []++ reports: list[dict] = []+ for row in rows:+ record = _normalize_report(row)+ if record is not None:+ reports.append(record)+ return reports+++def _normalize_report(row: Any) -> dict | None:+ """Map one raw reportapi row to our report record, or ``None`` if unusable.++ A row carrying neither a title nor a publish date holds no signal and is+ dropped; a single bad row never aborts the batch.++ Args:+ row: One element of the reportapi ``data`` array.++ Returns:+ ``{title, brokerage, analyst, publish_date, rating, eps_forecast,+ pe_forecast}`` or ``None``.+ """+ if not isinstance(row, dict):+ return None+ title = _clean_text(row.get("title"))+ publish_date = _clean_date(row.get("publishDate"))+ if title is None and publish_date is None:+ return None+ return {+ "title": title,+ "brokerage": _clean_text(row.get("orgSName")) or _clean_text(row.get("orgName")),+ "analyst": _clean_text(row.get("researcher")),+ "publish_date": publish_date,+ "rating": _clean_text(row.get("emRatingName")) or _clean_text(row.get("sRatingName")),+ "eps_forecast": {+ "this_year": _to_number(row.get("predictThisYearEps")),+ "next_year": _to_number(row.get("predictNextYearEps")),+ },+ "pe_forecast": {+ "this_year": _to_number(row.get("predictThisYearPe")),+ "next_year": _to_number(row.get("predictNextYearPe")),+ },+ }+++def _fetch_consensus_eps(code: str) -> list[dict]:+ """Fetch THS consensus (mean) EPS forecast per forward fiscal year.++ Best-effort: any network/parse failure is logged and degraded to an empty+ list so the primary report fetch is never aborted by a THS outage. THS+ rejects the bare requests UA, so the call presents a desktop browser UA and+ a Referer and is spaced under its own ``ths`` host bucket.++ Args:+ code: A-share symbol such as ``"600519.SH"``.++ Returns:+ A list of ``{fiscal_year, consensus_eps}`` dicts ordered as served,+ empty when THS returns nothing usable or the request fails.+ """+ try:+ response = throttled_get(+ _THS_CONSENSUS_URL,+ host_key=_THS_HOST_KEY,+ min_interval=resolve_min_interval(+ _THS_MIN_INTERVAL_ENV, _THS_DEFAULT_MIN_INTERVAL+ ),+ params={"code": _bare_code(code)},+ headers={+ "User-Agent": DEFAULT_USER_AGENT,+ "Referer": "https://basic.10jqka.com.cn/",+ },+ timeout=_THS_TIMEOUT_S,+ )+ response.raise_for_status()+ payload = response.json()+ except Exception as exc: # noqa: BLE001 - consensus is best-effort+ logger.warning("ths consensus eps fetch failed for %s: %s", code, exc)+ return []+ return _parse_consensus_eps(payload)+++def _parse_consensus_eps(payload: Any) -> list[dict]:+ """Extract per-year consensus EPS rows from a THS forecast payload.++ THS wraps its rows under ``data`` (a list of per-forward-year records, each+ carrying a fiscal year and a mean EPS estimate). Field naming varies, so we+ probe a small set of known key aliases for each value.++ Args:+ payload: Decoded THS JSON.++ Returns:+ A list of ``{fiscal_year, consensus_eps}`` dicts, empty when no usable+ row is present.+ """+ rows = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(rows, list):+ return []++ out: list[dict] = []+ for row in rows:+ if not isinstance(row, dict):+ continue+ year = _clean_text(_first(row, ("year", "fiscal_year", "report_year")))+ eps = _to_number(_first(row, ("eps", "avg_eps", "predict_eps", "forecast_eps")))+ if year is None and eps is None:+ continue+ out.append({"fiscal_year": year, "consensus_eps": eps})+ return out+++def _first(row: dict, keys: tuple[str, ...]) -> Any:+ """Return the first present, non-empty value among ``keys`` in ``row``."""+ for key in keys:+ value = row.get(key)+ if value is not None and value != "":+ return value+ return None+++def _clean_text(value: Any) -> str | None:+ """Trim a string cell, or ``None`` when absent/blank/non-string."""+ if not isinstance(value, str):+ return None+ trimmed = value.strip()+ return trimmed or None+++def _clean_date(value: Any) -> str | None:+ """Trim a timestamp cell to its ``YYYY-MM-DD`` date, or ``None``."""+ if not isinstance(value, str) or not value.strip():+ return None+ return value.strip().split(" ", 1)[0]+++def _to_number(value: Any) -> float | None:+ """Coerce a cell to ``float``, or ``None`` when absent/non-numeric."""+ if value is None or value == "":+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _error(message: str) -> str:+ """Render a failure envelope as a JSON string."""+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)diff --git a/agent/src/tools/sec_filings_tool.py b/agent/src/tools/sec_filings_tool.pynew file mode 100644index 000000000..3d510649f--- /dev/null+++ b/agent/src/tools/sec_filings_tool.py@@ -0,0 +1,351 @@+"""Read-only tool: U.S. SEC EDGAR filing index + XBRL GAAP metric series.++The U.S. SEC publishes free, no-auth JSON for every reporting company: a recent+filing index (10-K / 10-Q / 8-K and friends) and the full set of XBRL financial+concepts the company has reported. This tool wraps both behind the project's+BaseTool contract and the frozen, IP-throttled SEC client so the agent never+hits ``sec.gov`` un-throttled and never re-implements provider plumbing.++Two answers from one tool:++* a list of recent filings (optionally filtered to one ``form`` such as 10-K),+ each with accession number, filing/report dates, and the primary document URL;+* when ``metric`` is given, the reported time series for a single us-gaap+ concept (e.g. ``Revenues``, ``NetIncomeLoss``) drawn from XBRL companyfacts.++Markets: United States only. A ticker that the SEC table does not list returns+an error envelope.+"""++from __future__ import annotations++import json+from typing import Any, Dict, List, Optional++from backtest.loaders.sec_edgar_client import (+ cik_for,+ get_company_facts,+ get_submissions,+)+from src.agent.tools import BaseTool++# Hard caps so a long filing history or metric series cannot bloat the payload.+_MAX_LIMIT = 40+_DEFAULT_LIMIT = 20++# SEC primary-document URLs are built from the un-padded CIK + the accession+# number with its dashes stripped.+_DOC_BASE = "https://www.sec.gov/Archives/edgar/data"+++class SecFilingsTool(BaseTool):+ """List recent SEC filings and optionally one XBRL us-gaap metric series."""++ name = "get_sec_filings"+ description = (+ "Fetch U.S. SEC EDGAR data for a public company: a list of recent "+ "filings (10-K / 10-Q / 8-K, etc.) with accession number, filing and "+ "report dates, and the primary-document URL; or, when 'metric' is given, "+ "the reported XBRL us-gaap financial series for that concept (e.g. "+ "Revenues, NetIncomeLoss, Assets). Markets: United States only. "+ 'Example: {"ticker": "AAPL", "form": "10-K", "limit": 5}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "ticker": {+ "type": "string",+ "description": (+ "U.S. equity ticker, case-insensitive (e.g. 'AAPL', 'msft'). "+ "Resolved to a CIK via the SEC company-tickers table."+ ),+ },+ "form": {+ "type": "string",+ "description": (+ "Optional SEC form type to filter the filing list, "+ "case-insensitive (e.g. '10-K', '10-Q', '8-K'). Omit to "+ "return all recent forms."+ ),+ },+ "metric": {+ "type": "string",+ "description": (+ "Optional XBRL us-gaap concept name (e.g. 'Revenues', "+ "'NetIncomeLoss', 'Assets'). When set, the response also "+ "carries the reported time series for that concept."+ ),+ },+ "limit": {+ "type": "integer",+ "description": (+ f"Maximum number of most-recent filings and metric points to "+ f"return (1-{_MAX_LIMIT}). Defaults to {_DEFAULT_LIMIT}."+ ),+ "default": _DEFAULT_LIMIT,+ },+ },+ "required": ["ticker"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Resolve the ticker, fetch filings/facts, and return a JSON envelope.++ Args:+ **kwargs: ``ticker`` (required U.S. symbol), optional ``form`` filter,+ optional ``metric`` (us-gaap concept), and optional ``limit``.++ Returns:+ A JSON string envelope. On success:+ ``{"ok": true, "market": "US", "source": "sec_edgar",+ "data": {"ticker", "cik", "filings": [...], "metric": {...}}}``+ (``metric`` present only when requested). On failure:+ ``{"ok": false, "error": str}``.+ """+ ticker = kwargs.get("ticker")+ if not isinstance(ticker, str) or not ticker.strip():+ return _error("'ticker' is required and must be a non-empty U.S. symbol")+ ticker = ticker.strip().upper()++ form = kwargs.get("form")+ form_filter = form.strip().upper() if isinstance(form, str) and form.strip() else None++ metric = kwargs.get("metric")+ metric_name = metric.strip() if isinstance(metric, str) and metric.strip() else None++ limit = _clamp_limit(kwargs.get("limit", _DEFAULT_LIMIT))++ try:+ cik = cik_for(ticker)+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelope+ return _error(f"SEC ticker lookup failed: {exc}")+ if not cik:+ return _error(f"ticker '{ticker}' not found in the SEC company table (US only)")++ try:+ submissions = get_submissions(cik)+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelope+ return _error(f"SEC submissions request failed: {exc}")++ filings = _parse_filings(submissions, form_filter, cik)++ data: Dict[str, Any] = {+ "ticker": ticker,+ "cik": cik,+ "filings": filings,+ }++ if metric_name is not None:+ try:+ facts = get_company_facts(cik)+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelope+ return _error(f"SEC companyfacts request failed: {exc}")+ data["metric"] = _parse_metric(facts, metric_name, limit)++ return json.dumps(+ {"ok": True, "market": "US", "source": "sec_edgar", "data": data},+ ensure_ascii=False,+ )+++def _clamp_limit(value: Any) -> int:+ """Coerce a requested count into the supported ``1.._MAX_LIMIT`` range."""+ try:+ n = int(value)+ except (TypeError, ValueError):+ return _DEFAULT_LIMIT+ return max(1, min(n, _MAX_LIMIT))+++def _parse_filings(+ submissions: Any, form_filter: Optional[str], cik: str+) -> List[Dict[str, Any]]:+ """Extract recent filings from a submissions payload, newest first.++ The SEC submissions document stores the recent filing index as parallel+ arrays under ``filings.recent`` (``form``, ``accessionNumber``,+ ``filingDate``, ``reportDate``, ``primaryDocument``, ...). A row whose form+ does not match ``form_filter`` is skipped; a malformed row never aborts the+ batch.++ Args:+ submissions: Decoded submissions JSON.+ form_filter: Upper-cased form type to keep, or ``None`` for all forms.+ cik: The company CIK, used to build primary-document URLs.++ Returns:+ A list of normalized filing dicts (already newest-first from the SEC),+ capped at ``_MAX_LIMIT``.+ """+ recent = _recent_block(submissions)+ if recent is None:+ return []++ forms = recent.get("form") or []+ accessions = recent.get("accessionNumber") or []+ filing_dates = recent.get("filingDate") or []+ report_dates = recent.get("reportDate") or []+ primary_docs = recent.get("primaryDocument") or []+ descriptions = recent.get("primaryDocDescription") or []++ out: List[Dict[str, Any]] = []+ for idx, raw_form in enumerate(forms):+ form_type = str(raw_form).strip() if raw_form is not None else ""+ if form_filter is not None and form_type.upper() != form_filter:+ continue+ accession = _at(accessions, idx)+ out.append(+ {+ "form": form_type or None,+ "accession_number": accession,+ "filing_date": _at(filing_dates, idx),+ "report_date": _at(report_dates, idx) or None,+ "primary_document": _at(primary_docs, idx) or None,+ "description": _at(descriptions, idx) or None,+ "document_url": _document_url(cik, accession, _at(primary_docs, idx)),+ }+ )+ if len(out) >= _MAX_LIMIT:+ break+ return out+++def _recent_block(submissions: Any) -> Optional[Dict[str, Any]]:+ """Return the ``filings.recent`` mapping from a submissions payload, or ``None``."""+ if not isinstance(submissions, dict):+ return None+ filings = submissions.get("filings")+ if not isinstance(filings, dict):+ return None+ recent = filings.get("recent")+ return recent if isinstance(recent, dict) else None+++def _document_url(cik: str, accession: Optional[str], primary_doc: Optional[str]) -> Optional[str]:+ """Build the SEC primary-document URL, or ``None`` when parts are missing.++ Args:+ cik: Padded or un-padded CIK; leading zeros are dropped for the URL.+ accession: Accession number like ``0000320193-23-000106``.+ primary_doc: Primary document filename within the filing.++ Returns:+ A fully-qualified ``sec.gov`` document URL, or ``None``.+ """+ if not accession or not primary_doc:+ return None+ cik_digits = str(cik).lstrip("0") or "0"+ accession_nodash = str(accession).replace("-", "")+ return f"{_DOC_BASE}/{cik_digits}/{accession_nodash}/{primary_doc}"+++def _parse_metric(facts: Any, metric_name: str, limit: int) -> Dict[str, Any]:+ """Extract one us-gaap concept's reported series from a companyfacts payload.++ XBRL companyfacts nest as ``facts.us-gaap.<Concept>.units.<Unit>`` -> a list+ of points (``{end, val, fy, fp, form, accn, frame?}``). We surface the most+ populated unit, newest points last in source order then truncated to the+ most recent ``limit``.++ Args:+ facts: Decoded companyfacts JSON.+ metric_name: The us-gaap concept name to look up.+ limit: Maximum number of most-recent points to return.++ Returns:+ ``{"concept", "unit", "label", "points": [...]}``; ``unit`` and+ ``points`` are empty when the concept is absent or carries no data.+ """+ base: Dict[str, Any] = {"concept": metric_name, "unit": None, "label": None, "points": []}+ if not isinstance(facts, dict):+ return base+ gaap = (facts.get("facts") or {}).get("us-gaap")+ if not isinstance(gaap, dict):+ return base+ concept = gaap.get(metric_name)+ if not isinstance(concept, dict):+ return base++ base["label"] = concept.get("label")+ units = concept.get("units")+ if not isinstance(units, dict) or not units:+ return base++ unit_key, rows = _pick_unit(units)+ base["unit"] = unit_key++ points = [p for p in (_normalize_point(r) for r in rows) if p is not None]+ base["points"] = points[-limit:] if limit > 0 else points+ return base+++def _pick_unit(units: Dict[str, Any]) -> tuple[str, List[Any]]:+ """Choose the unit bucket with the most reported rows.++ Args:+ units: The ``units`` mapping of a us-gaap concept.++ Returns:+ ``(unit_key, rows)`` for the richest unit; ``rows`` is ``[]`` when none.+ """+ best_key = ""+ best_rows: List[Any] = []+ for key, rows in units.items():+ if isinstance(rows, list) and len(rows) >= len(best_rows):+ best_key, best_rows = str(key), rows+ return best_key, best_rows+++def _normalize_point(row: Any) -> Optional[Dict[str, Any]]:+ """Map one XBRL fact row to our metric point, or ``None`` if unusable.++ A row without both a value and an end date carries no signal and is dropped.++ Args:+ row: One element of a unit's fact list.++ Returns:+ ``{end, val, fiscal_year, fiscal_period, form, accession, frame}`` or+ ``None``.+ """+ if not isinstance(row, dict):+ return None+ end = row.get("end")+ val = _to_number(row.get("val"))+ if not end and val is None:+ return None+ return {+ "end": end,+ "val": val,+ "fiscal_year": row.get("fy"),+ "fiscal_period": row.get("fp"),+ "form": row.get("form"),+ "accession": row.get("accn"),+ "frame": row.get("frame"),+ }+++def _at(seq: Any, idx: int) -> Optional[str]:+ """Return ``seq[idx]`` as a stripped string, or ``None`` when out of range/empty."""+ if not isinstance(seq, list) or idx >= len(seq):+ return None+ value = seq[idx]+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++def _to_number(value: Any) -> Optional[float]:+ """Coerce a fact value to ``float``, or ``None`` when absent/non-numeric."""+ if value is None or value == "":+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _error(message: str) -> str:+ """Render a failure envelope as a JSON string."""+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)diff --git a/agent/src/tools/sector_tool.py b/agent/src/tools/sector_tool.pynew file mode 100644index 000000000..f3956b935--- /dev/null+++ b/agent/src/tools/sector_tool.py@@ -0,0 +1,319 @@+"""Read-only sector / concept board tool backed by the Eastmoney client.++Eastmoney publishes a free, no-auth board taxonomy that groups A-shares into+industry sectors (行业板块) and thematic concept boards (概念板块). This tool+exposes two read-only views over that taxonomy:++* **Membership** — given a stock ``code``, list the industry / concept boards+ that stock belongs to. Served by the push2 ``slist`` endpoint, addressed by+ the same ``secid`` scheme used for klines.+* **Ranking** — with ``mode="ranking"``, rank the industry boards themselves by+ intraday percent change. Served by the push2 ``clist`` endpoint over the+ industry-board universe (``fs=m:90+t:2``).++Both endpoints route through :mod:`backtest.loaders.eastmoney_client` so every+request goes through the shared per-host throttle (Eastmoney rate-limits by IP+and bans bursting clients). Membership covers A-shares (``.SH`` / ``.SZ`` /+``.BJ``); ranking is the A-share board universe.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from backtest.loaders.eastmoney_client import get_json, resolve_secid+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney push2 board endpoints. ``slist`` returns the boards one stock+# belongs to; ``clist`` enumerates / ranks a board universe.+_MEMBERSHIP_URL = "https://push2.eastmoney.com/api/qt/slist/get"+_RANKING_URL = "https://push2.eastmoney.com/api/qt/clist/get"++# Field selectors. f12 = board/security code, f14 = name, f3 = change percent,+# f2 = latest price, f104/f105 = up/down constituent counts (ranking only).+_MEMBERSHIP_FIELDS = "f12,f13,f14,f3,f2"+_RANKING_FIELDS = "f12,f14,f3,f2,f104,f105,f128,f140"++# Industry-board universe selector for the ranking view (m:90 = board market,+# t:2 = industry board sub-type). Sort by f3 (change percent), descending.+_RANKING_FS = "m:90+t:2"++# Defensive caps so a payload can never blow up the LLM context.+_MAX_RANKING = 100+_DEFAULT_RANKING = 30+_VALID_MODES = ("membership", "ranking")+++def _error(message: str) -> str:+ """Build the failure envelope as a JSON string.++ Args:+ message: Human-readable error description.++ Returns:+ A ``{"ok": false, "error": ...}`` JSON string.+ """+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)+++def _as_float(value: Any) -> float | None:+ """Coerce an Eastmoney numeric cell to ``float``, or ``None`` if unusable.++ Eastmoney emits ``"-"`` for missing numerics; those map to ``None``.++ Args:+ value: Raw cell value from a push2 row.++ Returns:+ The float value, or ``None`` when the cell is missing / non-numeric.+ """+ if value is None or value == "-" or value == "":+ return None+ try:+ return float(value)+ except (ValueError, TypeError):+ return None+++def _parse_membership_row(row: Any) -> dict[str, Any] | None:+ """Parse one ``slist`` diff row into a labelled board-membership dict.++ Args:+ row: One element of ``data.diff`` (a dict keyed by ``f12``/``f14``/...).++ Returns:+ A dict ``{board_code, board_name, change_pct, price}``, or ``None`` when+ the row lacks an identifiable board code/name.+ """+ if not isinstance(row, dict):+ return None+ board_code = row.get("f12")+ board_name = row.get("f14")+ if not board_code or not board_name:+ return None+ return {+ "board_code": str(board_code),+ "board_name": str(board_name),+ "change_pct": _as_float(row.get("f3")),+ "price": _as_float(row.get("f2")),+ }+++def _parse_ranking_row(row: Any) -> dict[str, Any] | None:+ """Parse one ``clist`` diff row into a labelled board-ranking dict.++ Args:+ row: One element of ``data.diff`` (a dict keyed by ``f12``/``f14``/...).++ Returns:+ A dict ``{board_code, board_name, change_pct, index, leader, up_count,+ down_count}``, or ``None`` when the row lacks a board code/name.+ """+ if not isinstance(row, dict):+ return None+ board_code = row.get("f12")+ board_name = row.get("f14")+ if not board_code or not board_name:+ return None+ leader = row.get("f140")+ return {+ "board_code": str(board_code),+ "board_name": str(board_name),+ "change_pct": _as_float(row.get("f3")),+ "index": _as_float(row.get("f2")),+ "up_count": _as_float(row.get("f104")),+ "down_count": _as_float(row.get("f105")),+ "leader": str(leader) if leader and leader != "-" else None,+ }+++def _diff_rows(payload: Any) -> list:+ """Extract the ``data.diff`` row list from a push2 payload, defensively.++ Args:+ payload: Decoded JSON from a push2 board endpoint.++ Returns:+ The list of diff rows, or ``[]`` when the payload carries none.+ """+ data = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(data, dict):+ return []+ diff = data.get("diff")+ if isinstance(diff, dict):+ # Some push2 responses key diff rows by string index instead of a list.+ return list(diff.values())+ if isinstance(diff, list):+ return diff+ return []+++def _fetch_membership(code: str) -> str:+ """Fetch the industry / concept boards one stock belongs to.++ Args:+ code: Vibe-Trading A-share symbol (e.g. ``"600519.SH"``).++ Returns:+ A JSON envelope string with the resolved boards, or an error envelope+ when the symbol is unresolvable or the request fails.+ """+ secid = resolve_secid(code)+ if secid is None:+ return _error(f"unresolvable symbol: {code}")++ try:+ payload = get_json(+ _MEMBERSHIP_URL,+ params={+ "secid": secid,+ "spt": "3",+ "pi": "0",+ "pz": "100",+ "fields": _MEMBERSHIP_FIELDS,+ "fltt": "2",+ "po": "1",+ },+ )+ except Exception as exc: # noqa: BLE001 - surface a clean error envelope+ logger.warning("sector membership fetch failed for %s: %s", code, exc)+ return _error(f"membership request failed: {exc}")++ boards = [+ parsed+ for parsed in (_parse_membership_row(r) for r in _diff_rows(payload))+ if parsed is not None+ ]+ envelope = {+ "ok": True,+ "market": "stock",+ "source": "eastmoney",+ "mode": "membership",+ "data": {"code": code, "secid": secid, "boards": boards},+ }+ return json.dumps(envelope, ensure_ascii=False)+++def _fetch_ranking(limit: int) -> str:+ """Fetch the industry-board ranking by intraday percent change.++ Args:+ limit: Number of top boards to keep (already validated and capped).++ Returns:+ A JSON envelope string with the ranked boards, or an error envelope when+ the request fails.+ """+ try:+ payload = get_json(+ _RANKING_URL,+ params={+ "fs": _RANKING_FS,+ "fields": _RANKING_FIELDS,+ "pn": "1",+ "pz": str(limit),+ "po": "1",+ "fid": "f3",+ "fltt": "2",+ },+ )+ except Exception as exc: # noqa: BLE001 - surface a clean error envelope+ logger.warning("sector ranking fetch failed: %s", exc)+ return _error(f"ranking request failed: {exc}")++ boards = [+ parsed+ for parsed in (_parse_ranking_row(r) for r in _diff_rows(payload))+ if parsed is not None+ ]+ if len(boards) > limit:+ boards = boards[:limit]+ envelope = {+ "ok": True,+ "market": "stock",+ "source": "eastmoney",+ "mode": "ranking",+ "data": {"boards": boards},+ }+ return json.dumps(envelope, ensure_ascii=False)+++class SectorInfoTool(BaseTool):+ """Look up sector / concept board membership for a stock, or rank boards."""++ name = "get_sector_info"+ description = (+ "Look up Chinese A-share sector / concept board info via Eastmoney "+ "(free, no auth). Two modes: (1) membership — given a stock 'code' "+ "(e.g. 600519.SH / 000001.SZ / .BJ), list the industry and concept "+ "boards it belongs to; (2) ranking — set mode='ranking' to rank "+ "industry boards by today's percent change (with up/down constituent "+ "counts and the leading stock). Use this to map a stock to its sectors "+ "or to see which sectors are hot today. Market: A-share stocks. "+ 'Example: {"code": "600519.SH"} or {"mode": "ranking", "limit": 20}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": (+ "A-share stock symbol with market suffix, e.g. '600519.SH', "+ "'000001.SZ', '430139.BJ'. Required when mode='membership' "+ "(the default); ignored when mode='ranking'."+ ),+ },+ "mode": {+ "type": "string",+ "enum": ["membership", "ranking"],+ "description": (+ "'membership' (default) lists the boards a stock belongs to "+ "and requires 'code'. 'ranking' ranks industry boards by "+ "today's percent change and ignores 'code'."+ ),+ "default": "membership",+ },+ "limit": {+ "type": "integer",+ "description": (+ "For mode='ranking', number of top boards to return "+ f"(1-{_MAX_RANKING}). Ignored for mode='membership'. "+ f"Default {_DEFAULT_RANKING}."+ ),+ "default": _DEFAULT_RANKING,+ },+ },+ "required": [],+ }++ def execute(self, **kwargs: Any) -> str:+ """Dispatch to the membership or ranking view and return a JSON envelope.++ Args:+ **kwargs: ``mode`` ("membership"|"ranking", default "membership"),+ ``code`` (str, required for membership), ``limit`` (int, default+ 30, used by ranking).++ Returns:+ A JSON string ``{"ok": true, "market": "stock", "source":+ "eastmoney", "mode": ..., "data": {...}}`` on success, or+ ``{"ok": false, "error": ...}`` on a validation / request failure.+ """+ mode = kwargs.get("mode", "membership")+ if mode not in _VALID_MODES:+ return _error(f"mode must be one of {list(_VALID_MODES)}")++ if mode == "ranking":+ limit = kwargs.get("limit", _DEFAULT_RANKING)+ if not isinstance(limit, int) or isinstance(limit, bool) or limit < 1:+ return _error("limit must be a positive integer")+ return _fetch_ranking(min(limit, _MAX_RANKING))++ code = kwargs.get("code")+ if not isinstance(code, str) or not code.strip():+ return _error("code must be a non-empty string for mode='membership'")+ return _fetch_membership(code.strip())diff --git a/agent/src/tools/shareholder_count_tool.py b/agent/src/tools/shareholder_count_tool.pynew file mode 100644index 000000000..20a218e9c--- /dev/null+++ b/agent/src/tools/shareholder_count_tool.py@@ -0,0 +1,218 @@+"""Read-only tool: A-share quarterly shareholder count via Eastmoney datacenter.++Eastmoney's datacenter report API publishes the periodic "股东户数" (number of+registered shareholders) disclosure for mainland A-shares: the holder count per+report period, the quarter-over-quarter change, and the average holding value+per account. This tool wraps that report behind the project's BaseTool contract+and the frozen, IP-throttled Eastmoney client so the agent never hits the host+un-throttled and never re-implements provider plumbing.++Only mainland A-shares (``.SH`` / ``.SZ`` / ``.BJ``) carry this disclosure;+other markets return an error envelope.+"""++from __future__ import annotations++import json+from typing import Any++from backtest.loaders.eastmoney_client import get_json, resolve_secid+from src.agent.tools import BaseTool++# Eastmoney datacenter report endpoint + the shareholder-number report id.+_DATACENTER_URL = "https://datacenter-web.eastmoney.com/api/data/v1/get"+_REPORT_NAME = "RPT_HOLDERNUMLATEST"++# Report columns we surface, mapped to the API's field names.+_COLUMNS = (+ "SECUCODE,SECURITY_CODE,END_DATE,HOLDER_NUM,HOLDER_NUM_CHANGE,"+ "HOLDER_NUM_RATIO,AVG_HOLD_AMT,AVG_HOLD_NUM,TOTAL_MARKET_CAP"+)++# Hard cap on returned periods so a long history cannot bloat the payload.+_MAX_PERIODS = 24++# A-share exchange suffixes this disclosure covers.+_A_SHARE_SUFFIXES = ("SH", "SZ", "BJ")+++class ShareholderCountTool(BaseTool):+ """Fetch A-share quarterly shareholder counts with QoQ change and avg holding."""++ name = "get_shareholder_count"+ description = (+ "Fetch mainland A-share quarterly shareholder count (股东户数) from the "+ "Eastmoney datacenter: holder count per report period, quarter-over-quarter "+ "change (absolute and percent), and average holding (shares and market value) "+ "per account. Markets: China A-shares only (.SH / .SZ / .BJ). "+ 'Example: {"code": "600519.SH"}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": (+ "A-share symbol in <code>.<exchange> form, exchange suffix one of "+ "SH / SZ / BJ (e.g. '600519.SH', '000001.SZ', '830799.BJ')."+ ),+ },+ "max_periods": {+ "type": "integer",+ "description": (+ "Maximum number of most-recent report periods to return "+ f"(1-{_MAX_PERIODS}). Defaults to {_MAX_PERIODS}."+ ),+ "default": _MAX_PERIODS,+ },+ },+ "required": ["code"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Resolve the symbol, query the report, and return a JSON envelope.++ Args:+ **kwargs: ``code`` (required A-share symbol) and optional+ ``max_periods`` (period cap).++ Returns:+ A JSON string envelope. On success:+ ``{"ok": true, "market": "CN", "source": "eastmoney",+ "data": {"code", "periods": [...]}}``. On failure:+ ``{"ok": false, "error": str}``.+ """+ code = kwargs.get("code")+ if not isinstance(code, str) or not code.strip():+ return _error("'code' is required and must be a non-empty A-share symbol")+ code = code.strip().upper()++ suffix = code.rpartition(".")[2]+ if suffix not in _A_SHARE_SUFFIXES:+ return _error(+ f"shareholder count is China A-share only (.SH/.SZ/.BJ); got '{code}'"+ )+ if resolve_secid(code) is None:+ return _error(f"could not resolve A-share symbol '{code}'")++ limit = _clamp_periods(kwargs.get("max_periods", _MAX_PERIODS))++ try:+ payload = get_json(+ _DATACENTER_URL,+ params={+ "reportName": _REPORT_NAME,+ "columns": _COLUMNS,+ "filter": f'(SECUCODE="{code}")',+ "sortColumns": "END_DATE",+ "sortTypes": "-1",+ "pageNumber": "1",+ "pageSize": str(limit),+ "source": "WEB",+ "client": "WEB",+ },+ )+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelope+ return _error(f"eastmoney datacenter request failed: {exc}")++ periods = _parse_periods(payload)+ if not periods:+ return _error(f"no shareholder-count disclosure found for '{code}'")++ return json.dumps(+ {+ "ok": True,+ "market": "CN",+ "source": "eastmoney",+ "data": {"code": code, "periods": periods[:limit]},+ },+ ensure_ascii=False,+ )+++def _clamp_periods(value: Any) -> int:+ """Coerce a requested period count into the supported ``1.._MAX_PERIODS`` range."""+ try:+ n = int(value)+ except (TypeError, ValueError):+ return _MAX_PERIODS+ return max(1, min(n, _MAX_PERIODS))+++def _parse_periods(payload: Any) -> list[dict]:+ """Extract per-period shareholder records from a datacenter payload.++ Args:+ payload: Decoded datacenter JSON; rows live under ``result.data``.++ Returns:+ A list of normalized period dicts (newest first), empty when the payload+ carries no usable rows.+ """+ if not isinstance(payload, dict):+ return []+ result = payload.get("result")+ if not isinstance(result, dict):+ return []+ rows = result.get("data")+ if not isinstance(rows, list):+ return []++ periods: list[dict] = []+ for row in rows:+ record = _normalize_row(row)+ if record is not None:+ periods.append(record)+ return periods+++def _normalize_row(row: Any) -> dict | None:+ """Map one raw datacenter row to our period record, or ``None`` if unusable.++ A row missing both an end date and a holder count carries no signal and is+ dropped; a single bad row never aborts the batch.++ Args:+ row: One element of ``result.data``.++ Returns:+ ``{end_date, holder_count, holder_count_change, holder_count_change_pct,+ avg_hold_shares, avg_hold_amount, total_market_cap}`` or ``None``.+ """+ if not isinstance(row, dict):+ return None+ end_date = _clean_date(row.get("END_DATE"))+ holder_count = _to_number(row.get("HOLDER_NUM"))+ if end_date is None and holder_count is None:+ return None+ return {+ "end_date": end_date,+ "holder_count": holder_count,+ "holder_count_change": _to_number(row.get("HOLDER_NUM_CHANGE")),+ "holder_count_change_pct": _to_number(row.get("HOLDER_NUM_RATIO")),+ "avg_hold_shares": _to_number(row.get("AVG_HOLD_NUM")),+ "avg_hold_amount": _to_number(row.get("AVG_HOLD_AMT")),+ "total_market_cap": _to_number(row.get("TOTAL_MARKET_CAP")),+ }+++def _clean_date(value: Any) -> str | None:+ """Trim a datacenter timestamp to its ``YYYY-MM-DD`` date, or ``None``."""+ if not isinstance(value, str) or not value.strip():+ return None+ return value.strip().split(" ", 1)[0]+++def _to_number(value: Any) -> float | None:+ """Coerce a datacenter cell to ``float``, or ``None`` when absent/non-numeric."""+ if value is None or value == "":+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _error(message: str) -> str:+ """Render a failure envelope as a JSON string."""+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)diff --git a/agent/src/tools/stock_news_tool.py b/agent/src/tools/stock_news_tool.pynew file mode 100644index 000000000..db9a96ec1--- /dev/null+++ b/agent/src/tools/stock_news_tool.py@@ -0,0 +1,408 @@+"""Read-only news tool: per-stock and global financial headlines.++Two public, no-auth news surfaces are wrapped behind one BaseTool contract:++* China A-share (and general China-market finance) headlines come from+ Eastmoney's free ``search-api`` news-list endpoint. Like every Eastmoney+ surface it rate-limits by source IP, so the request routes through the frozen,+ IP-throttled :mod:`backtest.loaders.eastmoney_client` rather than touching the+ host directly.+* US / HK have no free no-auth article feed here: the frozen+ :func:`backtest.loaders.yahoo_client.search` helper exposes only the search+ endpoint's instrument ``quotes`` (not its ``news`` array), so the tool returns+ honest related-instrument *matches* under a ``matches`` key — never instrument+ hits relabelled as articles.++The tool never re-implements provider plumbing and never issues an un-throttled+request: every outbound call goes through a frozen client.++Scopes:++* ``stock`` (default) — headlines for a single security named by ``code``.+* ``global`` — broad market headlines, no ``code`` required.++A failure for one upstream is reported as an error envelope; the tool never+raises out of :meth:`StockNewsTool.execute`.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from backtest.loaders import eastmoney_client, yahoo_client++from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney free news search endpoint (JSON list of CMS articles). It is the+# same surface the site's search box calls; no auth, IP-throttled.+_EM_NEWS_URL = "https://search-api-web.eastmoney.com/search/jsonp"++# A-share / China-market suffixes that route to the Eastmoney news surface.+_EM_SUFFIXES = ("SH", "SZ", "BJ")+# Suffixes that route to Yahoo's search-news surface.+_YAHOO_SUFFIXES = ("US", "HK")++# Default broad-market query used when ``scope='global'`` carries no code.+_GLOBAL_QUERY = "财经"++# Bounds so a noisy upstream can never return an unbounded payload.+_DEFAULT_LIMIT = 20+_MAX_LIMIT = 50+# Per-article body trim so the envelope stays compact for the LLM.+_SNIPPET_CHARS = 280+++def _clamp_limit(raw: Any) -> int:+ """Coerce a caller-supplied ``limit`` into the supported ``1.._MAX_LIMIT`` range.++ Args:+ raw: The raw ``limit`` value from the tool arguments (any type).++ Returns:+ An integer in ``[1, _MAX_LIMIT]``, falling back to ``_DEFAULT_LIMIT``+ when ``raw`` is missing or non-numeric.+ """+ try:+ value = int(raw)+ except (TypeError, ValueError):+ return _DEFAULT_LIMIT+ if value < 1:+ return 1+ return min(value, _MAX_LIMIT)+++def _suffix_of(code: str) -> str:+ """Return the upper-cased exchange suffix of a symbol, or ``""`` when none."""+ if "." not in code:+ return ""+ return code.rpartition(".")[2].strip().upper()+++def _bare_query(code: str) -> str:+ """Strip any exchange suffix to the bare code used as a news search term."""+ return code.strip().split(".", 1)[0].strip()+++def _snippet(text: Any) -> str:+ """Trim an article body to a bounded plain-text snippet.++ Args:+ text: Raw body/summary value (any type).++ Returns:+ A whitespace-collapsed snippet capped at ``_SNIPPET_CHARS`` characters,+ or ``""`` when ``text`` is not a usable string.+ """+ if not isinstance(text, str):+ return ""+ collapsed = " ".join(text.split())+ if len(collapsed) <= _SNIPPET_CHARS:+ return collapsed+ return collapsed[:_SNIPPET_CHARS].rstrip() + "…"+++def _decode_jsonp(payload: Any) -> Any:+ """Decode an Eastmoney response that may arrive JSON or JSONP-wrapped.++ The search endpoint usually returns a JSON object, but can echo a+ ``callback(...)`` JSONP envelope. A single outer call wrapper is stripped+ before parsing.++ Args:+ payload: The decoded body from the throttled client (``dict`` already, or+ a raw ``str`` when JSONP-wrapped).++ Returns:+ The decoded object, or ``None`` when nothing parseable is found.+ """+ if isinstance(payload, dict):+ return payload+ if not isinstance(payload, str):+ return None+ start = payload.find("(")+ end = payload.rfind(")")+ inner = payload[start + 1 : end] if start != -1 and end > start else payload+ try:+ return json.loads(inner)+ except (ValueError, TypeError):+ return None+++def _em_article(raw: dict[str, Any]) -> dict[str, Any]:+ """Project one Eastmoney CMS article into a compact, named record.++ Args:+ raw: A single article dict from ``result.cmsArticleWebOld``.++ Returns:+ A flat ``{title, url, source, published, snippet}`` record.+ """+ return {+ "title": _snippet(raw.get("title")),+ "url": raw.get("url"),+ "source": raw.get("mediaName"),+ "published": raw.get("date"),+ "snippet": _snippet(raw.get("content")),+ }+++def _fetch_eastmoney_news(query: str, limit: int) -> list[dict[str, Any]]:+ """Fetch China-market news headlines for a query from Eastmoney.++ Args:+ query: Free-text search term (bare code or keyword).+ limit: Maximum number of articles to return.++ Returns:+ A capped list of compact article records; empty when none.++ Raises:+ requests.RequestException: Network failure, propagated to the caller.+ requests.HTTPError: Non-2xx response status.+ ValueError: Body is not valid JSON.+ """+ param = json.dumps(+ {+ "uid": "",+ "keyword": query,+ "type": ["cmsArticleWebOld"],+ "client": "web",+ "clientType": "web",+ "param": {"cmsArticleWebOld": {"searchScope": "default", "sort": "default", "pageIndex": 1, "pageSize": limit}},+ },+ ensure_ascii=False,+ )+ payload = eastmoney_client.get_json(+ _EM_NEWS_URL,+ params={"cb": "", "param": param, "_": "0"},+ )+ decoded = _decode_jsonp(payload)+ if not isinstance(decoded, dict):+ return []+ result = decoded.get("result")+ if not isinstance(result, dict):+ return []+ articles = result.get("cmsArticleWebOld")+ if not isinstance(articles, list):+ return []+ return [_em_article(a) for a in articles if isinstance(a, dict)][:limit]+++def _yahoo_match(raw: dict[str, Any]) -> dict[str, Any]:+ """Project one Yahoo search match into a compact headline-style record.++ Yahoo's ``search`` helper returns instrument matches; each is surfaced as a+ related-instrument headline so callers get the symbol, name and exchange.++ Args:+ raw: A single quote dict from :func:`yahoo_client.search`.++ Returns:+ A flat ``{title, symbol, exchange, quote_type}`` record.+ """+ name = raw.get("shortname") or raw.get("longname") or raw.get("symbol")+ return {+ "title": _snippet(name),+ "symbol": raw.get("symbol"),+ "exchange": raw.get("exchange"),+ "quote_type": raw.get("quoteType"),+ }+++def _fetch_yahoo_matches(query: str, limit: int) -> list[dict[str, Any]]:+ """Fetch US/HK related-instrument matches for a query via Yahoo search.++ Yahoo's public search endpoint also carries a ``news`` array, but the frozen+ :func:`yahoo_client.search` helper exposes only the instrument ``quotes``.+ Rather than mislabel those quotes as articles, this returns them honestly as+ related-instrument matches.++ Args:+ query: Free-text search term (bare ticker or keyword).+ limit: Maximum number of records to return.++ Returns:+ A capped list of compact instrument-match records; empty when none.++ Raises:+ requests.RequestException: Network/HTTP failure, propagated to caller.+ """+ matches = yahoo_client.search(query)+ return [_yahoo_match(m) for m in matches if isinstance(m, dict)][:limit]+++class StockNewsTool(BaseTool):+ """Read-only per-stock and global financial news headlines."""++ name = "get_stock_news"+ description = (+ "Fetch recent financial news headlines, read-only and no auth. Markets: "+ "China A-share (SH/SZ/BJ) returns Eastmoney news ARTICLES "+ "(title/url/source/published/snippet) under 'articles'. US (.US) and Hong "+ "Kong (.HK) do NOT return news articles: Yahoo's public search surface "+ "yields related-instrument MATCHES (symbol/name/exchange/quote_type), "+ "returned under 'matches' (result_type='matches'), not 'articles'. Use "+ "scope 'stock' with a 'code', or scope 'global' (no code) for broad "+ "China-market finance articles. "+ 'Example: {"code": "600519.SH", "scope": "stock", "limit": 10}.'+ )+ parameters = {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": (+ "Symbol whose news to fetch, e.g. '600519.SH', 'AAPL.US', "+ "'00700.HK'. Required when scope='stock'; ignored when "+ "scope='global'. The exchange suffix selects the upstream: "+ "SH/SZ/BJ -> Eastmoney, US/HK -> Yahoo Finance."+ ),+ },+ "scope": {+ "type": "string",+ "enum": ["stock", "global"],+ "description": (+ "'stock' (default) for one security named by 'code'; "+ "'global' for broad China-market finance headlines."+ ),+ "default": "stock",+ },+ "limit": {+ "type": "integer",+ "description": (+ "Maximum number of headlines to return (1-50). Default 20."+ ),+ "default": _DEFAULT_LIMIT,+ },+ },+ "required": [],+ }++ def execute(self, **kwargs: Any) -> str:+ """Fetch news headlines for one stock or the broad market.++ Args:+ **kwargs: ``scope`` ('stock' | 'global', default 'stock'), ``code``+ (required when scope='stock'), and optional ``limit`` (1-50).++ Returns:+ A JSON string envelope. On success:+ ``{"ok": true, "market": <market>, "source": <source>,+ "data": {...}}``. On failure: ``{"ok": false, "error": "..."}``.+ """+ scope = kwargs.get("scope", "stock")+ if scope not in ("stock", "global"):+ return self._error(f"invalid scope: {scope!r}; expected 'stock' or 'global'")++ limit = _clamp_limit(kwargs.get("limit"))++ if scope == "global":+ return self._run_global(limit)+ return self._run_stock(kwargs.get("code"), limit)++ def _run_global(self, limit: int) -> str:+ """Fetch broad China-market headlines from Eastmoney.++ Args:+ limit: Maximum number of headlines.++ Returns:+ A success or error JSON envelope.+ """+ try:+ articles = _fetch_eastmoney_news(_GLOBAL_QUERY, limit)+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelope+ logger.warning("global news fetch failed: %s", exc)+ return self._error(f"eastmoney news fetch failed: {exc}")+ return self._ok("global", "eastmoney", {"scope": "global", "articles": articles})++ def _run_stock(self, code_arg: Any, limit: int) -> str:+ """Fetch single-security headlines, routing by exchange suffix.++ Args:+ code_arg: Raw ``code`` argument (any type).+ limit: Maximum number of headlines.++ Returns:+ A success or error JSON envelope.+ """+ if not isinstance(code_arg, str) or not code_arg.strip():+ return self._error("missing required parameter: code (required when scope='stock')")++ code = code_arg.strip()+ suffix = _suffix_of(code)+ query = _bare_query(code)+ if not query:+ return self._error(f"invalid code: {code!r}")++ if suffix in _EM_SUFFIXES:+ return self._stock_via_eastmoney(code, query, limit)+ if suffix in _YAHOO_SUFFIXES:+ return self._stock_via_yahoo(code, query, limit)+ return self._error(+ f"unsupported market for code {code!r}; expected suffix in "+ f"{_EM_SUFFIXES + _YAHOO_SUFFIXES}"+ )++ def _stock_via_eastmoney(self, code: str, query: str, limit: int) -> str:+ """Fetch A-share headlines from Eastmoney for one code."""+ try:+ articles = _fetch_eastmoney_news(query, limit)+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelope+ logger.warning("eastmoney news fetch failed for %s: %s", code, exc)+ return self._error(f"eastmoney news fetch failed: {exc}")+ return self._ok(+ "a_share", "eastmoney", {"scope": "stock", "code": code, "articles": articles}+ )++ def _stock_via_yahoo(self, code: str, query: str, limit: int) -> str:+ """Fetch US/HK related-instrument matches from Yahoo for one code.++ Yahoo's public ``search`` surface yields instrument matches, not news+ articles, so the payload is labelled ``matches`` (never ``articles``) to+ avoid passing instrument hits off as headlines.+ """+ market = "hk" if _suffix_of(code) == "HK" else "us"+ try:+ matches = _fetch_yahoo_matches(query, limit)+ except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelope+ logger.warning("yahoo search fetch failed for %s: %s", code, exc)+ return self._error(f"yahoo search fetch failed: {exc}")+ return self._ok(+ market,+ "yahoo",+ {"scope": "stock", "code": code, "result_type": "matches", "matches": matches},+ )++ @staticmethod+ def _ok(market: str, source: str, data: dict[str, Any]) -> str:+ """Render a success envelope as a JSON string.++ Args:+ market: Market label (e.g. ``"a_share"``, ``"us"``, ``"global"``).+ source: Upstream provider name (``"eastmoney"`` or ``"yahoo"``).+ data: The payload mapping.++ Returns:+ ``{"ok": true, "market": ..., "source": ..., "data": ...}`` as JSON.+ """+ return json.dumps(+ {"ok": True, "market": market, "source": source, "data": data},+ ensure_ascii=False,+ )++ @staticmethod+ def _error(message: str) -> str:+ """Render a failure envelope as a JSON string.++ Args:+ message: Human-readable error text.++ Returns:+ ``{"ok": false, "error": message}`` as a JSON string.+ """+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)diff --git a/agent/src/tools/stock_profile_tool.py b/agent/src/tools/stock_profile_tool.pynew file mode 100644index 000000000..710458a33--- /dev/null+++ b/agent/src/tools/stock_profile_tool.py@@ -0,0 +1,306 @@+"""Read-only company-profile tool: key stats, estimates, and ownership.++Backed by the shared Yahoo Finance quoteSummary client+(:func:`backtest.loaders.yahoo_client.get_quote_summary`), which routes every+request through the throttled HTTP layer and handles the cookie+crumb+handshake. This tool only selects modules, projects the verbose Yahoo payload+into compact rows, and wraps the result in the project envelope.+"""++from __future__ import annotations++import json+import logging+from typing import Any, Dict, List, Optional++from backtest.loaders.yahoo_client import get_quote_summary+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Section name (tool-facing) -> Yahoo quoteSummary module name.+_SECTION_MODULES: Dict[str, str] = {+ "key_stats": "defaultKeyStatistics",+ "financials": "financialData",+ "earnings_trend": "earningsTrend",+ "institution_ownership": "institutionOwnership",+ "insider_holders": "insiderHolders",+ "recommendation_trend": "recommendationTrend",+}+_ALL_SECTIONS = tuple(_SECTION_MODULES)++# Cap list-valued sections so a verbose payload cannot bloat the envelope.+_MAX_ROWS = 25+++def _raw(value: Any) -> Any:+ """Unwrap a Yahoo ``{"raw":..,"fmt":..}`` cell to its numeric ``raw`` value.++ Args:+ value: A Yahoo scalar, which may be a plain value or a formatted dict.++ Returns:+ The ``raw`` member when ``value`` is a Yahoo formatted dict, the value+ itself when scalar, or ``None`` for an empty/absent cell.+ """+ if isinstance(value, dict):+ return value.get("raw")+ return value+++def _pick(source: Dict[str, Any], fields: tuple[str, ...]) -> Dict[str, Any]:+ """Project selected Yahoo fields into a flat, raw-unwrapped row."""+ return {field: _raw(source.get(field)) for field in fields}+++def _key_stats(module: Dict[str, Any]) -> Dict[str, Any]:+ """Shape the defaultKeyStatistics module into a compact row."""+ return _pick(+ module,+ (+ "enterpriseValue",+ "forwardPE",+ "trailingEps",+ "forwardEps",+ "pegRatio",+ "priceToBook",+ "profitMargins",+ "beta",+ "sharesOutstanding",+ "floatShares",+ "heldPercentInsiders",+ "heldPercentInstitutions",+ ),+ )+++def _financials(module: Dict[str, Any]) -> Dict[str, Any]:+ """Shape the financialData module into a compact row."""+ return _pick(+ module,+ (+ "currentPrice",+ "targetMeanPrice",+ "targetHighPrice",+ "targetLowPrice",+ "recommendationKey",+ "numberOfAnalystOpinions",+ "totalRevenue",+ "revenueGrowth",+ "grossMargins",+ "operatingMargins",+ "returnOnEquity",+ "totalCash",+ "totalDebt",+ ),+ )+++def _earnings_trend(module: Dict[str, Any]) -> List[Dict[str, Any]]:+ """Shape the earningsTrend periods into per-period estimate rows."""+ rows: List[Dict[str, Any]] = []+ for entry in (module.get("trend") or [])[:_MAX_ROWS]:+ if not isinstance(entry, dict):+ continue+ eps = entry.get("earningsEstimate") or {}+ rev = entry.get("revenueEstimate") or {}+ rows.append(+ {+ "period": entry.get("period"),+ "end_date": entry.get("endDate"),+ "growth": _raw(entry.get("growth")),+ "eps_avg": _raw(eps.get("avg")),+ "eps_low": _raw(eps.get("low")),+ "eps_high": _raw(eps.get("high")),+ "eps_analysts": _raw(eps.get("numberOfAnalysts")),+ "revenue_avg": _raw(rev.get("avg")),+ }+ )+ return rows+++def _institution_ownership(module: Dict[str, Any]) -> List[Dict[str, Any]]:+ """Shape the institutionOwnership holders into per-holder rows."""+ rows: List[Dict[str, Any]] = []+ for entry in (module.get("ownershipList") or [])[:_MAX_ROWS]:+ if not isinstance(entry, dict):+ continue+ rows.append(+ {+ "organization": entry.get("organization"),+ "report_date": _raw(entry.get("reportDate")),+ "pct_held": _raw(entry.get("pctHeld")),+ "position": _raw(entry.get("position")),+ "value": _raw(entry.get("value")),+ }+ )+ return rows+++def _insider_holders(module: Dict[str, Any]) -> List[Dict[str, Any]]:+ """Shape the insiderHolders holders into per-insider rows."""+ rows: List[Dict[str, Any]] = []+ for entry in (module.get("holders") or [])[:_MAX_ROWS]:+ if not isinstance(entry, dict):+ continue+ rows.append(+ {+ "name": entry.get("name"),+ "relation": entry.get("relation"),+ "latest_transaction": entry.get("latestTransDate"),+ "position": _raw(entry.get("positionDirect")),+ }+ )+ return rows+++def _recommendation_trend(module: Dict[str, Any]) -> List[Dict[str, Any]]:+ """Shape the recommendationTrend periods into per-period rating rows."""+ rows: List[Dict[str, Any]] = []+ for entry in (module.get("trend") or [])[:_MAX_ROWS]:+ if not isinstance(entry, dict):+ continue+ rows.append(+ {+ "period": entry.get("period"),+ "strong_buy": entry.get("strongBuy"),+ "buy": entry.get("buy"),+ "hold": entry.get("hold"),+ "sell": entry.get("sell"),+ "strong_sell": entry.get("strongSell"),+ }+ )+ return rows+++# Section name -> (yahoo module name, shaper). One entry per supported section.+_SHAPERS = {+ "key_stats": _key_stats,+ "financials": _financials,+ "earnings_trend": _earnings_trend,+ "institution_ownership": _institution_ownership,+ "insider_holders": _insider_holders,+ "recommendation_trend": _recommendation_trend,+}+++def _resolve_sections(sections: Optional[List[str]]) -> List[str]:+ """Validate the requested sections, defaulting to all when omitted.++ Args:+ sections: Requested section names, or ``None`` for every section.++ Returns:+ An ordered, de-duplicated list of valid section names.++ Raises:+ ValueError: If any requested name is not a supported section.+ """+ if not sections:+ return list(_ALL_SECTIONS)+ resolved: List[str] = []+ for name in sections:+ key = str(name).strip().lower()+ if key not in _SECTION_MODULES:+ raise ValueError(+ f"unknown section '{name}'; valid: {', '.join(_ALL_SECTIONS)}"+ )+ if key not in resolved:+ resolved.append(key)+ return resolved+++def _market_for(ticker: str) -> str:+ """Classify a ticker into a coarse market label for the envelope."""+ return "hk" if ticker.strip().upper().endswith(".HK") else "us"+++class StockProfileTool(BaseTool):+ """Company profile: key stats, analyst estimates, and ownership."""++ name = "get_stock_profile"+ description = (+ "Fetch a read-only company profile for a US or Hong Kong listing from "+ "Yahoo Finance: valuation key statistics, analyst price targets and "+ "earnings/revenue estimates, institutional and insider ownership, and "+ "the analyst recommendation trend. Use this for fundamentals and "+ "consensus context, not for OHLCV price bars (use get_market_data). "+ 'Example: get_stock_profile(ticker="AAPL.US", '+ 'sections=["key_stats", "financials"]).'+ )+ parameters = {+ "type": "object",+ "properties": {+ "ticker": {+ "type": "string",+ "description": (+ "US or HK symbol. US uses a bare or .US suffix (AAPL or "+ "AAPL.US); HK uses a zero-padded .HK code (00700.HK)."+ ),+ },+ "sections": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": list(_ALL_SECTIONS),+ },+ "description": (+ "Which profile sections to return. One or more of: "+ "key_stats, financials, earnings_trend, "+ "institution_ownership, insider_holders, "+ "recommendation_trend. Defaults to all sections."+ ),+ "default": list(_ALL_SECTIONS),+ },+ },+ "required": ["ticker"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Fetch and shape the requested profile sections for one ticker.++ Args:+ **kwargs: ``ticker`` (str, required) and ``sections`` (list[str],+ optional; defaults to all sections).++ Returns:+ A JSON envelope string. On success:+ ``{"ok": true, "market": str, "source": "yahoo",+ "data": {"ticker": str, "sections": {<name>: <shaped>}}}``.+ On failure: ``{"ok": false, "error": str}``.+ """+ ticker = str(kwargs.get("ticker") or "").strip()+ if not ticker:+ return self._error("ticker is required")++ try:+ sections = _resolve_sections(kwargs.get("sections"))+ except ValueError as exc:+ return self._error(str(exc))++ modules = [_SECTION_MODULES[name] for name in sections]+ try:+ summary = get_quote_summary(ticker, modules)+ except Exception as exc: # noqa: BLE001 - surface upstream as envelope+ logger.warning("get_stock_profile failed for %s: %s", ticker, exc)+ return self._error(f"yahoo quoteSummary request failed: {exc}")++ shaped: Dict[str, Any] = {}+ for name in sections:+ module = summary.get(_SECTION_MODULES[name]) or {}+ shaped[name] = _SHAPERS[name](module if isinstance(module, dict) else {})++ return json.dumps(+ {+ "ok": True,+ "market": _market_for(ticker),+ "source": "yahoo",+ "data": {"ticker": ticker, "sections": shaped},+ },+ ensure_ascii=False,+ )++ @staticmethod+ def _error(message: str) -> str:+ """Render a failure envelope as a JSON string."""+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.pynew file mode 100644index 000000000..5fa7a9336--- /dev/null+++ b/agent/src/tools/symbol_search_tool.py@@ -0,0 +1,422 @@+"""Read-only symbol-search tool: resolve a name/ticker to symbols + market.++Backed by three frozen, IP-throttled public-API clients so the agent never+hits a provider un-throttled and never re-implements transport plumbing:++* :mod:`backtest.loaders.eastmoney_client` — Eastmoney's free suggest endpoint+ matches Chinese/English names and tickers across A-shares (.SH/.SZ/.BJ),+ Hong Kong (.HK) and U.S. (.US) listings, each carrying a fully-qualified+ ``secid`` already in ``<market>.<code>`` form.+* :mod:`backtest.loaders.yahoo_client` — Yahoo's v1 search endpoint matches+ global tickers/company names (US, HK, crypto, indices, FX, ...).+* :mod:`backtest.loaders.sec_edgar_client` — the SEC company-tickers table+ enriches a resolved U.S. equity ticker with its zero-padded CIK.++The tool fans out across these sources, normalizes every hit into one compact+candidate row in the project's symbol convention, de-duplicates by symbol, and+caps the payload. A single failing source never aborts the others; its error is+recorded under ``sources`` and the surviving candidates still return.+"""++from __future__ import annotations++import json+import logging+from typing import Any, Dict, List, Optional++from backtest.loaders import eastmoney_client, sec_edgar_client, yahoo_client+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney's free, no-auth suggest endpoint (the same one the quote site calls)+# returns multi-market candidates under ``QuotationCodeTable.Data`` with a+# ready-made ``QuoteID`` secid. Requests route through the frozen, throttled+# Eastmoney client; this is just the documented endpoint URL + query shape.+_EASTMONEY_SUGGEST_URL = "https://searchapi.eastmoney.com/api/suggest/get"++# Eastmoney market-number -> our symbol suffix. Anything else is left unmapped+# (those candidates are skipped rather than emitted with a wrong suffix).+_EASTMONEY_SUFFIX_BY_MARKET: Dict[str, str] = {+ "1": "SH", # Shanghai+ "0": "SZ", # Shenzhen / Beijing share the 0 prefix on Eastmoney+ "116": "HK",+ "105": "US", # NASDAQ+ "106": "US", # NYSE+ "107": "US", # AMEX+}++# Coarse market label for the candidate row, keyed by symbol suffix.+_MARKET_BY_SUFFIX: Dict[str, str] = {+ "SH": "cn",+ "SZ": "cn",+ "BJ": "cn",+ "HK": "hk",+ "US": "us",+}++# Hard caps so a broad query cannot bloat the envelope.+_MAX_LIMIT = 25+_DEFAULT_LIMIT = 10+# Per-source fan-out ceiling before de-dup/merge keeps each provider bounded.+_PER_SOURCE_CAP = 25++# Sentinel for "no U.S. candidate, SEC was not consulted" so the caller can omit+# the ``sec_edgar`` source entry entirely.+_NO_US = "__no_us__"+++class SymbolSearchTool(BaseTool):+ """Resolve a company name or ticker fragment to candidate symbols."""++ name = "search_symbol"+ description = (+ "Resolve a company name or ticker fragment to candidate trading symbols "+ "with their market, in the project's symbol convention (A-shares "+ "600519.SH, Hong Kong 00700.HK, U.S. AAPL.US, plus crypto/index/FX from "+ "Yahoo). Searches Eastmoney (China/HK/US names and tickers) and Yahoo "+ "(global) and, for U.S. equities, attaches the SEC CIK. Use this to turn "+ "an ambiguous name into a concrete symbol before calling get_market_data "+ 'or get_sec_filings. Example: search_symbol(query="apple", limit=5).'+ )+ parameters = {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": (+ "Free-text company name or ticker fragment to resolve, e.g. "+ "'apple', '贵州茅台', '茅台', 'AAPL', '00700'. Chinese and "+ "English both accepted."+ ),+ },+ "limit": {+ "type": "integer",+ "description": (+ f"Maximum number of merged candidates to return "+ f"(1-{_MAX_LIMIT}). Defaults to {_DEFAULT_LIMIT}."+ ),+ "default": _DEFAULT_LIMIT,+ },+ },+ "required": ["query"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Fan out across providers and return a merged candidate envelope.++ Args:+ **kwargs: ``query`` (str, required free-text name/ticker) and+ ``limit`` (int, optional; clamped to ``1.._MAX_LIMIT``).++ Returns:+ A JSON envelope string. On success:+ ``{"ok": true, "market": "multi", "source": "symbol_search",+ "data": {"query": str, "count": int, "candidates": [...],+ "sources": {<name>: "ok"|<error>}}}``. On failure (only when the+ query itself is invalid):+ ``{"ok": false, "error": str}``.+ """+ query = str(kwargs.get("query") or "").strip()+ if not query:+ return _error("'query' is required and must be a non-empty string")++ limit = _clamp_limit(kwargs.get("limit", _DEFAULT_LIMIT))++ candidates: List[Dict[str, Any]] = []+ sources: Dict[str, str] = {}++ em_hits, sources["eastmoney"] = _search_eastmoney(query)+ candidates.extend(em_hits)++ yh_hits, sources["yahoo"] = _search_yahoo(query)+ candidates.extend(yh_hits)++ merged = _merge_candidates(candidates)+ merged, sources["sec_edgar"] = _enrich_us_cik(merged)+ if sources["sec_edgar"] == _NO_US:+ del sources["sec_edgar"]+ merged = merged[:limit]++ return json.dumps(+ {+ "ok": True,+ "market": "multi",+ "source": "symbol_search",+ "data": {+ "query": query,+ "count": len(merged),+ "candidates": merged,+ "sources": sources,+ },+ },+ ensure_ascii=False,+ )+++def _clamp_limit(value: Any) -> int:+ """Coerce a requested count into the supported ``1.._MAX_LIMIT`` range."""+ try:+ n = int(value)+ except (TypeError, ValueError):+ return _DEFAULT_LIMIT+ return max(1, min(n, _MAX_LIMIT))+++def _search_eastmoney(query: str) -> tuple[List[Dict[str, Any]], str]:+ """Query Eastmoney's suggest endpoint and normalize the candidates.++ Args:+ query: Free-text name or ticker fragment.++ Returns:+ ``(candidates, status)`` where ``status`` is ``"ok"`` on success or a+ short error string when the source failed (candidates is then empty).+ """+ try:+ payload = eastmoney_client.get_json(+ _EASTMONEY_SUGGEST_URL,+ params={"input": query, "type": "14", "count": str(_PER_SOURCE_CAP)},+ )+ except Exception as exc: # noqa: BLE001 - one source failing is non-fatal+ logger.warning("eastmoney suggest failed for %r: %s", query, exc)+ return [], f"eastmoney search failed: {exc}"++ rows = _eastmoney_data_rows(payload)+ candidates = [c for c in (_eastmoney_candidate(r) for r in rows) if c is not None]+ return candidates, "ok"+++def _eastmoney_data_rows(payload: Any) -> List[Dict[str, Any]]:+ """Extract the ``QuotationCodeTable.Data`` rows from a suggest payload."""+ if not isinstance(payload, dict):+ return []+ table = payload.get("QuotationCodeTable")+ if not isinstance(table, dict):+ return []+ data = table.get("Data")+ if not isinstance(data, list):+ return []+ return [row for row in data if isinstance(row, dict)]+++def _eastmoney_candidate(row: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ """Map one Eastmoney suggest row to a normalized candidate, or ``None``.++ Eastmoney rows carry ``QuoteID`` (``<market>.<code>``), ``Code``, ``Name``,+ ``MktNum`` and ``SecurityTypeName``. A row whose market we cannot map to a+ project suffix is dropped rather than emitted with a wrong symbol.++ Args:+ row: One ``QuotationCodeTable.Data`` element.++ Returns:+ A candidate dict, or ``None`` when the row is unusable.+ """+ quote_id = row.get("QuoteID")+ market = ""+ code = str(row.get("Code") or "").strip()+ if isinstance(quote_id, str) and "." in quote_id:+ market, _, qid_code = quote_id.partition(".")+ code = code or qid_code.strip()+ else:+ market = str(row.get("MktNum") or "").strip()+ suffix = _EASTMONEY_SUFFIX_BY_MARKET.get(market)+ if not suffix or not code:+ return None++ symbol = _format_symbol(code, suffix)+ if symbol is None:+ return None+ name = str(row.get("Name") or "").strip() or None+ sec_type = str(row.get("SecurityTypeName") or "").strip() or None+ return {+ "symbol": symbol,+ "name": name,+ "market": _MARKET_BY_SUFFIX.get(suffix, suffix.lower()),+ "type": sec_type,+ "source": "eastmoney",+ }+++def _format_symbol(code: str, suffix: str) -> Optional[str]:+ """Render a bare code + suffix into the project symbol convention.++ HK codes are zero-padded to five digits to match the loader/secid scheme.++ Args:+ code: Bare instrument code (e.g. ``"600519"``, ``"700"``, ``"AAPL"``).+ suffix: One of ``SH``/``SZ``/``BJ``/``HK``/``US``.++ Returns:+ The formatted symbol (``"600519.SH"``, ``"00700.HK"``, ``"AAPL.US"``),+ or ``None`` when the code is empty.+ """+ code = code.strip().upper()+ if not code:+ return None+ if suffix == "HK":+ return f"{code.zfill(5)}.HK"+ return f"{code}.{suffix}"+++def _search_yahoo(query: str) -> tuple[List[Dict[str, Any]], str]:+ """Query Yahoo's search endpoint and normalize the quote candidates.++ Args:+ query: Free-text name or ticker fragment.++ Returns:+ ``(candidates, status)`` where ``status`` is ``"ok"`` on success or a+ short error string when the source failed (candidates is then empty).+ """+ try:+ quotes = yahoo_client.search(query)+ except Exception as exc: # noqa: BLE001 - one source failing is non-fatal+ logger.warning("yahoo search failed for %r: %s", query, exc)+ return [], f"yahoo search failed: {exc}"++ candidates: List[Dict[str, Any]] = []+ for quote in quotes[:_PER_SOURCE_CAP]:+ candidate = _yahoo_candidate(quote)+ if candidate is not None:+ candidates.append(candidate)+ return candidates, "ok"+++def _yahoo_candidate(quote: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ """Map one Yahoo search quote to a normalized candidate, or ``None``.++ Yahoo carries US tickers bare and HK tickers as ``0700.HK``. We translate+ those into the project convention (``AAPL.US`` / ``00700.HK``) and leave+ other instruments (crypto, indices, FX) on their native Yahoo symbol.++ Args:+ quote: One element of Yahoo search's ``quotes`` list.++ Returns:+ A candidate dict, or ``None`` when the quote has no symbol.+ """+ raw_symbol = str(quote.get("symbol") or "").strip()+ if not raw_symbol:+ return None+ symbol, market = _from_yahoo_symbol(raw_symbol, quote)+ name = (+ str(quote.get("shortname") or quote.get("longname") or "").strip() or None+ )+ return {+ "symbol": symbol,+ "name": name,+ "market": market,+ "type": str(quote.get("quoteType") or "").strip().lower() or None,+ "exchange": str(quote.get("exchange") or "").strip() or None,+ "source": "yahoo",+ }+++def _from_yahoo_symbol(raw_symbol: str, quote: Dict[str, Any]) -> tuple[str, str]:+ """Translate a Yahoo symbol into the project convention + market label.++ Args:+ raw_symbol: The Yahoo-side symbol (e.g. ``AAPL``, ``0700.HK``, ``BTC-USD``).+ quote: The full Yahoo quote, used to distinguish a bare US equity from a+ crypto/index instrument via ``quoteType``.++ Returns:+ ``(symbol, market)`` in the project convention.+ """+ upper = raw_symbol.upper()+ if upper.endswith(".HK"):+ base = raw_symbol[: -len(".HK")].lstrip("0") or "0"+ return f"{base.zfill(5)}.HK", "hk"+ quote_type = str(quote.get("quoteType") or "").strip().upper()+ if quote_type == "EQUITY" and "." not in raw_symbol and "-" not in raw_symbol:+ return f"{upper}.US", "us"+ # Crypto, indices, FX, ETFs on non-HK exchanges: keep Yahoo's native symbol.+ return raw_symbol, "global"+++def _merge_candidates(candidates: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """De-duplicate candidates by symbol, preserving first-seen order.++ When two sources resolve the same symbol the first hit wins and the second+ source name is appended to a ``also_from`` list so provenance is not lost.++ Args:+ candidates: Raw candidates from every source, in fan-out order.++ Returns:+ A de-duplicated candidate list (immutable inputs are copied, not mutated).+ """+ by_symbol: Dict[str, Dict[str, Any]] = {}+ order: List[str] = []+ for candidate in candidates:+ symbol = candidate.get("symbol")+ if not symbol:+ continue+ if symbol not in by_symbol:+ by_symbol[symbol] = dict(candidate)+ order.append(symbol)+ continue+ existing = by_symbol[symbol]+ other = candidate.get("source")+ if other and other != existing.get("source"):+ also = list(existing.get("also_from") or [])+ if other not in also:+ also.append(other)+ merged = dict(existing)+ merged["also_from"] = also+ # Backfill a missing name from the duplicate hit.+ if not merged.get("name") and candidate.get("name"):+ merged["name"] = candidate["name"]+ by_symbol[symbol] = merged+ return [by_symbol[sym] for sym in order]+++def _enrich_us_cik(+ candidates: List[Dict[str, Any]],+) -> tuple[List[Dict[str, Any]], str]:+ """Return new candidates with a SEC CIK attached to U.S.-equity rows.++ Only ``.US`` equity symbols are looked up; the SEC table maps bare tickers+ to a zero-padded 10-digit CIK. A lookup failure stops further lookups and is+ reported via the status; resolved CIKs found before it still apply.++ Args:+ candidates: Merged candidate rows (left unmodified).++ Returns:+ ``(new_candidates, status)`` where ``status`` is :data:`_NO_US` when no+ U.S. equity was present, ``"ok"`` on a clean pass, or a short error+ string when a SEC lookup failed.+ """+ has_us = any(+ isinstance(c.get("symbol"), str) and c["symbol"].upper().endswith(".US")+ for c in candidates+ )+ if not has_us:+ return candidates, _NO_US++ status = "ok"+ out: List[Dict[str, Any]] = []+ for candidate in candidates:+ symbol = candidate.get("symbol")+ if status == "ok" and isinstance(symbol, str) and symbol.upper().endswith(".US"):+ ticker = symbol[: -len(".US")]+ try:+ cik = sec_edgar_client.cik_for(ticker)+ except Exception as exc: # noqa: BLE001 - enrichment failure is non-fatal+ logger.warning("sec cik_for failed for %s: %s", ticker, exc)+ status = f"sec lookup failed: {exc}"+ out.append(candidate)+ continue+ if cik:+ out.append({**candidate, "cik": cik})+ continue+ out.append(candidate)+ return out, status+++def _error(message: str) -> str:+ """Render a failure envelope as a JSON string."""+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)diff --git a/agent/tests/test_alphavantage_loader.py b/agent/tests/test_alphavantage_loader.pynew file mode 100644index 000000000..eee170230--- /dev/null+++ b/agent/tests/test_alphavantage_loader.py@@ -0,0 +1,192 @@+"""Tests for alphavantage_loader: availability, payload parsing, error paths.++All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported+into the loader module), so no test touches a live Alpha Vantage endpoint.+"""++from unittest.mock import patch++import pandas as pd+import pytest++from backtest.loaders import alphavantage_loader as av+++def _payload(*dates_rows) -> dict:+ """Build a TIME_SERIES_DAILY-shaped payload from (date, o, h, l, c, v) tuples."""+ series = {}+ for date, o, h, l, c, vol in dates_rows:+ series[date] = {+ "1. open": str(o),+ "2. high": str(h),+ "3. low": str(l),+ "4. close": str(c),+ "5. volume": str(vol),+ }+ return {"Time Series (Daily)": series}++[email protected](autouse=True)+def _clear_key(monkeypatch):+ """Default every test to no key unless it sets one explicitly."""+ monkeypatch.delenv("ALPHAVANTAGE_API_KEY", raising=False)+ yield+++class TestAvailability:+ """is_available() keys off a non-placeholder ALPHAVANTAGE_API_KEY."""++ def test_unset_key_is_unavailable(self):+ assert av.DataLoader().is_available() is False++ def test_placeholder_key_is_unavailable(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "your-alphavantage-api-key")+ assert av.DataLoader().is_available() is False+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "demo")+ assert av.DataLoader().is_available() is False++ def test_real_key_is_available(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ assert av.DataLoader().is_available() is True+++class TestRegistration:+ """Loader metadata matches the parcel contract."""++ def test_classvars(self):+ assert av.DataLoader.name == "alphavantage"+ assert av.DataLoader.markets == {"us_equity"}+ assert av.DataLoader.requires_auth is True+++class TestFetch:+ """fetch() parses, shapes, and date-slices the daily series."""++ def test_returns_shaped_dataframe(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ payload = _payload(+ ("2024-01-02", 100.0, 112.0, 99.0, 110.0, 1000),+ ("2024-01-03", 110.0, 111.0, 107.0, 108.0, 2000),+ )+ with patch.object(av, "throttled_get_json", return_value=payload) as mock_get:+ out = av.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")++ assert set(out) == {"AAPL"}+ df = out["AAPL"]+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"+ assert isinstance(df.index, pd.DatetimeIndex)+ assert df.index.is_monotonic_increasing+ assert all(df[col].dtype == float for col in df.columns)+ assert df.loc["2024-01-02", "open"] == 100.0+ assert df.loc["2024-01-02", "close"] == 110.0+ assert df.loc["2024-01-03", "volume"] == 2000.0+ # Request params carry the documented function + symbol + key.+ _, kwargs = mock_get.call_args+ assert kwargs["params"]["function"] == "TIME_SERIES_DAILY"+ assert kwargs["params"]["symbol"] == "AAPL"+ assert kwargs["params"]["apikey"] == "ABC123"++ def test_slices_to_requested_range(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ payload = _payload(+ ("2023-12-29", 1, 1, 1, 1, 1),+ ("2024-01-02", 2, 2, 2, 2, 2),+ ("2024-02-15", 3, 3, 3, 3, 3),+ )+ with patch.object(av, "throttled_get_json", return_value=payload):+ df = av.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")["AAPL"]+ assert [d.strftime("%Y-%m-%d") for d in df.index] == ["2024-01-02"]++ def test_lowercase_symbol_is_upcased(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ payload = _payload(("2024-01-02", 1, 1, 1, 1, 1))+ with patch.object(av, "throttled_get_json", return_value=payload) as mock_get:+ av.DataLoader().fetch(["aapl"], "2024-01-01", "2024-01-31")+ _, kwargs = mock_get.call_args+ assert kwargs["params"]["symbol"] == "AAPL"++ def test_no_key_returns_empty_without_http(self):+ with patch.object(av, "throttled_get_json") as mock_get:+ out = av.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")+ assert out == {}+ mock_get.assert_not_called()+++class TestErrorPaths:+ """Bad symbols and quota envelopes never abort the batch."""++ def test_rate_limit_note_skips_symbol(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ with patch.object(+ av, "throttled_get_json", return_value={"Note": "call frequency limit"}+ ):+ assert av.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31") == {}++ def test_error_message_skips_symbol(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ with patch.object(+ av, "throttled_get_json", return_value={"Error Message": "invalid symbol"}+ ):+ assert av.DataLoader().fetch(["NOPE"], "2024-01-01", "2024-01-31") == {}++ def test_one_failure_does_not_abort_batch(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ good = _payload(("2024-01-02", 5, 5, 5, 5, 5))++ def side_effect(url, **kwargs):+ if kwargs["params"]["symbol"] == "BAD":+ raise RuntimeError("HTTP 500")+ return good++ with patch.object(av, "throttled_get_json", side_effect=side_effect):+ out = av.DataLoader().fetch(["BAD", "AAPL"], "2024-01-01", "2024-01-31")+ assert set(out) == {"AAPL"}++ def test_data_with_upsell_note_is_parsed_not_rejected(self, monkeypatch):+ """A payload carrying BOTH a usable series and a note keeps the data."""+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ payload = _payload(("2024-01-02", 1, 2, 0.5, 1.5, 10))+ payload["Information"] = (+ "Thank you for using Alpha Vantage! Premium plans unlock higher limits."+ )+ with patch.object(av, "throttled_get_json", return_value=payload):+ out = av.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")+ assert set(out) == {"AAPL"}+ df = out["AAPL"]+ assert [d.strftime("%Y-%m-%d") for d in df.index] == ["2024-01-02"]+ assert df.loc["2024-01-02", "close"] == 1.5++ def test_empty_series_with_note_skips_symbol(self, monkeypatch):+ """An empty series alongside a note still surfaces as an error skip."""+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ payload = {"Time Series (Daily)": {}, "Note": "call frequency limit"}+ with patch.object(av, "throttled_get_json", return_value=payload):+ assert av.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31") == {}++ def test_empty_series_omits_symbol(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ with patch.object(+ av, "throttled_get_json", return_value={"Time Series (Daily)": {}}+ ):+ assert av.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31") == {}++ def test_malformed_bar_is_skipped(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ payload = {+ "Time Series (Daily)": {+ "2024-01-02": {"1. open": "oops"},+ "2024-01-03": {+ "1. open": "1", "2. high": "1", "3. low": "1",+ "4. close": "1", "5. volume": "1",+ },+ }+ }+ with patch.object(av, "throttled_get_json", return_value=payload):+ df = av.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")["AAPL"]+ assert [d.strftime("%Y-%m-%d") for d in df.index] == ["2024-01-03"]++ def test_invalid_date_range_raises(self, monkeypatch):+ monkeypatch.setenv("ALPHAVANTAGE_API_KEY", "ABC123")+ with pytest.raises(ValueError):+ av.DataLoader().fetch(["AAPL"], "2024-02-01", "2024-01-01")diff --git a/agent/tests/test_block_trades_tool.py b/agent/tests/test_block_trades_tool.pynew file mode 100644index 000000000..fc4fc5424--- /dev/null+++ b/agent/tests/test_block_trades_tool.py@@ -0,0 +1,123 @@+"""Tests for the get_block_trades tool.++All HTTP is mocked at :func:`backtest.loaders.eastmoney_client.get_json` as it is+imported into the tool module, so no test touches a live Eastmoney endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from src.tools import block_trades_tool as bt+++def _sample_payload() -> dict:+ return {+ "result": {+ "data": [+ {+ "TRADE_DATE": "2026-06-18",+ "SECURITY_CODE": "600519",+ "SECURITY_NAME_ABBR": "贵州茅台",+ "CLOSE_PRICE": "1700.00",+ "DEAL_PRICE": "1650.00",+ "PREMIUM_RATIO": "-2.94",+ "DEAL_VOLUME": "10000",+ "DEAL_AMT": "16500000",+ "BUYER_NAME": "机构专用",+ "SELLER_NAME": "中信证券某营业部",+ },+ {+ "TRADE_DATE": "2026-06-17",+ "SECURITY_CODE": "600519",+ "SECURITY_NAME_ABBR": "贵州茅台",+ "CLOSE_PRICE": "1690.00",+ "DEAL_PRICE": "",+ "PREMIUM_RATIO": None,+ "DEAL_VOLUME": "5000",+ "DEAL_AMT": "8400000",+ "BUYER_NAME": "中金某营业部",+ "SELLER_NAME": "机构专用",+ },+ ]+ }+ }+++class TestBlockTradesSuccess:+ """Happy-path envelope shape and field normalization."""++ def test_success_envelope_normalizes_records(self):+ with patch.object(+ bt, "get_json", return_value=_sample_payload()+ ) as mock_get:+ out = bt.BlockTradesTool().execute(code="600519.SH", days=30)++ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["market"] == "china_a"+ assert payload["source"] == "eastmoney"+ data = payload["data"]+ assert data["code"] == "600519.SH"+ assert data["days"] == 30+ assert data["count"] == 2++ first = data["records"][0]+ assert first["trade_date"] == "2026-06-18"+ assert first["deal_price"] == 1650.0+ assert first["premium_ratio"] == -2.94+ assert first["buyer_seat"] == "机构专用"+ assert first["seller_seat"] == "中信证券某营业部"++ # Blank/None cells coerce to None, not a crash.+ second = data["records"][1]+ assert second["deal_price"] is None+ assert second["premium_ratio"] is None++ # The bare 6-digit code (no market prefix) flows into the filter.+ _, kwargs = mock_get.call_args+ assert kwargs["params"]["reportName"] == "RPT_DATA_BLOCKTRADE"+ assert '600519' in kwargs["params"]["filter"]++ def test_empty_window_is_ok_with_zero_records(self):+ with patch.object(bt, "get_json", return_value={"result": {"data": None}}):+ out = bt.BlockTradesTool().execute(code="000001.SZ")+ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["data"]["count"] == 0+ assert payload["data"]["records"] == []+ # Default lookback window applies when days is omitted.+ assert payload["data"]["days"] == bt._DEFAULT_DAYS++ def test_days_clamped_to_max(self):+ with patch.object(bt, "get_json", return_value=_sample_payload()):+ out = bt.BlockTradesTool().execute(code="600519.SH", days=99999)+ assert json.loads(out)["data"]["days"] == bt._MAX_DAYS+++class TestBlockTradesErrors:+ """Error envelopes: bad symbol, missing code, upstream failure."""++ def test_missing_code_returns_error_envelope(self):+ out = bt.BlockTradesTool().execute(code=" ")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "required" in payload["error"]++ def test_non_a_share_symbol_rejected(self):+ # HK/US listings have no A-share block-trade report here.+ out = bt.BlockTradesTool().execute(code="00700.HK")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "A-share" in payload["error"]++ def test_upstream_failure_becomes_error_envelope(self):+ with patch.object(+ bt, "get_json", side_effect=RuntimeError("HTTP 429 banned")+ ):+ out = bt.BlockTradesTool().execute(code="600519.SH", days=10)+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "eastmoney request failed" in payload["error"]+ assert "429" in payload["error"]diff --git a/agent/tests/test_data_routing_sources_subset.py b/agent/tests/test_data_routing_sources_subset.pynew file mode 100644index 000000000..aaef66b86--- /dev/null+++ b/agent/tests/test_data_routing_sources_subset.py@@ -0,0 +1,156 @@+"""Guard test: data-routing SKILL.md can never drift from the loader registry.++The ``data-routing`` skill is the single ROUTER and its Source Overview table+enumerates the registered backtest data sources by name. This test parses those+names straight from the markdown and asserts they form a strict **subset** of+``backtest.loaders.registry.VALID_SOURCES`` — so the doc can never name a source+the code does not actually register (code-first invariant).+"""++from __future__ import annotations++import re+from pathlib import Path++from backtest.loaders.registry import VALID_SOURCES++# SKILL.md lives next to the loader registry under the source tree:+# agent/backtest/loaders/registry.py -> agent/src/skills/data-routing/SKILL.md+_AGENT_ROOT = Path(__file__).resolve().parents[1]+_SKILL_PATH = _AGENT_ROOT / "src" / "skills" / "data-routing" / "SKILL.md"++# A Source Overview row looks like ``| tushare | A-shares ... |``; the source name+# is the first pipe-delimited cell. We collect only rows whose first cell is a bare+# lowercase identifier (the source names), skipping the header / separator rows.+_ROW_RE = re.compile(r"^\|\s*([a-z][a-z0-9_]*)\s*\|")+++def _source_names_in_skill() -> set[str]:+ """Extract the source names listed in the SKILL.md Source Overview table.++ Returns:+ The set of lowercase source identifiers named in the first column of any+ markdown table row in the skill document.++ Raises:+ AssertionError: If the SKILL.md file is missing.+ """+ assert _SKILL_PATH.exists(), f"data-routing SKILL.md not found at {_SKILL_PATH}"+ text = _SKILL_PATH.read_text(encoding="utf-8")+ names: set[str] = set()+ for line in text.splitlines():+ match = _ROW_RE.match(line.strip())+ if match:+ names.add(match.group(1))+ return names+++def test_skill_names_a_nonempty_source_set() -> None:+ """The skill must actually enumerate sources (guards a broken parse / empty doc)."""+ named = _source_names_in_skill()+ # Intersect with VALID_SOURCES so we count only genuine source rows, not stray+ # first-column identifiers from the capability table (e.g. ``tushare`` appears+ # in both, ``get_fund_flow`` does not match the lowercase-id row regex anyway).+ source_rows = named & VALID_SOURCES+ assert source_rows, "data-routing SKILL.md names no registered sources"+++def test_skill_sources_are_subset_of_valid_sources() -> None:+ """Every source named in the skill must be registered in VALID_SOURCES."""+ named = _source_names_in_skill()+ # The capability table's first column holds tool names (``get_market_data`` etc.)+ # which also match the lowercase-id regex; restrict the drift check to rows that+ # look like data-source rows by excluding known tool-name prefixes.+ tool_prefixes = ("get_", "screen_", "search_", "iwencai")+ candidate_sources = {+ name for name in named if not name.startswith(tool_prefixes)+ }+ unknown = candidate_sources - VALID_SOURCES+ assert not unknown, (+ f"data-routing SKILL.md names sources absent from VALID_SOURCES: "+ f"{sorted(unknown)}"+ )+++def test_new_sources_are_documented() -> None:+ """The eight newly registered sources must each appear in the Source Overview."""+ named = _source_names_in_skill()+ new_sources = {+ "eastmoney",+ "sina",+ "stooq",+ "yahoo",+ "finnhub",+ "alphavantage",+ "tiingo",+ "fmp",+ }+ missing = new_sources - named+ assert not missing, f"data-routing SKILL.md missing new source rows: {sorted(missing)}"+++# A Capability table row looks like ``| Stock news | `get_stock_news` | A-share, US, HK | — |``.+# Capture the tool name (col 2, backtick-wrapped) and its market-coverage cell (col 3).+_CAPABILITY_RE = re.compile(+ r"^\|[^|]*\|\s*`([a-z_]+)`\s*\|\s*([^|]+?)\s*\|"+)++# Market tokens we assert on, mapped to the substrings each tool's live ``description``+# uses to name that market. The doc's coverage column must name every market the+# tool's own description claims to cover (doc-vs-code drift guard).+_MARKET_TOKENS = {+ "A-share": ("A-share",),+ "US": ("US",),+ "HK": ("HK", "Hong Kong"),+}+++def _capability_markets_in_skill() -> dict[str, str]:+ """Extract the market-coverage cell for each Capability-table tool.++ Returns:+ Mapping of tool name -> the raw market-coverage cell text (column 3) for+ every row in the SKILL.md Capability table.+ """+ text = _SKILL_PATH.read_text(encoding="utf-8")+ coverage: dict[str, str] = {}+ for line in text.splitlines():+ match = _CAPABILITY_RE.match(line.strip())+ if match:+ coverage[match.group(1)] = match.group(2)+ return coverage+++def test_capability_market_coverage_matches_tool_descriptions() -> None:+ """The Capability table must name every market each tool's description covers.++ Regression guard for B12: ``get_stock_news`` and ``get_financial_statements``+ both cover A-share/US/HK per their live tool ``description`` strings, but the+ router table previously listed only ``A-share, US`` (dropping HK). Derive the+ expected markets from the tools themselves so the doc can never under-state+ coverage again.+ """+ from src.tools.financial_statements_tool import FinancialStatementsTool+ from src.tools.stock_news_tool import StockNewsTool++ coverage = _capability_markets_in_skill()+ tools = {+ "get_stock_news": StockNewsTool.description,+ "get_financial_statements": FinancialStatementsTool.description,+ }+ for tool_name, tool_desc in tools.items():+ assert tool_name in coverage, (+ f"data-routing SKILL.md Capability table missing row for {tool_name}"+ )+ doc_cell = coverage[tool_name]+ for market, desc_aliases in _MARKET_TOKENS.items():+ covered_by_tool = any(alias in tool_desc for alias in desc_aliases)+ if not covered_by_tool:+ continue+ doc_aliases = (market,) + tuple(+ a for a in desc_aliases if a != market+ )+ assert any(alias in doc_cell for alias in doc_aliases), (+ f"{tool_name} description covers {market} but the data-routing "+ f"Capability column lists only {doc_cell!r}"+ )diff --git a/agent/tests/test_dragon_tiger_tool.py b/agent/tests/test_dragon_tiger_tool.pynew file mode 100644index 000000000..d849f7aac--- /dev/null+++ b/agent/tests/test_dragon_tiger_tool.py@@ -0,0 +1,153 @@+"""Tests for the dragon-tiger (龙虎榜) tool.++No request leaves the process: the HTTP boundary+(:func:`backtest.loaders.eastmoney_client.throttled_get_json`) is mocked so the+real client + tool parsing runs offline.+"""++from __future__ import annotations++import json+from typing import Any+from unittest.mock import patch++import pytest++from backtest.loaders import eastmoney_client+from src.tools.dragon_tiger_tool import DragonTigerTool, _bare_code, _compact_date+++def _appearance_payload() -> dict[str, Any]:+ """A datacenter appearance payload with two board rows."""+ return {+ "result": {+ "data": [+ {+ "SECURITY_CODE": "600519",+ "SECURITY_NAME_ABBR": "贵州茅台",+ "CLOSE_PRICE": 1700.0,+ "CHANGE_RATE": 5.2,+ "BILLBOARD_NET_AMT": 1.2e8,+ "BILLBOARD_BUY_AMT": 3.0e8,+ "BILLBOARD_SELL_AMT": 1.8e8,+ "ACCUM_AMOUNT": 9.0e8,+ "EXPLANATION": "日涨幅偏离值达7%",+ },+ {+ "SECURITY_CODE": "000001",+ "SECURITY_NAME_ABBR": "平安银行",+ "CLOSE_PRICE": 12.0,+ "CHANGE_RATE": -4.1,+ "BILLBOARD_NET_AMT": -5.0e7,+ "BILLBOARD_BUY_AMT": 1.0e8,+ "BILLBOARD_SELL_AMT": 1.5e8,+ "ACCUM_AMOUNT": 4.0e8,+ "EXPLANATION": "日跌幅偏离值达7%",+ },+ ]+ }+ }+++def _seat_payload() -> dict[str, Any]:+ """A datacenter seat payload with one buy seat."""+ return {+ "result": {+ "data": [+ {+ "OPERATEDEPT_NAME": "机构专用",+ "SIDE": "BUY",+ "BUY": 2.0e8,+ "SELL": 0.0,+ "NET": 2.0e8,+ "RANK": 1,+ }+ ]+ }+ }+++class TestHelpers:+ def test_compact_date_normalizes(self) -> None:+ assert _compact_date("20240102") == "2024-01-02"+ assert _compact_date(" 2024-01-02 ") == "2024-01-02"++ def test_compact_date_rejects_garbage(self) -> None:+ with pytest.raises(ValueError):+ _compact_date("not-a-date")++ def test_bare_code_strips_suffix(self) -> None:+ assert _bare_code("600519.SH") == "600519"+ assert _bare_code("000001") == "000001"+++class TestToolContract:+ def test_name_and_schema(self) -> None:+ tool = DragonTigerTool()+ assert tool.name == "get_dragon_tiger"+ assert tool.is_readonly is True+ assert tool.parameters["required"] == ["date"]+ assert "code" in tool.parameters["properties"]+++class TestExecuteSuccess:+ def test_full_market_list_no_code(self) -> None:+ tool = DragonTigerTool()+ with patch.object(+ eastmoney_client, "throttled_get_json", return_value=_appearance_payload()+ ) as http:+ out = json.loads(tool.execute(date="2024-01-02"))++ # Only the appearance report is queried when no code is supplied.+ http.assert_called_once()+ _, kwargs = http.call_args+ assert kwargs["host_key"] == "eastmoney"+ assert kwargs["params"]["reportName"] == "RPT_DAILYBILLBOARD_DETAILS"++ assert out["ok"] is True+ assert out["market"] == "a_share"+ assert out["source"] == "eastmoney"+ assert out["data"]["date"] == "2024-01-02"+ assert "seats" not in out["data"]+ assert len(out["data"]["appearances"]) == 2+ assert out["data"]["appearances"][0]["code"] == "600519"+ assert out["data"]["appearances"][0]["net_buy"] == pytest.approx(1.2e8)++ def test_with_code_adds_seats(self) -> None:+ tool = DragonTigerTool()+ payloads = [_appearance_payload(), _seat_payload()]+ with patch.object(+ eastmoney_client, "throttled_get_json", side_effect=payloads+ ) as http:+ out = json.loads(tool.execute(date="2024-01-02", code="600519.SH"))++ assert http.call_count == 2+ assert out["ok"] is True+ assert out["data"]["code"] == "600519"+ assert len(out["data"]["seats"]) == 1+ assert out["data"]["seats"][0]["seat"] == "机构专用"+ assert out["data"]["seats"][0]["net"] == pytest.approx(2.0e8)+++class TestExecuteError:+ def test_missing_date_returns_error_envelope(self) -> None:+ out = json.loads(DragonTigerTool().execute())+ assert out["ok"] is False+ assert "date" in out["error"]++ def test_bad_date_returns_error_envelope(self) -> None:+ out = json.loads(DragonTigerTool().execute(date="nope"))+ assert out["ok"] is False+ assert "invalid date" in out["error"]++ def test_http_failure_returns_error_envelope(self) -> None:+ tool = DragonTigerTool()+ with patch.object(+ eastmoney_client,+ "throttled_get_json",+ side_effect=RuntimeError("eastmoney banned"),+ ):+ out = json.loads(tool.execute(date="2024-01-02"))++ assert out["ok"] is False+ assert "eastmoney banned" in out["error"]diff --git a/agent/tests/test_eastmoney_client.py b/agent/tests/test_eastmoney_client.pynew file mode 100644index 000000000..1d090cf7b--- /dev/null+++ b/agent/tests/test_eastmoney_client.py@@ -0,0 +1,198 @@+"""Tests for eastmoney_client: secid resolution, kline parsing, error paths.++All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported+into the client module), so no test touches a live Eastmoney endpoint.+"""++from unittest.mock import patch++import pytest++from backtest.loaders import eastmoney_client as ec++[email protected](autouse=True)+def _clear_us_cache():+ """Reset the module-level US secid cache so tests stay independent."""+ ec._US_SECID_CACHE.clear()+ yield+ ec._US_SECID_CACHE.clear()+++class TestResolveSecidAShare:+ """A-share / HK secid mapping is pure and needs no network."""++ def test_shanghai_uses_market_1(self):+ assert ec.resolve_secid("600519.SH") == "1.600519"++ def test_shenzhen_uses_market_0(self):+ assert ec.resolve_secid("000001.SZ") == "0.000001"++ def test_beijing_uses_market_0(self):+ assert ec.resolve_secid("830799.BJ") == "0.830799"++ def test_hong_kong_zero_pads_to_five(self):+ assert ec.resolve_secid("00700.HK") == "116.00700"+ assert ec.resolve_secid("700.HK") == "116.00700"++ def test_case_insensitive_suffix(self):+ assert ec.resolve_secid("600519.sh") == "1.600519"++ def test_unrecognized_suffix_returns_none(self):+ assert ec.resolve_secid("BTC-USD") is None+ assert ec.resolve_secid("AAPL") is None+ assert ec.resolve_secid("") is None+ assert ec.resolve_secid(".SH") is None+++class TestResolveSecidUS:+ """US tickers resolve via the search endpoint and cache the result."""++ def test_resolves_and_caches_us_secid(self):+ payload = {+ "QuotationCodeTable": {+ "Data": [+ {"Code": "AAPL", "QuoteID": "105.AAPL"},+ ]+ }+ }+ with patch.object(ec, "throttled_get_json", return_value=payload) as mock_get:+ assert ec.resolve_secid("AAPL.US") == "105.AAPL"+ # Second call is served from cache: no further HTTP.+ assert ec.resolve_secid("AAPL.US") == "105.AAPL"+ assert mock_get.call_count == 1++ def test_handles_jsonp_wrapped_search_body(self):+ body = 'cb({"QuotationCodeTable":{"Data":[{"QuoteID":"106.BRK"}]}})'+ with patch.object(ec, "throttled_get_json", return_value=body):+ assert ec.resolve_secid("BRK.US") == "106.BRK"++ def test_plain_json_body_with_parens_in_values(self):+ """A non-JSONP body whose strings contain parens must parse intact.++ Regression for B8-em-jsonp: the old first-``(`` / last-``)`` slice+ corrupted plain JSON like ``"Apple Inc. (AAPL)"`` and returned ``None``.+ """+ body = (+ '{"QuotationCodeTable":{"Data":'+ '[{"QuoteID":"105.AAPL","Name":"Apple Inc. (AAPL) [NASDAQ]"}]}}'+ )+ with patch.object(ec, "throttled_get_json", return_value=body):+ assert ec.resolve_secid("AAPL.US") == "105.AAPL"++ def test_no_us_candidate_returns_none(self):+ payload = {"QuotationCodeTable": {"Data": [{"QuoteID": "1.600519"}]}}+ with patch.object(ec, "throttled_get_json", return_value=payload):+ assert ec.resolve_secid("NOPE.US") is None++ def test_search_failure_returns_none_without_raising(self):+ with patch.object(+ ec, "throttled_get_json", side_effect=RuntimeError("banned")+ ):+ assert ec.resolve_secid("AAPL.US") is None+++class TestFetchKline:+ """push2his payload parsing into ascending OHLCV dicts."""++ def test_parses_ohlcv_amount_rows(self):+ payload = {+ "data": {+ "code": "600519",+ "klines": [+ "2024-01-02,100.0,110.0,112.0,99.0,1000,123456.0",+ "2024-01-03,110.0,108.0,111.0,107.0,2000,234567.0",+ ],+ }+ }+ with patch.object(ec, "throttled_get_json", return_value=payload) as mock_get:+ rows = ec.fetch_kline("1.600519", klt=ec.KLT_BY_INTERVAL["1D"])++ assert rows == [+ {+ "trade_date": "2024-01-02",+ "open": 100.0,+ "close": 110.0,+ "high": 112.0,+ "low": 99.0,+ "volume": 1000.0,+ "amount": 123456.0,+ },+ {+ "trade_date": "2024-01-03",+ "open": 110.0,+ "close": 108.0,+ "high": 111.0,+ "low": 107.0,+ "volume": 2000.0,+ "amount": 234567.0,+ },+ ]+ # secid + klt flow through to the request params.+ _, kwargs = mock_get.call_args+ assert kwargs["params"]["secid"] == "1.600519"+ assert kwargs["params"]["klt"] == "101"++ def test_empty_data_returns_empty_list(self):+ with patch.object(ec, "throttled_get_json", return_value={"data": None}):+ assert ec.fetch_kline("1.600519", klt=101) == []++ def test_malformed_row_is_skipped_not_fatal(self):+ payload = {+ "data": {+ "klines": [+ "garbage,row",+ "2024-01-03,110.0,108.0,111.0,107.0,2000,234567.0",+ ]+ }+ }+ with patch.object(ec, "throttled_get_json", return_value=payload):+ rows = ec.fetch_kline("1.600519", klt=101)+ assert len(rows) == 1+ assert rows[0]["trade_date"] == "2024-01-03"++ def test_http_error_propagates(self):+ with patch.object(+ ec, "throttled_get_json", side_effect=RuntimeError("HTTP 429")+ ):+ with pytest.raises(RuntimeError, match="429"):+ ec.fetch_kline("1.600519", klt=101)+++class TestStripJsonp:+ """_strip_jsonp must prefer raw JSON and only unwrap real JSONP."""++ def test_plain_json_with_parens_parses_unchanged(self):+ # Parens inside string values must not be stripped.+ body = '{"name":"Berkshire (BRK.A)","ids":["106.BRK","x(y)z"]}'+ assert ec._strip_jsonp(body) == {+ "name": "Berkshire (BRK.A)",+ "ids": ["106.BRK", "x(y)z"],+ }++ def test_plain_json_array_parses_unchanged(self):+ assert ec._strip_jsonp('["a(b)", "c"]') == ["a(b)", "c"]++ def test_real_jsonp_wrapper_is_stripped(self):+ body = 'cb({"QuoteID":"106.BRK","name":"foo (bar)"})'+ assert ec._strip_jsonp(body) == {"QuoteID": "106.BRK", "name": "foo (bar)"}++ def test_dotted_callback_identifier_is_stripped(self):+ body = 'jQuery.cb123(["x", "y"]);'+ assert ec._strip_jsonp(body) == ["x", "y"]++ def test_unparseable_body_returns_none(self):+ assert ec._strip_jsonp("not json at all (oops") is None+++class TestKltMapping:+ """Interval-to-klt table covers the documented periods."""++ def test_intraday_and_daily_codes(self):+ assert ec.KLT_BY_INTERVAL["1m"] == 1+ assert ec.KLT_BY_INTERVAL["5m"] == 5+ assert ec.KLT_BY_INTERVAL["1H"] == 60+ assert ec.KLT_BY_INTERVAL["60m"] == 60+ assert ec.KLT_BY_INTERVAL["1D"] == 101+ assert ec.KLT_BY_INTERVAL["1W"] == 102+ assert ec.KLT_BY_INTERVAL["1M"] == 103diff --git a/agent/tests/test_eastmoney_loader.py b/agent/tests/test_eastmoney_loader.pynew file mode 100644index 000000000..5c61efcc6--- /dev/null+++ b/agent/tests/test_eastmoney_loader.py@@ -0,0 +1,191 @@+"""Tests for the Eastmoney OHLCV loader.++These never touch the network: the cross-market path mocks the shared client+(:mod:`backtest.loaders.eastmoney_client`), and the end-to-end path mocks the+HTTP boundary (``throttled_get_json``) so the real client parsing runs while no+request leaves the process.+"""++from __future__ import annotations++from typing import List+from unittest.mock import patch++import pandas as pd+import pytest++from backtest.loaders import eastmoney_client+from backtest.loaders.eastmoney_loader import DataLoader, _to_compact_date+++def _client_rows() -> List[dict]:+ """Two ascending bars in eastmoney_client.fetch_kline output shape."""+ return [+ {+ "trade_date": "2024-01-02",+ "open": 1700.0,+ "close": 1710.0,+ "high": 1720.0,+ "low": 1690.0,+ "volume": 100000.0,+ "amount": 1.7e8,+ },+ {+ "trade_date": "2024-01-03",+ "open": 1711.0,+ "close": 1705.0,+ "high": 1725.0,+ "low": 1700.0,+ "volume": 120000.0,+ "amount": 2.0e8,+ },+ ]+++# ---------------------------------------------------------------------------+# Loader contract+# ---------------------------------------------------------------------------+++class TestLoaderContract:+ def test_class_attributes(self) -> None:+ loader = DataLoader()+ assert loader.name == "eastmoney"+ assert loader.markets == {"a_share", "hk_equity", "us_equity"}+ assert loader.requires_auth is False++ def test_is_available_true(self) -> None:+ assert DataLoader().is_available() is True+++class TestToCompactDate:+ def test_dashed_date_compacts(self) -> None:+ assert _to_compact_date("2024-01-02") == "20240102"++ def test_invalid_date_raises(self) -> None:+ with pytest.raises(ValueError):+ _to_compact_date("not-a-date")+++# ---------------------------------------------------------------------------+# fetch() — client mocked+# ---------------------------------------------------------------------------+++class TestFetchWithMockedClient:+ def test_a_share_builds_canonical_frame(self) -> None:+ loader = DataLoader()+ with patch.object(+ eastmoney_client, "resolve_secid", return_value="1.600519"+ ) as resolve, patch.object(+ eastmoney_client, "fetch_kline", return_value=_client_rows()+ ) as fetch_kline:+ out = loader.fetch(+ ["600519.SH"], "2024-01-01", "2024-01-31", interval="1D"+ )++ resolve.assert_called_once_with("600519.SH")+ # 1D -> klt 101, compact dates passed through.+ _, kwargs = fetch_kline.call_args+ assert kwargs["klt"] == eastmoney_client.KLT_BY_INTERVAL["1D"]+ assert kwargs["beg"] == "20240101"+ assert kwargs["end"] == "20240131"++ assert set(out) == {"600519.SH"}+ df = out["600519.SH"]+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"+ assert isinstance(df.index, pd.DatetimeIndex)+ assert df.index.is_monotonic_increasing+ assert len(df) == 2+ assert df.iloc[0]["close"] == pytest.approx(1710.0)+ assert all(str(df[c].dtype) == "float64" for c in df.columns)++ def test_unsupported_interval_yields_no_frame(self) -> None:+ loader = DataLoader()+ with patch.object(eastmoney_client, "resolve_secid") as resolve, patch.object(+ eastmoney_client, "fetch_kline"+ ) as fetch_kline:+ out = loader.fetch(["600519.SH"], "2024-01-01", "2024-01-31", interval="3m")++ assert out == {}+ resolve.assert_not_called()+ fetch_kline.assert_not_called()++ def test_unresolvable_symbol_omitted(self) -> None:+ loader = DataLoader()+ with patch.object(+ eastmoney_client, "resolve_secid", return_value=None+ ), patch.object(eastmoney_client, "fetch_kline") as fetch_kline:+ out = loader.fetch(["WAT.XYZ"], "2024-01-01", "2024-01-31")++ assert out == {}+ fetch_kline.assert_not_called()++ def test_one_bad_symbol_does_not_abort_batch(self) -> None:+ loader = DataLoader()++ def _resolve(symbol: str) -> str | None:+ return "1.600519" if symbol == "600519.SH" else "0.000001"++ def _fetch_kline(secid: str, **_kwargs: object) -> List[dict]:+ if secid == "0.000001":+ raise RuntimeError("eastmoney boom")+ return _client_rows()++ with patch.object(eastmoney_client, "resolve_secid", side_effect=_resolve), patch.object(+ eastmoney_client, "fetch_kline", side_effect=_fetch_kline+ ):+ out = loader.fetch(+ ["000001.SZ", "600519.SH"], "2024-01-01", "2024-01-31"+ )++ # The boom symbol is dropped; the healthy one survives.+ assert set(out) == {"600519.SH"}++ def test_empty_klines_omitted(self) -> None:+ loader = DataLoader()+ with patch.object(+ eastmoney_client, "resolve_secid", return_value="116.00700"+ ), patch.object(eastmoney_client, "fetch_kline", return_value=[]):+ out = loader.fetch(["00700.HK"], "2024-01-01", "2024-01-31")++ assert out == {}++ def test_invalid_date_range_raises(self) -> None:+ loader = DataLoader()+ with pytest.raises(ValueError):+ loader.fetch(["600519.SH"], "2024-02-01", "2024-01-01")+++# ---------------------------------------------------------------------------+# End-to-end — only the HTTP boundary mocked, real client parsing runs.+# ---------------------------------------------------------------------------+++class TestFetchEndToEndHttpMocked:+ def test_a_share_through_real_client(self) -> None:+ # push2his kline rows: "date,open,close,high,low,volume,amount".+ payload = {+ "data": {+ "klines": [+ "2024-01-02,1700.00,1710.00,1720.00,1690.00,100000,1.7e8",+ "2024-01-03,1711.00,1705.00,1725.00,1700.00,120000,2.0e8",+ ]+ }+ }+ loader = DataLoader()+ with patch.object(+ eastmoney_client, "throttled_get_json", return_value=payload+ ) as http:+ out = loader.fetch(["600519.SH"], "2024-01-01", "2024-01-31")++ http.assert_called_once()+ _, kwargs = http.call_args+ assert kwargs["params"]["secid"] == "1.600519"+ assert kwargs["host_key"] == "eastmoney"++ df = out["600519.SH"]+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert len(df) == 2+ assert df.iloc[1]["close"] == pytest.approx(1705.0)diff --git a/agent/tests/test_financial_statements_tool.py b/agent/tests/test_financial_statements_tool.pynew file mode 100644index 000000000..c2ef9604e--- /dev/null+++ b/agent/tests/test_financial_statements_tool.py@@ -0,0 +1,262 @@+"""Tests for financial_statements_tool: envelope shape, dispatch, isolation.++All HTTP is mocked at the functions the tool imports — every market routes+through the Eastmoney client's ``get_json`` / ``resolve_secid`` — so no test+touches a live endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from src.tools.financial_statements_tool import FinancialStatementsTool++# Eastmoney datacenter report success body: result.data is a list of rows.+_EM_PAYLOAD = {+ "result": {+ "data": [+ {"REPORT_DATE": "2024-12-31", "TOTAL_REVENUE": 383.0, "NETPROFIT": 96.0},+ ]+ }+}++# Eastmoney A-share report success body: two periods of flat rows.+_EM_A_PAYLOAD = {+ "result": {+ "data": [+ {"REPORT_DATE": "2024-12-31", "TOTAL_ASSETS": 100.0, "NETPROFIT": 12.0},+ {"REPORT_DATE": "2023-12-31", "TOTAL_ASSETS": 90.0, "NETPROFIT": 10.0},+ ]+ }+}+++class TestSuccessEnvelope:+ """A resolvable symbol yields the ok envelope with parsed periods."""++ def test_a_share_uses_eastmoney_and_parses_periods(self):+ with patch(+ "src.tools.financial_statements_tool.resolve_secid",+ return_value="1.600519",+ ), patch(+ "src.tools.financial_statements_tool.get_json",+ return_value=_EM_A_PAYLOAD,+ ) as mock_get:+ text = FinancialStatementsTool().execute(+ code="600519.SH", statement="balance", period="annual"+ )++ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["market"] == "a_share"+ assert payload["source"] == "eastmoney"+ assert payload["statement"] == "balance"+ assert payload["period"] == "annual"+ assert "error" not in payload++ periods = payload["data"]["600519.SH"]["periods"]+ assert len(periods) == 2+ assert periods[0]["REPORT_DATE"] == "2024-12-31"++ # A-share balance sheet hits the A-share F10 report, filtered on the+ # dotted SECUCODE (not the bare SECURITY_CODE used for US/HK).+ sent_params = mock_get.call_args.kwargs["params"]+ assert sent_params["reportName"] == "RPT_F10_FINANCE_GBALANCE"+ assert 'SECUCODE="600519.SH"' in sent_params["filter"]+ assert "SECURITY_CODE" not in sent_params["filter"]++ def test_us_uses_eastmoney_report_api(self):+ with patch(+ "src.tools.financial_statements_tool.resolve_secid",+ return_value="105.AAPL",+ ), patch(+ "src.tools.financial_statements_tool.get_json",+ return_value=_EM_PAYLOAD,+ ) as mock_get:+ text = FinancialStatementsTool().execute(+ code="AAPL.US", statement="income", period="quarter"+ )++ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["market"] == "us"+ assert payload["source"] == "eastmoney"++ periods = payload["data"]["AAPL.US"]["periods"]+ assert periods[0]["REPORT_DATE"] == "2024-12-31"++ # US income report name + bare code filter were passed through.+ sent_params = mock_get.call_args.kwargs["params"]+ assert sent_params["reportName"] == "RPT_USF10_FN_INCOME"+ assert 'SECURITY_CODE="AAPL"' in sent_params["filter"]++ def test_hk_indicators_use_hk_report_name(self):+ with patch(+ "src.tools.financial_statements_tool.resolve_secid",+ return_value="116.00700",+ ), patch(+ "src.tools.financial_statements_tool.get_json",+ return_value=_EM_PAYLOAD,+ ) as mock_get:+ FinancialStatementsTool().execute(+ code="00700.HK", statement="indicators", period="annual"+ )++ assert (+ mock_get.call_args.kwargs["params"]["reportName"]+ == "RPT_HKF10_FN_GMAININDICATOR"+ )+++class TestAllFailedSurfacesError:+ """When the fetch fails for every requested code, the envelope is ok=false.++ The failure detail stays in the per-code result AND is mirrored to a+ top-level ``error`` so a nested fetch failure is never masked by a+ top-level ``ok: true``.+ """++ def test_http_failure_yields_top_level_ok_false(self):+ with patch(+ "src.tools.financial_statements_tool.resolve_secid",+ return_value="1.600519",+ ), patch(+ "src.tools.financial_statements_tool.get_json",+ side_effect=RuntimeError("HTTP 429"),+ ):+ text = FinancialStatementsTool().execute(+ code="600519.SH", statement="income"+ )++ payload = json.loads(text)+ assert payload["ok"] is False+ assert "429" in payload["error"]+ assert "429" in payload["data"]["600519.SH"]["error"]++ def test_unresolvable_us_symbol_yields_ok_false(self):+ with patch(+ "src.tools.financial_statements_tool.resolve_secid",+ return_value=None,+ ):+ text = FinancialStatementsTool().execute(code="ZZZZ.US")++ payload = json.loads(text)+ assert payload["ok"] is False+ assert payload["error"] == "unresolvable symbol"+ assert payload["data"]["ZZZZ.US"]["error"] == "unresolvable symbol"++ def test_empty_a_share_payload_yields_no_periods_but_ok_true(self):+ # An empty-but-well-formed payload is data (zero periods), not a fetch+ # failure, so the envelope stays ok=true.+ with patch(+ "src.tools.financial_statements_tool.resolve_secid",+ return_value="0.000001",+ ), patch(+ "src.tools.financial_statements_tool.get_json",+ return_value={"result": {}},+ ):+ text = FinancialStatementsTool().execute(code="000001.SZ")++ payload = json.loads(text)+ assert payload["ok"] is True+ assert "error" not in payload+ assert payload["data"]["000001.SZ"]["periods"] == []+++class TestPeriodSelection:+ """Period is chosen client-side. Eastmoney's REPORT_TYPE is locale text+ (年报 / 一季报) or a market-specific string (2026/Q1), so no REPORT_TYPE+ filter is sent; 'annual' keeps fiscal-year-end rows, falling back to the+ full series when an issuer has no December year-end (e.g. a US fiscal year).+ """++ _MIXED = {+ "result": {+ "data": [+ {"REPORT_DATE": "2025-03-31 00:00:00", "TOTAL_ASSETS": 1},+ {"REPORT_DATE": "2024-12-31 00:00:00", "TOTAL_ASSETS": 2},+ {"REPORT_DATE": "2024-09-30 00:00:00", "TOTAL_ASSETS": 3},+ {"REPORT_DATE": "2023-12-31 00:00:00", "TOTAL_ASSETS": 4},+ ]+ }+ }+ _NO_YEAR_END = {+ "result": {+ "data": [+ {"REPORT_DATE": "2026-03-28 00:00:00", "TOTAL_ASSETS": 1},+ {"REPORT_DATE": "2025-09-28 00:00:00", "TOTAL_ASSETS": 2},+ ]+ }+ }++ def _run(self, payload, *, period, statement="balance",+ code="600519.SH", secid="1.600519"):+ with patch(+ "src.tools.financial_statements_tool.resolve_secid", return_value=secid,+ ), patch(+ "src.tools.financial_statements_tool.get_json", return_value=payload,+ ) as mock_get:+ text = FinancialStatementsTool().execute(+ code=code, statement=statement, period=period+ )+ return json.loads(text), mock_get++ def test_no_report_type_clause_in_filter(self):+ _, mock_get = self._run(self._MIXED, period="annual")+ assert "REPORT_TYPE" not in mock_get.call_args.kwargs["params"]["filter"]++ def test_annual_keeps_only_fiscal_year_end(self):+ payload, _ = self._run(self._MIXED, period="annual")+ dates = [p["REPORT_DATE"] for p in payload["data"]["600519.SH"]["periods"]]+ assert dates == ["2024-12-31 00:00:00", "2023-12-31 00:00:00"]++ def test_quarter_returns_full_series(self):+ payload, _ = self._run(self._MIXED, period="quarter")+ assert len(payload["data"]["600519.SH"]["periods"]) == 4++ def test_annual_falls_back_when_no_december_year_end(self):+ payload, _ = self._run(+ self._NO_YEAR_END, period="annual", code="AAPL.US", secid="105.AAPL"+ )+ # No -12-31 row -> return the full series rather than drop all data.+ assert len(payload["data"]["AAPL.US"]["periods"]) == 2++ def test_a_share_indicators_use_mainfinadata_report(self):+ _, mock_get = self._run(self._MIXED, period="annual", statement="indicators")+ assert (+ mock_get.call_args.kwargs["params"]["reportName"]+ == "RPT_F10_FINANCE_MAINFINADATA"+ )+++class TestErrorEnvelope:+ """Input validation returns the ok=false envelope before any HTTP."""++ def test_missing_code_rejected(self):+ payload = json.loads(FinancialStatementsTool().execute())+ assert payload["ok"] is False+ assert "code" in payload["error"]++ def test_blank_code_rejected(self):+ payload = json.loads(FinancialStatementsTool().execute(code=" "))+ assert payload["ok"] is False++ def test_unknown_suffix_rejected(self):+ payload = json.loads(FinancialStatementsTool().execute(code="BTC-USDT"))+ assert payload["ok"] is False+ assert "suffix" in payload["error"]++ def test_invalid_statement_rejected(self):+ payload = json.loads(+ FinancialStatementsTool().execute(code="600519.SH", statement="equity")+ )+ assert payload["ok"] is False+ assert "statement" in payload["error"]++ def test_invalid_period_rejected(self):+ payload = json.loads(+ FinancialStatementsTool().execute(code="600519.SH", period="ttm")+ )+ assert payload["ok"] is False+ assert "period" in payload["error"]diff --git a/agent/tests/test_finnhub_loader.py b/agent/tests/test_finnhub_loader.pynew file mode 100644index 000000000..154409c59--- /dev/null+++ b/agent/tests/test_finnhub_loader.py@@ -0,0 +1,213 @@+"""Tests for finnhub_loader: symbol mapping, payload parsing, auth gating, errors.++All HTTP is mocked — no test ever reaches a live Finnhub endpoint. The loader+imports ``throttled_get_json`` from :mod:`backtest.loaders._http` into its own+namespace, so we monkeypatch that name on the ``finnhub_loader`` module.+"""++from __future__ import annotations++from typing import Any, Dict, List++import pandas as pd++from backtest.loaders import finnhub_loader+from backtest.loaders.finnhub_loader import (+ DataLoader,+ _to_epoch_seconds,+ _to_finnhub_symbol,+)+++def _ok_payload() -> Dict[str, Any]:+ """Two ascending daily candles in Finnhub's parallel-array layout."""+ return {+ "s": "ok",+ "t": [1704067200, 1704153600], # 2024-01-01, 2024-01-02 (UTC)+ "o": [10.0, 11.0],+ "h": [12.0, 13.0],+ "l": [9.0, 10.5],+ "c": [11.5, 12.5],+ "v": [1000, 2000],+ }+++# ---------------------------------------------------------------------------+# Symbol mapping+# ---------------------------------------------------------------------------+++class TestToFinnhubSymbol:+ """Vibe-Trading -> Finnhub ticker translation."""++ def test_us_suffix_stripped(self):+ assert _to_finnhub_symbol("AAPL.US") == "AAPL"+ assert _to_finnhub_symbol("aapl.us") == "AAPL"++ def test_bare_ticker_uppercased(self):+ assert _to_finnhub_symbol("msft") == "MSFT"+ assert _to_finnhub_symbol(" tsla ") == "TSLA"+++# ---------------------------------------------------------------------------+# Epoch-second bounds+# ---------------------------------------------------------------------------+++class TestToEpochSeconds:+ """Inclusive date -> UTC epoch-second bound."""++ def test_start_is_midnight(self):+ assert _to_epoch_seconds("2024-01-01", end_of_day=False) == 1704067200++ def test_end_pushes_to_end_of_day(self):+ # 2024-01-01 23:59:59 UTC.+ assert _to_epoch_seconds("2024-01-01", end_of_day=True) == 1704153599+++# ---------------------------------------------------------------------------+# Availability / auth gating+# ---------------------------------------------------------------------------+++class TestAvailability:+ """is_available reflects only the env key; __init__ never raises."""++ def test_construct_without_key_does_not_raise(self, monkeypatch):+ monkeypatch.delenv("FINNHUB_API_KEY", raising=False)+ loader = DataLoader() # must not raise+ assert loader.is_available() is False++ def test_available_when_key_present(self, monkeypatch):+ monkeypatch.setenv("FINNHUB_API_KEY", "tok_123")+ assert DataLoader().is_available() is True++ def test_metadata(self):+ assert DataLoader.name == "finnhub"+ assert DataLoader.markets == {"us_equity"}+ assert DataLoader.requires_auth is True+++# ---------------------------------------------------------------------------+# fetch — happy path, gating, and per-symbol isolation+# ---------------------------------------------------------------------------+++class TestFetch:+ """fetch parses payloads, gates on key, and isolates per-symbol failures."""++ def test_returns_empty_without_key(self, monkeypatch):+ monkeypatch.delenv("FINNHUB_API_KEY", raising=False)+ monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "0")++ def boom(*args, **kwargs): # pragma: no cover - must never be called+ raise AssertionError("no network call without a key")++ monkeypatch.setattr(finnhub_loader, "throttled_get_json", boom)+ assert DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31") == {}++ def test_parses_candles_into_ohlcv_frame(self, monkeypatch):+ monkeypatch.setenv("FINNHUB_API_KEY", "tok_123")+ monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "0")++ captured: Dict[str, Any] = {}++ def fake_get_json(url, **kwargs):+ captured["url"] = url+ captured["params"] = kwargs.get("params")+ return _ok_payload()++ monkeypatch.setattr(finnhub_loader, "throttled_get_json", fake_get_json)++ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")++ assert list(out.keys()) == ["AAPL.US"]+ df = out["AAPL.US"]+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"+ assert isinstance(df.index, pd.DatetimeIndex)+ assert len(df) == 2+ assert df.index.is_monotonic_increasing+ assert df["close"].dtype == float+ assert df["volume"].iloc[0] == 1000.0+ # Symbol is mapped to the bare Finnhub ticker and the token is sent.+ assert captured["url"] == finnhub_loader._CANDLE_URL+ assert captured["params"]["symbol"] == "AAPL"+ assert captured["params"]["resolution"] == "D"+ assert captured["params"]["token"] == "tok_123"++ def test_index_is_nanosecond_resolution(self, monkeypatch):+ """Regression (B9): the trade_date index must be datetime64[ns].++ The epoch ``t`` array used to flow through a ``unit="s"`` conversion+ that left the index at second resolution, diverging from the other+ loaders' nanosecond index and from a plain ``datetime64[ns]`` literal.+ """+ monkeypatch.setenv("FINNHUB_API_KEY", "tok_123")+ monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "0")+ monkeypatch.setattr(+ finnhub_loader, "throttled_get_json", lambda url, **kwargs: _ok_payload()+ )++ df = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")["AAPL.US"]+ assert df.index.dtype == "datetime64[ns]"+ # The actual instants must survive the resolution coercion intact.+ assert list(df.index) == [+ pd.Timestamp("2024-01-01"),+ pd.Timestamp("2024-01-02"),+ ]++ def test_no_data_status_yields_no_entry(self, monkeypatch):+ monkeypatch.setenv("FINNHUB_API_KEY", "tok_123")+ monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "0")+ monkeypatch.setattr(+ finnhub_loader,+ "throttled_get_json",+ lambda url, **kwargs: {"s": "no_data"},+ )+ assert DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31") == {}++ def test_one_failing_symbol_does_not_abort_batch(self, monkeypatch):+ monkeypatch.setenv("FINNHUB_API_KEY", "tok_123")+ monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "0")++ def selective(url, **kwargs):+ if kwargs["params"]["symbol"] == "BAD":+ raise RuntimeError("429 rate limited")+ return _ok_payload()++ monkeypatch.setattr(finnhub_loader, "throttled_get_json", selective)++ out = DataLoader().fetch(["BAD.US", "AAPL.US"], "2024-01-01", "2024-01-31")+ assert list(out.keys()) == ["AAPL.US"]++ def test_skips_bars_with_missing_ohlc(self, monkeypatch):+ monkeypatch.setenv("FINNHUB_API_KEY", "tok_123")+ monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "0")+ payload = _ok_payload()+ payload["c"] = [None, 12.5] # first bar's close is a gap++ monkeypatch.setattr(+ finnhub_loader, "throttled_get_json", lambda url, **kwargs: payload+ )+ df = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")["AAPL.US"]+ assert len(df) == 1+ assert df["close"].iloc[0] == 12.5++ def test_empty_codes_returns_empty(self, monkeypatch):+ monkeypatch.setenv("FINNHUB_API_KEY", "tok_123")+ assert DataLoader().fetch([], "2024-01-01", "2024-01-31") == {}+++class TestRowParsing:+ """_rows_from_payload tolerance for malformed bodies."""++ def test_non_dict_payload(self):+ assert finnhub_loader._rows_from_payload(None) == []+ assert finnhub_loader._rows_from_payload("error") == []++ def test_missing_timestamp_array(self):+ assert finnhub_loader._rows_from_payload({"s": "ok"}) == []++ def test_status_not_ok(self):+ assert finnhub_loader._rows_from_payload({"s": "no_data", "t": [1]}) == []diff --git a/agent/tests/test_fmp_loader.py b/agent/tests/test_fmp_loader.pynew file mode 100644index 000000000..d972cf61e--- /dev/null+++ b/agent/tests/test_fmp_loader.py@@ -0,0 +1,163 @@+"""Tests for fmp_loader: auth gating, symbol mapping, parsing, batch resilience.++All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported+into the loader module), so no test touches a live FMP endpoint.+"""++from unittest.mock import patch++import pandas as pd+import pytest++from backtest.loaders import fmp_loader as fl+from backtest.loaders.fmp_loader import DataLoader, _fmp_symbol, _parse_historical+++def _body(symbol, bars):+ """Build a minimal FMP historical-price-full body."""+ return {"symbol": symbol, "historical": bars}+++_AAPL_BARS = [+ {"date": "2024-01-04", "open": 3.0, "high": 4.0, "low": 2.5, "close": 3.5, "volume": 200.0},+ {"date": "2024-01-03", "open": 1.0, "high": 2.0, "low": 0.5, "close": 1.5, "volume": 100.0},+]+++class TestRegistration:+ """Loader self-registers with the expected metadata."""++ def test_registered_in_registry(self):+ from backtest.loaders import registry++ registry._ensure_registered()+ # Importing the module fired @register regardless of registry bootstrap.+ assert registry.LOADER_REGISTRY.get("fmp") is DataLoader++ def test_metadata(self):+ assert DataLoader.name == "fmp"+ assert DataLoader.markets == {"us_equity"}+ assert DataLoader.requires_auth is True+++class TestIsAvailable:+ """Availability is gated purely on FMP_API_KEY presence."""++ def test_available_with_key(self, monkeypatch):+ monkeypatch.setenv("FMP_API_KEY", "secret")+ assert DataLoader().is_available() is True++ def test_unavailable_without_key(self, monkeypatch):+ monkeypatch.delenv("FMP_API_KEY", raising=False)+ assert DataLoader().is_available() is False++ def test_unavailable_with_blank_key(self, monkeypatch):+ monkeypatch.setenv("FMP_API_KEY", " ")+ assert DataLoader().is_available() is False+++class TestSymbolMapping:+ """US tickers are bare; the .US project suffix is dropped."""++ def test_strips_us_suffix(self):+ assert _fmp_symbol("AAPL.US") == "AAPL"++ def test_bare_ticker_uppercased(self):+ assert _fmp_symbol("msft") == "MSFT"++ def test_passthrough_other(self):+ assert _fmp_symbol("brk-b") == "BRK-B"+++class TestParseHistorical:+ """Pure parsing of the JSON body needs no network."""++ def test_sorts_ascending_and_typed(self):+ df = _parse_historical(_body("AAPL", _AAPL_BARS))+ assert list(df.index) == [pd.Timestamp("2024-01-03"), pd.Timestamp("2024-01-04")]+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"+ assert df["close"].iloc[0] == 1.5+ for col in df.columns:+ assert df[col].dtype == float++ def test_integer_volume_cast_to_float(self):+ # FMP often returns integer volume; the float-OHLCV contract requires+ # every numeric column (incl. volume) to be float, not int64.+ bars = [+ {"date": "2024-01-03", "open": 1, "high": 2, "low": 0, "close": 1, "volume": 100},+ {"date": "2024-01-04", "open": 3, "high": 4, "low": 2, "close": 3, "volume": 200},+ ]+ df = _parse_historical(_body("AAPL", bars))+ assert df["volume"].dtype == float+ for col in df.columns:+ assert df[col].dtype == float++ def test_empty_historical_returns_none(self):+ assert _parse_historical(_body("AAPL", [])) is None++ def test_missing_historical_key_returns_none(self):+ assert _parse_historical({"symbol": "AAPL"}) is None++ def test_non_dict_payload_returns_none(self):+ assert _parse_historical(None) is None+ assert _parse_historical([]) is None++ def test_rows_with_incomplete_ohlc_dropped(self):+ bars = [+ {"date": "2024-01-03", "open": None, "high": 2.0, "low": 0.5, "close": 1.5, "volume": 100.0},+ ]+ assert _parse_historical(_body("AAPL", bars)) is None+++class TestFetch:+ """End-to-end fetch with the HTTP layer mocked."""++ def test_fetch_one_symbol(self, monkeypatch):+ monkeypatch.setenv("FMP_API_KEY", "secret")+ with patch.object(fl, "throttled_get_json", return_value=_body("AAPL", _AAPL_BARS)) as mock_get:+ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")+ assert set(out) == {"AAPL.US"}+ assert len(out["AAPL.US"]) == 2+ # .US suffix stripped in the request URL.+ url = mock_get.call_args[0][0]+ assert url.endswith("/AAPL")+ params = mock_get.call_args.kwargs["params"]+ assert params == {"from": "2024-01-01", "to": "2024-01-31", "apikey": "secret"}++ def test_one_failing_symbol_does_not_abort_batch(self, monkeypatch):+ monkeypatch.setenv("FMP_API_KEY", "secret")++ def _side(url, **kwargs):+ if url.endswith("/BAD"):+ raise RuntimeError("boom")+ return _body("AAPL", _AAPL_BARS)++ with patch.object(fl, "throttled_get_json", side_effect=_side):+ out = DataLoader().fetch(["BAD.US", "AAPL.US"], "2024-01-01", "2024-01-31")+ assert set(out) == {"AAPL.US"}++ def test_empty_result_symbol_omitted(self, monkeypatch):+ monkeypatch.setenv("FMP_API_KEY", "secret")+ with patch.object(fl, "throttled_get_json", return_value=_body("ZZZZ", [])):+ out = DataLoader().fetch(["ZZZZ.US"], "2024-01-01", "2024-01-31")+ assert out == {}++ def test_non_daily_interval_returns_empty(self, monkeypatch):+ monkeypatch.setenv("FMP_API_KEY", "secret")+ with patch.object(fl, "throttled_get_json") as mock_get:+ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31", interval="5m")+ assert out == {}+ mock_get.assert_not_called()++ def test_invalid_date_range_raises(self, monkeypatch):+ monkeypatch.setenv("FMP_API_KEY", "secret")+ with pytest.raises(ValueError):+ DataLoader().fetch(["AAPL.US"], "2024-02-01", "2024-01-01")++ def test_missing_key_at_fetch_time_skips_symbol(self, monkeypatch):+ monkeypatch.delenv("FMP_API_KEY", raising=False)+ with patch.object(fl, "throttled_get_json") as mock_get:+ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")+ assert out == {}+ mock_get.assert_not_called()diff --git a/agent/tests/test_fred_macro_tool.py b/agent/tests/test_fred_macro_tool.pynew file mode 100644index 000000000..af13f57bc--- /dev/null+++ b/agent/tests/test_fred_macro_tool.py@@ -0,0 +1,181 @@+"""Tests for fred_macro_tool: availability gating, success + error envelopes.++All HTTP is mocked — no test ever reaches a live FRED endpoint. The tool imports+``throttled_get_json`` from :mod:`backtest.loaders._http` into its own namespace,+so we monkeypatch that name on the ``fred_macro_tool`` module.+"""++from __future__ import annotations++import json+from typing import Any, Dict++from src.tools import fred_macro_tool+from src.tools.fred_macro_tool import FredMacroTool+++def _ok_payload() -> Dict[str, Any]:+ """Three ascending observations with one FRED missing-value gap (".")."""+ return {+ "observations": [+ {"date": "2024-01-01", "value": "100.0"},+ {"date": "2024-02-01", "value": "."},+ {"date": "2024-03-01", "value": "101.5"},+ ]+ }+++# ---------------------------------------------------------------------------+# Availability / auth gating+# ---------------------------------------------------------------------------+++class TestAvailability:+ """check_available reflects only the env key and never raises."""++ def test_unavailable_without_key(self, monkeypatch):+ monkeypatch.delenv("FRED_API_KEY", raising=False)+ assert FredMacroTool.check_available() is False++ def test_available_with_key(self, monkeypatch):+ monkeypatch.setenv("FRED_API_KEY", "tok_123")+ assert FredMacroTool.check_available() is True++ def test_metadata(self):+ assert FredMacroTool.name == "get_macro_series"+ assert FredMacroTool().is_readonly is True+++# ---------------------------------------------------------------------------+# execute — success envelope+# ---------------------------------------------------------------------------+++class TestExecuteSuccess:+ """execute parses observations into the success envelope."""++ def test_success_envelope(self, monkeypatch):+ monkeypatch.setenv("FRED_API_KEY", "tok_123")+ captured: Dict[str, Any] = {}++ def fake_get_json(url, **kwargs):+ captured["url"] = url+ captured["params"] = kwargs.get("params")+ captured["host_key"] = kwargs.get("host_key")+ return _ok_payload()++ monkeypatch.setattr(fred_macro_tool, "throttled_get_json", fake_get_json)++ raw = FredMacroTool().execute(+ series_id="cpiaucsl",+ start_date="2024-01-01",+ end_date="2024-03-31",+ )+ out = json.loads(raw)++ assert out["ok"] is True+ assert out["market"] == "US"+ assert out["source"] == "fred"+ data = out["data"]+ assert data["series_id"] == "CPIAUCSL" # upper-cased+ assert data["count"] == 3+ obs = data["observations"]+ assert obs[0] == {"date": "2024-01-01", "value": 100.0}+ assert obs[1] == {"date": "2024-02-01", "value": None} # "." gap -> None+ assert obs[2] == {"date": "2024-03-01", "value": 101.5}++ # Request was routed through the throttled fred host bucket with auth ++ # date window params.+ assert captured["url"] == fred_macro_tool._OBSERVATIONS_URL+ assert captured["host_key"] == "fred"+ assert captured["params"]["series_id"] == "CPIAUCSL"+ assert captured["params"]["api_key"] == "tok_123"+ assert captured["params"]["file_type"] == "json"+ assert captured["params"]["observation_start"] == "2024-01-01"+ assert captured["params"]["observation_end"] == "2024-03-31"++ def test_limit_keeps_most_recent(self, monkeypatch):+ monkeypatch.setenv("FRED_API_KEY", "tok_123")+ monkeypatch.setattr(+ fred_macro_tool, "throttled_get_json", lambda url, **kw: _ok_payload()+ )++ out = json.loads(FredMacroTool().execute(series_id="UNRATE", limit=1))+ assert out["data"]["count"] == 1+ assert out["data"]["observations"][0]["date"] == "2024-03-01"++ def test_omitted_dates_send_no_window_params(self, monkeypatch):+ monkeypatch.setenv("FRED_API_KEY", "tok_123")+ captured: Dict[str, Any] = {}++ def fake_get_json(url, **kwargs):+ captured["params"] = kwargs.get("params")+ return _ok_payload()++ monkeypatch.setattr(fred_macro_tool, "throttled_get_json", fake_get_json)+ FredMacroTool().execute(series_id="DGS10")+ assert "observation_start" not in captured["params"]+ assert "observation_end" not in captured["params"]+++# ---------------------------------------------------------------------------+# execute — error envelopes+# ---------------------------------------------------------------------------+++class TestExecuteErrors:+ """execute returns a failure envelope and never raises."""++ def test_missing_key(self, monkeypatch):+ monkeypatch.delenv("FRED_API_KEY", raising=False)+ out = json.loads(FredMacroTool().execute(series_id="CPIAUCSL"))+ assert out["ok"] is False+ assert "FRED_API_KEY" in out["error"]++ def test_missing_series_id(self, monkeypatch):+ monkeypatch.setenv("FRED_API_KEY", "tok_123")+ out = json.loads(FredMacroTool().execute(series_id=" "))+ assert out["ok"] is False+ assert "series_id" in out["error"]++ def test_request_failure_becomes_error_envelope(self, monkeypatch):+ monkeypatch.setenv("FRED_API_KEY", "tok_123")++ def boom(url, **kwargs):+ raise RuntimeError("429 rate limited")++ monkeypatch.setattr(fred_macro_tool, "throttled_get_json", boom)+ out = json.loads(FredMacroTool().execute(series_id="CPIAUCSL"))+ assert out["ok"] is False+ assert "fred observations request failed" in out["error"]+ assert "429" in out["error"]++ def test_empty_observations_becomes_error_envelope(self, monkeypatch):+ monkeypatch.setenv("FRED_API_KEY", "tok_123")+ monkeypatch.setattr(+ fred_macro_tool, "throttled_get_json", lambda url, **kw: {"observations": []}+ )+ out = json.loads(FredMacroTool().execute(series_id="CPIAUCSL"))+ assert out["ok"] is False+ assert "no observations found" in out["error"]+++# ---------------------------------------------------------------------------+# Pure-helper parsing tolerance+# ---------------------------------------------------------------------------+++class TestParsing:+ """_parse_observations tolerates malformed bodies."""++ def test_non_dict_payload(self):+ assert fred_macro_tool._parse_observations(None) == []+ assert fred_macro_tool._parse_observations("error") == []++ def test_missing_observations_array(self):+ assert fred_macro_tool._parse_observations({"foo": 1}) == []++ def test_row_without_date_dropped(self):+ payload = {"observations": [{"value": "1.0"}, {"date": "2024-01-01", "value": "2.0"}]}+ rows = fred_macro_tool._parse_observations(payload)+ assert rows == [{"date": "2024-01-01", "value": 2.0}]diff --git a/agent/tests/test_fund_flow_tool.py b/agent/tests/test_fund_flow_tool.pynew file mode 100644index 000000000..bc7f14844--- /dev/null+++ b/agent/tests/test_fund_flow_tool.py@@ -0,0 +1,179 @@+"""Tests for fund_flow_tool: envelope shape, parsing, per-symbol isolation.++All HTTP is mocked at the Eastmoney client functions the tool imports+(:func:`get_json` / :func:`resolve_secid`), so no test touches a live endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from src.tools.fund_flow_tool import FundFlowTool++_DAILY_PAYLOAD = {+ "data": {+ "code": "600519",+ "klines": [+ "2024-01-02,100.0,-10.0,5.0,60.0,40.0,0,0,0,0,0,0,0,0,0",+ "2024-01-03,-50.0,20.0,-5.0,-30.0,-20.0,0,0,0,0,0,0,0,0,0",+ ],+ }+}+++class TestSuccessEnvelope:+ """A resolvable symbol yields the ok envelope with labelled buckets."""++ def test_daily_flow_parses_into_buckets(self):+ with patch(+ "src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"+ ), patch(+ "src.tools.fund_flow_tool.get_json", return_value=_DAILY_PAYLOAD+ ):+ text = FundFlowTool().execute(codes=["600519.SH"], period="daily", days=30)++ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["market"] == "stock"+ assert payload["source"] == "eastmoney"+ assert payload["period"] == "daily"+ assert payload["buckets"] == ["main", "small", "medium", "large", "super_large"]++ rows = payload["data"]["600519.SH"]["rows"]+ assert len(rows) == 2+ assert rows[0] == {+ "timestamp": "2024-01-02",+ "main": 100.0,+ "small": -10.0,+ "medium": 5.0,+ "large": 60.0,+ "super_large": 40.0,+ }++ def test_days_cap_keeps_most_recent_rows(self):+ with patch(+ "src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"+ ), patch(+ "src.tools.fund_flow_tool.get_json", return_value=_DAILY_PAYLOAD+ ):+ text = FundFlowTool().execute(codes=["600519.SH"], period="daily", days=1)++ rows = json.loads(text)["data"]["600519.SH"]["rows"]+ assert len(rows) == 1+ assert rows[0]["timestamp"] == "2024-01-03"++ def test_minute_period_uses_minute_url(self):+ minute_payload = {"data": {"klines": ["2024-01-02 09:31,1.0,2.0,3.0,4.0,5.0"]}}+ with patch(+ "src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"+ ), patch(+ "src.tools.fund_flow_tool.get_json", return_value=minute_payload+ ) as mock_get:+ text = FundFlowTool().execute(codes=["600519.SH"], period="min")++ url = mock_get.call_args[0][0]+ assert "fflow/kline/get" in url+ rows = json.loads(text)["data"]["600519.SH"]["rows"]+ assert rows[0]["timestamp"] == "2024-01-02 09:31"+ assert rows[0]["main"] == 1.0+++class TestPerSymbolIsolation:+ """A single failing/unresolvable symbol never aborts the batch."""++ def test_unresolvable_symbol_is_reported_not_fatal(self):+ def fake_resolve(symbol):+ return None if symbol == "BAD" else "1.600519"++ with patch(+ "src.tools.fund_flow_tool.resolve_secid", side_effect=fake_resolve+ ), patch(+ "src.tools.fund_flow_tool.get_json", return_value=_DAILY_PAYLOAD+ ):+ text = FundFlowTool().execute(codes=["BAD", "600519.SH"])++ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["data"]["BAD"]["error"] == "unresolvable symbol"+ assert len(payload["data"]["600519.SH"]["rows"]) == 2++ def test_http_failure_on_one_symbol_is_captured(self):+ with patch(+ "src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"+ ), patch(+ "src.tools.fund_flow_tool.get_json", side_effect=RuntimeError("HTTP 429")+ ):+ text = FundFlowTool().execute(codes=["600519.SH"])++ payload = json.loads(text)+ assert payload["ok"] is True+ assert "429" in payload["data"]["600519.SH"]["error"]++ def test_malformed_row_skipped(self):+ bad = {"data": {"klines": ["garbage", "2024-01-03,-50.0,20.0,-5.0,-30.0,-20.0"]}}+ with patch(+ "src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"+ ), patch("src.tools.fund_flow_tool.get_json", return_value=bad):+ text = FundFlowTool().execute(codes=["600519.SH"])++ rows = json.loads(text)["data"]["600519.SH"]["rows"]+ assert len(rows) == 1+++class TestErrorEnvelope:+ """Input validation returns the ok=false envelope before any HTTP."""++ def test_empty_codes_rejected(self):+ payload = json.loads(FundFlowTool().execute(codes=[]))+ assert payload["ok"] is False+ assert "codes" in payload["error"]++ def test_missing_codes_rejected(self):+ payload = json.loads(FundFlowTool().execute())+ assert payload["ok"] is False++ def test_non_string_code_rejected(self):+ payload = json.loads(FundFlowTool().execute(codes=[123]))+ assert payload["ok"] is False++ def test_invalid_period_rejected(self):+ payload = json.loads(+ FundFlowTool().execute(codes=["600519.SH"], period="hourly")+ )+ assert payload["ok"] is False+ assert "period" in payload["error"]++ def test_non_positive_days_rejected(self):+ payload = json.loads(+ FundFlowTool().execute(codes=["600519.SH"], days=0)+ )+ assert payload["ok"] is False+ assert "days" in payload["error"]++ def test_bool_days_rejected(self):+ payload = json.loads(+ FundFlowTool().execute(codes=["600519.SH"], days=True)+ )+ assert payload["ok"] is False+++class TestRoutingDescription:+ """Description must scope to PER-STOCK flow so vague prompts don't misroute.++ Regression for B10-routing-desc: get_fund_flow and get_northbound_flow both+ used to open on a generic 'net capital flow' phrase, so a vague prompt could+ route to either. The fund-flow description must lead with the per-stock,+ order-level scope and point market-wide intent at get_northbound_flow.+ """++ def test_description_leads_with_per_stock_order_level(self):+ desc = FundFlowTool().description+ # Leads with the per-stock, order-level scope, not a generic phrase.+ assert desc.startswith("PER-STOCK order-level net inflow")+ assert "market-wide" not in desc.lower().split("not market-wide")[0]+ # Disambiguates against the market-wide tool.+ assert "get_northbound_flow" in desc++ def test_description_keeps_a_concrete_example(self):+ assert '{"codes": ["600519.SH"' in FundFlowTool().descriptiondiff --git a/agent/tests/test_iwencai_tool.py b/agent/tests/test_iwencai_tool.pynew file mode 100644index 000000000..5708b2c49--- /dev/null+++ b/agent/tests/test_iwencai_tool.py@@ -0,0 +1,138 @@+"""Tests for the iWenCai (问财) natural-language A-share search tool.++No request leaves the process: the HTTP boundary+(:func:`backtest.loaders._http.throttled_get_json`, imported into the tool+module) is mocked so the real auth/parsing/envelope path runs offline.+"""++from __future__ import annotations++import json+from typing import Any+from unittest.mock import patch++import pytest++from src.tools import iwencai_tool+from src.tools.iwencai_tool import IWenCaiSearchTool, _coerce_limit, _extract_rows++_KEY_ENV = "VIBE_TRADING_IWENCAI_KEY"+++def _robot_payload() -> dict[str, Any]:+ """An iWenCai robot-data response nesting two security rows."""+ return {+ "data": {+ "answer": [+ {+ "txt": [+ {+ "content": {+ "components": [+ {+ "data": {+ "datas": [+ {"code": "600036", "name": "招商银行", "pe": 6.1},+ {"code": "601398", "name": "工商银行", "pe": 5.2},+ ]+ }+ }+ ]+ }+ }+ ]+ }+ ]+ }+ }+++class TestHelpers:+ def test_coerce_limit_defaults_and_clamps(self) -> None:+ assert _coerce_limit(None) == iwencai_tool._DEFAULT_LIMIT+ assert _coerce_limit("nope") == iwencai_tool._DEFAULT_LIMIT+ assert _coerce_limit(0) == iwencai_tool._DEFAULT_LIMIT+ assert _coerce_limit(10) == 10+ assert _coerce_limit(9999) == iwencai_tool._MAX_LIMIT++ def test_extract_rows_handles_missing_branches(self) -> None:+ assert _extract_rows(None) == []+ assert _extract_rows({}) == []+ assert _extract_rows({"data": {"answer": []}}) == []+ assert len(_extract_rows(_robot_payload())) == 2+++class TestAvailability:+ def test_excluded_when_key_absent(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv(_KEY_ENV, raising=False)+ assert IWenCaiSearchTool.check_available() is False++ def test_available_when_key_present(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(_KEY_ENV, "secret-token")+ assert IWenCaiSearchTool.check_available() is True+++class TestToolContract:+ def test_name_and_schema(self) -> None:+ tool = IWenCaiSearchTool()+ assert tool.name == "iwencai_search"+ assert tool.is_readonly is True+ assert tool.parameters["required"] == ["query"]+ assert "limit" in tool.parameters["properties"]+++class TestExecuteSuccess:+ def test_returns_rows_with_auth_header(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(_KEY_ENV, "secret-token")+ tool = IWenCaiSearchTool()+ with patch.object(+ iwencai_tool, "throttled_get_json", return_value=_robot_payload()+ ) as http:+ out = json.loads(tool.execute(query="市盈率低于15的银行股", limit=10))++ http.assert_called_once()+ _, kwargs = http.call_args+ assert kwargs["host_key"] == "iwencai"+ assert kwargs["headers"]["Authorization"] == "Bearer secret-token"+ assert kwargs["params"]["question"] == "市盈率低于15的银行股"+ assert kwargs["params"]["perpage"] == "10"++ assert out["ok"] is True+ assert out["market"] == "a_share"+ assert out["source"] == "iwencai"+ assert out["data"]["query"] == "市盈率低于15的银行股"+ assert out["data"]["count"] == 2+ assert out["data"]["results"][0]["code"] == "600036"++ def test_limit_clamps_result_count(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(_KEY_ENV, "secret-token")+ tool = IWenCaiSearchTool()+ with patch.object(iwencai_tool, "throttled_get_json", return_value=_robot_payload()):+ out = json.loads(tool.execute(query="银行股", limit=1))+ assert out["data"]["count"] == 1+++class TestExecuteError:+ def test_missing_key_returns_error_envelope(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv(_KEY_ENV, raising=False)+ out = json.loads(IWenCaiSearchTool().execute(query="银行股"))+ assert out["ok"] is False+ assert _KEY_ENV in out["error"]++ def test_missing_query_returns_error_envelope(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(_KEY_ENV, "secret-token")+ out = json.loads(IWenCaiSearchTool().execute())+ assert out["ok"] is False+ assert "query" in out["error"]++ def test_http_failure_returns_error_envelope(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(_KEY_ENV, "secret-token")+ tool = IWenCaiSearchTool()+ with patch.object(+ iwencai_tool,+ "throttled_get_json",+ side_effect=RuntimeError("iwencai banned"),+ ):+ out = json.loads(tool.execute(query="银行股"))+ assert out["ok"] is False+ assert "iwencai banned" in out["error"]diff --git a/agent/tests/test_lockup_expiry_tool.py b/agent/tests/test_lockup_expiry_tool.pynew file mode 100644index 000000000..992b1357e--- /dev/null+++ b/agent/tests/test_lockup_expiry_tool.py@@ -0,0 +1,165 @@+"""Tests for the Eastmoney-backed lockup-expiry (限售解禁) tool.++No request ever leaves the process: the success/shape paths mock the shared+client (:mod:`backtest.loaders.eastmoney_client`), and the end-to-end path mocks+the frozen HTTP boundary (``throttled_get_json``) so the real client routing and+this tool's parsing both run while nothing hits the network.+"""++from __future__ import annotations++import json+from datetime import date+from unittest.mock import patch++from backtest.loaders import eastmoney_client+from src.tools import lockup_expiry_tool+from src.tools.lockup_expiry_tool import LockupExpiryTool+++def _payload(rows: list[dict]) -> dict:+ """Wrap report rows in the datacenter ``result.data`` envelope."""+ return {"result": {"data": rows, "count": len(rows)}}+++def _row(code: str, free_date: str) -> dict:+ """One RPT_LIFT_STOCK-shaped record."""+ return {+ "SECURITY_CODE": code,+ "SECURITY_NAME_ABBR": "贵州茅台",+ "FREE_DATE": f"{free_date} 00:00:00",+ "FREE_SHARES_TYPE": "首发原股东限售股份",+ "FREE_SHARES": 1000000.0,+ "ABLE_FREE_SHARES": 900000.0,+ "LIFT_MARKET_CAP": 1.7e9,+ "FREE_RATIO": 0.8,+ "TOTAL_RATIO": 1.2,+ }+++# ---------------------------------------------------------------------------+# Tool contract+# ---------------------------------------------------------------------------+++class TestToolContract:+ def test_class_attributes(self) -> None:+ tool = LockupExpiryTool()+ assert tool.name == "get_lockup_expiry"+ assert tool.is_readonly is True+ assert tool.parameters["required"] == []+ assert "code" in tool.parameters["properties"]+ assert "horizon_days" in tool.parameters["properties"]++ def test_description_self_contained(self) -> None:+ desc = LockupExpiryTool().description+ assert "解禁" in desc+ assert "Example" in desc+++# ---------------------------------------------------------------------------+# Success — client.get_json mocked+# ---------------------------------------------------------------------------+++class TestSuccess:+ def test_single_code_returns_history(self) -> None:+ rows = [_row("600519", "2024-06-01"), _row("600519", "2023-06-01")]+ with patch.object(+ eastmoney_client, "get_json", return_value=_payload(rows)+ ) as get_json:+ out = json.loads(LockupExpiryTool().execute(code="600519.SH"))++ # Single-code path keys on the bare numeric code, newest-first.+ _, kwargs = get_json.call_args+ params = kwargs["params"]+ assert params["reportName"] == "RPT_LIFT_STOCK"+ assert 'SECURITY_CODE="600519"' in params["filter"]+ assert params["sortTypes"] == "-1"++ assert out["ok"] is True+ assert out["market"] == "a_share"+ assert out["source"] == "eastmoney"+ assert out["data"]["scope"] == "single_code"+ assert out["data"]["code"] == "600519"+ assert out["data"]["count"] == 2+ first = out["data"]["records"][0]+ assert first["free_date"] == "2024-06-01"+ assert first["lift_market_cap"] == 1.7e9++ def test_market_calendar_uses_horizon_window(self) -> None:+ rows = [_row("000001", "2026-07-01")]+ with patch.object(+ lockup_expiry_tool, "_today", return_value=date(2026, 6, 19)+ ), patch.object(+ eastmoney_client, "get_json", return_value=_payload(rows)+ ) as get_json:+ out = json.loads(LockupExpiryTool().execute(horizon_days=30))++ _, kwargs = get_json.call_args+ params = kwargs["params"]+ # Soonest-first calendar bounded by [today, today+30d].+ assert params["sortTypes"] == "1"+ assert "FREE_DATE>='2026-06-19'" in params["filter"]+ assert "FREE_DATE<='2026-07-19'" in params["filter"]++ assert out["data"]["scope"] == "market_calendar"+ assert out["data"]["horizon_days"] == 30+ assert out["data"]["as_of"] == "2026-06-19"++ def test_horizon_clamped_to_max(self) -> None:+ with patch.object(+ eastmoney_client, "get_json", return_value=_payload([])+ ):+ out = json.loads(LockupExpiryTool().execute(horizon_days=99999))+ assert out["data"]["horizon_days"] == 365++ def test_payload_capped(self) -> None:+ rows = [_row(f"6005{i:02d}", "2026-07-01") for i in range(250)]+ with patch.object(+ eastmoney_client, "get_json", return_value=_payload(rows)+ ):+ out = json.loads(LockupExpiryTool().execute(horizon_days=90))+ assert out["data"]["count"] == 200+ assert out["data"]["truncated"] is True+++# ---------------------------------------------------------------------------+# Error envelopes+# ---------------------------------------------------------------------------+++class TestErrors:+ def test_bad_code_returns_error_envelope(self) -> None:+ out = json.loads(LockupExpiryTool().execute(code="AAPL.US"))+ assert out["ok"] is False+ assert "unrecognized" in out["error"]++ def test_upstream_failure_returns_error_envelope(self) -> None:+ with patch.object(+ eastmoney_client, "get_json", side_effect=RuntimeError("eastmoney boom")+ ):+ out = json.loads(LockupExpiryTool().execute(code="600519"))+ assert out["ok"] is False+ assert "eastmoney boom" in out["error"]+++# ---------------------------------------------------------------------------+# End-to-end — only the frozen HTTP boundary mocked, real client routing runs.+# ---------------------------------------------------------------------------+++class TestEndToEndHttpMocked:+ def test_single_code_through_real_client(self) -> None:+ rows = [_row("600519", "2024-06-01")]+ with patch.object(+ eastmoney_client, "throttled_get_json", return_value=_payload(rows)+ ) as http:+ out = json.loads(LockupExpiryTool().execute(code="600519"))++ http.assert_called_once()+ _, kwargs = http.call_args+ assert kwargs["host_key"] == "eastmoney"+ assert kwargs["params"]["reportName"] == "RPT_LIFT_STOCK"+ assert out["ok"] is True+ assert out["data"]["records"][0]["name"] == "贵州茅台"diff --git a/agent/tests/test_margin_trading_tool.py b/agent/tests/test_margin_trading_tool.pynew file mode 100644index 000000000..1d329d63b--- /dev/null+++ b/agent/tests/test_margin_trading_tool.py@@ -0,0 +1,122 @@+"""Tests for the margin-trading (融资融券) tool.++No request leaves the process: the success path patches the shared Eastmoney+client (:func:`backtest.loaders.eastmoney_client.get_json`) so the tool's own+parsing/envelope logic runs against a canned datacenter payload, and the error+path makes that boundary raise.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from backtest.loaders import eastmoney_client+from src.tools.margin_trading_tool import MarginTradingTool+++def _datacenter_payload() -> dict:+ """Two daily rows in the Eastmoney RZRQ datacenter response shape."""+ return {+ "result": {+ "data": [+ {+ "DATE": "2024-01-03 00:00:00",+ "SCODE": "600519",+ "RZYE": 1.23e9,+ "RZMRE": 4.5e7,+ "RZCHE": 3.0e7,+ "RQYE": 2.0e6,+ "RQYL": 1500.0,+ "RZRQYE": 1.232e9,+ },+ {+ "DATE": "2024-01-02 00:00:00",+ "SCODE": "600519",+ "RZYE": 1.20e9,+ "RZMRE": 4.0e7,+ "RZCHE": 2.5e7,+ "RQYE": "",+ "RQYL": None,+ "RZRQYE": 1.202e9,+ },+ ]+ }+ }+++class TestSuccess:+ def test_a_share_returns_envelope(self) -> None:+ tool = MarginTradingTool()+ with patch.object(+ eastmoney_client, "get_json", return_value=_datacenter_payload()+ ) as get_json:+ out = tool.execute(code="600519.SH", days=30)++ # Query went through the throttled client with the bare code filter.+ get_json.assert_called_once()+ _, kwargs = get_json.call_args+ assert kwargs["params"]["filter"] == '(SCODE="600519")'+ assert kwargs["params"]["pageSize"] == "30"++ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["market"] == "a_share"+ assert payload["source"] == "eastmoney"+ assert payload["data"]["code"] == "600519"++ rows = payload["data"]["rows"]+ assert len(rows) == 2+ assert rows[0]["trade_date"] == "2024-01-03"+ assert rows[0]["financing_balance"] == 1.23e9+ assert rows[0]["margin_total_balance"] == 1.232e9+ # Missing/empty cells normalize to None, not a crash.+ assert rows[1]["short_balance"] is None+ assert rows[1]["short_volume"] is None++ def test_bare_code_and_days_clamped(self) -> None:+ tool = MarginTradingTool()+ with patch.object(+ eastmoney_client, "get_json", return_value=_datacenter_payload()+ ) as get_json:+ out = tool.execute(code="000001", days=99999)++ _, kwargs = get_json.call_args+ # Days clamped to the hard cap (250).+ assert kwargs["params"]["pageSize"] == "250"+ assert kwargs["params"]["filter"] == '(SCODE="000001")'+ assert json.loads(out)["ok"] is True+++class TestErrors:+ def test_unsupported_symbol_rejected_without_request(self) -> None:+ tool = MarginTradingTool()+ with patch.object(eastmoney_client, "get_json") as get_json:+ out = tool.execute(code="AAPL.US")++ get_json.assert_not_called()+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "A-shares only" in payload["error"]++ def test_provider_failure_becomes_error_envelope(self) -> None:+ tool = MarginTradingTool()+ with patch.object(+ eastmoney_client, "get_json", side_effect=RuntimeError("eastmoney boom")+ ):+ out = tool.execute(code="600519.SH", days=5)++ payload = json.loads(out)+ assert payload["ok"] is False+ assert "eastmoney boom" in payload["error"]++ def test_empty_data_becomes_error_envelope(self) -> None:+ tool = MarginTradingTool()+ with patch.object(+ eastmoney_client, "get_json", return_value={"result": {"data": []}}+ ):+ out = tool.execute(code="600519.SH")++ payload = json.loads(out)+ assert payload["ok"] is False+ assert "No margin-trading data" in payload["error"]diff --git a/agent/tests/test_market_screener_tool.py b/agent/tests/test_market_screener_tool.pynew file mode 100644index 000000000..21974e40b--- /dev/null+++ b/agent/tests/test_market_screener_tool.py@@ -0,0 +1,164 @@+"""Tests for market_screener_tool: envelope shape, sorting params, validation.++All HTTP is mocked at the Eastmoney client function the tool imports+(:func:`get_json`), so no test touches a live endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from src.tools.market_screener_tool import MarketScreenerTool++_CLIST_PAYLOAD = {+ "data": {+ "total": 2,+ "diff": [+ {+ "f12": "600519",+ "f14": "贵州茅台",+ "f2": 1688.0,+ "f3": 9.98,+ "f4": 153.0,+ "f5": 1234567.0,+ "f6": 2.08e9,+ "f8": 1.23,+ },+ {+ "f12": "000001",+ "f14": "平安银行",+ "f2": 11.5,+ "f3": 5.01,+ "f4": 0.55,+ "f5": 9876543.0,+ "f6": 1.1e8,+ "f8": "-",+ },+ ],+ }+}+++class TestSuccessEnvelope:+ """A successful screen yields the ok envelope with shaped rows."""++ def test_change_pct_screen_parses_rows(self):+ with patch(+ "src.tools.market_screener_tool.get_json", return_value=_CLIST_PAYLOAD+ ):+ text = MarketScreenerTool().execute(+ market="a", sort_by="change_pct", top_n=20+ )++ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["market"] == "a"+ assert payload["source"] == "eastmoney"+ # The row list nests under data:{...} like every other tool's envelope,+ # never a bare list directly under "data".+ data = payload["data"]+ assert isinstance(data, dict)+ assert data["market"] == "a"+ assert data["sort_by"] == "change_pct"++ rows = data["rows"]+ assert len(rows) == 2+ assert rows[0] == {+ "code": "600519",+ "name": "贵州茅台",+ "price": 1688.0,+ "change_pct": 9.98,+ "change": 153.0,+ "volume": 1234567.0,+ "amount": 2.08e9,+ "turnover_rate": 1.23,+ }+ # The "-" sentinel turnover rate becomes None, not 0.0.+ assert rows[1]["turnover_rate"] is None++ def test_sort_by_maps_to_eastmoney_fid(self):+ with patch(+ "src.tools.market_screener_tool.get_json", return_value=_CLIST_PAYLOAD+ ) as mock_get:+ MarketScreenerTool().execute(market="us", sort_by="amount", top_n=5)++ params = mock_get.call_args.kwargs["params"]+ assert params["fid"] == "f6" # amount+ assert params["po"] == "1" # descending+ assert params["pz"] == "5"+ assert params["fs"] == "m:105,m:106,m:107" # US universe++ def test_diff_as_dict_is_normalized(self):+ dict_diff = {"data": {"diff": {"0": _CLIST_PAYLOAD["data"]["diff"][0]}}}+ with patch(+ "src.tools.market_screener_tool.get_json", return_value=dict_diff+ ):+ text = MarketScreenerTool().execute(market="hk")++ rows = json.loads(text)["data"]["rows"]+ assert len(rows) == 1+ assert rows[0]["code"] == "600519"++ def test_top_n_caps_returned_rows(self):+ with patch(+ "src.tools.market_screener_tool.get_json", return_value=_CLIST_PAYLOAD+ ):+ text = MarketScreenerTool().execute(market="a", top_n=1)++ assert len(json.loads(text)["data"]["rows"]) == 1++ def test_rowless_payload_yields_empty_data(self):+ with patch(+ "src.tools.market_screener_tool.get_json", return_value={"data": None}+ ):+ text = MarketScreenerTool().execute(market="a")++ payload = json.loads(text)+ assert payload["ok"] is True+ # Rowless payload still yields the nested data:{...} envelope, not a+ # bare list, with an empty "rows".+ assert payload["data"]["rows"] == []+ assert payload["data"]["sort_by"] == "change_pct"+++class TestErrorEnvelope:+ """Validation and request failures return the ok=false envelope."""++ def test_missing_market_rejected(self):+ payload = json.loads(MarketScreenerTool().execute())+ assert payload["ok"] is False+ assert "market" in payload["error"]++ def test_invalid_market_rejected(self):+ payload = json.loads(MarketScreenerTool().execute(market="jp"))+ assert payload["ok"] is False+ assert "market" in payload["error"]++ def test_invalid_sort_by_rejected(self):+ payload = json.loads(+ MarketScreenerTool().execute(market="a", sort_by="price")+ )+ assert payload["ok"] is False+ assert "sort_by" in payload["error"]++ def test_non_positive_top_n_rejected(self):+ payload = json.loads(MarketScreenerTool().execute(market="a", top_n=0))+ assert payload["ok"] is False+ assert "top_n" in payload["error"]++ def test_bool_top_n_rejected(self):+ payload = json.loads(MarketScreenerTool().execute(market="a", top_n=True))+ assert payload["ok"] is False+ assert "top_n" in payload["error"]++ def test_http_failure_surfaces_as_error_envelope(self):+ with patch(+ "src.tools.market_screener_tool.get_json",+ side_effect=RuntimeError("HTTP 429"),+ ):+ text = MarketScreenerTool().execute(market="a")++ payload = json.loads(text)+ assert payload["ok"] is False+ assert "429" in payload["error"]diff --git a/agent/tests/test_mootdx_loader.py b/agent/tests/test_mootdx_loader.pyindex 2d5c0f42c..9b4ebab88 100644--- a/agent/tests/test_mootdx_loader.py+++ b/agent/tests/test_mootdx_loader.py@@ -204,6 +204,8 @@ def test_registry_lists_mootdx_in_a_share_chain() -> None:assert "mootdx" in LOADER_REGISTRYchain = FALLBACK_CHAINS["a_share"]assert "mootdx" in chain- # Order: tushare (auth) > mootdx (TCP, no auth) > akshare (HTTP scrape).+ # Order is by IP-ban risk: throttle-tolerant public/no-auth sources lead,+ # key-gated REST trails. So mootdx (TCP, no auth) > akshare (HTTP scrape) >+ # tushare (key-gated REST, placed last).assert chain.index("mootdx") < chain.index("akshare")- assert chain.index("tushare") < chain.index("mootdx")+ assert chain.index("akshare") < chain.index("tushare")diff --git a/agent/tests/test_northbound_tool.py b/agent/tests/test_northbound_tool.pynew file mode 100644index 000000000..a48b189b3--- /dev/null+++ b/agent/tests/test_northbound_tool.py@@ -0,0 +1,137 @@+"""Tests for get_northbound_flow: success + error envelopes, HTTP fully mocked.++All Eastmoney HTTP is mocked at ``src.tools.northbound_tool.get_json`` (the name+the tool imported), so no test touches a live Eastmoney endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++import pytest++from src.tools import northbound_tool as nb+++def _realtime_payload() -> dict:+ return {+ "data": {+ "hk2sh": {"netBuyAmt": 1200.5},+ "hk2sz": {"netBuyAmt": -300.0},+ }+ }+++def _history_payload() -> dict:+ return {+ "data": {+ "klines": [+ "2024-01-02,100.0,50.0",+ "2024-01-03,-20.0,80.0",+ "2024-01-04,-,-",+ ]+ }+ }+++def _fake_get_json(url: str, *, params: dict):+ if "kamt.kline" in url:+ return _history_payload()+ return _realtime_payload()+++class TestSuccessEnvelope:+ def test_returns_realtime_and_history(self):+ with patch.object(nb, "get_json", side_effect=_fake_get_json):+ text = nb.NorthboundFlowTool().execute(lookback_days=10)++ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["market"] == "China A"+ assert payload["source"] == "eastmoney"++ data = payload["data"]+ assert data["lookback_days"] == 10+ assert data["realtime"]["shanghai_connect"] == 1200.5+ assert data["realtime"]["shenzhen_connect"] == -300.0+ assert data["realtime"]["total"] == 900.5++ history = data["history"]+ assert len(history) == 3+ assert history[0] == {+ "trade_date": "2024-01-02",+ "shanghai_connect": 100.0,+ "shenzhen_connect": 50.0,+ "total": 150.0,+ }+ # A "-" sentinel row coerces to None without aborting the batch.+ assert history[-1]["shanghai_connect"] is None+ assert history[-1]["total"] is None++ def test_default_lookback_applied_when_absent(self):+ with patch.object(nb, "get_json", side_effect=_fake_get_json):+ text = nb.NorthboundFlowTool().execute()+ payload = json.loads(text)+ assert payload["data"]["lookback_days"] == nb._DEFAULT_LOOKBACK_DAYS++ def test_lookback_is_clamped_to_ceiling(self):+ with patch.object(nb, "get_json", side_effect=_fake_get_json):+ text = nb.NorthboundFlowTool().execute(lookback_days=99999)+ payload = json.loads(text)+ assert payload["data"]["lookback_days"] == nb._MAX_LOOKBACK_DAYS++ def test_history_trimmed_to_lookback(self):+ with patch.object(nb, "get_json", side_effect=_fake_get_json):+ text = nb.NorthboundFlowTool().execute(lookback_days=1)+ payload = json.loads(text)+ history = payload["data"]["history"]+ assert len(history) == 1+ assert history[0]["trade_date"] == "2024-01-04"+++class TestErrorEnvelope:+ def test_http_failure_returns_error_envelope(self):+ with patch.object(nb, "get_json", side_effect=RuntimeError("HTTP 429")):+ text = nb.NorthboundFlowTool().execute(lookback_days=5)+ payload = json.loads(text)+ assert payload["ok"] is False+ assert "429" in payload["error"]++ def test_missing_data_block_yields_empty_history_and_null_realtime(self):+ with patch.object(nb, "get_json", return_value={"data": None}):+ text = nb.NorthboundFlowTool().execute(lookback_days=5)+ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["data"]["history"] == []+ assert payload["data"]["realtime"]["total"] is None+++class TestToolMetadata:+ def test_name_and_required_params(self):+ tool = nb.NorthboundFlowTool()+ assert tool.name == "get_northbound_flow"+ assert tool.is_readonly is True+ assert tool.parameters["required"] == []+ assert "lookback_days" in tool.parameters["properties"]+++class TestRoutingDescription:+ """Description must scope to MARKET-WIDE Stock-Connect flow, not per-stock.++ Regression for B10-routing-desc: get_fund_flow and get_northbound_flow both+ used to open on a generic 'net capital flow' phrase, so a vague prompt could+ route to either. The northbound description must lead with the market-wide+ Stock-Connect scope and point per-stock intent at get_fund_flow.+ """++ def test_description_leads_with_market_wide_stock_connect(self):+ desc = nb.NorthboundFlowTool().description+ assert desc.startswith("MARKET-WIDE Northbound")+ assert "北向" in desc+ # Disambiguates against the per-stock tool.+ assert "get_fund_flow" in desc+ assert "NOT per-stock" in desc++ def test_description_keeps_a_concrete_example(self):+ assert "get_northbound_flow(lookback_days=10)" in nb.NorthboundFlowTool().descriptiondiff --git a/agent/tests/test_options_chain_tool.py b/agent/tests/test_options_chain_tool.pynew file mode 100644index 000000000..f4ad8d520--- /dev/null+++ b/agent/tests/test_options_chain_tool.py@@ -0,0 +1,144 @@+"""Tests for the get_options_chain tool.++All HTTP is mocked at ``yahoo_client.get_options`` (the client function the tool+imports), so no test ever reaches a live Yahoo endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from src.tools import options_chain_tool as oc+++def _sample_result() -> dict:+ return {+ "expirationDates": [1750000000, 1750604800],+ "strikes": [190.0, 195.0, 200.0],+ "options": [+ {+ "expirationDate": 1750000000,+ "calls": [+ {+ "contractSymbol": "AAPL250101C00190000",+ "strike": 190.0,+ "lastPrice": 12.5,+ "bid": 12.3,+ "ask": 12.7,+ "volume": 1500,+ "openInterest": 8000,+ "impliedVolatility": 0.2841,+ "inTheMoney": True,+ "expiration": 1750000000,+ }+ ],+ "puts": [+ {+ "contractSymbol": "AAPL250101P00190000",+ "strike": 190.0,+ "lastPrice": 3.1,+ "bid": 3.0,+ "ask": 3.2,+ "volume": 900,+ "openInterest": 4200,+ "impliedVolatility": 0.3012,+ "inTheMoney": False,+ "expiration": 1750000000,+ }+ ],+ }+ ],+ }+++class TestOptionsChainSuccess:+ """Happy-path envelope shape and field normalization."""++ def test_success_envelope_normalizes_contracts(self):+ with patch.object(+ oc.yahoo_client, "get_options", return_value=_sample_result()+ ) as mock_get:+ out = oc.OptionsChainTool().execute(ticker="AAPL.US")++ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["market"] == "us"+ assert payload["source"] == "yahoo"++ data = payload["data"]+ assert data["ticker"] == "AAPL.US"+ assert data["expiration"] == 1750000000+ assert data["expirations"] == [1750000000, 1750604800]+ assert data["calls_count"] == 1+ assert data["puts_count"] == 1++ call = data["calls"][0]+ assert call["contract_symbol"] == "AAPL250101C00190000"+ assert call["strike"] == 190.0+ assert call["implied_volatility"] == 0.2841+ assert call["open_interest"] == 8000+ assert call["in_the_money"] is True++ put = data["puts"][0]+ assert put["in_the_money"] is False+ assert put["bid"] == 3.0++ # Ticker flows through unchanged; no expiration -> nearest.+ _, kwargs = mock_get.call_args+ assert kwargs["expiration"] is None++ def test_explicit_expiration_passed_through(self):+ with patch.object(+ oc.yahoo_client, "get_options", return_value=_sample_result()+ ) as mock_get:+ oc.OptionsChainTool().execute(ticker="AAPL", expiration="1750000000")+ _, kwargs = mock_get.call_args+ assert kwargs["expiration"] == 1750000000++ def test_empty_chain_is_ok_with_zero_contracts(self):+ with patch.object(oc.yahoo_client, "get_options", return_value={}):+ out = oc.OptionsChainTool().execute(ticker="AAPL")+ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["data"]["calls"] == []+ assert payload["data"]["puts"] == []+ assert payload["data"]["expiration"] is None++ def test_contracts_capped(self):+ bloated = _sample_result()+ bloated["options"][0]["calls"] = [+ {"strike": float(i)} for i in range(500)+ ]+ with patch.object(oc.yahoo_client, "get_options", return_value=bloated):+ out = oc.OptionsChainTool().execute(ticker="AAPL")+ payload = json.loads(out)+ assert payload["data"]["calls_count"] == oc._MAX_CONTRACTS_PER_SIDE+++class TestOptionsChainErrors:+ """Error envelopes: missing ticker, bad expiration, upstream failure."""++ def test_missing_ticker_returns_error_envelope(self):+ out = oc.OptionsChainTool().execute(ticker=" ")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "required" in payload["error"]++ def test_bad_expiration_returns_error_envelope(self):+ out = oc.OptionsChainTool().execute(ticker="AAPL", expiration="not-an-int")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "epoch" in payload["error"]++ def test_upstream_failure_becomes_error_envelope(self):+ with patch.object(+ oc.yahoo_client,+ "get_options",+ side_effect=RuntimeError("HTTP 429 banned"),+ ):+ out = oc.OptionsChainTool().execute(ticker="AAPL")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "yahoo options request failed" in payload["error"]+ assert "429" in payload["error"]diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.pyindex 836ea6486..f360978ac 100644--- a/agent/tests/test_registry.py+++ b/agent/tests/test_registry.py@@ -11,6 +11,7 @@ from backtest.loaders.base import DataLoaderProtocol, NoAvailableSourceErrorfrom backtest.loaders.registry import (FALLBACK_CHAINS,LOADER_REGISTRY,+ VALID_SOURCES,get_loader_cls_with_fallback,register,resolve_loader,@@ -75,6 +76,21 @@ class _FakeCryptoLoader:return {}+class _FakeLocalLoader:+ """Mimics the real local loader: broad ``markets``, unavailable when the+ user has no Data Bridge config."""++ name = "local"+ markets = {"a_share", "us_equity", "crypto"}+ requires_auth = False++ def is_available(self) -> bool:+ return False++ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):+ return {}++# ---------------------------------------------------------------------------# @register decorator# ---------------------------------------------------------------------------@@ -130,6 +146,64 @@ class TestFallbackChains:# OKX and CCXT should still be preferredassert FALLBACK_CHAINS["crypto"][:2] == ["okx", "ccxt"]+ def test_chains_ordered_by_ip_ban_risk(self) -> None:+ """Equity chains lead with throttle-tolerant public sources and trail+ with key-gated REST fallbacks, in the exact reviewed order."""+ assert FALLBACK_CHAINS["a_share"] == [+ "tencent", "mootdx", "eastmoney", "baostock", "akshare", "tushare", "local",+ ]+ assert FALLBACK_CHAINS["us_equity"] == [+ "yahoo", "stooq", "sina", "eastmoney", "yfinance", "tiingo", "fmp",+ "finnhub", "alphavantage", "akshare", "local",+ ]+ assert FALLBACK_CHAINS["hk_equity"] == [+ "eastmoney", "yahoo", "futu", "yfinance", "akshare", "local",+ ]++ def test_us_equity_includes_sina_fallback(self) -> None:+ """'sina' must be reachable for US equities (after yahoo/stooq) so it is+ not a dead config source that no chain can ever select."""+ chain = FALLBACK_CHAINS["us_equity"]+ assert "sina" in chain+ assert chain.index("sina") > chain.index("yahoo")+ assert chain.index("sina") > chain.index("stooq")++ def test_a_share_includes_baostock(self) -> None:+ """'baostock' must remain a reachable A-share fallback."""+ assert "baostock" in FALLBACK_CHAINS["a_share"]++ def test_unchanged_chains_preserved(self) -> None:+ """crypto/futures/fund/macro/forex chains must be left untouched."""+ assert FALLBACK_CHAINS["crypto"] == ["okx", "ccxt", "yfinance", "local"]+ assert FALLBACK_CHAINS["futures"] == ["tushare", "akshare", "local"]+ assert FALLBACK_CHAINS["fund"] == ["tushare", "akshare", "local"]+ assert FALLBACK_CHAINS["macro"] == ["akshare", "tushare", "local"]+ assert FALLBACK_CHAINS["forex"] == ["akshare", "yfinance", "local"]+++# ---------------------------------------------------------------------------+# VALID_SOURCES+# ---------------------------------------------------------------------------+++class TestValidSources:+ def test_includes_new_loaders(self) -> None:+ """Newly registered loaders must be accepted config sources."""+ new_sources = {+ "eastmoney", "sina", "stooq", "yahoo",+ "finnhub", "alphavantage", "tiingo", "fmp",+ }+ assert new_sources <= VALID_SOURCES++ def test_covers_all_registered_loaders(self) -> None:+ """Every registered loader name must be an accepted config source so a+ new loader can never be silently rejected by config validation."""+ from backtest.loaders.registry import _ensure_registered++ _ensure_registered()+ missing = set(LOADER_REGISTRY) - VALID_SOURCES+ assert not missing, f"loaders missing from VALID_SOURCES: {missing}"+# ---------------------------------------------------------------------------# resolve_loader@@ -201,6 +275,23 @@ class TestGetLoaderWithFallback:with pytest.raises(NoAvailableSourceError):get_loader_cls_with_fallback("fake_unavailable")+ def test_explicit_local_does_not_fall_through_to_network(self) -> None:+ """An explicit unavailable 'local' request must raise a clear error, never+ silently degrade to an unrelated network loader via its broad markets."""+ with patch.dict(LOADER_REGISTRY, {+ "local": _FakeLocalLoader,+ "fake_available": _FakeAvailableLoader, # available a_share network src+ }, clear=True):+ # Even though a network loader is available for one of local's markets,+ # the explicit 'local' request must not borrow it.+ with patch.dict(FALLBACK_CHAINS, {"a_share": ["fake_available"]}):+ with pytest.raises(NoAvailableSourceError) as excinfo:+ get_loader_cls_with_fallback("local")+ msg = str(excinfo.value)+ assert "local" in msg+ # The error must point the user at the Data Bridge config, not a network hop.+ assert "data-bridge" in msg.lower() or "config" in msg.lower()+# ---------------------------------------------------------------------------# Issue #50 — loaders that explode in __init__ (e.g. Tushare with no token)diff --git a/agent/tests/test_research_reports_tool.py b/agent/tests/test_research_reports_tool.pynew file mode 100644index 000000000..d3c34fe83--- /dev/null+++ b/agent/tests/test_research_reports_tool.py@@ -0,0 +1,160 @@+"""Tests for get_research_reports: success + error envelopes, HTTP mocked.++Eastmoney is mocked at ``get_json`` (imported into the tool module) and THS at+``throttled_get`` (imported as ``research_reports_tool.throttled_get``), so no+test reaches a live endpoint.+"""++from __future__ import annotations++import json+from types import SimpleNamespace+from unittest.mock import patch++from src.tools import research_reports_tool as rrt+from src.tools.research_reports_tool import ResearchReportsTool++_REPORT_PAYLOAD = {+ "data": [+ {+ "title": "Q1 beat, raise target",+ "orgSName": "Broker A",+ "researcher": "Analyst One",+ "publishDate": "2024-04-30 08:00:00",+ "emRatingName": "Buy",+ "predictThisYearEps": "12.34",+ "predictNextYearEps": "15.00",+ "predictThisYearPe": "20.1",+ "predictNextYearPe": "16.5",+ },+ {+ "title": "Margins stable",+ "orgSName": "Broker B",+ "researcher": "Analyst Two",+ "publishDate": "2024-03-15 09:30:00",+ "emRatingName": "Hold",+ "predictThisYearEps": "11.80",+ "predictNextYearEps": "13.20",+ "predictThisYearPe": "21.0",+ "predictNextYearPe": "18.8",+ },+ ]+}++_THS_PAYLOAD = {+ "data": [+ {"year": "2024", "eps": "12.10"},+ {"year": "2025", "eps": "14.50"},+ ]+}+++def _fake_response(payload: dict, status_ok: bool = True):+ def raise_for_status() -> None:+ if not status_ok:+ raise RuntimeError("HTTP error")++ return SimpleNamespace(json=lambda: payload, raise_for_status=raise_for_status)+++def test_success_envelope_merges_reports_and_consensus():+ with patch.object(rrt, "get_json", return_value=_REPORT_PAYLOAD) as mock_em, patch.object(+ rrt, "throttled_get", return_value=_fake_response(_THS_PAYLOAD)+ ) as mock_ths:+ out = ResearchReportsTool().execute(code="600519.SH", limit=10)++ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["market"] == "CN"+ assert payload["source"] == "eastmoney+ths"+ assert payload["data"]["code"] == "600519.SH"++ reports = payload["data"]["reports"]+ assert len(reports) == 2+ assert reports[0] == {+ "title": "Q1 beat, raise target",+ "brokerage": "Broker A",+ "analyst": "Analyst One",+ "publish_date": "2024-04-30",+ "rating": "Buy",+ "eps_forecast": {"this_year": 12.34, "next_year": 15.0},+ "pe_forecast": {"this_year": 20.1, "next_year": 16.5},+ }++ consensus = payload["data"]["consensus_eps"]+ assert consensus == [+ {"fiscal_year": "2024", "consensus_eps": 12.1},+ {"fiscal_year": "2025", "consensus_eps": 14.5},+ ]++ # Eastmoney called with the bare numeric code; THS routed to the ths bucket.+ assert mock_em.call_args.kwargs["params"]["code"] == "600519"+ assert mock_ths.call_args.kwargs["host_key"] == "ths"+ assert mock_ths.call_args.kwargs["params"]["code"] == "600519"+++def test_limit_caps_returned_reports():+ with patch.object(rrt, "get_json", return_value=_REPORT_PAYLOAD), patch.object(+ rrt, "throttled_get", return_value=_fake_response(_THS_PAYLOAD)+ ):+ out = ResearchReportsTool().execute(code="600519.SH", limit=1)+ payload = json.loads(out)+ assert len(payload["data"]["reports"]) == 1+++def test_ths_failure_degrades_consensus_but_keeps_reports():+ with patch.object(rrt, "get_json", return_value=_REPORT_PAYLOAD), patch.object(+ rrt, "throttled_get", side_effect=RuntimeError("ths 503")+ ):+ out = ResearchReportsTool().execute(code="600519.SH")+ payload = json.loads(out)+ assert payload["ok"] is True+ assert len(payload["data"]["reports"]) == 2+ assert payload["data"]["consensus_eps"] == []+++def test_ths_non_2xx_degrades_consensus():+ with patch.object(rrt, "get_json", return_value=_REPORT_PAYLOAD), patch.object(+ rrt, "throttled_get", return_value=_fake_response(_THS_PAYLOAD, status_ok=False)+ ):+ out = ResearchReportsTool().execute(code="600519.SH")+ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["data"]["consensus_eps"] == []+++def test_non_a_share_returns_error_without_http():+ with patch.object(rrt, "get_json") as mock_em, patch.object(rrt, "throttled_get") as mock_ths:+ out = ResearchReportsTool().execute(code="AAPL.US")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "A-share" in payload["error"]+ mock_em.assert_not_called()+ mock_ths.assert_not_called()+++def test_missing_code_returns_error_envelope():+ out = ResearchReportsTool().execute()+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "required" in payload["error"]+++def test_report_request_failure_is_caught_as_error_envelope():+ with patch.object(rrt, "get_json", side_effect=RuntimeError("HTTP 429")), patch.object(+ rrt, "throttled_get", return_value=_fake_response(_THS_PAYLOAD)+ ):+ out = ResearchReportsTool().execute(code="600519.SH")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "429" in payload["error"]+++def test_empty_coverage_returns_error_envelope():+ with patch.object(rrt, "get_json", return_value={"data": []}), patch.object(+ rrt, "throttled_get", return_value=_fake_response({"data": []})+ ):+ out = ResearchReportsTool().execute(code="600519.SH")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "no research coverage" in payload["error"]diff --git a/agent/tests/test_sec_edgar_client.py b/agent/tests/test_sec_edgar_client.pynew file mode 100644index 000000000..aec60fb57--- /dev/null+++ b/agent/tests/test_sec_edgar_client.py@@ -0,0 +1,155 @@+"""Tests for sec_edgar_client: ticker->CIK mapping, CIK padding, payload parse.++All HTTP is fully mocked by patching ``throttled_get_json`` in the client+module — no test makes a real SEC request.+"""+from unittest.mock import patch++import pytest+import requests++from backtest.loaders import sec_edgar_client as sec+++_TICKERS_PAYLOAD = {+ "0": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."},+ "1": {"cik_str": 789019, "ticker": "MSFT", "title": "Microsoft Corp"},+ # lower-case ticker + already-int CIK to exercise normalization+ "2": {"cik_str": 1318605, "ticker": "tsla", "title": "Tesla, Inc."},+}++[email protected](autouse=True)+def _clear_cache():+ """Reset the memoized ticker map before and after every test."""+ sec._reset_ticker_cache_for_tests()+ yield+ sec._reset_ticker_cache_for_tests()+++class TestCikFor:+ """Ticker -> zero-padded 10-digit CIK resolution."""++ def test_resolves_and_pads_cik(self):+ with patch.object(sec, "throttled_get_json", return_value=_TICKERS_PAYLOAD):+ assert sec.cik_for("AAPL") == "0000320193"++ def test_case_insensitive(self):+ with patch.object(sec, "throttled_get_json", return_value=_TICKERS_PAYLOAD):+ assert sec.cik_for("aapl") == "0000320193"+ assert sec.cik_for("Tsla") == "0001318605"++ def test_unknown_ticker_returns_none(self):+ with patch.object(sec, "throttled_get_json", return_value=_TICKERS_PAYLOAD):+ assert sec.cik_for("NOPE") is None++ def test_empty_ticker_returns_none_without_fetch(self):+ with patch.object(sec, "throttled_get_json") as mock_get:+ assert sec.cik_for("") is None+ assert sec.cik_for(" ") is None+ mock_get.assert_not_called()++ def test_map_is_fetched_once_and_memoized(self):+ with patch.object(+ sec, "throttled_get_json", return_value=_TICKERS_PAYLOAD+ ) as mock_get:+ assert sec.cik_for("AAPL") == "0000320193"+ assert sec.cik_for("MSFT") == "0000789019"+ assert mock_get.call_count == 1++ def test_malformed_rows_skipped(self):+ payload = {+ "0": {"cik_str": 320193, "ticker": "AAPL"},+ "1": {"ticker": "NOCIK"}, # missing cik+ "2": {"cik_str": 5}, # missing ticker+ "3": "garbage", # not a dict+ }+ with patch.object(sec, "throttled_get_json", return_value=payload):+ assert sec.cik_for("AAPL") == "0000320193"+ assert sec.cik_for("NOCIK") is None+++class TestCikPadding:+ """_pad_cik normalizes ints, padded strings, and CIK-prefixed strings."""++ def test_pads_int(self):+ assert sec._pad_cik(320193) == "0000320193"++ def test_passes_through_already_padded(self):+ assert sec._pad_cik("0000320193") == "0000320193"++ def test_strips_cik_prefix(self):+ assert sec._pad_cik("CIK0000320193") == "0000320193"++ def test_no_digits_raises(self):+ with pytest.raises(ValueError):+ sec._pad_cik("ABC")+++class TestSubmissionsAndFacts:+ """Endpoint URL construction + raw payload passthrough."""++ def test_get_submissions_builds_padded_url(self):+ payload = {"cik": "320193", "name": "Apple Inc.", "filings": {}}+ with patch.object(+ sec, "throttled_get_json", return_value=payload+ ) as mock_get:+ out = sec.get_submissions(320193)+ assert out == payload+ called_url = mock_get.call_args[0][0]+ assert called_url == "https://data.sec.gov/submissions/CIK0000320193.json"+ kwargs = mock_get.call_args.kwargs+ assert kwargs["host_key"] == "sec"+ assert kwargs["min_interval"] >= 0.12++ def test_get_company_facts_builds_padded_url(self):+ payload = {"cik": 320193, "facts": {"us-gaap": {}}}+ with patch.object(+ sec, "throttled_get_json", return_value=payload+ ) as mock_get:+ out = sec.get_company_facts("CIK0000320193")+ assert out == payload+ called_url = mock_get.call_args[0][0]+ assert called_url == (+ "https://data.sec.gov/api/xbrl/companyfacts/CIK0000320193.json"+ )++ def test_compliant_user_agent_sent(self):+ with patch.object(+ sec, "throttled_get_json", return_value={}+ ) as mock_get:+ sec.get_submissions(320193)+ ua = mock_get.call_args.kwargs["headers"]["User-Agent"]+ assert "Vibe-Trading" in ua and "contact" in ua.lower()++ def test_user_agent_env_override(self, monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_SEC_UA", "MyApp/2.0 ([email protected])")+ with patch.object(+ sec, "throttled_get_json", return_value={}+ ) as mock_get:+ sec.get_company_facts(320193)+ assert mock_get.call_args.kwargs["headers"]["User-Agent"] == (+ "MyApp/2.0 ([email protected])"+ )+++class TestErrorPath:+ """A transport error propagates unchanged for the caller's retry policy."""++ def test_http_error_propagates(self):+ with patch.object(+ sec,+ "throttled_get_json",+ side_effect=requests.HTTPError("404 Not Found"),+ ):+ with pytest.raises(requests.HTTPError):+ sec.get_submissions(999999)++ def test_ticker_fetch_error_propagates(self):+ with patch.object(+ sec,+ "throttled_get_json",+ side_effect=requests.ConnectionError("boom"),+ ):+ with pytest.raises(requests.ConnectionError):+ sec.cik_for("AAPL")diff --git a/agent/tests/test_sec_filings_tool.py b/agent/tests/test_sec_filings_tool.pynew file mode 100644index 000000000..5cb706c75--- /dev/null+++ b/agent/tests/test_sec_filings_tool.py@@ -0,0 +1,150 @@+"""Tests for get_sec_filings: success + error envelopes, HTTP fully mocked.++The SEC client functions (``cik_for`` / ``get_submissions`` /+``get_company_facts``) are patched on the tool module, so no test reaches a+live ``sec.gov`` endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from src.tools import sec_filings_tool as sft+from src.tools.sec_filings_tool import SecFilingsTool++_SUBMISSIONS = {+ "cik": "320193",+ "name": "Apple Inc.",+ "filings": {+ "recent": {+ "form": ["10-K", "8-K", "10-Q"],+ "accessionNumber": [+ "0000320193-23-000106",+ "0000320193-23-000077",+ "0000320193-23-000064",+ ],+ "filingDate": ["2023-11-03", "2023-08-04", "2023-08-04"],+ "reportDate": ["2023-09-30", "", "2023-07-01"],+ "primaryDocument": ["aapl-20230930.htm", "ex.htm", "aapl-20230701.htm"],+ "primaryDocDescription": ["10-K", "8-K", "10-Q"],+ }+ },+}++_FACTS = {+ "cik": 320193,+ "facts": {+ "us-gaap": {+ "Revenues": {+ "label": "Revenues",+ "units": {+ # richer bucket should win the unit pick+ "USD": [+ {"end": "2021-09-25", "val": 365817000000, "fy": 2021, "fp": "FY", "form": "10-K", "accn": "a1"},+ {"end": "2022-09-24", "val": 394328000000, "fy": 2022, "fp": "FY", "form": "10-K", "accn": "a2"},+ ],+ "USD-shares": [+ {"end": "2022-09-24", "val": 1, "fy": 2022, "fp": "FY", "form": "10-K", "accn": "a3"},+ ],+ },+ }+ }+ },+}+++def test_success_lists_filings_with_document_urls():+ with patch.object(sft, "cik_for", return_value="0000320193") as mock_cik, patch.object(+ sft, "get_submissions", return_value=_SUBMISSIONS+ ) as mock_sub:+ out = SecFilingsTool().execute(ticker="aapl")++ mock_cik.assert_called_once_with("AAPL")+ mock_sub.assert_called_once_with("0000320193")++ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["market"] == "US"+ assert payload["source"] == "sec_edgar"+ assert payload["data"]["ticker"] == "AAPL"+ assert payload["data"]["cik"] == "0000320193"++ filings = payload["data"]["filings"]+ assert len(filings) == 3+ assert filings[0]["form"] == "10-K"+ assert filings[0]["accession_number"] == "0000320193-23-000106"+ assert filings[0]["report_date"] == "2023-09-30"+ assert filings[0]["document_url"] == (+ "https://www.sec.gov/Archives/edgar/data/320193/"+ "000032019323000106/aapl-20230930.htm"+ )+ # empty reportDate normalizes to None, not ""+ assert filings[1]["report_date"] is None+ # no metric requested -> key absent+ assert "metric" not in payload["data"]+++def test_form_filter_keeps_only_matching_forms():+ with patch.object(sft, "cik_for", return_value="0000320193"), patch.object(+ sft, "get_submissions", return_value=_SUBMISSIONS+ ):+ out = SecFilingsTool().execute(ticker="AAPL", form="10-q")+ payload = json.loads(out)+ filings = payload["data"]["filings"]+ assert len(filings) == 1+ assert filings[0]["form"] == "10-Q"+++def test_metric_series_picks_richest_unit_and_caps_limit():+ with patch.object(sft, "cik_for", return_value="0000320193"), patch.object(+ sft, "get_submissions", return_value=_SUBMISSIONS+ ), patch.object(sft, "get_company_facts", return_value=_FACTS) as mock_facts:+ out = SecFilingsTool().execute(ticker="AAPL", metric="Revenues", limit=1)++ mock_facts.assert_called_once_with("0000320193")+ payload = json.loads(out)+ metric = payload["data"]["metric"]+ assert metric["concept"] == "Revenues"+ assert metric["unit"] == "USD"+ assert metric["label"] == "Revenues"+ # limit=1 keeps the most recent point (last in source order)+ assert len(metric["points"]) == 1+ assert metric["points"][0]["val"] == 394328000000.0+ assert metric["points"][0]["fiscal_year"] == 2022+++def test_unknown_metric_returns_empty_series_not_error():+ with patch.object(sft, "cik_for", return_value="0000320193"), patch.object(+ sft, "get_submissions", return_value=_SUBMISSIONS+ ), patch.object(sft, "get_company_facts", return_value=_FACTS):+ out = SecFilingsTool().execute(ticker="AAPL", metric="NotAConcept")+ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["data"]["metric"]["points"] == []+ assert payload["data"]["metric"]["unit"] is None+++def test_missing_ticker_returns_error_envelope():+ out = SecFilingsTool().execute()+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "required" in payload["error"]+++def test_unknown_ticker_returns_error_envelope():+ with patch.object(sft, "cik_for", return_value=None):+ out = SecFilingsTool().execute(ticker="NOPE")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "not found" in payload["error"]+++def test_submissions_failure_is_caught_as_error_envelope():+ with patch.object(sft, "cik_for", return_value="0000320193"), patch.object(+ sft, "get_submissions", side_effect=RuntimeError("HTTP 429")+ ):+ out = SecFilingsTool().execute(ticker="AAPL")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "429" in payload["error"]diff --git a/agent/tests/test_sector_tool.py b/agent/tests/test_sector_tool.pynew file mode 100644index 000000000..25e3bfb54--- /dev/null+++ b/agent/tests/test_sector_tool.py@@ -0,0 +1,194 @@+"""Tests for sector_tool: envelope shape, parsing, mode dispatch, validation.++All HTTP is mocked at the Eastmoney client functions the tool imports+(:func:`get_json` / :func:`resolve_secid`), so no test touches a live endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from src.tools.sector_tool import SectorInfoTool++_MEMBERSHIP_PAYLOAD = {+ "data": {+ "diff": [+ {"f12": "BK0477", "f14": "白酒", "f3": 1.23, "f2": 1700.0},+ {"f12": "BK0815", "f14": "酿酒行业", "f3": -0.5, "f2": "-"},+ {"f14": "missing-code"}, # dropped: no f12+ ]+ }+}++_RANKING_PAYLOAD = {+ "data": {+ "diff": [+ {+ "f12": "BK0477",+ "f14": "白酒",+ "f3": 3.4,+ "f2": 12345.0,+ "f104": 18,+ "f105": 2,+ "f140": "贵州茅台",+ },+ {+ "f12": "BK0727",+ "f14": "银行",+ "f3": 1.1,+ "f2": 6789.0,+ "f104": 30,+ "f105": 12,+ "f140": "-",+ },+ ]+ }+}+++class TestMembershipEnvelope:+ """A resolvable stock yields the ok envelope with parsed boards."""++ def test_membership_parses_boards(self):+ with patch(+ "src.tools.sector_tool.resolve_secid", return_value="1.600519"+ ), patch(+ "src.tools.sector_tool.get_json", return_value=_MEMBERSHIP_PAYLOAD+ ) as mock_get:+ text = SectorInfoTool().execute(code="600519.SH")++ url = mock_get.call_args[0][0]+ assert "slist/get" in url+ assert mock_get.call_args.kwargs["params"]["secid"] == "1.600519"++ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["market"] == "stock"+ assert payload["source"] == "eastmoney"+ assert payload["mode"] == "membership"+ assert payload["data"]["code"] == "600519.SH"+ assert payload["data"]["secid"] == "1.600519"++ boards = payload["data"]["boards"]+ assert len(boards) == 2 # the f12-less row is dropped+ assert boards[0] == {+ "board_code": "BK0477",+ "board_name": "白酒",+ "change_pct": 1.23,+ "price": 1700.0,+ }+ # "-" price coerces to None.+ assert boards[1]["price"] is None++ def test_membership_default_mode_when_only_code(self):+ with patch(+ "src.tools.sector_tool.resolve_secid", return_value="0.000001"+ ), patch("src.tools.sector_tool.get_json", return_value={"data": {"diff": []}}):+ payload = json.loads(SectorInfoTool().execute(code="000001.SZ"))++ assert payload["mode"] == "membership"+ assert payload["data"]["boards"] == []+++class TestRankingEnvelope:+ """mode='ranking' enumerates the industry-board universe."""++ def test_ranking_parses_boards(self):+ with patch(+ "src.tools.sector_tool.get_json", return_value=_RANKING_PAYLOAD+ ) as mock_get:+ text = SectorInfoTool().execute(mode="ranking", limit=20)++ url = mock_get.call_args[0][0]+ assert "clist/get" in url+ assert mock_get.call_args.kwargs["params"]["fs"] == "m:90+t:2"++ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["mode"] == "ranking"+ boards = payload["data"]["boards"]+ assert len(boards) == 2+ assert boards[0]["board_name"] == "白酒"+ assert boards[0]["leader"] == "贵州茅台"+ assert boards[0]["up_count"] == 18.0+ # "-" leader coerces to None.+ assert boards[1]["leader"] is None++ def test_ranking_ignores_code_and_skips_resolve(self):+ with patch("src.tools.sector_tool.resolve_secid") as resolve, patch(+ "src.tools.sector_tool.get_json", return_value=_RANKING_PAYLOAD+ ):+ payload = json.loads(+ SectorInfoTool().execute(mode="ranking", code="600519.SH")+ )++ assert payload["ok"] is True+ resolve.assert_not_called()++ def test_ranking_caps_limit(self):+ with patch(+ "src.tools.sector_tool.get_json", return_value=_RANKING_PAYLOAD+ ) as mock_get:+ SectorInfoTool().execute(mode="ranking", limit=10_000)++ # Request pz is capped at the defensive maximum.+ assert mock_get.call_args.kwargs["params"]["pz"] == "100"++ def test_diff_as_dict_is_handled(self):+ dict_payload = {"data": {"diff": {"0": _RANKING_PAYLOAD["data"]["diff"][0]}}}+ with patch("src.tools.sector_tool.get_json", return_value=dict_payload):+ payload = json.loads(SectorInfoTool().execute(mode="ranking"))++ assert len(payload["data"]["boards"]) == 1+++class TestErrorEnvelope:+ """Validation and request failures return the ok=false envelope."""++ def test_missing_code_for_membership_rejected(self):+ payload = json.loads(SectorInfoTool().execute())+ assert payload["ok"] is False+ assert "code" in payload["error"]++ def test_blank_code_rejected(self):+ payload = json.loads(SectorInfoTool().execute(code=" "))+ assert payload["ok"] is False++ def test_invalid_mode_rejected(self):+ payload = json.loads(SectorInfoTool().execute(mode="trending"))+ assert payload["ok"] is False+ assert "mode" in payload["error"]++ def test_non_positive_limit_rejected(self):+ payload = json.loads(SectorInfoTool().execute(mode="ranking", limit=0))+ assert payload["ok"] is False+ assert "limit" in payload["error"]++ def test_bool_limit_rejected(self):+ payload = json.loads(SectorInfoTool().execute(mode="ranking", limit=True))+ assert payload["ok"] is False++ def test_unresolvable_symbol_error_envelope(self):+ with patch("src.tools.sector_tool.resolve_secid", return_value=None):+ payload = json.loads(SectorInfoTool().execute(code="WAT.XYZ"))+ assert payload["ok"] is False+ assert "unresolvable" in payload["error"]++ def test_http_failure_membership_error_envelope(self):+ with patch(+ "src.tools.sector_tool.resolve_secid", return_value="1.600519"+ ), patch(+ "src.tools.sector_tool.get_json", side_effect=RuntimeError("HTTP 429")+ ):+ payload = json.loads(SectorInfoTool().execute(code="600519.SH"))+ assert payload["ok"] is False+ assert "429" in payload["error"]++ def test_http_failure_ranking_error_envelope(self):+ with patch(+ "src.tools.sector_tool.get_json", side_effect=RuntimeError("HTTP 503")+ ):+ payload = json.loads(SectorInfoTool().execute(mode="ranking"))+ assert payload["ok"] is False+ assert "503" in payload["error"]diff --git a/agent/tests/test_shareholder_count_tool.py b/agent/tests/test_shareholder_count_tool.pynew file mode 100644index 000000000..99a152b53--- /dev/null+++ b/agent/tests/test_shareholder_count_tool.py@@ -0,0 +1,104 @@+"""Tests for get_shareholder_count: success + error envelopes, HTTP mocked.++The Eastmoney datacenter call is mocked at ``get_json`` (imported into the tool+module), so no test reaches a live endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from src.tools import shareholder_count_tool as sct+from src.tools.shareholder_count_tool import ShareholderCountTool++_SAMPLE_PAYLOAD = {+ "result": {+ "data": [+ {+ "SECUCODE": "600519.SH",+ "END_DATE": "2024-03-31 00:00:00",+ "HOLDER_NUM": 188000,+ "HOLDER_NUM_CHANGE": -2000,+ "HOLDER_NUM_RATIO": -1.05,+ "AVG_HOLD_NUM": 6680.0,+ "AVG_HOLD_AMT": 12345678.0,+ "TOTAL_MARKET_CAP": 2.1e12,+ },+ {+ "SECUCODE": "600519.SH",+ "END_DATE": "2023-12-31 00:00:00",+ "HOLDER_NUM": 190000,+ "HOLDER_NUM_CHANGE": 1500,+ "HOLDER_NUM_RATIO": 0.80,+ "AVG_HOLD_NUM": 6610.0,+ "AVG_HOLD_AMT": 12000000.0,+ "TOTAL_MARKET_CAP": 2.0e12,+ },+ ]+ }+}+++def test_success_envelope_parses_periods_newest_first():+ with patch.object(sct, "get_json", return_value=_SAMPLE_PAYLOAD) as mock_get:+ out = ShareholderCountTool().execute(code="600519.SH")++ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["market"] == "CN"+ assert payload["source"] == "eastmoney"+ assert payload["data"]["code"] == "600519.SH"++ periods = payload["data"]["periods"]+ assert len(periods) == 2+ assert periods[0] == {+ "end_date": "2024-03-31",+ "holder_count": 188000.0,+ "holder_count_change": -2000.0,+ "holder_count_change_pct": -1.05,+ "avg_hold_shares": 6680.0,+ "avg_hold_amount": 12345678.0,+ "total_market_cap": 2.1e12,+ }++ # SECUCODE filter flows through to the datacenter request.+ _, kwargs = mock_get.call_args+ assert kwargs["params"]["filter"] == '(SECUCODE="600519.SH")'+++def test_max_periods_caps_returned_rows():+ with patch.object(sct, "get_json", return_value=_SAMPLE_PAYLOAD):+ out = ShareholderCountTool().execute(code="600519.SH", max_periods=1)+ payload = json.loads(out)+ assert len(payload["data"]["periods"]) == 1+++def test_non_a_share_returns_error_envelope():+ out = ShareholderCountTool().execute(code="AAPL.US")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "A-share" in payload["error"]+++def test_missing_code_returns_error_envelope():+ out = ShareholderCountTool().execute()+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "required" in payload["error"]+++def test_empty_disclosure_returns_error_envelope():+ with patch.object(sct, "get_json", return_value={"result": {"data": []}}):+ out = ShareholderCountTool().execute(code="600519.SH")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "no shareholder-count" in payload["error"]+++def test_request_failure_is_caught_as_error_envelope():+ with patch.object(sct, "get_json", side_effect=RuntimeError("HTTP 429")):+ out = ShareholderCountTool().execute(code="600519.SH")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "429" in payload["error"]diff --git a/agent/tests/test_sina_loader.py b/agent/tests/test_sina_loader.pynew file mode 100644index 000000000..9dd865271--- /dev/null+++ b/agent/tests/test_sina_loader.py@@ -0,0 +1,224 @@+"""Tests for the Sina US-equity daily OHLCV loader.++All HTTP is mocked at :func:`backtest.loaders._http.throttled_get` (imported into+the loader module as ``sina_loader.throttled_get``), so no test touches a live+Sina endpoint.+"""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import patch++import pandas as pd+import pytest++from backtest.loaders.sina_loader import (+ DataLoader,+ _bars_to_frame,+ _is_us_equity,+ _strip_jsonp,+ _to_sina_symbol,+)+++# ---------------------------------------------------------------------------+# Symbol detection / mapping+# ---------------------------------------------------------------------------+++ "code, expected",+ [+ ("AAPL.US", True),+ ("aapl.us", True),+ ("BRK.B.US", True),+ ("600519.SH", False),+ ("00700.HK", False),+ ("BTC-USDT", False),+ ("", False),+ ],+)+def test_is_us_equity(code: str, expected: bool) -> None:+ assert _is_us_equity(code) is expected+++ "code, expected",+ [("AAPL.US", "AAPL"), ("aapl.us", "AAPL"), ("BRK.B.US", "BRK.B")],+)+def test_to_sina_symbol(code: str, expected: bool) -> None:+ assert _to_sina_symbol(code) == expected+++# ---------------------------------------------------------------------------+# JSONP wrapper stripping+# ---------------------------------------------------------------------------+++def _jsonp(bars_json: str) -> str:+ return f"var x=({bars_json});"+++def test_strip_jsonp_extracts_array() -> None:+ raw = _jsonp('[{"d":"2024-01-02","o":"1","h":"2","l":"0.5","c":"1.5","v":"100"}]')+ bars = _strip_jsonp(raw)+ assert isinstance(bars, list)+ assert bars[0]["d"] == "2024-01-02"+++def test_strip_jsonp_handles_extra_whitespace() -> None:+ raw = " var x = ( [] ) ; \n"+ assert _strip_jsonp(raw) == []+++def test_strip_jsonp_raises_on_garbage() -> None:+ with pytest.raises(ValueError, match="no JSON array"):+ _strip_jsonp("not jsonp at all")+++def test_strip_jsonp_raises_when_payload_not_list() -> None:+ with pytest.raises(ValueError):+ _strip_jsonp('var x=({"d":"x"});')+++# ---------------------------------------------------------------------------+# Bar reshaping+# ---------------------------------------------------------------------------+++_SAMPLE_BARS = [+ {"d": "2024-01-02", "o": "10.0", "h": "11.0", "l": "9.5", "c": "10.5", "v": "1000"},+ {"d": "2024-01-03", "o": "10.5", "h": "12.0", "l": "10.0", "c": "11.5", "v": "2000"},+ {"d": "2024-01-04", "o": "11.5", "h": "13.0", "l": "11.0", "c": "12.5", "v": "3000"},+]+++def test_bars_to_frame_shape_and_dtypes() -> None:+ df = _bars_to_frame(_SAMPLE_BARS, "2024-01-01", "2024-01-31")+ assert df is not None+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"+ assert isinstance(df.index, pd.DatetimeIndex)+ assert all(str(df[c].dtype) == "float64" for c in df.columns)+ assert len(df) == 3+ assert df.index.is_monotonic_increasing+++def test_bars_to_frame_clips_to_window() -> None:+ df = _bars_to_frame(_SAMPLE_BARS, "2024-01-03", "2024-01-03")+ assert df is not None+ assert len(df) == 1+ assert df.index[0] == pd.Timestamp("2024-01-03")+++def test_bars_to_frame_empty_window_returns_none() -> None:+ assert _bars_to_frame(_SAMPLE_BARS, "2030-01-01", "2030-01-02") is None+++def test_bars_to_frame_skips_malformed_rows() -> None:+ bars = [+ {"d": "2024-01-02", "o": "10", "h": "11", "l": "9", "c": "10", "v": "1"},+ {"d": "2024-01-03", "o": "bad", "h": "11", "l": "9", "c": "10", "v": "1"},+ {"no_date": True},+ "junk",+ ]+ df = _bars_to_frame(bars, "2024-01-01", "2024-01-31")+ assert df is not None+ assert len(df) == 1+++def test_bars_to_frame_all_malformed_returns_none() -> None:+ assert _bars_to_frame([{"bad": 1}, "x"], "2024-01-01", "2024-01-31") is None+++# ---------------------------------------------------------------------------+# Loader behavior (HTTP mocked)+# ---------------------------------------------------------------------------+++def _fake_response(text: str, status_ok: bool = True):+ def raise_for_status() -> None:+ if not status_ok:+ raise RuntimeError("HTTP error")++ return SimpleNamespace(text=text, raise_for_status=raise_for_status)+++def test_fetch_returns_frame_for_us_symbol() -> None:+ raw = _jsonp(+ '[{"d":"2024-01-02","o":"10.0","h":"11.0","l":"9.5","c":"10.5","v":"1000"},'+ '{"d":"2024-01-03","o":"10.5","h":"12.0","l":"10.0","c":"11.5","v":"2000"}]'+ )+ with patch(+ "backtest.loaders.sina_loader.throttled_get",+ return_value=_fake_response(raw),+ ) as mock_get:+ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")++ assert "AAPL.US" in out+ df = out["AAPL.US"]+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"+ assert len(df) == 2+ # Symbol stripping: Sina called with the bare ticker.+ assert mock_get.call_args.kwargs["params"] == {"symbol": "AAPL"}+ assert mock_get.call_args.kwargs["host_key"] == "sina"+++def test_fetch_skips_non_us_symbols_without_http() -> None:+ with patch("backtest.loaders.sina_loader.throttled_get") as mock_get:+ out = DataLoader().fetch(["600519.SH", "00700.HK", "BTC-USDT"], "2024-01-01", "2024-01-31")+ assert out == {}+ mock_get.assert_not_called()+++def test_fetch_one_symbol_failure_does_not_abort_batch() -> None:+ good = _jsonp('[{"d":"2024-01-02","o":"1","h":"2","l":"0.5","c":"1.5","v":"100"}]')++ def side_effect(*args, **kwargs):+ if kwargs["params"]["symbol"] == "BAD":+ raise RuntimeError("network blip")+ return _fake_response(good)++ with patch("backtest.loaders.sina_loader.throttled_get", side_effect=side_effect):+ out = DataLoader().fetch(["BAD.US", "AAPL.US"], "2024-01-01", "2024-01-31")++ assert "BAD.US" not in out+ assert "AAPL.US" in out+++def test_fetch_non_2xx_status_skips_symbol() -> None:+ with patch(+ "backtest.loaders.sina_loader.throttled_get",+ return_value=_fake_response("var x=([]);", status_ok=False),+ ):+ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")+ assert out == {}+++def test_fetch_rejects_non_daily_interval() -> None:+ with pytest.raises(ValueError, match="daily-only"):+ DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31", interval="5m")+++def test_fetch_invalid_date_range_raises() -> None:+ with pytest.raises(ValueError):+ DataLoader().fetch(["AAPL.US"], "2024-02-01", "2024-01-01")+++def test_is_available_always_true() -> None:+ assert DataLoader().is_available() is True+++# ---------------------------------------------------------------------------+# Registry integration+# ---------------------------------------------------------------------------+++def test_register_decorator_added_sina_to_registry() -> None:+ from backtest.loaders.registry import LOADER_REGISTRY++ assert LOADER_REGISTRY.get("sina") is DataLoader+ assert DataLoader.markets == {"us_equity"}+ assert DataLoader.requires_auth is Falsediff --git a/agent/tests/test_skill_reference_links.py b/agent/tests/test_skill_reference_links.pynew file mode 100644index 000000000..793a3b97e--- /dev/null+++ b/agent/tests/test_skill_reference_links.py@@ -0,0 +1,110 @@+"""Regression tests: every ``references/`` link in data-source SKILL.md files+resolves through the ``read_file`` tool.++Background:+ ``read_file`` roots reads at the bundled ``skills/`` directory, so a link+ must carry the skill-name prefix (e.g. ``tushare/references/...``) to be+ reachable. Bare ``references/...`` links silently fail because+ ``skills/references/`` does not exist. These tests lock in the prefixed+ convention so the bug cannot regress.++No live API is touched: ``read_file`` performs local filesystem reads of the+bundled skill docs only.+"""++from __future__ import annotations++import json+import re+from pathlib import Path+from typing import List, Tuple++import pytest++from src.tools.read_file_tool import ReadFileTool++# Bundled skills root (mirrors ReadFileTool's own allowed-root computation).+_SKILLS_DIR = Path(__file__).resolve().parents[1] / "src" / "skills"++# Skills whose SKILL.md links into a references/ and/or scripts/ tree.+_SKILLS_UNDER_TEST = ("tushare", "okx-market", "eastmoney", "sec-edgar", "yfinance")++# Markdown link whose target is a references/*.md or scripts/*.py path, e.g.+# "[label](tushare/references/foo/bar.md)" or "[ex](sec-edgar/scripts/x.py)".+# The target itself may contain parentheses (some tushare filenames do, e.g.+# "社融增量(月度).md"), so anchor on the trailing ".md)"/".py)" rather than the+# first ")".+_MD_LINK_RE = re.compile(+ r"\]\((?P<target>[^(]*(?:references/.+?\.md|scripts/.+?\.py))\)"+)+++def _extract_reference_links(skill: str) -> List[str]:+ """Return every markdown link target containing ``references/``.++ Args:+ skill: Skill directory name (e.g. ``tushare``).++ Returns:+ List of raw link targets as written in SKILL.md.+ """+ text = (_SKILLS_DIR / skill / "SKILL.md").read_text(encoding="utf-8")+ return [m.group("target") for m in _MD_LINK_RE.finditer(text)]+++def _read(path: str) -> dict:+ """Resolve a path through the read_file tool and return the parsed body.++ Args:+ path: Path argument passed to read_file (no run_dir; skills/ root).++ Returns:+ Parsed JSON response from ReadFileTool.execute.+ """+ return json.loads(ReadFileTool().execute(path=path))+++def _all_links() -> List[Tuple[str, str]]:+ """Collect (skill, link) pairs across all skills under test."""+ pairs: List[Tuple[str, str]] = []+ for skill in _SKILLS_UNDER_TEST:+ for link in _extract_reference_links(skill):+ pairs.append((skill, link))+ return pairs+++def test_skills_have_reference_links() -> None:+ """Sanity: each skill under test exposes references/ links to validate."""+ for skill in _SKILLS_UNDER_TEST:+ assert _extract_reference_links(skill), f"{skill} has no references/ links"++[email protected]("skill,link", _all_links())+def test_reference_links_carry_skill_prefix(skill: str, link: str) -> None:+ """Every references/ or scripts/ link is written with its skill-name prefix.++ A bare ``references/...`` / ``scripts/...`` link is unreachable because+ read_file roots at ``skills/`` and ``skills/references/`` does not exist.+ """+ assert link.startswith(f"{skill}/"), (+ f"{skill}/SKILL.md link must carry the '{skill}/' prefix, got: {link}"+ )++[email protected]("skill,link", _all_links())+def test_reference_links_resolve_through_read_file(skill: str, link: str) -> None:+ """Every references/ link resolves to an existing file via read_file."""+ body = _read(link)+ assert body["status"] == "ok", f"{link} did not resolve: {body}"+ assert body["content"], f"{link} resolved to empty content"+++def test_bare_reference_link_would_fail() -> None:+ """Guard: a bare references/ path (no prefix) is NOT resolvable.++ This documents the exact failure mode the prefix convention prevents.+ """+ skill, link = _all_links()[0]+ bare = link[len(f"{skill}/"):] # strip the skill-name prefix+ body = _read(bare)+ assert body["status"] == "error"diff --git a/agent/tests/test_stock_news_tool.py b/agent/tests/test_stock_news_tool.pynew file mode 100644index 000000000..72e0fc3f3--- /dev/null+++ b/agent/tests/test_stock_news_tool.py@@ -0,0 +1,211 @@+"""Tests for the stock-news tool.++No request leaves the process: the Eastmoney HTTP boundary+(:func:`backtest.loaders.eastmoney_client.throttled_get_json`) and the Yahoo+:func:`backtest.loaders.yahoo_client.search` helper are mocked so the real+client + tool parsing run fully offline.+"""++from __future__ import annotations++import json+from typing import Any+from unittest.mock import patch++import pytest++from backtest.loaders import eastmoney_client, yahoo_client+from src.tools.stock_news_tool import (+ StockNewsTool,+ _bare_query,+ _clamp_limit,+ _snippet,+ _suffix_of,+)+++def _em_news_payload() -> dict[str, Any]:+ """An Eastmoney search payload carrying two CMS articles."""+ return {+ "result": {+ "cmsArticleWebOld": [+ {+ "title": "贵州茅台一季度净利大增",+ "url": "https://finance.eastmoney.com/a/1.html",+ "mediaName": "东方财富",+ "date": "2024-04-30 08:00:00",+ "content": "公司披露一季报,营收同比增长 " * 30,+ },+ {+ "title": "白酒板块全线走强",+ "url": "https://finance.eastmoney.com/a/2.html",+ "mediaName": "证券时报",+ "date": "2024-04-29 18:30:00",+ "content": "市场情绪回暖",+ },+ ]+ }+ }+++def _yahoo_matches() -> list[dict[str, Any]]:+ """A Yahoo search result list with two instrument matches."""+ return [+ {+ "symbol": "AAPL",+ "shortname": "Apple Inc.",+ "exchange": "NMS",+ "quoteType": "EQUITY",+ },+ {+ "symbol": "AAPL.MX",+ "shortname": "Apple Inc.",+ "exchange": "MEX",+ "quoteType": "EQUITY",+ },+ ]+++class TestHelpers:+ def test_suffix_of(self) -> None:+ assert _suffix_of("600519.SH") == "SH"+ assert _suffix_of("AAPL.US") == "US"+ assert _suffix_of("NOSUFFIX") == ""++ def test_bare_query(self) -> None:+ assert _bare_query("600519.SH") == "600519"+ assert _bare_query(" AAPL.US ") == "AAPL"++ def test_clamp_limit(self) -> None:+ assert _clamp_limit(None) == 20+ assert _clamp_limit("garbage") == 20+ assert _clamp_limit(0) == 1+ assert _clamp_limit(999) == 50+ assert _clamp_limit(5) == 5++ def test_snippet_trims(self) -> None:+ assert _snippet(None) == ""+ long = "x" * 400+ out = _snippet(long)+ assert len(out) <= 281+ assert out.endswith("…")+++class TestToolContract:+ def test_name_and_schema(self) -> None:+ tool = StockNewsTool()+ assert tool.name == "get_stock_news"+ assert tool.is_readonly is True+ assert tool.parameters["required"] == []+ assert tool.parameters["properties"]["scope"]["enum"] == ["stock", "global"]+ # Description must honestly state US/HK returns matches, not articles (B6).+ desc = tool.description.lower()+ assert "matches" in desc+ assert "not return news articles" in desc or "not 'articles'" in desc+++class TestExecuteSuccess:+ def test_a_share_stock_news(self) -> None:+ tool = StockNewsTool()+ with patch.object(+ eastmoney_client, "throttled_get_json", return_value=_em_news_payload()+ ) as http:+ out = json.loads(tool.execute(code="600519.SH", scope="stock", limit=10))++ http.assert_called_once()+ _, kwargs = http.call_args+ assert kwargs["host_key"] == "eastmoney"++ assert out["ok"] is True+ assert out["market"] == "a_share"+ assert out["source"] == "eastmoney"+ assert out["data"]["code"] == "600519.SH"+ assert len(out["data"]["articles"]) == 2+ first = out["data"]["articles"][0]+ assert first["title"] == "贵州茅台一季度净利大增"+ assert first["source"] == "东方财富"+ assert first["snippet"].endswith("…")++ def test_global_scope_needs_no_code(self) -> None:+ tool = StockNewsTool()+ with patch.object(+ eastmoney_client, "throttled_get_json", return_value=_em_news_payload()+ ):+ out = json.loads(tool.execute(scope="global"))++ assert out["ok"] is True+ assert out["market"] == "global"+ assert out["source"] == "eastmoney"+ assert out["data"]["scope"] == "global"+ assert len(out["data"]["articles"]) == 2++ def test_us_stock_via_yahoo_returns_matches_not_articles(self) -> None:+ tool = StockNewsTool()+ with patch.object(yahoo_client, "search", return_value=_yahoo_matches()) as srch:+ out = json.loads(tool.execute(code="AAPL.US", limit=1))++ srch.assert_called_once_with("AAPL")+ assert out["ok"] is True+ assert out["market"] == "us"+ assert out["source"] == "yahoo"+ # Instrument hits must NOT be mislabelled as articles (B6 regression).+ assert "articles" not in out["data"]+ assert out["data"]["result_type"] == "matches"+ # limit=1 caps the two matches to one.+ assert len(out["data"]["matches"]) == 1+ first = out["data"]["matches"][0]+ assert first["symbol"] == "AAPL"+ assert first["exchange"] == "NMS"+ assert first["quote_type"] == "EQUITY"++ def test_hk_stock_routes_to_yahoo(self) -> None:+ tool = StockNewsTool()+ with patch.object(yahoo_client, "search", return_value=[]):+ out = json.loads(tool.execute(code="00700.HK"))++ assert out["ok"] is True+ assert out["market"] == "hk"+ assert out["source"] == "yahoo"+ assert "articles" not in out["data"]+ assert out["data"]["result_type"] == "matches"+ assert out["data"]["matches"] == []+++class TestExecuteError:+ def test_missing_code_when_stock_scope(self) -> None:+ out = json.loads(StockNewsTool().execute(scope="stock"))+ assert out["ok"] is False+ assert "code" in out["error"]++ def test_invalid_scope(self) -> None:+ out = json.loads(StockNewsTool().execute(scope="weird"))+ assert out["ok"] is False+ assert "invalid scope" in out["error"]++ def test_unsupported_market(self) -> None:+ out = json.loads(StockNewsTool().execute(code="BTC-USDT"))+ assert out["ok"] is False+ assert "unsupported market" in out["error"]++ def test_eastmoney_http_failure_envelope(self) -> None:+ tool = StockNewsTool()+ with patch.object(+ eastmoney_client,+ "throttled_get_json",+ side_effect=RuntimeError("eastmoney banned"),+ ):+ out = json.loads(tool.execute(code="600519.SH"))++ assert out["ok"] is False+ assert "eastmoney banned" in out["error"]++ def test_yahoo_failure_envelope(self) -> None:+ tool = StockNewsTool()+ with patch.object(+ yahoo_client, "search", side_effect=RuntimeError("yahoo 429")+ ):+ out = json.loads(tool.execute(code="AAPL.US"))++ assert out["ok"] is False+ assert "yahoo 429" in out["error"]+ assert "yahoo search fetch failed" in out["error"]diff --git a/agent/tests/test_stock_profile_tool.py b/agent/tests/test_stock_profile_tool.pynew file mode 100644index 000000000..ea30cb832--- /dev/null+++ b/agent/tests/test_stock_profile_tool.py@@ -0,0 +1,179 @@+"""Tests for the get_stock_profile tool.++All HTTP is mocked at :func:`get_quote_summary` as it is imported into the tool+module, so no test touches a live Yahoo Finance endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from src.tools import stock_profile_tool as sp+++def _sample_summary() -> dict:+ return {+ "defaultKeyStatistics": {+ "forwardPE": {"raw": 28.5, "fmt": "28.50"},+ "trailingEps": {"raw": 6.13},+ "beta": {"raw": 1.25},+ "heldPercentInstitutions": {"raw": 0.61},+ "sharesOutstanding": {"raw": 15_000_000_000},+ },+ "financialData": {+ "currentPrice": {"raw": 195.0},+ "targetMeanPrice": {"raw": 210.0},+ "recommendationKey": "buy",+ "numberOfAnalystOpinions": {"raw": 40},+ "returnOnEquity": {"raw": 1.47},+ },+ "earningsTrend": {+ "trend": [+ {+ "period": "0q",+ "endDate": "2026-06-30",+ "growth": {"raw": 0.08},+ "earningsEstimate": {+ "avg": {"raw": 1.34},+ "low": {"raw": 1.30},+ "high": {"raw": 1.40},+ "numberOfAnalysts": {"raw": 28},+ },+ "revenueEstimate": {"avg": {"raw": 89_000_000_000}},+ }+ ]+ },+ "institutionOwnership": {+ "ownershipList": [+ {+ "organization": "Vanguard Group Inc",+ "reportDate": {"raw": 1_711_843_200},+ "pctHeld": {"raw": 0.084},+ "position": {"raw": 1_300_000_000},+ "value": {"raw": 250_000_000_000},+ }+ ]+ },+ "insiderHolders": {+ "holders": [+ {+ "name": "COOK TIMOTHY D",+ "relation": "Chief Executive Officer",+ "latestTransDate": "2026-04-01",+ "positionDirect": {"raw": 3_280_000},+ }+ ]+ },+ "recommendationTrend": {+ "trend": [+ {+ "period": "0m",+ "strongBuy": 12,+ "buy": 20,+ "hold": 8,+ "sell": 1,+ "strongSell": 0,+ }+ ]+ },+ }+++class TestStockProfileSuccess:+ """Happy-path envelope shape and section shaping."""++ def test_default_returns_all_sections(self):+ with patch.object(+ sp, "get_quote_summary", return_value=_sample_summary()+ ) as mock_get:+ out = sp.StockProfileTool().execute(ticker="AAPL.US")++ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["market"] == "us"+ assert payload["source"] == "yahoo"+ data = payload["data"]+ assert data["ticker"] == "AAPL.US"+ assert set(data["sections"]) == set(sp._ALL_SECTIONS)++ # raw cells are unwrapped to scalars.+ assert data["sections"]["key_stats"]["forwardPE"] == 28.5+ assert data["sections"]["financials"]["recommendationKey"] == "buy"++ # list sections are projected into compact rows.+ est = data["sections"]["earnings_trend"][0]+ assert est["period"] == "0q"+ assert est["eps_avg"] == 1.34+ assert est["eps_analysts"] == 28++ inst = data["sections"]["institution_ownership"][0]+ assert inst["organization"] == "Vanguard Group Inc"+ assert inst["pct_held"] == 0.084++ insider = data["sections"]["insider_holders"][0]+ assert insider["name"] == "COOK TIMOTHY D"+ assert insider["position"] == 3_280_000++ rec = data["sections"]["recommendation_trend"][0]+ assert rec["strong_buy"] == 12++ # Default fans out to all six Yahoo modules.+ _, args, kwargs = mock_get.mock_calls[0]+ requested_modules = args[1]+ assert "defaultKeyStatistics" in requested_modules+ assert "recommendationTrend" in requested_modules+ assert len(requested_modules) == len(sp._ALL_SECTIONS)++ def test_section_subset_only_requests_those_modules(self):+ with patch.object(+ sp, "get_quote_summary", return_value=_sample_summary()+ ) as mock_get:+ out = sp.StockProfileTool().execute(+ ticker="00700.HK", sections=["financials", "financials"]+ )++ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["market"] == "hk"+ # De-duplicated subset only.+ assert list(payload["data"]["sections"]) == ["financials"]++ _, args, _ = mock_get.mock_calls[0]+ assert args[1] == ["financialData"]++ def test_missing_module_yields_empty_shaped_section(self):+ # Yahoo can omit a module for a symbol; shaper must not crash.+ with patch.object(sp, "get_quote_summary", return_value={}):+ out = sp.StockProfileTool().execute(+ ticker="AAPL.US", sections=["key_stats", "insider_holders"]+ )+ data = json.loads(out)["data"]["sections"]+ assert data["key_stats"]["forwardPE"] is None+ assert data["insider_holders"] == []+++class TestStockProfileErrors:+ """Error envelopes: missing ticker, bad section, upstream failure."""++ def test_missing_ticker_returns_error_envelope(self):+ out = sp.StockProfileTool().execute(ticker=" ")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "required" in payload["error"]++ def test_unknown_section_returns_error_envelope(self):+ out = sp.StockProfileTool().execute(ticker="AAPL.US", sections=["bogus"])+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "unknown section" in payload["error"]++ def test_upstream_failure_becomes_error_envelope(self):+ with patch.object(+ sp, "get_quote_summary", side_effect=RuntimeError("HTTP 429 banned")+ ):+ out = sp.StockProfileTool().execute(ticker="AAPL.US")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "yahoo quoteSummary request failed" in payload["error"]+ assert "429" in payload["error"]diff --git a/agent/tests/test_stooq_loader.py b/agent/tests/test_stooq_loader.pynew file mode 100644index 000000000..055aa22a0--- /dev/null+++ b/agent/tests/test_stooq_loader.py@@ -0,0 +1,176 @@+"""Tests for stooq_loader: symbol mapping, CSV parsing, batch isolation, errors.++All HTTP is mocked — no test reaches a live Stooq endpoint. The loader imports+``throttled_get`` from :mod:`backtest.loaders._http` into its own namespace, so+we monkeypatch that name on the ``stooq_loader`` module.+"""++from __future__ import annotations++from typing import Any, Dict, List++import pandas as pd+import pytest+import requests++from backtest.loaders import stooq_loader++_CSV = (+ "Date,Open,High,Low,Close,Volume\n"+ "2024-01-03,184.22,185.88,183.43,184.25,58414460\n"+ "2024-01-02,187.15,188.44,183.89,185.64,82488700\n"+)+++class _FakeResponse:+ """Minimal stand-in for ``requests.Response`` used by throttled_get."""++ def __init__(self, *, status_code: int = 200, text: str = "") -> None:+ self.status_code = status_code+ self.text = text++ def raise_for_status(self) -> None:+ if self.status_code >= 400:+ raise requests.HTTPError(f"status {self.status_code}")+++# ---------------------------------------------------------------------------+# Loader contract / registration+# ---------------------------------------------------------------------------+++class TestLoaderContract:+ """Static attributes and availability."""++ def test_attributes(self):+ loader = stooq_loader.DataLoader()+ assert loader.name == "stooq"+ assert loader.markets == {"us_equity"}+ assert loader.requires_auth is False+ assert loader.is_available() is True+++# ---------------------------------------------------------------------------+# Symbol mapping+# ---------------------------------------------------------------------------+++class TestMapSymbol:+ """Vibe-Trading -> Stooq ticker translation."""++ def test_us_lowercased(self):+ assert stooq_loader.map_symbol("AAPL.US") == "aapl.us"++ def test_strips_and_lowercases(self):+ assert stooq_loader.map_symbol(" MSFT.US ") == "msft.us"+++# ---------------------------------------------------------------------------+# CSV parsing via fetch+# ---------------------------------------------------------------------------+++class TestFetch:+ """End-to-end fetch with throttled_get mocked."""++ def test_parses_csv_into_sorted_ohlcv(self, monkeypatch):+ captured: Dict[str, Any] = {}++ def fake_get(url, **kwargs):+ captured["url"] = url+ captured["params"] = kwargs.get("params")+ captured["host_key"] = kwargs.get("host_key")+ return _FakeResponse(text=_CSV)++ monkeypatch.setattr(stooq_loader, "throttled_get", fake_get)++ out = stooq_loader.DataLoader().fetch(+ ["AAPL.US"], "2024-01-01", "2024-01-31",+ )++ assert captured["url"] == stooq_loader._BASE_URL+ assert captured["host_key"] == "stooq"+ assert captured["params"] == {+ "s": "aapl.us",+ "d1": "20240101",+ "d2": "20240131",+ "i": "d",+ }++ assert list(out) == ["AAPL.US"]+ df = out["AAPL.US"]+ assert df.index.name == "trade_date"+ assert isinstance(df.index, pd.DatetimeIndex)+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ # Sorted ascending: 01-02 before 01-03.+ assert list(df.index) == [pd.Timestamp("2024-01-02"), pd.Timestamp("2024-01-03")]+ assert df.loc[pd.Timestamp("2024-01-02"), "open"] == pytest.approx(187.15)+ assert df.loc[pd.Timestamp("2024-01-03"), "close"] == pytest.approx(184.25)+ assert df["volume"].dtype == float++ def test_nd_body_yields_no_data(self, monkeypatch):+ monkeypatch.setattr(+ stooq_loader, "throttled_get", lambda url, **kw: _FakeResponse(text="N/D\n")+ )+ out = stooq_loader.DataLoader().fetch(["BOGUS.US"], "2024-01-01", "2024-01-31")+ assert out == {}++ def test_empty_body_yields_no_data(self, monkeypatch):+ monkeypatch.setattr(+ stooq_loader, "throttled_get", lambda url, **kw: _FakeResponse(text=" ")+ )+ out = stooq_loader.DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")+ assert out == {}++ def test_one_bad_symbol_does_not_abort_batch(self, monkeypatch):+ def fake_get(url, **kwargs):+ symbol = kwargs["params"]["s"]+ if symbol == "boom.us":+ raise requests.ConnectionError("network down")+ return _FakeResponse(text=_CSV)++ monkeypatch.setattr(stooq_loader, "throttled_get", fake_get)++ out = stooq_loader.DataLoader().fetch(+ ["BOOM.US", "AAPL.US"], "2024-01-01", "2024-01-31",+ )+ # The failing symbol is skipped; the good one still comes through.+ assert list(out) == ["AAPL.US"]++ def test_http_error_skips_symbol(self, monkeypatch):+ monkeypatch.setattr(+ stooq_loader,+ "throttled_get",+ lambda url, **kw: _FakeResponse(status_code=429, text=""),+ )+ out = stooq_loader.DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")+ assert out == {}++ def test_invalid_date_range_raises(self):+ with pytest.raises(ValueError):+ stooq_loader.DataLoader().fetch(["AAPL.US"], "2024-02-01", "2024-01-01")+++# ---------------------------------------------------------------------------+# Direct CSV parser unit coverage+# ---------------------------------------------------------------------------+++class TestParseCsv:+ """`_parse_csv` edge handling."""++ def test_rows_with_nan_ohlc_dropped(self):+ body = (+ "Date,Open,High,Low,Close,Volume\n"+ "2024-01-02,,,,,\n"+ "2024-01-03,1,2,0.5,1.5,100\n"+ )+ df = stooq_loader._parse_csv(body)+ assert list(df.index) == [pd.Timestamp("2024-01-03")]++ def test_missing_columns_returns_none(self):+ assert stooq_loader._parse_csv("Date,Close\n2024-01-03,1.5\n") is None++ def test_all_rows_dropped_returns_none(self):+ body = "Date,Open,High,Low,Close,Volume\n2024-01-02,,,,,\n"+ assert stooq_loader._parse_csv(body) is Nonediff --git a/agent/tests/test_symbol_search_tool.py b/agent/tests/test_symbol_search_tool.pynew file mode 100644index 000000000..92bf9a3fc--- /dev/null+++ b/agent/tests/test_symbol_search_tool.py@@ -0,0 +1,212 @@+"""Tests for the search_symbol tool.++All HTTP is mocked at the client functions the tool imports+(``eastmoney_client.get_json``, ``yahoo_client.search``,+``sec_edgar_client.cik_for``), so no test ever reaches a live endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from src.tools import symbol_search_tool as ss+++def _eastmoney_payload() -> dict:+ """A suggest payload spanning A-share, HK, and US markets."""+ return {+ "QuotationCodeTable": {+ "Data": [+ {+ "QuoteID": "1.600519",+ "Code": "600519",+ "Name": "贵州茅台",+ "MktNum": "1",+ "SecurityTypeName": "沪A",+ },+ {+ "QuoteID": "116.00700",+ "Code": "00700",+ "Name": "腾讯控股",+ "MktNum": "116",+ "SecurityTypeName": "港股",+ },+ {+ "QuoteID": "105.AAPL",+ "Code": "AAPL",+ "Name": "苹果",+ "MktNum": "105",+ "SecurityTypeName": "美股",+ },+ {+ # Unmappable market (e.g. a fund/board) -> dropped, not fatal.+ "QuoteID": "90.BK0001",+ "Code": "BK0001",+ "Name": "板块",+ "MktNum": "90",+ "SecurityTypeName": "板块",+ },+ ]+ }+ }+++def _yahoo_quotes() -> list:+ return [+ {+ "symbol": "AAPL",+ "shortname": "Apple Inc.",+ "exchange": "NMS",+ "quoteType": "EQUITY",+ },+ {+ "symbol": "0700.HK",+ "shortname": "TENCENT",+ "exchange": "HKG",+ "quoteType": "EQUITY",+ },+ {+ "symbol": "BTC-USD",+ "shortname": "Bitcoin USD",+ "exchange": "CCC",+ "quoteType": "CRYPTOCURRENCY",+ },+ {"symbol": "", "shortname": "no symbol"}, # dropped+ ]+++class TestSymbolSearchSuccess:+ """Happy-path fan-out, normalization, merge, and CIK enrichment."""++ def test_merges_and_normalizes_across_sources(self):+ with patch.object(+ ss.eastmoney_client, "get_json", return_value=_eastmoney_payload()+ ), patch.object(+ ss.yahoo_client, "search", return_value=_yahoo_quotes()+ ), patch.object(+ ss.sec_edgar_client, "cik_for", return_value="0000320193"+ ):+ out = ss.SymbolSearchTool().execute(query="apple", limit=10)++ payload = json.loads(out)+ assert payload["ok"] is True+ assert payload["market"] == "multi"+ assert payload["source"] == "symbol_search"++ data = payload["data"]+ assert data["query"] == "apple"+ assert data["sources"]["eastmoney"] == "ok"+ assert data["sources"]["yahoo"] == "ok"+ assert data["sources"]["sec_edgar"] == "ok"++ by_symbol = {c["symbol"]: c for c in data["candidates"]}++ # A-share secid -> 600519.SH, market cn.+ assert by_symbol["600519.SH"]["market"] == "cn"+ assert by_symbol["600519.SH"]["name"] == "贵州茅台"++ # HK code zero-padded to 5 digits from both Eastmoney and Yahoo, merged.+ assert "00700.HK" in by_symbol+ assert by_symbol["00700.HK"]["market"] == "hk"+ assert "yahoo" in by_symbol["00700.HK"].get("also_from", [])++ # US equity: Eastmoney + Yahoo merge, SEC CIK attached.+ aapl = by_symbol["AAPL.US"]+ assert aapl["market"] == "us"+ assert aapl["cik"] == "0000320193"+ assert "yahoo" in aapl.get("also_from", [])++ # Crypto keeps its native Yahoo symbol and a global market label.+ assert by_symbol["BTC-USD"]["market"] == "global"++ # Unmappable Eastmoney market dropped; empty Yahoo symbol dropped.+ assert "BK0001" not in by_symbol+ assert data["count"] == len(data["candidates"])++ def test_limit_clamped_and_applied(self):+ with patch.object(+ ss.eastmoney_client, "get_json", return_value=_eastmoney_payload()+ ), patch.object(+ ss.yahoo_client, "search", return_value=_yahoo_quotes()+ ), patch.object(+ ss.sec_edgar_client, "cik_for", return_value=None+ ):+ out = ss.SymbolSearchTool().execute(query="x", limit=2)+ payload = json.loads(out)+ assert payload["data"]["count"] == 2++ def test_no_us_candidate_omits_sec_source(self):+ em = {+ "QuotationCodeTable": {+ "Data": [+ {+ "QuoteID": "1.600519",+ "Code": "600519",+ "Name": "贵州茅台",+ "MktNum": "1",+ }+ ]+ }+ }+ with patch.object(+ ss.eastmoney_client, "get_json", return_value=em+ ), patch.object(+ ss.yahoo_client, "search", return_value=[]+ ), patch.object(+ ss.sec_edgar_client, "cik_for"+ ) as mock_cik:+ out = ss.SymbolSearchTool().execute(query="茅台")+ payload = json.loads(out)+ assert "sec_edgar" not in payload["data"]["sources"]+ mock_cik.assert_not_called()+++class TestSymbolSearchErrors:+ """Error envelopes and per-source resilience."""++ def test_missing_query_returns_error_envelope(self):+ out = ss.SymbolSearchTool().execute(query=" ")+ payload = json.loads(out)+ assert payload["ok"] is False+ assert "required" in payload["error"]++ def test_one_source_failure_does_not_abort_others(self):+ with patch.object(+ ss.eastmoney_client,+ "get_json",+ side_effect=RuntimeError("HTTP 429 banned"),+ ), patch.object(+ ss.yahoo_client, "search", return_value=_yahoo_quotes()+ ), patch.object(+ ss.sec_edgar_client, "cik_for", return_value="0000320193"+ ):+ out = ss.SymbolSearchTool().execute(query="apple")++ payload = json.loads(out)+ # Overall call still succeeds with the surviving source's hits.+ assert payload["ok"] is True+ sources = payload["data"]["sources"]+ assert "eastmoney search failed" in sources["eastmoney"]+ assert "429" in sources["eastmoney"]+ assert sources["yahoo"] == "ok"+ symbols = {c["symbol"] for c in payload["data"]["candidates"]}+ assert "AAPL.US" in symbols++ def test_sec_lookup_failure_recorded_not_fatal(self):+ with patch.object(+ ss.eastmoney_client, "get_json", return_value=_eastmoney_payload()+ ), patch.object(+ ss.yahoo_client, "search", return_value=[]+ ), patch.object(+ ss.sec_edgar_client,+ "cik_for",+ side_effect=RuntimeError("tickers fetch failed"),+ ):+ out = ss.SymbolSearchTool().execute(query="apple")+ payload = json.loads(out)+ assert payload["ok"] is True+ assert "sec lookup failed" in payload["data"]["sources"]["sec_edgar"]+ # The US candidate still appears, just without a CIK.+ aapl = next(c for c in payload["data"]["candidates"] if c["symbol"] == "AAPL.US")+ assert "cik" not in aapldiff --git a/agent/tests/test_tiingo_loader.py b/agent/tests/test_tiingo_loader.pynew file mode 100644index 000000000..721e62c4e--- /dev/null+++ b/agent/tests/test_tiingo_loader.py@@ -0,0 +1,202 @@+"""Tests for the Tiingo US-equity OHLCV loader.++All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported+into the loader module as ``throttled_get_json``), so no test touches a live+Tiingo endpoint.+"""++from __future__ import annotations++from unittest.mock import patch++import pandas as pd+import pytest++from backtest.loaders.tiingo_loader import (+ DataLoader,+ _resolve_key,+ _rows_to_frame,+ _to_tiingo_symbol,+)+++# ---------------------------------------------------------------------------+# Symbol mapping+# ---------------------------------------------------------------------------+++ "code, expected",+ [+ ("AAPL.US", "aapl"),+ ("AAPL", "aapl"),+ ("msft", "msft"),+ ("BRK", "brk"),+ ("00700.HK", None), # HK suffix+ ("000001.SZ", None), # A-share suffix+ ("BTC-USDT", None), # crypto pair+ ("", None),+ ],+)+def test_to_tiingo_symbol(code: str, expected) -> None:+ assert _to_tiingo_symbol(code) == expected+++# ---------------------------------------------------------------------------+# Key resolution / availability+# ---------------------------------------------------------------------------+++def test_is_available_false_without_key(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("TIINGO_API_KEY", raising=False)+ assert DataLoader().is_available() is False+++def test_is_available_false_for_placeholder(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TIINGO_API_KEY", "your_tiingo_api_key")+ assert DataLoader().is_available() is False+ assert _resolve_key() == ""+++def test_is_available_true_with_key(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TIINGO_API_KEY", "real-token-123")+ assert DataLoader().is_available() is True+++# ---------------------------------------------------------------------------+# Row parsing+# ---------------------------------------------------------------------------+++def _sample_rows() -> list[dict]:+ return [+ {+ "date": "2024-01-02T00:00:00.000Z",+ "open": 187.15,+ "high": 188.44,+ "low": 183.89,+ "close": 185.64,+ "volume": 82488700,+ },+ {+ "date": "2024-01-03T00:00:00.000Z",+ "open": 184.22,+ "high": 185.88,+ "low": 183.43,+ "close": 184.25,+ "volume": 58414500,+ },+ ]+++def test_rows_to_frame_shape_and_dtypes() -> None:+ df = _rows_to_frame(_sample_rows())+ assert df is not None+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"+ assert isinstance(df.index, pd.DatetimeIndex)+ assert df.index.tz is None+ assert all(str(df[col].dtype) == "float64" for col in df.columns)+ assert len(df) == 2+ assert df.index[0] == pd.Timestamp("2024-01-02")+++def test_rows_to_frame_empty_returns_none() -> None:+ assert _rows_to_frame([]) is None+ assert _rows_to_frame([{"open": 1.0}]) is None # no date field+++def test_rows_to_frame_drops_rows_missing_ohlc() -> None:+ rows = _sample_rows() + [{"date": "2024-01-04T00:00:00.000Z", "volume": 100}]+ df = _rows_to_frame(rows)+ assert df is not None+ assert len(df) == 2 # row with no OHLC dropped+++# ---------------------------------------------------------------------------+# fetch() behavior (HTTP mocked)+# ---------------------------------------------------------------------------+++def test_fetch_returns_normalized_frame(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TIINGO_API_KEY", "real-token-123")+ with patch(+ "backtest.loaders.tiingo_loader.throttled_get_json",+ return_value=_sample_rows(),+ ) as mock_get:+ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-05")++ assert "AAPL.US" in out+ df = out["AAPL.US"]+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"+ assert len(df) == 2+ # URL uses the bare lower-cased ticker; key + dates passed as params.+ url = mock_get.call_args.args[0]+ assert url.endswith("/tiingo/daily/aapl/prices")+ params = mock_get.call_args.kwargs["params"]+ assert params["token"] == "real-token-123"+ assert params["startDate"] == "2024-01-01"+ assert params["endDate"] == "2024-01-05"+ assert mock_get.call_args.kwargs["host_key"] == "tiingo"+++def test_fetch_without_key_returns_empty(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("TIINGO_API_KEY", raising=False)+ with patch("backtest.loaders.tiingo_loader.throttled_get_json") as mock_get:+ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-05")+ assert out == {}+ mock_get.assert_not_called() # no key -> no HTTP+++def test_fetch_skips_non_us_symbols(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TIINGO_API_KEY", "real-token-123")+ with patch("backtest.loaders.tiingo_loader.throttled_get_json") as mock_get:+ out = DataLoader().fetch(["00700.HK", "BTC-USDT"], "2024-01-01", "2024-01-05")+ assert out == {}+ mock_get.assert_not_called() # symbols rejected before any request+++def test_fetch_one_bad_symbol_does_not_abort_batch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("TIINGO_API_KEY", "real-token-123")++ def fake_get(url, **kwargs):+ if "/aapl/" in url:+ raise RuntimeError("boom")+ return _sample_rows()++ with patch("backtest.loaders.tiingo_loader.throttled_get_json", side_effect=fake_get):+ out = DataLoader().fetch(["AAPL.US", "MSFT.US"], "2024-01-01", "2024-01-05")++ assert "AAPL.US" not in out # failing symbol skipped+ assert "MSFT.US" in out # batch continued+++def test_fetch_empty_payload_omits_symbol(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TIINGO_API_KEY", "real-token-123")+ with patch("backtest.loaders.tiingo_loader.throttled_get_json", return_value=[]):+ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-05")+ assert out == {}+++def test_fetch_rejects_bad_date_range(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TIINGO_API_KEY", "real-token-123")+ with pytest.raises(ValueError):+ DataLoader().fetch(["AAPL.US"], "2024-02-01", "2024-01-01")+++# ---------------------------------------------------------------------------+# Registry integration+# ---------------------------------------------------------------------------+++def test_loader_self_registers() -> None:+ import backtest.loaders.tiingo_loader # noqa: F401 (import triggers @register)+ from backtest.loaders.registry import LOADER_REGISTRY++ assert "tiingo" in LOADER_REGISTRY+ cls = LOADER_REGISTRY["tiingo"]+ assert cls.markets == {"us_equity"}+ assert cls.requires_auth is Truediff --git a/agent/tests/test_yahoo_client.py b/agent/tests/test_yahoo_client.pynew file mode 100644index 000000000..07abb5b5d--- /dev/null+++ b/agent/tests/test_yahoo_client.py@@ -0,0 +1,369 @@+"""Tests for yahoo_client: symbol mapping, payload parsing, crumb retry, errors.++All HTTP is mocked — no test ever reaches a live Yahoo endpoint. The client+imports ``throttled_get`` / ``throttled_get_json`` from+:mod:`backtest.loaders._http` into its own namespace, so we monkeypatch those+names on the ``yahoo_client`` module.+"""++from __future__ import annotations++from typing import Any, Dict, List, Optional++import pytest+import requests++from backtest.loaders import yahoo_client+++class _FakeResponse:+ """Minimal stand-in for ``requests.Response`` used by throttled_get."""++ def __init__(+ self,+ *,+ status_code: int = 200,+ text: str = "",+ json_body: Optional[Any] = None,+ cookies: Optional[Dict[str, str]] = None,+ ) -> None:+ self.status_code = status_code+ self.text = text+ self._json_body = json_body+ self.cookies = requests.utils.cookiejar_from_dict(cookies or {})++ def raise_for_status(self) -> None:+ if self.status_code >= 400:+ raise requests.HTTPError(f"status {self.status_code}")++ def json(self) -> Any:+ return self._json_body+++def _reset_crumb() -> None:+ """Clear the process-wide crumb cache so each test handshakes fresh."""+ yahoo_client._CRUMB_STORE = yahoo_client._CrumbStore()+++# ---------------------------------------------------------------------------+# Symbol mapping+# ---------------------------------------------------------------------------+++class TestMapSymbol:+ """Vibe-Trading -> Yahoo ticker translation."""++ def test_us_suffix_stripped(self):+ assert yahoo_client.map_symbol("AAPL.US") == "AAPL"+ assert yahoo_client.map_symbol("aapl.us") == "aapl"++ def test_hk_normalized_to_four_digits(self):+ assert yahoo_client.map_symbol("00700.HK") == "0700.HK"+ assert yahoo_client.map_symbol("09988.HK") == "9988.HK"++ def test_hk_already_four_digits_unchanged(self):+ assert yahoo_client.map_symbol("0700.HK") == "0700.HK"++ def test_passthrough_for_other_symbols(self):+ assert yahoo_client.map_symbol("BTC-USD") == "BTC-USD"+ assert yahoo_client.map_symbol("^GSPC") == "^GSPC"+++# ---------------------------------------------------------------------------+# get_chart parsing+# ---------------------------------------------------------------------------+++class TestGetChart:+ """v8 chart payload -> ascending OHLCV rows."""++ def test_parses_ascending_rows_and_maps_symbol(self, monkeypatch):+ captured: Dict[str, Any] = {}++ def fake_get_json(url, **kwargs):+ captured["url"] = url+ captured["params"] = kwargs.get("params")+ return {+ "chart": {+ "error": None,+ "result": [+ {+ "timestamp": [1700000000, 1700086400, 1700172800],+ "indicators": {+ "quote": [+ {+ "open": [10.0, 11.0, None],+ "high": [10.5, 11.5, None],+ "low": [9.5, 10.5, None],+ "close": [10.2, 11.2, None],+ "volume": [1000, 2000, None],+ }+ ]+ },+ }+ ],+ }+ }++ monkeypatch.setattr(yahoo_client, "throttled_get_json", fake_get_json)++ rows = yahoo_client.get_chart("AAPL.US", interval="1d", range_="5d")++ assert captured["url"].endswith("/AAPL")+ assert captured["params"] == {"interval": "1d", "range": "5d"}+ # Third bar has null OHLC and must be dropped.+ assert len(rows) == 2+ assert rows[0] == {+ "trade_date": 1700000000,+ "open": 10.0,+ "high": 10.5,+ "low": 9.5,+ "close": 10.2,+ "volume": 1000.0,+ }+ assert rows[1]["trade_date"] == 1700086400++ def test_period_window_when_no_range(self, monkeypatch):+ captured: Dict[str, Any] = {}++ def fake_get_json(url, **kwargs):+ captured["params"] = kwargs.get("params")+ return {"chart": {"result": [{"timestamp": [], "indicators": {"quote": [{}]}}]}}++ monkeypatch.setattr(yahoo_client, "throttled_get_json", fake_get_json)++ rows = yahoo_client.get_chart("0700.HK", period1=100, period2=200)++ assert rows == []+ assert captured["params"] == {"interval": "1d", "period1": 100, "period2": 200}++ def test_chart_error_raises(self, monkeypatch):+ def fake_get_json(url, **kwargs):+ return {"chart": {"error": {"code": "Not Found", "description": "No data found"}}}++ monkeypatch.setattr(yahoo_client, "throttled_get_json", fake_get_json)++ with pytest.raises(ValueError, match="No data found"):+ yahoo_client.get_chart("BOGUS.US", range_="1d")+++# ---------------------------------------------------------------------------+# get_quote_summary crumb handshake + 401 retry+# ---------------------------------------------------------------------------+++class TestGetQuoteSummary:+ """v10 quoteSummary with the cookie+crumb handshake."""++ def test_handshake_then_success(self, monkeypatch):+ _reset_crumb()+ calls: List[str] = []++ def fake_get(url, **kwargs):+ calls.append(url)+ if url == yahoo_client._COOKIE_URL:+ return _FakeResponse(cookies={"A1": "token"})+ if url == yahoo_client._CRUMB_URL:+ assert kwargs["headers"]["Cookie"] == "A1=token"+ return _FakeResponse(text="the-crumb\n")+ # quoteSummary call+ assert kwargs["params"]["crumb"] == "the-crumb"+ assert kwargs["params"]["modules"] == "price,summaryDetail"+ assert kwargs["headers"]["Cookie"] == "A1=token"+ return _FakeResponse(+ json_body={"quoteSummary": {"error": None, "result": [{"price": {"symbol": "AAPL"}}]}}+ )++ monkeypatch.setattr(yahoo_client, "throttled_get", fake_get)++ result = yahoo_client.get_quote_summary("AAPL.US", ["price", "summaryDetail"])++ assert result == {"price": {"symbol": "AAPL"}}+ # cookie + crumb handshake, then the data call.+ assert calls.count(yahoo_client._COOKIE_URL) == 1+ assert calls.count(yahoo_client._CRUMB_URL) == 1++ def test_401_triggers_single_crumb_refresh(self, monkeypatch):+ _reset_crumb()+ crumbs = iter(["stale-crumb", "fresh-crumb"])+ summary_attempts: List[str] = []++ def fake_get(url, **kwargs):+ if url == yahoo_client._COOKIE_URL:+ return _FakeResponse(cookies={"A1": "c"})+ if url == yahoo_client._CRUMB_URL:+ return _FakeResponse(text=next(crumbs))+ crumb = kwargs["params"]["crumb"]+ summary_attempts.append(crumb)+ if crumb == "stale-crumb":+ return _FakeResponse(status_code=401)+ return _FakeResponse(json_body={"quoteSummary": {"result": [{"ok": True}]}})++ monkeypatch.setattr(yahoo_client, "throttled_get", fake_get)++ result = yahoo_client.get_quote_summary("MSFT", ["price"])++ assert result == {"ok": True}+ # First attempt with stale crumb 401s, refreshed crumb succeeds.+ assert summary_attempts == ["stale-crumb", "fresh-crumb"]++ def test_persistent_401_propagates(self, monkeypatch):+ _reset_crumb()++ def fake_get(url, **kwargs):+ if url == yahoo_client._COOKIE_URL:+ return _FakeResponse(cookies={"A1": "c"})+ if url == yahoo_client._CRUMB_URL:+ return _FakeResponse(text="any-crumb")+ return _FakeResponse(status_code=401)++ monkeypatch.setattr(yahoo_client, "throttled_get", fake_get)++ with pytest.raises(requests.HTTPError):+ yahoo_client.get_quote_summary("MSFT", ["price"])++ def test_empty_crumb_raises(self, monkeypatch):+ _reset_crumb()++ def fake_get(url, **kwargs):+ if url == yahoo_client._COOKIE_URL:+ return _FakeResponse(cookies={"A1": "c"})+ return _FakeResponse(text=" ")++ monkeypatch.setattr(yahoo_client, "throttled_get", fake_get)++ with pytest.raises(ValueError, match="empty crumb"):+ yahoo_client.get_quote_summary("MSFT", ["price"])+++# ---------------------------------------------------------------------------+# get_options + search+# ---------------------------------------------------------------------------+++class TestGetOptions:+ """v7 option chain — now behind the same cookie+crumb handshake."""++ def test_handshake_carries_crumb_and_cookie(self, monkeypatch):+ _reset_crumb()+ captured: Dict[str, Any] = {}+ calls: List[str] = []++ def fake_get(url, **kwargs):+ calls.append(url)+ if url == yahoo_client._COOKIE_URL:+ return _FakeResponse(cookies={"A1": "token"})+ if url == yahoo_client._CRUMB_URL:+ assert kwargs["headers"]["Cookie"] == "A1=token"+ return _FakeResponse(text="the-crumb\n")+ # options call must carry both the crumb param and the cookie.+ captured["url"] = url+ captured["params"] = kwargs.get("params")+ captured["headers"] = kwargs.get("headers")+ return _FakeResponse(+ json_body={"optionChain": {"result": [{"expirationDates": [1, 2]}]}}+ )++ monkeypatch.setattr(yahoo_client, "throttled_get", fake_get)++ result = yahoo_client.get_options("00700.HK", expiration=1700000000)++ assert captured["url"].endswith("/0700.HK")+ assert captured["params"] == {"crumb": "the-crumb", "date": 1700000000}+ assert captured["headers"]["Cookie"] == "A1=token"+ assert result == {"expirationDates": [1, 2]}+ assert calls.count(yahoo_client._COOKIE_URL) == 1+ assert calls.count(yahoo_client._CRUMB_URL) == 1++ def test_401_triggers_single_crumb_refresh(self, monkeypatch):+ _reset_crumb()+ crumbs = iter(["stale-crumb", "fresh-crumb"])+ options_attempts: List[str] = []++ def fake_get(url, **kwargs):+ if url == yahoo_client._COOKIE_URL:+ return _FakeResponse(cookies={"A1": "c"})+ if url == yahoo_client._CRUMB_URL:+ return _FakeResponse(text=next(crumbs))+ crumb = kwargs["params"]["crumb"]+ options_attempts.append(crumb)+ if crumb == "stale-crumb":+ return _FakeResponse(status_code=401)+ return _FakeResponse(json_body={"optionChain": {"result": [{"ok": True}]}})++ monkeypatch.setattr(yahoo_client, "throttled_get", fake_get)++ result = yahoo_client.get_options("AAPL.US")++ assert result == {"ok": True}+ # Stale crumb 401s, refreshed crumb succeeds — exactly one refresh.+ assert options_attempts == ["stale-crumb", "fresh-crumb"]++ def test_persistent_401_propagates(self, monkeypatch):+ _reset_crumb()++ def fake_get(url, **kwargs):+ if url == yahoo_client._COOKIE_URL:+ return _FakeResponse(cookies={"A1": "c"})+ if url == yahoo_client._CRUMB_URL:+ return _FakeResponse(text="any-crumb")+ return _FakeResponse(status_code=401)++ monkeypatch.setattr(yahoo_client, "throttled_get", fake_get)++ with pytest.raises(requests.HTTPError):+ yahoo_client.get_options("MSFT")++ def test_no_date_param_when_expiration_omitted(self, monkeypatch):+ _reset_crumb()+ captured: Dict[str, Any] = {}++ def fake_get(url, **kwargs):+ if url == yahoo_client._COOKIE_URL:+ return _FakeResponse(cookies={"A1": "c"})+ if url == yahoo_client._CRUMB_URL:+ return _FakeResponse(text="crumb")+ captured["params"] = kwargs.get("params")+ return _FakeResponse(json_body={"optionChain": {"result": [{}]}})++ monkeypatch.setattr(yahoo_client, "throttled_get", fake_get)++ yahoo_client.get_options("AAPL.US")++ assert captured["params"] == {"crumb": "crumb"}++ def test_error_raises(self, monkeypatch):+ _reset_crumb()++ def fake_get(url, **kwargs):+ if url == yahoo_client._COOKIE_URL:+ return _FakeResponse(cookies={"A1": "c"})+ if url == yahoo_client._CRUMB_URL:+ return _FakeResponse(text="crumb")+ return _FakeResponse(+ json_body={"optionChain": {"error": {"description": "bad symbol"}}}+ )++ monkeypatch.setattr(yahoo_client, "throttled_get", fake_get)++ with pytest.raises(ValueError, match="bad symbol"):+ yahoo_client.get_options("NOPE.US")+++class TestSearch:+ """v1 search."""++ def test_filters_to_dict_quotes(self, monkeypatch):+ def fake_get_json(url, **kwargs):+ assert kwargs["params"] == {"q": "apple"}+ return {"quotes": [{"symbol": "AAPL"}, "garbage", {"symbol": "APLE"}]}++ monkeypatch.setattr(yahoo_client, "throttled_get_json", fake_get_json)++ quotes = yahoo_client.search("apple")++ assert quotes == [{"symbol": "AAPL"}, {"symbol": "APLE"}]++ def test_empty_payload_returns_empty(self, monkeypatch):+ monkeypatch.setattr(yahoo_client, "throttled_get_json", lambda url, **kw: {})+ assert yahoo_client.search("zzz") == []diff --git a/agent/tests/test_yahoo_loader.py b/agent/tests/test_yahoo_loader.pynew file mode 100644index 000000000..dac2769da--- /dev/null+++ b/agent/tests/test_yahoo_loader.py@@ -0,0 +1,282 @@+"""Tests for yahoo_loader: symbol gating, epoch window, frame normalization.++All network access is mocked at the loader's ``yahoo_client.get_chart`` import+site, so no test ever reaches a live Yahoo endpoint.+"""+from __future__ import annotations++import datetime as dt+from unittest.mock import patch++import pandas as pd++from backtest.loaders.yahoo_loader import (+ DataLoader,+ _epoch_seconds,+ _is_intraday_interval,+ _is_us_or_hk,+ _rows_to_frame,+ _to_yahoo_interval,+)+++def _epoch(date_str: str) -> int:+ """UTC-midnight epoch seconds for a date, used to build fake chart rows."""+ day = pd.Timestamp(date_str).date()+ return int(dt.datetime(day.year, day.month, day.day, tzinfo=dt.timezone.utc).timestamp())+++def _open_epoch(date_str: str) -> int:+ """Epoch seconds at 14:30 UTC (US market open) on *date_str*.++ Mirrors how Yahoo actually stamps daily bars: at the session open, not at+ midnight. Used to prove daily bars are normalized back to 00:00:00.+ """+ return _epoch(date_str) + 14 * 3600 + 30 * 60+++def _row(date_str: str, open_, high, low, close, volume):+ return {+ "trade_date": _epoch(date_str),+ "open": open_,+ "high": high,+ "low": low,+ "close": close,+ "volume": volume,+ }+++def _intraday_stamped_row(date_str: str, open_, high, low, close, volume):+ """A daily bar carrying Yahoo's real session-open epoch (14:30 UTC)."""+ row = _row(date_str, open_, high, low, close, volume)+ row["trade_date"] = _open_epoch(date_str)+ return row+++class TestSymbolGating:+ """_is_us_or_hk only accepts US/HK suffixes."""++ def test_accepts_us(self):+ assert _is_us_or_hk("AAPL.US") is True+ assert _is_us_or_hk("aapl.us") is True++ def test_accepts_hk(self):+ assert _is_us_or_hk("00700.HK") is True+ assert _is_us_or_hk("00700.hk") is True++ def test_rejects_others(self):+ assert _is_us_or_hk("601398.SH") is False+ assert _is_us_or_hk("BTC-USDT") is False+ assert _is_us_or_hk("") is False+++class TestIntervalMap:+ """_to_yahoo_interval maps project intervals to Yahoo's strings."""++ def test_daily(self):+ assert _to_yahoo_interval("1D") == "1d"++ def test_hourly(self):+ assert _to_yahoo_interval("1H") == "1h"++ def test_unknown_lowercased(self):+ assert _to_yahoo_interval("5m") == "5m"++ def test_empty_defaults_daily(self):+ assert _to_yahoo_interval("") == "1d"+++class TestIsIntradayInterval:+ """_is_intraday_interval splits minute/hour from day/week/month."""++ def test_daily_is_not_intraday(self):+ assert _is_intraday_interval("1D") is False+ assert _is_intraday_interval("1d") is False++ def test_weekly_monthly_not_intraday(self):+ assert _is_intraday_interval("1W") is False+ assert _is_intraday_interval("1M") is False+ assert _is_intraday_interval("1mo") is False++ def test_minute_and_hour_are_intraday(self):+ assert _is_intraday_interval("1H") is True+ assert _is_intraday_interval("5m") is True+ assert _is_intraday_interval("15min") is True++ def test_empty_defaults_daily(self):+ assert _is_intraday_interval("") is False+++class TestDailyIndexNormalization:+ """Daily-and-coarser bars normalize to midnight; intraday keep their time.++ Regression for B1-yahoo-ts: Yahoo stamps daily bars at the US session-open+ epoch (14:30 UTC). Left unnormalized that intraday time broke fallback+ merge/join/dedup against other loaders' midnight-indexed daily bars.+ """++ def test_daily_bars_indexed_at_midnight(self):+ rows = [+ _intraday_stamped_row("2024-01-02", 10, 11, 9, 10.5, 1000),+ _intraday_stamped_row("2024-01-03", 10.5, 12, 10, 11.5, 2000),+ ]+ df = _rows_to_frame(rows, "2024-01-01", "2024-01-31", "1D")+ assert len(df) == 2+ for ts in df.index:+ assert ts.hour == 0 and ts.minute == 0 and ts.second == 0+ assert ts == ts.normalize()++ def test_daily_index_matches_other_sources_date_index(self):+ rows = [+ _intraday_stamped_row("2024-01-02", 10, 11, 9, 10.5, 1000),+ _intraday_stamped_row("2024-01-03", 10.5, 12, 10, 11.5, 2000),+ ]+ df = _rows_to_frame(rows, "2024-01-01", "2024-01-31", "1D")+ # A peer loader's midnight-indexed daily index for the same dates.+ expected = pd.DatetimeIndex(+ [pd.Timestamp("2024-01-02"), pd.Timestamp("2024-01-03")],+ name="trade_date",+ )+ # Compare timestamps + name, not resolution units (s vs us).+ assert df.index.name == expected.name+ assert list(df.index) == list(expected)++ def test_intraday_bars_keep_their_timestamp(self):+ rows = [+ _intraday_stamped_row("2024-01-02", 10, 11, 9, 10.5, 1000),+ ]+ df = _rows_to_frame(rows, "2024-01-01", "2024-01-31", "1H")+ ts = df.index[0]+ assert ts.hour == 14 and ts.minute == 30++ def test_default_interval_normalizes_to_midnight(self):+ rows = [_intraday_stamped_row("2024-01-02", 10, 11, 9, 10.5, 1000)]+ df = _rows_to_frame(rows, "2024-01-01", "2024-01-31")+ assert df.index[0] == pd.Timestamp("2024-01-02")+++class TestEpochSeconds:+ """_epoch_seconds derives from the calendar date, not wall-clock time."""++ def test_matches_utc_midnight(self):+ assert _epoch_seconds("2024-01-02") == _epoch("2024-01-02")++ def test_is_deterministic(self):+ assert _epoch_seconds("2024-03-15") == _epoch_seconds("2024-03-15")+++class TestRowsToFrame:+ """_rows_to_frame normalizes, clips to the inclusive window, drops bad bars."""++ def test_empty_rows(self):+ assert _rows_to_frame([], "2024-01-01", "2024-01-31").empty++ def test_basic_shape_and_dtypes(self):+ rows = [+ _row("2024-01-02", 10, 11, 9, 10.5, 1000),+ _row("2024-01-03", 10.5, 12, 10, 11.5, 2000),+ ]+ df = _rows_to_frame(rows, "2024-01-01", "2024-01-31")+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"+ assert isinstance(df.index, pd.DatetimeIndex)+ assert df.index.tz is None+ assert all(str(df[col].dtype) == "float64" for col in df.columns)+ assert df.index.is_monotonic_increasing+ assert len(df) == 2++ def test_clips_to_inclusive_window(self):+ rows = [+ _row("2023-12-31", 1, 1, 1, 1, 1), # before start+ _row("2024-01-05", 2, 2, 2, 2, 2), # inside+ _row("2024-01-31", 3, 3, 3, 3, 3), # inclusive end retained+ _row("2024-02-01", 4, 4, 4, 4, 4), # after end+ ]+ df = _rows_to_frame(rows, "2024-01-01", "2024-01-31")+ dates = [ts.strftime("%Y-%m-%d") for ts in df.index]+ assert dates == ["2024-01-05", "2024-01-31"]++ def test_drops_bars_with_null_ohlc(self):+ rows = [+ _row("2024-01-02", 10, 11, 9, 10.5, 1000),+ _row("2024-01-03", None, 12, 10, 11.5, 2000), # null open -> dropped+ ]+ df = _rows_to_frame(rows, "2024-01-01", "2024-01-31")+ assert len(df) == 1+ assert df.index[0].strftime("%Y-%m-%d") == "2024-01-02"+++class TestFetch:+ """fetch dispatches per symbol, mocks get_chart, isolates failures."""++ def test_fetch_us_symbol(self):+ rows = [+ _row("2024-01-02", 10, 11, 9, 10.5, 1000),+ _row("2024-01-03", 10.5, 12, 10, 11.5, 2000),+ ]+ with patch(+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart",+ return_value=rows,+ ) as mock_chart:+ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")+ assert "AAPL.US" in out+ assert len(out["AAPL.US"]) == 2+ # Symbol passes through to the client unchanged (client maps it).+ assert mock_chart.call_args.args[0] == "AAPL.US"+ # period1/period2 derived from the dates; period2 is exclusive (+1 day).+ kwargs = mock_chart.call_args.kwargs+ assert kwargs["period1"] == _epoch("2024-01-01")+ assert kwargs["period2"] == _epoch("2024-01-31") + 86400+ assert kwargs["interval"] == "1d"++ def test_non_us_hk_symbol_skipped(self):+ with patch(+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart"+ ) as mock_chart:+ out = DataLoader().fetch(["601398.SH"], "2024-01-01", "2024-01-31")+ assert out == {}+ mock_chart.assert_not_called()++ def test_one_failure_does_not_abort_batch(self):+ good_rows = [_row("2024-01-02", 10, 11, 9, 10.5, 1000)]++ def fake_chart(symbol, **_kwargs):+ if symbol == "BAD.US":+ raise ValueError("yahoo chart error")+ return good_rows++ with patch(+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart",+ side_effect=fake_chart,+ ):+ out = DataLoader().fetch(+ ["BAD.US", "GOOD.US"], "2024-01-01", "2024-01-31"+ )+ assert "BAD.US" not in out+ assert "GOOD.US" in out++ def test_empty_codes_short_circuits(self):+ with patch(+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart"+ ) as mock_chart:+ assert DataLoader().fetch([], "2024-01-01", "2024-01-31") == {}+ mock_chart.assert_not_called()++ def test_no_data_symbol_omitted(self):+ with patch(+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart",+ return_value=[],+ ):+ out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")+ assert out == {}+++class TestLoaderMetadata:+ """Static loader attributes match the registry contract."""++ def test_name_and_markets(self):+ loader = DataLoader()+ assert loader.name == "yahoo"+ assert loader.markets == {"us_equity", "hk_equity"}+ assert loader.requires_auth is False+ assert loader.is_available() is True