"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(tools): get_fund_nav — NAV history for Chinese off-exchange funds
sambazhu1620acef0199
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0a12d9f02..96abe046b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,16 @@ This project adheres to [Semantic Versioning](https://semver.org/).### Added+- **`get_fund_nav`: NAV history for Chinese off-exchange funds (场外基金).**+ Off-exchange funds publish no OHLCV bars — their series is the daily NAV —+ so this lands as an agent tool (`NetFundUnitValueReport` behind the same+ recall+cache machinery as the loader) instead of stretching the loader+ contract. Serves unit NAV (单位净值), accumulated NAV (累计净值),+ dividend-adjusted NAV (复权净值) and the daily growth rate, ascending,+ most-recent `limit` rows, per-fund errors never abort the batch.+ Exchange-listed ETF/LOF codes are rejected with a pointer to+ `get_market_data`. Key-gated on `GILDATA_TOKEN`; exposed as MCP tool #75.+- **Gildata (恒生聚源) now serves HK equities and CN indices too.** HK symbols(`00700.HK`) route to `HKStockDailyQuotes`, CN index codes (`000300.SH`,`399xxx.SZ` — exchange-specific, so `000001.SZ` stays Ping An Bank) route todiff --git a/README.md b/README.mdindex 442cbf106..ade15c7f6 100644--- a/README.md+++ b/README.md@@ -93,7 +93,7 @@- **2026-08-23** 🔌 **The IBKR MCP seed named the wrong URL, and closing one LLM adapter closed them all**: The seeded official IBKR read-only MCP profile, the README and `SKILL.md` all pointed at `https://api.ibkr.com/v1/api/mcp`; IBKR's own AI-integration page publishes `https://api.ibkr.com/v1/api/mcp-public`, and the seed, all six READMEs and `SKILL.md` now name it — re-run `vibe-trading connector configure ibkr-live-official-mcp-readonly --yes` if your `agent.json` still carries the old URL. The OAuth client-registration step that IBKR's gateway rejects is still open in [#1126](https://github.com/HKUDS/Vibe-Trading/issues/1126) ([#1178](https://github.com/HKUDS/Vibe-Trading/pull/1178)). **Fixed:** `ChatLLM.close()` closed LangChain's process-wide cached HTTPX clients, so one finished title-generation or image-vision call left every later request failing with "client has been closed" until a restart — only transports Vibe-Trading created itself are closed now ([#1182](https://github.com/HKUDS/Vibe-Trading/pull/1182)); a service restart mid-reply dropped the streamed text and left the attempt *running* forever — partial replies are now checkpointed and reconciled as an explicit *interrupted* transcript entry on the next start ([#1180](https://github.com/HKUDS/Vibe-Trading/pull/1180)). **New:** Web chat attaches up to five files per turn through the picker, drag-and-drop, or clipboard paste ([#1179](https://github.com/HKUDS/Vibe-Trading/pull/1179)). Thanks [@c020627](https://github.com/c020627) and [@AirHua-byte](https://github.com/AirHua-byte)!- **2026-08-22** 💼 **A Portfolio page — your holdings across brokers, read-only**: Pick any read-only connector profiles (connection instances over `account.read` + `positions.read`; the IBKR official-MCP profile is not yet eligible) and the new `/portfolio` page aggregates them into immutable snapshots with per-source provenance, USD/CNY valuation, CSV export and a history chart. A source that fails to refresh is reported as an **error and excluded from the totals** — never carried forward — and the snapshot is marked incomplete. The `portfolio_summary` agent tool returns `risk_xray_args` that feed the existing `portfolio_risk_xray`, and `vibe-trading portfolio show|refresh|sources` prints the same snapshot in the terminal. Read-only connector plugins you write yourself live under `~/.vibe-trading/connectors/` (a manifest declaring any write capability is rejected; secrets go to the OS keyring via the `[keyring]` extra), and nothing on this path can place an order ([#1072](https://github.com/HKUDS/Vibe-Trading/pull/1072), toward [#1171](https://github.com/HKUDS/Vibe-Trading/issues/1171)). **Fixed:** thirteen Alpha Zoo factors forward-filled a missing close before computing returns, turning a data gap into a finite "0% return" — the gap now stays `NaN` ([#1172](https://github.com/HKUDS/Vibe-Trading/pull/1172)); independent MCP clients on one http/sse server shared a single fallback research-goal session ([#1173](https://github.com/HKUDS/Vibe-Trading/pull/1173)); memory GC and compression left stale FTS rows and orphaned relation sidecars ([#1174](https://github.com/HKUDS/Vibe-Trading/pull/1174)); `cancel_run()` never reached a swarm worker already streaming — the stop now interrupts the stream, skips that turn's tool calls and lands as a *cancelled* task ([#1175](https://github.com/HKUDS/Vibe-Trading/pull/1175)); MCP `get_research_reports` dropped `beginTime`/`endTime` ([#1176](https://github.com/HKUDS/Vibe-Trading/pull/1176)); `get_options_chain` answered a wrong-cycle expiration with `ok: true` and another date's contracts ([#1177](https://github.com/HKUDS/Vibe-Trading/pull/1177)). Thanks [@goatyyc](https://github.com/goatyyc), [@Shizoqua](https://github.com/Shizoqua) and [@cgycorey](https://github.com/cgycorey)!- **2026-08-21** ⏱️ **Runs that hung forever**: A `bash` timeout killed the shell but not the grandchildren holding its pipe handles, so a run sat "running" for 20+ minutes. Commands now spawn in their own process group, a timeout kills the whole tree, a stall watchdog ends a run making no forward progress, and compaction stopped discarding the model's own verification records ([#1169](https://github.com/HKUDS/Vibe-Trading/pull/1169)). **Fixed:** multi-year Tencent history silently truncated at 500 bars ([#1154](https://github.com/HKUDS/Vibe-Trading/pull/1154)). **New:** swarm runs replay only their failed subgraph ([#1158](https://github.com/HKUDS/Vibe-Trading/pull/1158), closes [#1157](https://github.com/HKUDS/Vibe-Trading/issues/1157)); Market Watch shows each monitor's latest verdict inline ([#1156](https://github.com/HKUDS/Vibe-Trading/pull/1156), closes [#943](https://github.com/HKUDS/Vibe-Trading/issues/943)); `quantlib` reaches 286 tested functions ([#1159](https://github.com/HKUDS/Vibe-Trading/pull/1159)–[#1168](https://github.com/HKUDS/Vibe-Trading/pull/1168)). Thanks [@wiliao](https://github.com/wiliao), [@cgycorey](https://github.com/cgycorey), [@he-yufeng](https://github.com/he-yufeng), [@BigFishEmily](https://github.com/BigFishEmily), [@santhreal](https://github.com/santhreal), [@SiMinus](https://github.com/SiMinus), and [@alinv0](https://github.com/alinv0)!-- **2026-08-20** 🚀 **v0.1.14 released** ([Release notes](https://github.com/HKUDS/Vibe-Trading/releases/tag/v0.1.14), `pip install -U vibe-trading-ai`): 272 commits and 74 merged pull requests since 0.1.13. **The headline is that a finished backtest is now something you can read rather than a folder of CSVs.** Run Detail grows four tabs — **Factor Research** (IC series with its mean line, IC statistics, quantile-group equity, and a pairwise IC correlation matrix that existed nowhere before), **Positions** (weight pie/treemap on a date slider, sector net-exposure bars, weight-evolution area — the pie is gross composition and the bars are net, so a long/short pair in one sector nets to zero on the bars while both legs stay visible on the pie), **Tearsheet** (monthly-returns heatmap, annual bars, top-5 drawdowns annotated onto the equity curve), and an interactive **research dashboard** with KPIs, benchmark-relative equity, rolling Sharpe and the full trade ledger. All four read artifacts a run already writes — no new pipeline. A new **Options Lab** page adds an expiry payoff diagram, a spot×IV scenario matrix, portfolio Greeks and a live options chain, computed through the same test-pinned engine the MCP tools use. **Install:** Intel Macs can `pip install vibe-trading-ai` again — `smartmoneyconcepts` pulled in `llvmlite`, which ships no macOS x86_64 wheel from 0.46 on, so every Intel install became a CMake source build; it is now the opt-in `[smc]` extra and the stale `<3.14` cap is gone ([#1035](https://github.com/HKUDS/Vibe-Trading/discussions/1035)). **New:** evidence-gated **Strategy Discovery** across the Alpha Zoo and the SDM store, with a population path, read-time freshness (`fresh`/`aging`/`stale`) and stale rows failing closed out of recommendations; scheduled research that **delivers itself** through a leased outbox and persists each monitor's verdict for the Market Watch list; seven read-only **Futu** endpoints; **Vietnam (HOSE)** as a backtest market; offline **USD-M account reconciliation**; **Novita AI** and **GitHub Copilot** providers; a hosted **MetaTrader 5** data source; **Spanish** and **German** locales; and MCP grows to 74 tools. **Correctness:** the test suite stopped escaping into your real config root, where a full run had been appending synthetic `order_rejected` records to the live hash-chained audit ledger; `build_registry()` no longer returns a short tool list in silence; `xirr` survives long-horizon discount underflow and DCF refuses non-finite inputs instead of returning a negative share price; `.VN` symbols stopped executing under China A-share rules; the backtest archive stopped mixing two runs' artifacts; and a broad grounding pass ended a class of false refusals on dates, ordered lists, identity constants in rate formulas, and order lines read as quotes. Thanks @Shizoqua, @shadowinlife, @pengpengyi92, @cgycorey, @ofeksh-tr, @lorenzozanee, @AndyLongest, @zzz607, @wiliao, @jay79-boop, @Robin1987China, @Echoandelementwebsites, @zhiwuyazhe-fjr, @x-lambda, @sykuang, @straun-repo, @nstavros, @ngoanpv, @miguelangelo78, @lukiod, @jax-novita, @honginp, @he-yufeng, @fixXxerTech, @er-s-an, @daviddaco1, @birdxs, @QCYTSN, @549236606-oss and @1psconstructor.+- **2026-08-20** 🚀 **v0.1.14 released** ([Release notes](https://github.com/HKUDS/Vibe-Trading/releases/tag/v0.1.14), `pip install -U vibe-trading-ai`): 272 commits and 75 merged pull requests since 0.1.13. **The headline is that a finished backtest is now something you can read rather than a folder of CSVs.** Run Detail grows four tabs — **Factor Research** (IC series with its mean line, IC statistics, quantile-group equity, and a pairwise IC correlation matrix that existed nowhere before), **Positions** (weight pie/treemap on a date slider, sector net-exposure bars, weight-evolution area — the pie is gross composition and the bars are net, so a long/short pair in one sector nets to zero on the bars while both legs stay visible on the pie), **Tearsheet** (monthly-returns heatmap, annual bars, top-5 drawdowns annotated onto the equity curve), and an interactive **research dashboard** with KPIs, benchmark-relative equity, rolling Sharpe and the full trade ledger. All four read artifacts a run already writes — no new pipeline. A new **Options Lab** page adds an expiry payoff diagram, a spot×IV scenario matrix, portfolio Greeks and a live options chain, computed through the same test-pinned engine the MCP tools use. **Install:** Intel Macs can `pip install vibe-trading-ai` again — `smartmoneyconcepts` pulled in `llvmlite`, which ships no macOS x86_64 wheel from 0.46 on, so every Intel install became a CMake source build; it is now the opt-in `[smc]` extra and the stale `<3.14` cap is gone ([#1035](https://github.com/HKUDS/Vibe-Trading/discussions/1035)). **New:** evidence-gated **Strategy Discovery** across the Alpha Zoo and the SDM store, with a population path, read-time freshness (`fresh`/`aging`/`stale`) and stale rows failing closed out of recommendations; scheduled research that **delivers itself** through a leased outbox and persists each monitor's verdict for the Market Watch list; seven read-only **Futu** endpoints; **Vietnam (HOSE)** as a backtest market; offline **USD-M account reconciliation**; **Novita AI** and **GitHub Copilot** providers; a hosted **MetaTrader 5** data source; **Spanish** and **German** locales; and MCP grows to 74 tools. **Correctness:** the test suite stopped escaping into your real config root, where a full run had been appending synthetic `order_rejected` records to the live hash-chained audit ledger; `build_registry()` no longer returns a short tool list in silence; `xirr` survives long-horizon discount underflow and DCF refuses non-finite inputs instead of returning a negative share price; `.VN` symbols stopped executing under China A-share rules; the backtest archive stopped mixing two runs' artifacts; and a broad grounding pass ended a class of false refusals on dates, ordered lists, identity constants in rate formulas, and order lines read as quotes. Thanks @Shizoqua, @shadowinlife, @pengpengyi92, @cgycorey, @ofeksh-tr, @lorenzozanee, @AndyLongest, @zzz607, @wiliao, @jay79-boop, @Robin1987China, @Echoandelementwebsites, @zhiwuyazhe-fjr, @x-lambda, @sykuang, @straun-repo, @nstavros, @ngoanpv, @miguelangelo78, @lukiod, @jax-novita, @honginp, @he-yufeng, @fixXxerTech, @er-s-an, @daviddaco1, @birdxs, @QCYTSN, @549236606-oss and @1psconstructor.- **2026-08-19** 🔌 **Stalled runs, a per-task connection leak, and Intel Macs that could not install**: A silent provider used to freeze a run — `VIBE_TRADING_LLM_TIMEOUT_SECONDS` (default 300s) now bounds the call, and tool-call markup is never released as a final answer ([#1105](https://github.com/HKUDS/Vibe-Trading/pull/1105)). Every swarm task leaked a pooled HTTP connection ([#1145](https://github.com/HKUDS/Vibe-Trading/pull/1145), closes [#1141](https://github.com/HKUDS/Vibe-Trading/issues/1141)). Also fixed: `vibe-trading show <run_id>` crashing ([#1147](https://github.com/HKUDS/Vibe-Trading/pull/1147), closes [#1146](https://github.com/HKUDS/Vibe-Trading/issues/1146)), overwritten in-flight deliveries ([#1140](https://github.com/HKUDS/Vibe-Trading/pull/1140)), dropped backtest validation evidence ([#1139](https://github.com/HKUDS/Vibe-Trading/pull/1139)), MCP paging ([#1137](https://github.com/HKUDS/Vibe-Trading/pull/1137), [#1138](https://github.com/HKUDS/Vibe-Trading/pull/1138)), and non-finite prediction-market fields ([#1136](https://github.com/HKUDS/Vibe-Trading/pull/1136)). **New:** seven read-only Futu endpoints ([#1135](https://github.com/HKUDS/Vibe-Trading/pull/1135)) and an explicit `Inferred` chip on guessed strategy titles ([#1134](https://github.com/HKUDS/Vibe-Trading/pull/1134)). **Install:** `smartmoneyconcepts` is now the `[smc]` extra — the `llvmlite` it pulled in ships no macOS x86_64 wheel, turning every Intel Mac install into a cmake source build ([#1035](https://github.com/HKUDS/Vibe-Trading/discussions/1035)); the `<3.14` cap goes with it. Thanks [@wiliao](https://github.com/wiliao), [@cgycorey](https://github.com/cgycorey), [@Shizoqua](https://github.com/Shizoqua), [@Echoandelementwebsites](https://github.com/Echoandelementwebsites), [@549236606-oss](https://github.com/549236606-oss), and [@fixXxerTech](https://github.com/fixXxerTech)!- **2026-08-18** 🈶 **Correct reports stopped being refused, and backtests stopped trading noise**: `\b` is Unicode-aware, so `最` counts as a word character and `(2026-07-14最低)` had no boundary after the day — the date survived the mask and `2026`, `7` and `14` reached the OHLC check as prices no observed range can contain ([#1132](https://github.com/HKUDS/Vibe-Trading/pull/1132), closes [#1122](https://github.com/HKUDS/Vibe-Trading/issues/1122)). Four refusals of the same family went with it: a dash-form trading day (`08-10(一)`), a level stated as a range leaving `-20` behind, a GTC line (`100 @ $3.50`) read as two observed quotes, and a report-style date cell that matched no evidence row at all. **Backtests:** `position_adjustment="hold"` dropped a requested resize in silence, and `"rebalance"` had no drift band — measured, a 0.01% daily move re-pinned a position on 19 of 30 bars, so a strategy with its own `rebalance_freq` traded every bar regardless. Dropped requests are now reported, and `rebalance_tolerance` is the band practitioners mean by "rebalance when weights move more than X", defaulting to `0.0` so no existing run changes. Nineteen industry-neutralized alpha101 alphas had been skipped on every SP500 bench run for want of a sector tag that was already in the table the constituents come from. **New:** a Market Watch monitor can push its briefing to an IM channel once the run finishes, through a persisted outbox that a restart cannot lose and a concurrent sweep cannot double-send ([#942](https://github.com/HKUDS/Vibe-Trading/issues/942)); **German is the seventh UI language** ([#1117](https://github.com/HKUDS/Vibe-Trading/pull/1117)); `run_dcf` refuses non-finite inputs instead of returning a plausible negative share price ([#1121](https://github.com/HKUDS/Vibe-Trading/pull/1121), closes [#1120](https://github.com/HKUDS/Vibe-Trading/issues/1120)); the MCP `get_market_data` response carries the `_provenance` its own docstring promised ([#1131](https://github.com/HKUDS/Vibe-Trading/pull/1131)); a tool module that fails to import is named rather than quietly shrinking the registry ([#1129](https://github.com/HKUDS/Vibe-Trading/pull/1129), closes [#1124](https://github.com/HKUDS/Vibe-Trading/issues/1124)); and offline USD-M account reconciliation compares local risk state with an exchange observation without opening a connection ([#1106](https://github.com/HKUDS/Vibe-Trading/pull/1106)). **Also:** importing `backtest.runner` no longer loads a `.env` into the process, which had made a local full-suite run untrustworthy on any machine that has one ([#1123](https://github.com/HKUDS/Vibe-Trading/issues/1123)). Thanks [@Robin1987China](https://github.com/Robin1987China), [@newgo](https://github.com/newgo), [@er-s-an](https://github.com/er-s-an), [@Shizoqua](https://github.com/Shizoqua), [@1psconstructor](https://github.com/1psconstructor), [@honginp](https://github.com/honginp), [@cgycorey](https://github.com/cgycorey), [@alinv0](https://github.com/alinv0), and [@jelech](https://github.com/jelech)!- **2026-08-17** 🔒 **The test suite stopped writing into your real config root — including the live audit ledger**: Running the project's own suite appended fabricated `order_rejected` records to `~/.vibe-trading/live/audit.jsonl`, an append-only, hash-chained ledger whose entire value is that its entries cannot be manufactured, and on Windows left a corrupted chain file behind. `conftest.py` had no config-root sandbox at all, so every module that baked `Path.home() / ".vibe-trading"` at import time resolved against the real home on **any** platform — Windows was worse only because `Path.home()` reads `%USERPROFILE%` there and ignores `$HOME`, leaving the isolation idiom the suite had been using inert. Home is now redirected before collection, the sandbox owns a single knob so per-test isolation still wins, and session end asserts the real ledgers are byte-identical instead of merely checking that the redirect was installed ([#1118](https://github.com/HKUDS/Vibe-Trading/pull/1118), closes [#1116](https://github.com/HKUDS/Vibe-Trading/issues/1116)). Also: `xirr` and `money_weighted_return` raised `ZeroDivisionError` on horizons past ~51 years, where the discount factor underflows to zero — exactly the long, irregular streams XIRR exists for ([#1119](https://github.com/HKUDS/Vibe-Trading/pull/1119)); and a backtest archived into an active run merged with the previous one's artifacts, so a single report could describe two different backtests while `/runs/{id}` listed the leftovers as its own ([#1094](https://github.com/HKUDS/Vibe-Trading/issues/1094)). Thanks [@lorenzozanee](https://github.com/lorenzozanee), [@straun-repo](https://github.com/straun-repo), and [@pengpengyi92](https://github.com/pengpengyi92)!@@ -1470,7 +1470,7 @@ with `--host` / `--port`.</details>-**MCP tools exposed (74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.+**MCP tools exposed (74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `get_fund_nav`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.### SWARM external MCP toolsdiff --git a/README_ar.md b/README_ar.mdindex 72e6c1482..a1213aff7 100644--- a/README_ar.md+++ b/README_ar.md@@ -1282,7 +1282,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**أدوات MCP المعروضة (74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.+**أدوات MCP المعروضة (75):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `get_fund_nav`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.### أدوات MCP الخارجية في SWARMdiff --git a/README_es.md b/README_es.mdindex 3914aa713..3695aa52d 100644--- a/README_es.md+++ b/README_es.md@@ -1357,7 +1357,7 @@ dirección de bind con `--host` / `--port`.</details>-**MCP tools expuestas (74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.+**MCP tools expuestas (75):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `get_fund_nav`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.### SWARM external MCP toolsdiff --git a/README_ja.md b/README_ja.mdindex 78d3d7952..178a3f826 100644--- a/README_ja.md+++ b/README_ja.md@@ -1284,7 +1284,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**公開される MCP tools(74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.+**公開される MCP tools(75):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `get_fund_nav`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.### SWARM の外部 MCP toolsdiff --git a/README_ko.md b/README_ko.mdindex 2625677a9..0106fd4b3 100644--- a/README_ko.md+++ b/README_ko.md@@ -1285,7 +1285,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**노출되는 MCP tools(74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.+**노출되는 MCP tools(75):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `get_fund_nav`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.### SWARM 외부 MCP toolsdiff --git a/README_zh.md b/README_zh.mdindex ee61d7a13..1d2bbadcc 100644--- a/README_zh.md+++ b/README_zh.md@@ -1289,7 +1289,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**暴露的 MCP tools(74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.+**暴露的 MCP tools(75):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `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`, `get_fund_nav`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.### SWARM 的外部 MCP toolsdiff --git a/agent/.env.example b/agent/.env.exampleindex 707d62288..1a9c25be6 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -211,7 +211,7 @@ TUSHARE_TOKEN=your-tushare-token# 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)-# GILDATA_TOKEN=xxx # optional Gildata (恒生聚源) A-share/HK/CN-index OHLCV fallback provider — commercial token via [email protected]; joins the a_share and hk_equity chains' tails when set (selectable get_market_data source)+# GILDATA_TOKEN=xxx # optional Gildata (恒生聚源) provider — commercial token via [email protected]; joins the a_share/hk_equity chain tails for OHLCV (selectable get_market_data source) and powers the get_fund_nav OTC-fund NAV tool# GILDATA_BASE_URL=xxx # optional endpoint override (defaults to the vendor's raw-api MCP endpoint)# TICKERALL_API_KEY=xxx # optional hosted MetaTrader 5 forex/metals feed — EXPLICIT source="tickerall" only, never an automatic fallback (no local terminal; https://tickerall.com)# TICKERALL_ACCOUNT_ID=xxx # required alongside the key: history is served per connected broker account (read-only)diff --git a/agent/SKILL.md b/agent/SKILL.mdindex 987b07fc4..0c97e7ea1 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -133,7 +133,7 @@ Comprehensive knowledge base covering:Use `load_skill(name)` to access full methodology docs with code templates.-## Available MCP Tools (74)+## Available MCP Tools (75)| Tool | Description | API Key ||------|-------------|---------|@@ -168,6 +168,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.| `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 |+| `get_fund_nav` | Chinese off-exchange fund NAV history | GILDATA_TOKEN || `iwencai_search` | A-share natural-language research search | IWENCAI_KEY || `qveris_search` | Search QVeris premium data/tool marketplace (free discovery) | QVERIS_API_KEY + paid mode || `qveris_inspect` | Inspect QVeris tool schemas before executing (free) | QVERIS_API_KEY + paid mode |diff --git a/agent/backtest/loaders/gildata_codes.py b/agent/backtest/loaders/gildata_codes.pyindex 35f5d84e3..7ebcfacd3 100644--- a/agent/backtest/loaders/gildata_codes.py+++ b/agent/backtest/loaders/gildata_codes.py@@ -28,10 +28,13 @@ from typing import Any, Callable, Dict, Optionallogger = logging.getLogger(__name__)# recall param -> tool wiring, keyed by the resolution kind.-_RECALL_WIRING: Dict[str, tuple[str, str]] = {+_RECALL_WIRING: dict[str, tuple[str, str]] = {# kind: (api_name, param_name the internal code belongs to)"hk_equity": ("HKStockDailyQuotes", "stockObject"),"cn_index": ("IndexDailyQuote", "indexObject"),+ # OTC funds: the NetFundUnitValueReport NAV tool (agent-facing, not a+ # loader — the loader protocol is OHLCV bars and NAV series are not).+ "otc_fund": ("NetFundUnitValueReport", "fundObject"),}_CACHE_FILENAME = "gildata-codes.json"diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex eaee3d302..88ece3f6e 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -1880,6 +1880,7 @@ def _key_gated_tool_classes() -> dict[str, Any]:Mapping of MCP tool name to its ``BaseTool`` subclass."""from src.tools.fred_macro_tool import FredMacroTool+ from src.tools.fund_nav_tool import GildataFundNavToolfrom src.tools.iwencai_tool import IWenCaiSearchToolfrom src.tools.qveris_tool import (QVerisExecuteTool,@@ -1889,6 +1890,7 @@ def _key_gated_tool_classes() -> dict[str, Any]:return {"get_macro_series": FredMacroTool,+ "get_fund_nav": GildataFundNavTool,"iwencai_search": IWenCaiSearchTool,"qveris_search": QVerisSearchTool,"qveris_inspect": QVerisInspectTool,@@ -2287,6 +2289,37 @@ def get_macro_series(params["end_date"] = end_datereturn _execute_key_gated("get_macro_series", params)+def get_fund_nav(+ codes: _lenient_str_list,+ start_date: str | None = None,+ end_date: str | None = None,+ limit: int = 2000,+) -> str:+ """Fetch daily NAV history for Chinese off-exchange funds (场外基金).++ Returns unit NAV (单位净值), accumulated NAV (累计净值), dividend-adjusted+ NAV (复权净值) and the daily growth rate per fund, over an optional date+ window. Codes are bare 6-digit ('110022') or '.OF'-suffixed+ ('110022.OF'). Exchange-listed ETF/LOF are OHLCV instruments — use+ get_market_data for those. Requires the commercial GILDATA_TOKEN; without+ it the tool returns a not-available error.++ Args:+ codes: Fund codes, e.g. ["110022", "000198.OF"].+ start_date: Inclusive window start, YYYY-MM-DD. Omit for the vendor's+ default history window.+ end_date: Inclusive window end, YYYY-MM-DD. Omit through the latest+ published NAV.+ limit: Maximum number of most-recent rows per fund.+ """+ params: dict[str, Any] = {"codes": codes, "limit": limit}+ if start_date:+ params["start_date"] = start_date+ if end_date:+ params["end_date"] = end_date+ return _execute_key_gated("get_fund_nav", params)+@mcp.tooldef iwencai_search(query: str, limit: int = 20) -> str:diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.mdindex ee90a4212..222dab159 100644--- a/agent/src/skills/data-routing/SKILL.md+++ b/agent/src/skills/data-routing/SKILL.md@@ -69,6 +69,7 @@ is required only where listed (no key listed = free / no auth).| Market screen | `screen_market` | A-share | — || Symbol search | `search_symbol` | A-share, US, HK, Canada, crypto/index/FX | — || Macro / FRED series | `get_macro_series` | Macro (US/global) | `FRED_API_KEY` |+| OTC fund NAV (场外基金净值) | `get_fund_nav` | CN off-exchange funds | `GILDATA_TOKEN` || iWenCai NL search (问财) | `iwencai_search` | A-share | `VIBE_TRADING_IWENCAI_KEY` |Notes:diff --git a/agent/src/tools/fund_nav_tool.py b/agent/src/tools/fund_nav_tool.pynew file mode 100644index 000000000..4372c7cb6--- /dev/null+++ b/agent/src/tools/fund_nav_tool.py@@ -0,0 +1,240 @@+"""Read-only tool: OTC fund NAV history from Gildata (恒生聚源).++Chinese off-exchange funds (场外基金 — ``110022.OF``-style open-end funds)+publish no OHLCV bars; their tradable series is the daily NAV. The project's+loader layer is an OHLCV contract and deliberately stays that way, so this+agent-facing tool serves NAV history instead, straight from the vendor's+``NetFundUnitValueReport`` raw-api tool.++Each fund code resolves to a 聚源内码 through the same recall machinery the+loader uses (:mod:`backtest.loaders.gildata_codes`), with an exact+``ref_code`` match and the shared disk cache. Requires ``GILDATA_TOKEN``;+without it the tool is silently excluded from the registry.++Field mapping (vendor -> served):+ enddate -> date+ unitnv -> unit_nav (单位净值)+ accumulatedunitnv -> accumulated_nav (单位累计净值)+ unitnvrestored -> adjusted_nav (复权单位净值)+ nvdailygrowthrate -> daily_growth_pct (单位基金净值增长率 %)+"""++from __future__ import annotations++import json+import logging+from typing import Any++from backtest.loaders.gildata_codes import resolve_vendor_code+from backtest.loaders.gildata_loader import _call_tool, _recall_candidates+from src.agent.tools import BaseTool+from src.config.accessor import get_env_config++logger = logging.getLogger(__name__)++_NAV_TOOL = "NetFundUnitValueReport"++# Keep the most-recent rows when the window exceeds the cap.+_DEFAULT_LIMIT = 2000+_MAX_LIMIT = 5000++# Vendor row fields -> served names. Adjusted NAV keeps its own key (not every+# fund publishes a meaningful 复权因子 — rows may carry nulls).+_ROW_FIELDS = {+ "enddate": "date",+ "unitnv": "unit_nav",+ "accumulatedunitnv": "accumulated_nav",+ "unitnvrestored": "adjusted_nav",+ "nvdailygrowthrate": "daily_growth_pct",+}+++def _normalize_fund_code(raw: Any) -> str | None:+ """Normalize a project fund code onto the vendor's ``NNNNNN.OF`` ref.++ Bare 6-digit codes are treated as off-exchange (``.OF``); a ``.OF`` /+ ``.of`` suffix is upper-cased; an explicit exchange suffix (``.SH`` /+ ``.SZ``) means an exchange-listed fund, which the OHLCV loaders already+ serve — the caller is told so instead of getting a wrong series.++ Returns:+ The normalized ``NNNNNN.OF`` code, or ``None`` for non-fund inputs.+ """+ if not isinstance(raw, str):+ return None+ code = raw.strip().upper()+ if not code:+ return None+ if code.endswith(".OF"):+ digits = code[: -len(".OF")]+ return code if len(digits) == 6 and digits.isdigit() else None+ if code.endswith((".SH", ".SZ")):+ return None # exchange-listed: served by get_market_data, not NAV+ if len(code) == 6 and code.isdigit():+ return code + ".OF"+ return None+++def _error(message: str) -> str:+ return json.dumps({"ok": False, "error": message}, ensure_ascii=False)+++class GildataFundNavTool(BaseTool):+ """Fetch off-exchange Chinese fund NAV history from Gildata."""++ name = "get_fund_nav"+ description = (+ "Fetch the daily NAV history of Chinese off-exchange funds (场外基金, "+ "e.g. 110022.OF 易方达消费行业): unit NAV (单位净值), accumulated NAV "+ "(累计净值), dividend-adjusted NAV (复权净值) and the daily growth rate, "+ "over an optional date window. Exchange-listed ETF/LOF (510300.SH-style) "+ "are OHLCV instruments — use get_market_data for those. Requires the "+ "commercial GILDATA_TOKEN. Example: {\"codes\": [\"110022\"], "+ "\"start_date\": \"2024-01-01\"}."+ )+ parameters = {+ "type": "object",+ "properties": {+ "codes": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "Fund codes, bare 6-digit ('110022') or '.OF'-suffixed "+ "('110022.OF')."+ ),+ },+ "start_date": {+ "type": "string",+ "description": (+ "Inclusive window start, YYYY-MM-DD. Omit for the "+ "vendor's default history window."+ ),+ },+ "end_date": {+ "type": "string",+ "description": (+ "Inclusive window end, YYYY-MM-DD. Omit through the "+ "latest published NAV."+ ),+ },+ "limit": {+ "type": "integer",+ "description": (+ "Maximum number of most-recent rows per fund "+ f"(1-{_MAX_LIMIT}). Defaults to {_DEFAULT_LIMIT}."+ ),+ "default": _DEFAULT_LIMIT,+ },+ },+ "required": ["codes"],+ }++ @classmethod+ def check_available(cls) -> bool:+ """Available only when ``GILDATA_TOKEN`` is configured."""+ return bool(get_env_config().data.gildata_token)++ def execute(self, **kwargs: Any) -> str:+ """Fetch NAV history for one or more funds and return a JSON envelope.++ Args:+ **kwargs: ``codes`` (required list), optional ``start_date`` /+ ``end_date`` (inclusive YYYY-MM-DD) and ``limit``.++ Returns:+ JSON envelope. On success: ``{"ok": true, "source": "gildata",+ "funds": {"110022.OF": {"ok": true, "fund_name", "rows": [...],+ "count"}}}``; a failing fund carries ``{"ok": false, "error"}``+ and never aborts the rest of the batch.+ """+ if not get_env_config().data.gildata_token:+ return _error("GILDATA_TOKEN is not configured")++ raw_codes = kwargs.get("codes")+ if isinstance(raw_codes, str):+ raw_codes = [raw_codes]+ if not isinstance(raw_codes, list) or not raw_codes:+ return _error("'codes' is required and must be a non-empty list")+ codes = [_normalize_fund_code(item) for item in raw_codes]+ if all(code is None for code in codes):+ return _error(+ "no valid off-exchange fund codes in request (expected "+ "6-digit or .OF codes; exchange-listed funds are served by "+ "get_market_data)"+ )++ try:+ limit = int(kwargs.get("limit", _DEFAULT_LIMIT) or _DEFAULT_LIMIT)+ except (TypeError, ValueError):+ limit = _DEFAULT_LIMIT+ limit = max(1, min(_MAX_LIMIT, limit))++ window: dict[str, str] = {}+ for key in ("start_date", "end_date"):+ value = kwargs.get(key)+ if isinstance(value, str) and value.strip():+ window[key] = value.strip()++ funds: dict[str, Any] = {}+ for raw, code in zip(raw_codes, codes):+ if code is None:+ funds[str(raw)] = {+ "ok": False,+ "error": "not an off-exchange fund code",+ }+ continue+ try:+ funds[code] = self._fetch_one(code, window, limit)+ except Exception as exc: # never abort the batch+ logger.warning("get_fund_nav failed for %s: %s", code, exc)+ funds[code] = {"ok": False, "error": str(exc)}++ return json.dumps(+ {"ok": True, "source": "gildata", "funds": funds},+ ensure_ascii=False,+ )++ def _fetch_one(+ self, code: str, window: dict[str, str], limit: int+ ) -> dict[str, Any]:+ """Resolve one fund's 内码 and fetch its NAV rows."""+ vendor_code = resolve_vendor_code("otc_fund", code, _recall_candidates)+ if vendor_code is None:+ return {"ok": False, "error": f"fund {code} not found"}++ arguments: dict[str, Any] = {+ "fundObject": [vendor_code],+ "statisticalPeriod": 0, # 0-日+ }+ if window.get("start_date"):+ arguments["beginDate"] = window["start_date"]+ if window.get("end_date"):+ arguments["endDate"] = window["end_date"]++ entry = _call_tool(_NAV_TOOL, arguments)+ rows = entry.get("rows") if isinstance(entry, dict) else None+ rows = rows if isinstance(rows, list) else []++ served: list[dict[str, Any]] = []+ fund_name = ""+ for row in rows:+ if not isinstance(row, dict) or not row.get("enddate"):+ continue+ if not fund_name and row.get("fundname"):+ fund_name = str(row["fundname"])+ served.append({+ served_name: row.get(vendor_field)+ for vendor_field, served_name in _ROW_FIELDS.items()+ })+ # Vendor rows arrive newest-first; serve ascending like every other+ # dated series in the project, keeping the most-recent `limit` rows.+ served = sorted(served, key=lambda r: str(r["date"]))[-limit:]++ if not served:+ return {"ok": False, "error": "no NAV rows in the requested window"}+ return {+ "ok": True,+ "fund_name": fund_name,+ "rows": served,+ "count": len(served),+ }diff --git a/agent/tests/test_fund_nav_tool.py b/agent/tests/test_fund_nav_tool.pynew file mode 100644index 000000000..55a15d758--- /dev/null+++ b/agent/tests/test_fund_nav_tool.py@@ -0,0 +1,180 @@+"""Tests for fund_nav_tool: availability gating, resolution, parsing, batching.++All MCP transport is mocked — no test reaches a live Gildata endpoint. The+tool imports ``_call_tool`` from the loader and ``resolve_vendor_code`` from+gildata_codes; both are patched on the ``fund_nav_tool`` module namespace,+except where the real resolver is exercised against a stubbed transport.+"""++from __future__ import annotations++import json+from typing import Any++from src.tools import fund_nav_tool as fnt+from src.tools.fund_nav_tool import GildataFundNavTool+++def _mcp_text(payload: dict[str, Any]) -> str:+ return json.dumps(payload, ensure_ascii=False)+++def _tool_entry(rows: list[dict[str, Any]]) -> dict[str, Any]:+ """The results[0] entry shape the loader's _call_tool returns."""+ return {"api_name": "基金净值", "columns": {}, "rows": rows}+++_NAV_ROWS = [+ # Newest-first, exactly as the vendor sends them.+ {+ "enddate": "2024-01-11", "fundname": "易方达消费行业股票",+ "fundcode": "110022", "unitnv": 3.29, "accumulatedunitnv": 3.29,+ "unitnvrestored": 3.29, "nvdailygrowthrate": 0.6116,+ },+ {+ "enddate": "2024-01-10", "fundname": "易方达消费行业股票",+ "fundcode": "110022", "unitnv": 3.27, "accumulatedunitnv": 3.27,+ "unitnvrestored": 3.27, "nvdailygrowthrate": 0.3683,+ },+]+++class TestAvailability:+ """check_available reflects only GILDATA_TOKEN."""++ def test_unavailable_without_token(self, monkeypatch):+ monkeypatch.delenv("GILDATA_TOKEN", raising=False)+ assert GildataFundNavTool.check_available() is False++ def test_available_with_token(self, monkeypatch):+ monkeypatch.setenv("GILDATA_TOKEN", "secret")+ assert GildataFundNavTool.check_available() is True++ def test_metadata(self):+ assert GildataFundNavTool.name == "get_fund_nav"+ assert GildataFundNavTool().is_readonly is True+++class TestNormalizeFundCode:+ """Project codes map onto the vendor's NNNNNN.OF ref."""++ def test_bare_digits_get_of_suffix(self):+ assert fnt._normalize_fund_code("110022") == "110022.OF"++ def test_of_suffix_uppercased(self):+ assert fnt._normalize_fund_code("110022.of") == "110022.OF"++ def test_exchange_listed_rejected(self):+ # OHLCV instruments — served by get_market_data, not this tool.+ assert fnt._normalize_fund_code("510300.SH") is None+ assert fnt._normalize_fund_code("159915.SZ") is None++ def test_garbage_rejected(self):+ assert fnt._normalize_fund_code("AAPL") is None+ assert fnt._normalize_fund_code("") is None+ assert fnt._normalize_fund_code(12345) is None+++class TestExecute:+ """End-to-end execute with the MCP transport mocked."""++ def _patch_transport(self, monkeypatch, side_effect):+ monkeypatch.setenv("GILDATA_TOKEN", "secret")+ from backtest.loaders import gildata_codes+ gildata_codes.reset_code_cache()+ monkeypatch.setattr(fnt, "_call_tool", side_effect)+ monkeypatch.setattr(fnt, "_recall_candidates", side_effect)++ def test_missing_token_error(self, monkeypatch):+ monkeypatch.delenv("GILDATA_TOKEN", raising=False)+ out = json.loads(GildataFundNavTool().execute(codes=["110022"]))+ assert out["ok"] is False+ assert "GILDATA_TOKEN" in out["error"]++ def test_happy_path(self, monkeypatch):+ def transport(tool, args):+ if tool == "ParamCandidateRecall":+ return {"candidates": [+ {"caption": "易方达消费行业股票", "code": "11363",+ "ref_code": "110022.OF"},+ ]}+ assert tool == "NetFundUnitValueReport"+ assert args["fundObject"] == ["11363"]+ assert args["statisticalPeriod"] == 0+ assert args.get("beginDate") == "2024-01-01"+ return _tool_entry(_NAV_ROWS)++ self._patch_transport(monkeypatch, transport)+ out = json.loads(GildataFundNavTool().execute(+ codes=["110022"], start_date="2024-01-01"))+ assert out["ok"] is True and out["source"] == "gildata"+ fund = out["funds"]["110022.OF"]+ assert fund["ok"] is True+ assert fund["fund_name"] == "易方达消费行业股票"+ assert fund["count"] == 2+ # Ascending order; served field names mapped off the vendor's.+ assert [r["date"] for r in fund["rows"]] == ["2024-01-10", "2024-01-11"]+ row = fund["rows"][0]+ assert row["unit_nav"] == 3.27+ assert row["accumulated_nav"] == 3.27+ assert row["adjusted_nav"] == 3.27+ assert row["daily_growth_pct"] == 0.3683++ def test_unresolved_fund_reports_error_not_abort(self, monkeypatch):+ def transport(tool, args):+ if tool == "ParamCandidateRecall":+ return {"candidates": [+ {"caption": "别的基金", "code": "1", "ref_code": "000001.OF"},+ ]}+ return _tool_entry(_NAV_ROWS)++ self._patch_transport(monkeypatch, transport)+ out = json.loads(GildataFundNavTool().execute(+ codes=["110022", "000198.OF"]))+ # 110022 resolves and serves; 000198 does not resolve and reports.+ assert out["ok"] is True+ assert out["funds"]["110022.OF"]["ok"] is True+ assert out["funds"]["000198.OF"]["ok"] is False++ def test_exchange_listed_code_reports_error(self, monkeypatch):+ self._patch_transport(monkeypatch, lambda tool, args: _tool_entry([]))+ out = json.loads(GildataFundNavTool().execute(+ codes=["510300.SH", "110022"]))+ assert out["ok"] is True+ assert out["funds"]["510300.SH"]["ok"] is False++ def test_all_invalid_codes_rejected_upfront(self, monkeypatch):+ monkeypatch.setenv("GILDATA_TOKEN", "secret")+ out = json.loads(GildataFundNavTool().execute(codes=["AAPL", "00700.HK"]))+ assert out["ok"] is False++ def test_limit_keeps_most_recent_rows(self, monkeypatch):+ rows = [+ {"enddate": f"2024-01-{day:02d}", "fundname": "F",+ "unitnv": 1.0, "accumulatedunitnv": 1.0,+ "unitnvrestored": 1.0, "nvdailygrowthrate": 0.0}+ for day in range(1, 11)+ ]+ def transport(tool, args):+ if tool == "ParamCandidateRecall":+ return {"candidates": [+ {"caption": "F", "code": "11363", "ref_code": "110022.OF"}]}+ return _tool_entry(rows)++ self._patch_transport(monkeypatch, transport)+ out = json.loads(GildataFundNavTool().execute(codes=["110022"], limit=3))+ fund = out["funds"]["110022.OF"]+ assert fund["count"] == 3+ assert fund["rows"][-1]["date"] == "2024-01-10" # newest kept++ def test_empty_window_reports_error(self, monkeypatch):+ def transport(tool, args):+ if tool == "ParamCandidateRecall":+ return {"candidates": [+ {"caption": "F", "code": "11363", "ref_code": "110022.OF"}]}+ return _tool_entry([])++ self._patch_transport(monkeypatch, transport)+ out = json.loads(GildataFundNavTool().execute(codes=["110022"]))+ assert out["funds"]["110022.OF"]["ok"] is False+ assert "no NAV rows" in out["funds"]["110022.OF"]["error"]