"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(fund-flow): preserve source and bucket semantics on fallback (#1954)
Haozhe Wu2efe63f3827a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex de1d865c7..20e2c00ee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,37 @@ This project adheres to [Semantic Versioning](https://semver.org/).## [Unreleased]+### Community feedback follow-up — 2026-10-21++- Fund-flow daily requests now try Tushare when Eastmoney returns no usable+ rows, as well as on request/resolution failure (discussion #486). Every+ successful symbol names its actual source; mixed batches report `mixed`.+ Minute requests never substitute daily data. Missing tokens, permissions or+ data remain visible per-symbol failures.+- Correct Tushare `moneyflow` mapping: `main` is large plus super-large net+ flow, while `net_mf_amount` is retained separately as `net_total`. Missing or+ non-finite buy/sell amounts remain unknown rather than becoming zero.+ Provider classifications may differ; the result states its methodology.+ Field definitions: https://tushare.pro/document/2?doc_id=170.+- Add a complete pip/Telegram setup example with sender authorization, matching+ API ports and recovery for commands installed in a different environment+ (discussion #702). Intel Mac's base-install fix remains the optional `[smc]`+ dependency introduced in 0.1.14 (discussion #1035).+- Verify the existing evidence/identity guards, Feishu progress dispatch (#1792)+ and bounded chat-history previews (#1852) against current main. This does+ not claim an on-device Intel Mac installation or authenticated Feishu delivery+ test, or guarantee that every model answer is correct.+- Complete engine-specific unused-setting warnings (#1947, closes #1934),+ following the path-wide unknown-key warnings in #1935. Crypto now warns about+ ignored `commission_rate`; it still uses `maker_rate`/`taker_rate`, and valid+ shared settings remain accepted.+- Reject invalid journal dates and retain input order for equal timestamps+ (#1942, #1941); price ICE coffee, sugar and cotton multipliers in cents+ (#1944); stabilize Carino attribution near coincident returns (#1943) and+ honor saved annualisation in attribution (#1948). Clean unpublished uploads+ on cancellation (#1945) and return structured directory listing errors+ (#1946).+### Daily paper trading — 2026-10-21- Add the deterministic `paper_trade_step` agent/MCP tool plus local paper@@ -24,7 +55,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).- Warn about unrecognized backtest configuration keys and include the warningin the run card (#1935). Runs still proceed. This is not engine-specificvalidation: a key read by another engine can still go unused for the selected- engine, including `commission_rate` for crypto; #1934 remains open.+ engine, including `commission_rate` for crypto. This remaining #1934 gap+ was subsequently addressed by #1947 on October 21 (see above).- Return undefined off-diagonal correlations as `null` and show them as muteddashes in the chart, keeping genuine zero correlations distinct (#1933).- Save the runner's annualisation factor in the run card and reuse it fordiff --git a/README.md b/README.mdindex fedd87f26..496a5bfc2 100644--- a/README.md+++ b/README.md@@ -52,6 +52,8 @@> ⚠️ **Security warning:** The X account `VibeTrading_HKU`, Virtuals project `101845`, and token contract `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` are not official Vibe-Trading assets. We have never launched or endorsed any token or memecoin. Do not buy, connect a wallet, or sign anything. [Details](SECURITY.md#official-channels--impersonation).+- **2026-10-21** 🛠️ **Paper accounts and community fixes**: Daily paper trading now has Agent/MCP, CLI, API and Web entries ([#1939](https://github.com/HKUDS/Vibe-Trading/pull/1939)). Backtests warn when the selected engine ignores a setting ([#1947](https://github.com/HKUDS/Vibe-Trading/pull/1947)). Fund-flow fallback handles empty daily responses, identifies its actual source and keeps total flow separate from main-order flow. Telegram setup instructions are clarified; journal, futures-unit, attribution, upload-cancellation and directory-error fixes are in [CHANGELOG](CHANGELOG.md).+- **2026-10-20** 🛠️ **Backtest diagnostics and research correctness**: Warn about unrecognized backtest config keys, show undefined correlations as unknown instead of zero, and reuse the saved annualisation factor when revalidating runs ([#1935](https://github.com/HKUDS/Vibe-Trading/pull/1935), [#1933](https://github.com/HKUDS/Vibe-Trading/pull/1933), [#1915](https://github.com/HKUDS/Vibe-Trading/pull/1915)). Also improve factor sample checks, tool input validation, journal market classification, numeric formatting and WeCom streaming. All 14 fixes and remaining limits are in [CHANGELOG](CHANGELOG.md).- **2026-10-19** 🛠️ **Nine financial correctness fixes**: Correct recency weights in factor decay, A-share board limits and Beijing symbol routing, SEC Q4 flow derivation, and event-study estimation windows. Preserve Futu holdings identity and tiny MACD/Bollinger values; reject negative specific variances and apply pair-specific fees to Yahoo forex symbols ([#1912](https://github.com/HKUDS/Vibe-Trading/pull/1912), [#1920](https://github.com/HKUDS/Vibe-Trading/pull/1920), [#1930](https://github.com/HKUDS/Vibe-Trading/pull/1930)). See [CHANGELOG](CHANGELOG.md) for all nine fixes and limits.@@ -1325,6 +1327,40 @@ vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025 --toIM channel adapters connect outside chat apps to the same session runtime used by the Web UI and CLI. Configure enabled adapters under `channels` in `~/.vibe-trading/agent.json`; SDK-backed adapters are optional extras, and missing SDKs report recovery hints instead of crashing the runtime.+**Telegram quick start (pip installation):** activate the same virtual environment+in both terminals, then upgrade the package and install its Telegram adapter:++```bash+python -m pip install -U "vibe-trading-ai[telegram]"+vibe-trading channels --help+```++Create a bot with `@BotFather`. Merge the following into+`~/.vibe-trading/agent.json`, replacing the token and sender ID (do not overwrite+other channel settings). `allow_from` accepts your numeric Telegram user ID or+username without `@`; listed senders do not need pairing approval.++```json+{+ "channels": {+ "telegram": {+ "enabled": true,+ "token": "YOUR_BOTFATHER_TOKEN",+ "allow_from": ["YOUR_TELEGRAM_USER_ID"]+ }+ }+}+```++Run `vibe-trading channels status --local` to check configuration and adapter+availability. Start `vibe-trading serve --port 8000` in terminal 1, then run+`vibe-trading channels start` in terminal 2 and send your bot a message.+For another port, set `VIBE_TRADING_API_URL` to that server's URL in terminal 2.+If `channels` is missing, check `python -m pip show vibe-trading-ai` in that+same environment and upgrade there; installing into one environment does not+update another environment's command. Missing SDK hints from `status --local`+mean the optional adapter still needs installation.+For long-running channel tasks, tune the central assistant-reply wait budget with `replyTimeoutS` (seconds, default `600`):```jsondiff --git a/README_ar.md b/README_ar.mdindex 25bd78413..1b1f1d038 100644--- a/README_ar.md+++ b/README_ar.md@@ -52,6 +52,8 @@> ⚠️ **تحذير أمني:** حساب X باسم `VibeTrading_HKU`، ومشروع Virtuals رقم `101845`، وعقد التوكن `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` كلّها غير رسمية ولا تتبع Vibe-Trading. لم نُطلق أو نؤيد مطلقًا أي توكن أو عملة ميم. لا تشترِ هذا التوكن، ولا تربط محفظتك، ولا توقّع أي شيء. [التفاصيل](SECURITY.md#official-channels--impersonation).+- **2026-10-21** 🛠️ **حسابات التداول التجريبي وإصلاحات المجتمع**: تتوفر المحاكاة اليومية عبر Agent/MCP وCLI وAPI والويب ([#1939](https://github.com/HKUDS/Vibe-Trading/pull/1939)). تظهر تحذيرات للإعدادات التي يتجاهلها المحرك المختار ([#1947](https://github.com/HKUDS/Vibe-Trading/pull/1947)). تفعّل الاستجابات اليومية الفارغة لتدفقات الأموال المصدر البديل، مع بيان المصدر الفعلي وفصل صافي التدفق الإجمالي عن صافي تدفق الأوامر الكبيرة. وُضّحت خطوات إعداد Telegram. بقية الإصلاحات والقيود في [CHANGELOG](CHANGELOG.md).+- **2026-10-20** 🛠️ **تشخيص الاختبارات التاريخية ودقة التحليل**: إصدار تحذير لمفاتيح الإعدادات غير المعروفة، وعرض الارتباطات غير المعرّفة بوصفها مجهولة بدلاً من صفر، وإعادة استخدام معامل التحويل السنوي المحفوظ عند إعادة التحقق ([#1935](https://github.com/HKUDS/Vibe-Trading/pull/1935), [#1933](https://github.com/HKUDS/Vibe-Trading/pull/1933), [#1915](https://github.com/HKUDS/Vibe-Trading/pull/1915)). تشمل التحسينات أيضاً فحص عينات العوامل، والتحقق من مدخلات الأدوات، وتصنيف الأسواق في سجلات التداول، وتنسيق الأرقام، والردود المتدفقة في WeCom. تفاصيل الإصلاحات الأربعة عشر والقيود المتبقية في [CHANGELOG](CHANGELOG.md).- **2026-10-19** 🛠️ **تسعة إصلاحات للحسابات المالية**: تصحيح أوزان اضمحلال العوامل، وحدود أسعار الأسهم الصينية A ورموز بورصة بكين، واشتقاق تدفقات الربع الرابع من بيانات SEC، ونوافذ التقدير لدراسات الأحداث. الحفاظ على هوية مراكز Futu وقيم MACD وBollinger الصغيرة، ورفض التباينات الخاصة السالبة، وتطبيق فروق الأسعار ورسوم التبييت الخاصة بكل زوج على رموز عملات Yahoo ([#1912](https://github.com/HKUDS/Vibe-Trading/pull/1912)، [#1920](https://github.com/HKUDS/Vibe-Trading/pull/1920)، [#1930](https://github.com/HKUDS/Vibe-Trading/pull/1930)). التفاصيل والقيود في [CHANGELOG](CHANGELOG.md).diff --git a/README_es.md b/README_es.mdindex ff37dd3e0..ffbe1d4fc 100644--- a/README_es.md+++ b/README_es.md@@ -52,6 +52,8 @@> ⚠️ **Advertencia de seguridad:** la cuenta de X `VibeTrading_HKU`, el proyecto de Virtuals `101845` y el contrato de token `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` no son activos oficiales de Vibe-Trading. Nunca hemos lanzado ni respaldado ningún token o memecoin. No compres, conectes una wallet ni firmes nada. [Detalles](SECURITY.md#official-channels--impersonation).+- **2026-10-21** 🛠️ **Cuentas de simulación y correcciones de la comunidad**: La simulación diaria incorpora accesos Agent/MCP, CLI, API y Web ([#1939](https://github.com/HKUDS/Vibe-Trading/pull/1939)). Se advierte sobre ajustes ignorados por el motor elegido ([#1947](https://github.com/HKUDS/Vibe-Trading/pull/1947)). Los flujos diarios vacíos activan la fuente alternativa; se identifica el proveedor real y se distingue el flujo neto total del de grandes órdenes. Se aclara la configuración de Telegram. Más correcciones y límites en [CHANGELOG](CHANGELOG.md).+- **2026-10-20** 🛠️ **Diagnóstico de backtests y precisión del análisis**: Advertimos sobre claves de configuración no reconocidas, mostramos las correlaciones indefinidas como desconocidas en vez de cero y reutilizamos el factor de anualización guardado al revalidar ([#1935](https://github.com/HKUDS/Vibe-Trading/pull/1935), [#1933](https://github.com/HKUDS/Vibe-Trading/pull/1933), [#1915](https://github.com/HKUDS/Vibe-Trading/pull/1915)). También mejoramos las comprobaciones de muestras de factores, la validación de entradas, la clasificación de mercados en diarios de operaciones, el formato numérico y las respuestas en streaming de WeCom. Las 14 correcciones y sus límites están en [CHANGELOG](CHANGELOG.md).- **2026-10-19** 🛠️ **Nueve correcciones de cálculos financieros**: Corregimos los pesos temporales de factores, los límites de precios de acciones A y los códigos de Pekín, la derivación de flujos del cuarto trimestre de la SEC y las ventanas de estimación de estudios de eventos. Conservamos la identidad de posiciones Futu y valores diminutos de MACD/Bollinger; rechazamos varianzas específicas negativas y aplicamos diferenciales y swaps por par a los símbolos de divisas de Yahoo ([#1912](https://github.com/HKUDS/Vibe-Trading/pull/1912), [#1920](https://github.com/HKUDS/Vibe-Trading/pull/1920), [#1930](https://github.com/HKUDS/Vibe-Trading/pull/1930)). Detalles y límites de las nueve correcciones en [CHANGELOG](CHANGELOG.md).diff --git a/README_id.md b/README_id.mdindex 92565e10a..d9113e6ad 100644--- a/README_id.md+++ b/README_id.md@@ -53,6 +53,8 @@> ⚠️ **Peringatan keamanan:** Akun X `VibeTrading_HKU`, proyek Virtuals `101845`, dan kontrak token `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` bukan aset resmi Vibe-Trading. Kami tidak pernah meluncurkan atau mendukung token maupun memecoin apa pun. Jangan membeli, menghubungkan wallet, atau menandatangani apa pun. [Detail](SECURITY.md#official-channels--impersonation).+- **2026-10-21** 🛠️ **Akun simulasi dan perbaikan komunitas**: Simulasi perdagangan harian kini tersedia melalui Agent/MCP, CLI, API, dan Web ([#1939](https://github.com/HKUDS/Vibe-Trading/pull/1939)). Pengaturan yang diabaikan mesin terpilih memunculkan peringatan ([#1947](https://github.com/HKUDS/Vibe-Trading/pull/1947)). Respons arus dana harian yang kosong memicu sumber cadangan; sumber sebenarnya dicantumkan dan arus bersih total dipisahkan dari arus pesanan besar. Panduan Telegram diperjelas. Perbaikan dan batasan lainnya ada di [CHANGELOG](CHANGELOG.md).+- **2026-10-20** 🛠️ **Diagnostik backtest dan ketepatan analisis**: Memberi peringatan untuk kunci konfigurasi yang tidak dikenali, menampilkan korelasi yang tidak terdefinisi sebagai tidak diketahui alih-alih nol, dan menggunakan kembali faktor annualisasi tersimpan saat validasi ulang ([#1935](https://github.com/HKUDS/Vibe-Trading/pull/1935), [#1933](https://github.com/HKUDS/Vibe-Trading/pull/1933), [#1915](https://github.com/HKUDS/Vibe-Trading/pull/1915)). Juga memperbaiki pemeriksaan sampel faktor, validasi masukan alat, klasifikasi pasar dalam jurnal perdagangan, format angka, dan balasan streaming WeCom. Seluruh 14 perbaikan dan batasan yang tersisa ada di [CHANGELOG](CHANGELOG.md).- **2026-10-19** 🛠️ **Sembilan perbaikan perhitungan keuangan**: Memperbaiki bobot peluruhan faktor, batas harga saham A dan kode Beijing, derivasi arus kuartal keempat SEC, serta jendela estimasi studi peristiwa. Mempertahankan identitas posisi Futu dan nilai MACD/Bollinger yang sangat kecil; menolak varians spesifik negatif dan menerapkan spread serta swap per pasangan pada simbol valas Yahoo ([#1912](https://github.com/HKUDS/Vibe-Trading/pull/1912), [#1920](https://github.com/HKUDS/Vibe-Trading/pull/1920), [#1930](https://github.com/HKUDS/Vibe-Trading/pull/1930)). Rincian sembilan perbaikan dan batasannya ada di [CHANGELOG](CHANGELOG.md).diff --git a/README_ja.md b/README_ja.mdindex 131eb8748..2cb238e31 100644--- a/README_ja.md+++ b/README_ja.md@@ -52,6 +52,8 @@> ⚠️ **セキュリティ警告:** Xアカウント `VibeTrading_HKU`、Virtualsプロジェクト `101845`、およびトークンコントラクト `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` は、いずれもVibe-Trading公式のものではありません。Vibe-Tradingはこれまで、いかなるトークンやミームコインも発行・公認していません。購入、ウォレットの接続、署名は行わないでください。[詳細](SECURITY.md#official-channels--impersonation)+- **2026-10-21** 🛠️ **ペーパー口座とコミュニティの問題修正**:日次ペーパー取引に Agent/MCP、CLI、API、Web の入口を追加([#1939](https://github.com/HKUDS/Vibe-Trading/pull/1939))。選択したエンジンが無視する設定を警告します([#1947](https://github.com/HKUDS/Vibe-Trading/pull/1947))。資金フローの日次空レスポンスでも代替ソースを試し、実際の出所を表示して総純流入と大口純流入を区別します。Telegram の設定手順を補足。その他の修正と制約は [CHANGELOG](CHANGELOG.md) を参照してください。+- **2026-10-20** 🛠️ **バックテスト診断と研究結果の正確性**:認識されない設定キーを警告し、未定義の相関をゼロではなく不明として表示。再検証では保存済みの年率換算係数を再利用します([#1935](https://github.com/HKUDS/Vibe-Trading/pull/1935), [#1933](https://github.com/HKUDS/Vibe-Trading/pull/1933), [#1915](https://github.com/HKUDS/Vibe-Trading/pull/1915))。因子のサンプル数チェック、ツール入力検証、取引日誌の市場分類、数値表示、WeComのストリーミング返信も改善。全14件の修正と残る制約は [CHANGELOG](CHANGELOG.md)。- **2026-10-19** 🛠️ **金融計算の9件の修正**:因子の減衰ウェイト、A株の市場別値幅制限と北京銘柄コード、SEC第4四半期のフロー推計、イベント分析の推定期間を修正。Futu保有銘柄の識別と微小なMACD・ボリンジャーバンドの値を保持し、負の固有分散を拒否。Yahooの為替コードにも通貨ペア別スプレッドとスワップを適用します([#1912](https://github.com/HKUDS/Vibe-Trading/pull/1912)、[#1920](https://github.com/HKUDS/Vibe-Trading/pull/1920)、[#1930](https://github.com/HKUDS/Vibe-Trading/pull/1930))。全9件の詳細と制約は [CHANGELOG](CHANGELOG.md)。diff --git a/README_ko.md b/README_ko.mdindex 292cc4746..b4c35e65b 100644--- a/README_ko.md+++ b/README_ko.md@@ -52,6 +52,8 @@> ⚠️ **보안 경고:** X 계정 `VibeTrading_HKU`, Virtuals 프로젝트 `101845`, 토큰 컨트랙트 `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4`는 모두 Vibe-Trading 공식과 무관합니다. Vibe-Trading은 어떠한 토큰이나 밈코인도 발행하거나 공식적으로 지지한 적이 없습니다. 해당 토큰을 구매하거나 지갑을 연결하거나 어떠한 서명도 하지 마세요. [자세히 보기](SECURITY.md#official-channels--impersonation).+- **2026-10-21** 🛠️ **모의 계좌와 커뮤니티 문제 수정**: 일별 모의 거래에 Agent/MCP, CLI, API, Web 진입점을 추가했습니다([#1939](https://github.com/HKUDS/Vibe-Trading/pull/1939)). 선택한 엔진이 무시하는 설정을 경고합니다([#1947](https://github.com/HKUDS/Vibe-Trading/pull/1947)). 일별 자금 흐름 응답이 비어 있어도 대체 소스를 시도하며, 실제 출처와 전체 순유입·대형 주문 순유입을 구분합니다. Telegram 설정 안내를 보완했습니다. 다른 수정과 제한 사항은 [CHANGELOG](CHANGELOG.md)를 참고하세요.+- **2026-10-20** 🛠️ **백테스트 진단과 연구 결과의 정확성**: 인식되지 않는 백테스트 설정 키를 경고하고, 정의되지 않은 상관관계를 0 대신 알 수 없음으로 표시하며, 재검증 시 저장된 연율화 계수를 재사용합니다([#1935](https://github.com/HKUDS/Vibe-Trading/pull/1935), [#1933](https://github.com/HKUDS/Vibe-Trading/pull/1933), [#1915](https://github.com/HKUDS/Vibe-Trading/pull/1915)). 팩터 표본 수 검사, 도구 입력 검증, 거래 일지 시장 분류, 숫자 표시와 WeCom 스트리밍 응답도 개선했습니다. 전체 14건의 수정과 남은 제한 사항은 [CHANGELOG](CHANGELOG.md)를 참고하세요.- **2026-10-19** 🛠️ **금융 계산 오류 9건 수정**: 팩터 감쇠 가중치, A주 시장별 가격 제한과 베이징 종목 코드, SEC 4분기 유량 추정, 이벤트 연구 추정 기간을 수정했습니다. Futu 보유 종목 식별과 작은 MACD·볼린저 밴드 값을 보존하고 음의 고유 분산을 거부합니다. Yahoo 외환 코드에도 통화쌍별 스프레드와 스왑을 적용합니다([#1912](https://github.com/HKUDS/Vibe-Trading/pull/1912), [#1920](https://github.com/HKUDS/Vibe-Trading/pull/1920), [#1930](https://github.com/HKUDS/Vibe-Trading/pull/1930)). 전체 9건과 제한 사항은 [CHANGELOG](CHANGELOG.md)를 참고하세요.diff --git a/README_zh.md b/README_zh.mdindex 791a2ab80..5dea01609 100644--- a/README_zh.md+++ b/README_zh.md@@ -52,6 +52,8 @@> ⚠️ **安全警告:** X 账号 `VibeTrading_HKU`、Virtuals 项目 `101845` 及代币合约 `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` 均非 Vibe-Trading 官方。我们从未发行或背书任何代币或 meme 币。请勿购买、连接钱包或签名。[详细说明](SECURITY.md#official-channels--impersonation)。+- **2026-10-21** 🛠️ **模拟账户与社区问题修复**:逐日模拟交易已提供 Agent/MCP、CLI、API 和 Web 入口([#1939](https://github.com/HKUDS/Vibe-Trading/pull/1939));回测会提示所选引擎忽略的配置([#1947](https://github.com/HKUDS/Vibe-Trading/pull/1947))。资金流日线空响应也会触发备用源,并标明实际来源、区分总净流入与主力净流入。补充 Telegram 配置步骤;交易日志、期货单位、归因、取消上传和目录错误修复详见 [CHANGELOG](CHANGELOG.md)。+- **2026-10-20** 🛠️ **回测诊断与研究正确性**:对无法识别的回测配置键发出告警,将未定义的相关性显示为未知而非零,并在重新验证时复用已保存的年化因子([#1935](https://github.com/HKUDS/Vibe-Trading/pull/1935), [#1933](https://github.com/HKUDS/Vibe-Trading/pull/1933), [#1915](https://github.com/HKUDS/Vibe-Trading/pull/1915))。同时改进因子样本检查、工具输入校验、交易日志市场分类、数值格式和企业微信流式回复。完整 14 项修复及剩余限制见 [CHANGELOG](CHANGELOG.md)。- **2026-10-19** 🛠️ **九项金融计算修复**:纠正因子衰减的新旧数据权重、A 股板块涨跌幅与北交所代码识别、SEC 第四季度流量推导及事件研究估计窗口。保留富途持仓代码身份和极小 MACD/布林带数值;拒绝负特异方差,让 Yahoo 外汇代码使用对应货币对的点差与隔夜费([#1912](https://github.com/HKUDS/Vibe-Trading/pull/1912)、[#1920](https://github.com/HKUDS/Vibe-Trading/pull/1920)、[#1930](https://github.com/HKUDS/Vibe-Trading/pull/1930))。完整九项修复与限制见 [CHANGELOG](CHANGELOG.md)。diff --git a/agent/src/tools/fund_flow_tool.py b/agent/src/tools/fund_flow_tool.pyindex fb736f1eb..af0e64247 100644--- a/agent/src/tools/fund_flow_tool.py+++ b/agent/src/tools/fund_flow_tool.py@@ -9,6 +9,10 @@ are delegated to :mod:`backtest.loaders.eastmoney_client` (every request routesthrough the shared per-host throttle — Eastmoney rate-limits by IP and bansbursting clients).+Daily A-share requests fall back to Tushare on failed or empty responses;+source labels identify the provider actually used. Minute data is never+substituted with daily bars.+Markets: A-share (``.SH`` / ``.SZ`` / ``.BJ``), Hong Kong (``.HK``) and US(``.US``). One unresolvable or failing symbol never aborts the batch."""@@ -17,6 +21,7 @@ from __future__ import annotationsimport jsonimport logging+import mathfrom typing import Anyfrom backtest.loaders.eastmoney_client import get_json, resolve_secid@@ -80,11 +85,35 @@ def _parse_flow_row(raw: str) -> dict[str, Any] | None:values = [float(parts[i + 1]) for i in range(len(_BUCKETS))]except (ValueError, TypeError):return None+ if not all(math.isfinite(value) for value in values):+ return Nonerow: dict[str, Any] = {"timestamp": timestamp}row.update(dict(zip(_BUCKETS, values)))return row+def _fallback_flow(symbol: str, *, period: str, days: int, reason: str) -> dict[str, Any]:+ """Recover daily data without disguising errors as observations.++ Args:+ symbol: Requested instrument, including its market suffix.+ period: Requested granularity; only daily data has a fallback.+ days: Maximum number of daily bars to retrieve.+ reason: Why the primary source could not provide usable data.++ Returns:+ Labelled fallback data or a per-symbol error with both failure reasons.+ """+ result: dict[str, Any] = {"symbol": symbol, "error": reason}+ if period == "daily":+ try:+ fallback = tushare_fallbacks.fetch_fund_flow(symbol, days=days)+ return {**fallback, "warning": f"{reason}; used tushare fallback"}+ except Exception as exc: # noqa: BLE001 - preserve per-symbol failures+ result["fallback_error"] = str(exc)+ return result++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.@@ -99,18 +128,7 @@ def _fetch_symbol_flow(symbol: str, *, period: str, days: int) -> dict[str, Any]"""secid = resolve_secid(symbol)if secid is None:- if period == "daily":- try:- fallback = tushare_fallbacks.fetch_fund_flow(symbol, days=days)- fallback["warning"] = "eastmoney symbol resolution failed; used tushare fallback"- return fallback- except Exception as exc: # noqa: BLE001 - fallback details belong in the symbol result- return {- "symbol": symbol,- "error": "unresolvable symbol",- "fallback_error": str(exc),- }- return {"symbol": symbol, "error": "unresolvable symbol"}+ return _fallback_flow(symbol, period=period, days=days, reason="unresolvable symbol")is_daily = period == "daily"url = _DAILY_URL if is_daily else _MINUTE_URL@@ -125,25 +143,12 @@ def _fetch_symbol_flow(symbol: str, *, period: str, days: int) -> dict[str, Any]payload = get_json(url, params=params)except Exception as exc: # noqa: BLE001 - one bad symbol must not kill the batchlogger.warning("fund flow fetch failed for %s: %s", symbol, exc)- if period == "daily":- try:- fallback = tushare_fallbacks.fetch_fund_flow(symbol, days=days)- fallback["warning"] = f"eastmoney failed ({exc}); used tushare fallback"- return fallback- except Exception as fallback_exc: # noqa: BLE001 - keep per-symbol isolation- return {- "symbol": symbol,- "error": str(exc),- "fallback_error": str(fallback_exc),- }- return {"symbol": symbol, "error": str(exc)}+ return _fallback_flow(symbol, period=period, days=days, reason=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")+ klines = data.get("klines") if isinstance(data, dict) else Noneif not isinstance(klines, list):- return {"symbol": symbol, "secid": secid, "rows": []}+ klines = []rows: list[dict[str, Any]] = []for raw in klines:@@ -153,12 +158,16 @@ def _fetch_symbol_flow(symbol: str, *, period: str, days: int) -> dict[str, Any]if parsed is not None:rows.append(parsed)+ if not rows and is_daily:+ return _fallback_flow(+ symbol, period=period, days=days, reason="eastmoney returned no valid fund-flow rows"+ )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}+ return {"symbol": symbol, "secid": secid, "source": "eastmoney", "rows": rows}class FundFlowTool(BaseTool):@@ -172,7 +181,9 @@ class FundFlowTool(BaseTool):"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: "+ "(.SH/.SZ/.BJ), Hong Kong (.HK) and US (.US). Daily A-share fallback uses "+ "TUSHARE_TOKEN; source and methodology are labelled per symbol. Missing "+ "buckets remain null, not zero. Example: "'{"codes": ["600519.SH", "00700.HK"], "period": "daily", "days": 30}.')parameters = {@@ -239,10 +250,15 @@ class FundFlowTool(BaseTool):symbol: _fetch_symbol_flow(symbol, period=period, days=days)for symbol in (c.strip() for c in codes)}+ sources = {+ result["source"] for result in results.values()+ if result.get("rows") and result.get("source")+ }+ source = next(iter(sources)) if len(sources) == 1 else ("mixed" if sources else None)envelope = {"ok": True,"market": "stock",- "source": "eastmoney",+ "source": source,"fallback_sources": ["tushare"],"period": period,"buckets": list(_BUCKETS),diff --git a/agent/src/tools/tushare_fallbacks.py b/agent/src/tools/tushare_fallbacks.pyindex 79871a27b..e36689e0b 100644--- a/agent/src/tools/tushare_fallbacks.py+++ b/agent/src/tools/tushare_fallbacks.py@@ -7,6 +7,7 @@ same research workflow through a separate provider with a compatible envelope.from __future__ import annotations+import mathfrom datetime import date, timedeltafrom typing import Any@@ -79,11 +80,12 @@ def _to_float(value: Any) -> float | None:def _net_amount(row: dict[str, Any], buy_key: str, sell_key: str) -> float | None:buy = _to_float(row.get(buy_key))sell = _to_float(row.get(sell_key))- if buy is None and sell is None:+ if buy is None or sell is None or not math.isfinite(buy) or not math.isfinite(sell):return None# Tushare moneyflow amount fields are in 10k CNY; the Eastmoney tool emits# CNY, so convert to keep the existing bucket units.- return ((buy or 0.0) - (sell or 0.0)) * 10_000+ value = (buy - sell) * 10_000+ return value if math.isfinite(value) else Nonedef _ts_code(code: str) -> str:@@ -111,6 +113,18 @@ def _ts_code(code: str) -> str:def fetch_fund_flow(symbol: str, *, days: int) -> dict[str, Any]:+ """Read daily Tushare buckets with explicit units and missing observations.++ Args:+ symbol: A-share instrument accepted by the Tushare adapter.+ days: Maximum number of recent trading days to return.++ Returns:+ Source-labelled rows in CNY, with total flow separate from main orders.++ Raises:+ TushareFallbackUnavailable: Symbol, credentials or data are unavailable.+ """ts_code = _ts_code(symbol)start_date, end_date = _date_window(days)rows = _records(@@ -118,19 +132,43 @@ def fetch_fund_flow(symbol: str, *, days: int) -> dict[str, Any]:)parsed: list[dict[str, Any]] = []for row in rows:+ large = _net_amount(row, "buy_lg_amount", "sell_lg_amount")+ super_large = _net_amount(row, "buy_elg_amount", "sell_elg_amount")+ net_total = _to_float(row.get("net_mf_amount"))+ net_total = net_total * 10_000 if net_total is not None else None+ if net_total is not None and not math.isfinite(net_total):+ net_total = None+ # moneyflow.net_mf_amount is total net flow, not the main-order bucket.+ # https://tushare.pro/document/2?doc_id=170+ main = large + super_large if large is not None and super_large is not None else None+ if main is not None and not math.isfinite(main):+ main = Noneparsed.append({"timestamp": _dashed_date(row.get("trade_date")),- "main": (_to_float(row.get("net_mf_amount")) or 0.0) * 10_000,+ "main": main,+ "net_total": net_total,"small": _net_amount(row, "buy_sm_amount", "sell_sm_amount"),"medium": _net_amount(row, "buy_md_amount", "sell_md_amount"),- "large": _net_amount(row, "buy_lg_amount", "sell_lg_amount"),- "super_large": _net_amount(row, "buy_elg_amount", "sell_elg_amount"),+ "large": large,+ "super_large": super_large,})+ if not parsed:+ raise TushareFallbackUnavailable("tushare returned no fund-flow rows")parsed.sort(key=lambda item: item.get("timestamp") or "")parsed = parsed[-days:]- return {"symbol": symbol, "ts_code": ts_code, "source": "tushare", "rows": parsed}+ return {+ "symbol": symbol,+ "ts_code": ts_code,+ "source": "tushare",+ "rows": parsed,+ "methodology": (+ "Tushare moneyflow active buy/sell buckets in CNY; main = large + "+ "super_large; net_total is the provider's total net flow. "+ "Provider classifications may differ from Eastmoney."+ ),+ }def fetch_dragon_tiger(trade_date: str, code: str | None) -> dict[str, Any]:diff --git a/agent/tests/test_fund_flow_tool.py b/agent/tests/test_fund_flow_tool.pyindex 5d992ed32..52e345299 100644--- a/agent/tests/test_fund_flow_tool.py+++ b/agent/tests/test_fund_flow_tool.py@@ -7,6 +7,8 @@ All HTTP is mocked at the Eastmoney client functions the tool importsfrom __future__ import annotationsimport json++import pytestfrom unittest.mock import patchfrom src.tools.fund_flow_tool import FundFlowTool@@ -204,3 +206,50 @@ class TestRoutingDescription:def test_description_keeps_a_concrete_example(self):assert '{"codes": ["600519.SH"' in FundFlowTool().description++[email protected]("response", [None, {"data": None}, {"data": {}},+ {"data": {"klines": []}},+ {"data": {"klines": ["bad", "2024-01-03,nan,1,2,3,4"]}}])+def test_daily_empty_or_invalid_response_recovers_with_labelled_fallback(response):+ fallback = {"symbol": "600519.SH", "source": "tushare",+ "rows": [{"timestamp": "2024-01-03", "main": 100.0}]}+ with patch("src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"), \+ patch("src.tools.fund_flow_tool.get_json", return_value=response), \+ patch("src.tools.fund_flow_tool.tushare_fallbacks.fetch_fund_flow", return_value=fallback):+ payload = json.loads(FundFlowTool().execute(codes=["600519.SH"]))+ assert payload["source"] == "tushare"+ assert payload["data"]["600519.SH"]["rows"] == fallback["rows"]+ assert "warning" in payload["data"]["600519.SH"]+++def test_mixed_sources_are_reported_per_symbol():+ with patch("src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"), \+ patch("src.tools.fund_flow_tool.get_json", side_effect=[_DAILY_PAYLOAD, RuntimeError("offline")]), \+ patch("src.tools.fund_flow_tool.tushare_fallbacks.fetch_fund_flow", return_value={+ "source": "tushare", "rows": [{"timestamp": "2024-01-03", "main": 1.0}]}):+ payload = json.loads(FundFlowTool().execute(codes=["600519.SH", "000001.SZ"]))+ assert payload["source"] == "mixed"+ assert payload["data"]["600519.SH"]["source"] == "eastmoney"+ assert payload["data"]["000001.SZ"]["source"] == "tushare"+++def test_no_daily_data_reports_both_sources_without_fabricating_rows():+ with patch("src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"), \+ patch("src.tools.fund_flow_tool.get_json", return_value={"data": None}), \+ patch("src.tools.fund_flow_tool.tushare_fallbacks.fetch_fund_flow",+ side_effect=RuntimeError("TUSHARE_TOKEN is not configured")):+ payload = json.loads(FundFlowTool().execute(codes=["600519.SH"]))+ result = payload["data"]["600519.SH"]+ assert payload["source"] is None+ assert "error" in result and "TUSHARE_TOKEN" in result["fallback_error"]+ assert not result.get("rows")+++def test_minute_empty_response_does_not_substitute_daily_data():+ with patch("src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"), \+ patch("src.tools.fund_flow_tool.get_json", return_value={"data": None}), \+ patch("src.tools.fund_flow_tool.tushare_fallbacks.fetch_fund_flow") as fallback:+ payload = json.loads(FundFlowTool().execute(codes=["600519.SH"], period="min"))+ fallback.assert_not_called()+ assert not payload["data"]["600519.SH"].get("rows")diff --git a/agent/tests/test_tushare_fallbacks.py b/agent/tests/test_tushare_fallbacks.pyindex c4e7955d8..120183315 100644--- a/agent/tests/test_tushare_fallbacks.py+++ b/agent/tests/test_tushare_fallbacks.py@@ -6,6 +6,8 @@ touch the network or require a real token.from __future__ import annotations+import pytest+from types import SimpleNamespacefrom unittest.mock import patch@@ -37,7 +39,8 @@ def test_fund_flow_maps_moneyflow_buckets_to_existing_schema() -> None:row = result["rows"][0]assert result["source"] == "tushare"assert row["timestamp"] == "2024-01-03"- assert row["main"] == 125000.0+ assert row["main"] == 330000.0+ assert row["net_total"] == 125000.0assert row["small"] == 20000.0assert row["medium"] == -30000.0assert row["large"] == 130000.0@@ -127,3 +130,34 @@ def test_ts_code_routes_beijing_920_codes_to_bj() -> None:assert tf._ts_code("900901") == "900901.SH"assert tf._ts_code("600519") == "600519.SH"assert tf._ts_code("000001") == "000001.SZ"++[email protected]("missing", [None, "-", float("nan"), float("inf")])+def test_fund_flow_missing_side_is_not_zero_or_total_flow(missing):+ pro = SimpleNamespace(moneyflow=lambda **_: [{+ "trade_date": "20240103", "net_mf_amount": 999,+ "buy_lg_amount": missing, "sell_lg_amount": 7,+ "buy_elg_amount": 30, "sell_elg_amount": 10,+ }])+ with patch.object(tf, "_pro_api", return_value=pro):+ row = tf.fetch_fund_flow("600519.SH", days=5)["rows"][0]+ assert row["large"] is None+ assert row["main"] is None+ assert row["small"] is None+ assert row["super_large"] == 200000+++def test_empty_tushare_fund_flow_is_unavailable():+ with patch.object(tf, "_pro_api", return_value=SimpleNamespace(moneyflow=lambda **_: [])):+ with pytest.raises(tf.TushareFallbackUnavailable, match="no.*rows"):+ tf.fetch_fund_flow("600519.SH", days=5)+++def test_real_zero_buckets_stay_zero_and_absent_total_stays_unknown():+ data = {"trade_date": "20240103"}+ for size in ("sm", "md", "lg", "elg"):+ data[f"buy_{size}_amount"] = data[f"sell_{size}_amount"] = 0+ with patch.object(tf, "_pro_api", return_value=SimpleNamespace(moneyflow=lambda **_: [data])):+ row = tf.fetch_fund_flow("600519.SH", days=5)["rows"][0]+ assert all(row[key] == 0 for key in ("main", "small", "medium", "large", "super_large"))+ assert row["net_total"] is None