"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: cross-market composite backtest engine with shared capital pool
warren6181f8f4a005f9b
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 8d988a72f..551b119e7 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -42,7 +42,7 @@ cd frontend && npm install && npm run dev| Directory | What lives here | Open to contribute? ||-----------|----------------|:-------------------:|-| `agent/src/skills/` | 68 finance skill definitions (SKILL.md) | Yes |+| `agent/src/skills/` | 69 finance skill definitions (SKILL.md) | Yes || `agent/src/tools/` | 21 agent tools | Yes || `agent/backtest/` | Backtest engines, loaders, optimizers | Yes || `agent/config/swarm/` | 29 swarm preset YAMLs | Yes |diff --git a/README.md b/README.mdindex 09626ecb3..24300363c 100644--- a/README.md+++ b/README.md@@ -19,7 +19,7 @@<a href="https://pypi.org/project/vibe-trading-ai/"><img src="https://img.shields.io/pypi/v/vibe-trading-ai?style=flat&logo=pypi&logoColor=white" alt="PyPI"></a><a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow?style=flat" alt="License"></a><br>- <img src="https://img.shields.io/badge/Skills-68-orange" alt="Skills">+ <img src="https://img.shields.io/badge/Skills-69-orange" alt="Skills"><img src="https://img.shields.io/badge/Swarm_Presets-29-7C3AED" alt="Swarm"><img src="https://img.shields.io/badge/Tools-21-0F766E" alt="Tools"><img src="https://img.shields.io/badge/Data_Sources-5-2563EB" alt="Data Sources">@@ -51,6 +51,7 @@## 📰 News+- **2026-04-13** 🌐 **Cross-Market Composite Backtest**: New `CompositeEngine` enables backtesting portfolios that span multiple markets (e.g. A-shares + crypto) in a single run with a **shared capital pool**. Per-market rules (T+1, funding fees, swap) enforced per symbol, signals aligned on each symbol's own trading calendar. Use `source: "auto"` with mixed codes like `["000001.SZ", "BTC-USDT"]`. Includes volatility-adjusted weighting skill and calendar-day annualization for accurate cross-market Sharpe.- **2026-04-12** 🌍 **Multi-Platform Indicator Export**: `/pine` now exports strategies to **TradingView (Pine Script v6)**, **通达信/同花顺/东方财富 (TDX formula)**, and **MetaTrader 5 (MQL5)** in a single file — covering international equities, China A-shares, and global forex/CFD markets. One command, three platforms.- **2026-04-11** 🛡️ **Reliability & DX**: `vibe-trading init` interactive .env bootstrap ([#19](https://github.com/HKUDS/Vibe-Trading/pull/19)), startup preflight checks for LLM & data sources, runtime data-source fallback when primary returns empty, hardened backtest engine with data validation & error isolation, date/time context injection into agent & swarm prompts. Multi-language README (zh/ja/ko) via community PR [#21](https://github.com/HKUDS/Vibe-Trading/pull/21).- **2026-04-10** 📦 **v0.1.4**: Fix Docker build ([#8](https://github.com/HKUDS/Vibe-Trading/issues/8)), add `web_search` MCP tool (17 total), `akshare`/`ccxt` in deps & MCP. 11 LLM providers (DeepSeek, Groq, Gemini, Ollama, etc.), all tuning params via `.env`. Hardened `ml-strategy` skill. Published to PyPI and ClawHub.@@ -81,7 +82,7 @@ Vibe-Trading is an AI-powered multi-agent finance workspace that turns natural l<td align="center" width="25%" valign="top"><img src="assets/scene-research.png" height="150" alt="Research"/><br><h3>🔍 DeepResearch for Trading</h3>- <img src="https://img.shields.io/badge/68_Skills-FF6B6B?style=for-the-badge&logo=bookstack&logoColor=white" alt="Skills" /><br><br>+ <img src="https://img.shields.io/badge/69_Skills-FF6B6B?style=for-the-badge&logo=bookstack&logoColor=white" alt="Skills" /><br><br><div align="left" style="font-size: 4px;">• Multi-domain analysis coverage across markets<br>• Auto strategy and signal generation<br>@@ -106,7 +107,7 @@ Vibe-Trading is an AI-powered multi-agent finance workspace that turns natural l<img src="https://img.shields.io/badge/5_Data_Sources-FFD93D?style=for-the-badge&logo=bitcoin&logoColor=black" alt="Backtest" /><br><br><div align="left">• A-shares, HK/US equities, crypto, futures & forex<br>- • 7 market engines: A-share, US/HK equity, crypto, China futures, global futures, forex<br>+ • 7 market engines + composite cross-market engine with shared capital pool<br>• Statistical validation: Monte Carlo, Bootstrap CI, Walk-Forward<br>• 15+ performance metrics & 4 optimizers</div>@@ -125,16 +126,16 @@ Vibe-Trading is an AI-powered multi-agent finance workspace that turns natural l</tr></table>-## 68 Skills across 7 Categories+## 69 Skills across 7 Categories-- 📊 68 specialized finance skills organized into 7 categories+- 📊 69 specialized finance skills organized into 7 categories- 🌐 Complete coverage from traditional markets to crypto & DeFi- 🔬 Comprehensive capabilities spanning data sourcing to quantitative research| Category | Skills | Examples ||----------|--------|----------|| Data Source | 6 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `ccxt` |-| Strategy | 16 | `strategy-generate`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |+| Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 15 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` || Crypto | 7 | `perp-funding-basis`, `liquidation-heatmap`, `stablecoin-flow`, `defi-yield`, `onchain-analysis` |@@ -326,7 +327,7 @@ vibe-trading serve # API server| Command | Description ||---------|-------------|| `/help` | Show all commands |-| `/skills` | List all 68 finance skills |+| `/skills` | List all 69 finance skills || `/swarm` | List 29 swarm team presets || `/swarm run <preset> [vars_json]` | Run a swarm team with live streaming || `/swarm list` | Swarm run history |@@ -460,7 +461,7 @@ Browse on ClawHub: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills/vi<details><summary><b>OpenSpace — self-evolving skills</b></summary>-All 68 finance skills are published on [open-space.cloud](https://open-space.cloud) and evolve autonomously through OpenSpace's self-evolution engine.+All 69 finance skills are published on [open-space.cloud](https://open-space.cloud) and evolve autonomously through OpenSpace's self-evolution engine.To use with OpenSpace, add both MCP servers to your agent config:@@ -482,7 +483,7 @@ To use with OpenSpace, add both MCP servers to your agent config:}```-OpenSpace will auto-discover all 68 skills, enabling auto-fix, auto-improve, and community sharing. Search for Vibe-Trading skills via `search_skills("finance backtest")` in any OpenSpace-connected agent.+OpenSpace will auto-discover all 69 skills, enabling auto-fix, auto-improve, and community sharing. Search for Vibe-Trading skills via `search_skills("finance backtest")` in any OpenSpace-connected agent.</details>@@ -503,7 +504,7 @@ Vibe-Trading/│ ├── src/│ │ ├── agent/ # ReAct agent core│ │ │ ├── loop.py # main reasoning loop-│ │ │ ├── skills.py # skill loader (68 SKILL.md files, 7 categories)+│ │ │ ├── skills.py # skill loader (69 SKILL.md files, 7 categories)│ │ │ ├── tools.py # tool orchestration│ │ │ ├── context.py # system prompt builder│ │ │ ├── memory.py # run memory / artifact store@@ -520,13 +521,13 @@ Vibe-Trading/│ │ │ ├── swarm_tool.py # launch swarm teams│ │ │ └── ... # file I/O, bash, tasks, etc.│ │ │-│ │ ├── skills/ # 68 finance skills in 7 categories (SKILL.md each)+│ │ ├── skills/ # 69 finance skills in 7 categories (SKILL.md each)│ │ ├── swarm/ # Swarm DAG execution engine│ │ ├── session/ # Multi-turn chat session management│ │ └── providers/ # LLM provider abstraction│ ││ ├── backtest/ # Backtest engines-│ │ ├── engines/ # 7 engines: china_a, global_equity, crypto, china_futures, global_futures, forex + options_portfolio+│ │ ├── engines/ # 7 engines + composite cross-market engine + options_portfolio│ │ ├── loaders/ # 5 sources: tushare, okx, yfinance, akshare, ccxt│ │ │ ├── base.py # DataLoader Protocol│ │ │ └── registry.py # Registry + auto-fallback chainsdiff --git a/README_ar.md b/README_ar.mdindex 3fd344a9e..e94ed9fd4 100644--- a/README_ar.md+++ b/README_ar.md@@ -19,7 +19,7 @@<a href="https://pypi.org/project/vibe-trading-ai/"><img src="https://img.shields.io/pypi/v/vibe-trading-ai?style=flat&logo=pypi&logoColor=white" alt="PyPI"></a><a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow?style=flat" alt="الرخصة"></a><br>- <img src="https://img.shields.io/badge/Skills-68-orange" alt="المهارات">+ <img src="https://img.shields.io/badge/Skills-69-orange" alt="المهارات"><img src="https://img.shields.io/badge/Swarm_Presets-29-7C3AED" alt="السرب"><img src="https://img.shields.io/badge/Tools-21-0F766E" alt="الأدوات"><img src="https://img.shields.io/badge/Data_Sources-5-2563EB" alt="مصادر البيانات">@@ -51,6 +51,7 @@## 📰 أحدث الأخبار+- **2026-04-13** 🌐 **الاختبار الرجعي المركب عبر الأسواق**: محرك `CompositeEngine` الجديد يتيح اختبار محافظ تشمل أسواقاً مختلفة (مثل أسهم A + العملات المشفرة) في تشغيل واحد مع **مجمع رأسمال مشترك**. قواعد كل سوق (T+1، رسوم التمويل، المقايضة) تُطبق لكل رمز، الإشارات تُحاذى وفق التقويم التجاري لكل رمز. استخدم `source: "auto"` مع رموز مختلطة مثل `["000001.SZ", "BTC-USDT"]`.- **2026-04-11** 🛡️ **الموثوقية وتجربة المطور**: إعداد تفاعلي لملف `.env` عبر `vibe-trading init` ([#19](https://github.com/HKUDS/Vibe-Trading/pull/19))، فحوصات بدء التشغيل المسبقة لمصادر البيانات ونماذج اللغة، بديل تلقائي لمصدر البيانات عند إرجاع المصدر الأساسي لنتائج فارغة، تعزيز محرك الاختبار الرجعي مع التحقق من البيانات وعزل الأخطاء، حقن سياق التاريخ/الوقت في أوامر الوكيل والسرب. ملف README متعدد اللغات (zh/ja/ko) عبر طلب سحب المجتمع [#21](https://github.com/HKUDS/Vibe-Trading/pull/21).- **2026-04-10** 📦 **الإصدار v0.1.4**: إصلاح بناء Docker ([#8](https://github.com/HKUDS/Vibe-Trading/issues/8))، إضافة أداة MCP `web_search` (17 إجمالاً)، `akshare`/`ccxt` في التبعيات وMCP. 11 مزود لنماذج اللغة (DeepSeek, Groq, Gemini, Ollama, إلخ)، جميع معلمات الضبط عبر `.env`. تعزيز مهارة `ml-strategy`. النشر على PyPI وClawHub.- **2026-04-09** 📊 **الموجة الثانية من الاختبار الرجعي — محركات متعددة الأصول**: إضافة العقود الآجلة الصينية (CFFEX/SHFE/DCE/ZCE، 50+ عقد)، العقود الآجلة العالمية (CME/ICE/Eurex، 30+ عقد)، الفوركس (24 زوجاً، السبريد + المقايضة)، الخيارات v2 (الممارسة الأمريكية، ابتسامة التقلب الضمني). التحقق الإحصائي: اختبار التبديل مونت كارلو، فاصل ثقة شارب bootstrap، تحليل المشي للأمام.@@ -80,7 +81,7 @@ Vibe-Trading هو مساحة عمل مالية متعددة الوكلاء مد<td align="center" width="25%" valign="top"><img src="assets/scene-research.png" height="150" alt="البحث"/><br><h3>🔍 بحث عميق للتداول</h3>- <img src="https://img.shields.io/badge/68_Skills-FF6B6B?style=for-the-badge&logo=bookstack&logoColor=white" alt="المهارات" /><br><br>+ <img src="https://img.shields.io/badge/69_Skills-FF6B6B?style=for-the-badge&logo=bookstack&logoColor=white" alt="المهارات" /><br><br><div align="left" style="font-size: 4px;">• تغطية تحليل متعددة المجالات عبر الأسواق<br>• توليد تلقائي للاستراتيجيات والإشارات<br>@@ -124,16 +125,16 @@ Vibe-Trading هو مساحة عمل مالية متعددة الوكلاء مد</tr></table>-## 68 مهارة عبر 7 فئات+## 69 مهارة عبر 7 فئات-- 📊 68 مهارة مالية متخصصة منظمة في 7 فئات+- 📊 69 مهارة مالية متخصصة منظمة في 7 فئات- 🌐 تغطية شاملة من الأسواق التقليدية إلى العملات المشفرة وDeFi- 🔬 قدرات شاملة تمتد من مصادر البيانات إلى البحث الكمي| الفئة | المهارات | أمثلة ||----------|--------|----------|| مصدر البيانات | 6 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `ccxt` |-| الاستراتيجية | 16 | `strategy-generate`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |+| الاستراتيجية | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || التحليل | 15 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis` || فئة الأصول | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` || العملات المشفرة | 7 | `perp-funding-basis`, `liquidation-heatmap`, `stablecoin-flow`, `defi-yield`, `onchain-analysis` |@@ -325,7 +326,7 @@ vibe-trading serve # خادم API| الأمر | الوصف ||---------|-------------|| `/help` | عرض جميع الأوامر |-| `/skills` | عرض جميع مهارات التداول الـ 68 |+| `/skills` | عرض جميع مهارات التداول الـ 69 || `/swarm` | عرض إعدادات فرق السرب الـ 29 || `/swarm run <preset> [vars_json]` | تشغيل فريق سرب مع بث مباشر || `/swarm list` | سجل تشغيلات السرب |@@ -459,7 +460,7 @@ npx clawhub@latest install vibe-trading --force<details><summary><b>OpenSpace — مهارات ذاتية التطور</b></summary>-جميع مهارات التداول الـ 68 منشورة على [open-space.cloud](https://open-space.cloud) وتتطور بشكل مستقل عبر محرك التطور الذاتي من OpenSpace.+جميع مهارات التداول الـ 69 منشورة على [open-space.cloud](https://open-space.cloud) وتتطور بشكل مستقل عبر محرك التطور الذاتي من OpenSpace.للاستخدام مع OpenSpace، أضف خادمي MCP إلى إعدادات وكيلك:@@ -481,7 +482,7 @@ npx clawhub@latest install vibe-trading --force}```-سيكتشف OpenSpace تلقائياً جميع المهارات الـ 68، مما يتيح الإصلاح التلقائي والتحسين التلقائي والمشاركة المجتمعية. ابحث عن مهارات Vibe-Trading عبر `search_skills("finance backtest")` في أي وكيل متصل بـ OpenSpace.+سيكتشف OpenSpace تلقائياً جميع المهارات الـ 69، مما يتيح الإصلاح التلقائي والتحسين التلقائي والمشاركة المجتمعية. ابحث عن مهارات Vibe-Trading عبر `search_skills("finance backtest")` في أي وكيل متصل بـ OpenSpace.</details>@@ -502,7 +503,7 @@ Vibe-Trading/│ ├── src/│ │ ├── agent/ # نواة وكيل ReAct│ │ │ ├── loop.py # حلقة الاستدلال الرئيسية-│ │ │ ├── skills.py # محمل المهارات (68 ملف SKILL.md، 7 فئات)+│ │ │ ├── skills.py # محمل المهارات (69 ملف SKILL.md، 7 فئات)│ │ │ ├── tools.py # تنسيق الأدوات│ │ │ ├── context.py # منشئ موجه النظام│ │ │ ├── memory.py # ذاكرة التشغيل / تخزين القطع الأثرية@@ -519,13 +520,13 @@ Vibe-Trading/│ │ │ ├── swarm_tool.py # إطلاق فرق السرب│ │ │ └── ... # إدخال/إخراج ملف، bash، مهام، إلخ│ │ │-│ │ ├── skills/ # 68 مهارة مالية في 7 فئات (SKILL.md لكل منها)+│ │ ├── skills/ # 69 مهارة مالية في 7 فئات (SKILL.md لكل منها)│ │ ├── swarm/ # محرك تنفيذ DAG للسرب│ │ ├── session/ # إدارة جلسات الدردشة متعددة الأدوار│ │ └── providers/ # تجريد مزود نموذج اللغة│ ││ ├── backtest/ # محركات الاختبار الرجعي-│ │ ├── engines/ # 7 محركات: china_a, global_equity, crypto, china_futures, global_futures, forex + options_portfolio+│ │ ├── engines/ # 7 محركات + محرك مركب عبر الأسواق + options_portfolio│ │ ├── loaders/ # 5 مصادر: tushare, okx, yfinance, akshare, ccxt│ │ │ ├── base.py # بروتوكول DataLoader│ │ │ └── registry.py # السجل + سلاسل البديل التلقائيdiff --git a/README_ja.md b/README_ja.mdindex dc9b77871..bd742d002 100644--- a/README_ja.md+++ b/README_ja.md@@ -19,7 +19,7 @@<a href="https://pypi.org/project/vibe-trading-ai/"><img src="https://img.shields.io/pypi/v/vibe-trading-ai?style=flat&logo=pypi&logoColor=white" alt="PyPI"></a><a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow?style=flat" alt="License"></a><br>- <img src="https://img.shields.io/badge/Skills-68-orange" alt="Skills">+ <img src="https://img.shields.io/badge/Skills-69-orange" alt="Skills"><img src="https://img.shields.io/badge/Swarm_Presets-29-7C3AED" alt="Swarm"><img src="https://img.shields.io/badge/Tools-21-0F766E" alt="Tools"><img src="https://img.shields.io/badge/Data_Sources-5-2563EB" alt="Data Sources">@@ -51,6 +51,7 @@## 📰 ニュース+- **2026-04-13** 🌐 **クロスマーケット複合バックテスト**: 新しい`CompositeEngine`により、異なる市場の銘柄(例:A株+暗号資産)を**共有資金プール**で同時にバックテスト可能。T+1、ファンディング手数料、スワップなどの市場ルールは銘柄ごとに適用、シグナルは各銘柄の取引カレンダーで整列。`source: "auto"`と`["000001.SZ", "BTC-USDT"]`のような混合コードで利用可能。- **2026-04-12** 🌍 **マルチプラットフォームインジケーター出力**: `/pine`コマンドで**TradingView (Pine Script v6)**、**通達信/同花順/東方財富 (TDX数式)**、**MetaTrader 5 (MQL5)** の3プラットフォームに一括エクスポート — 国際株式、中国A株、グローバルFX/CFD市場をカバー。- **2026-04-11** 🛡️ **信頼性とDX向上**:`vibe-trading init` 対話式 .env ブートストラップ([#19](https://github.com/HKUDS/Vibe-Trading/pull/19))、起動時にLLM・データソースのプリフライトチェック、プライマリソースが空の場合のランタイムフォールバック、バックテストエンジンのデータ検証とエラー分離を強化、エージェントとSwarmプロンプトに現在日時を注入。コミュニティPR [#21](https://github.com/HKUDS/Vibe-Trading/pull/21) で多言語README(zh/ja/ko)を追加。- **2026-04-10** 📦 **v0.1.4**: Dockerビルドを修正([#8](https://github.com/HKUDS/Vibe-Trading/issues/8))、`web_search` MCPツールを追加(合計17)、依存関係とMCPに`akshare`/`ccxt`を追加。11のLLMプロバイダー(DeepSeek, Groq, Gemini, Ollama など)、すべての調整パラメータを`.env`で設定可能。`ml-strategy`スキルを強化。PyPIとClawHubに公開。@@ -81,7 +82,7 @@ Vibe-Tradingは、自然言語リクエストをグローバル市場向けの<td align="center" width="25%" valign="top"><img src="assets/scene-research.png" height="150" alt="Research"/><br><h3>🔍 トレーディング向けDeepResearch</h3>- <img src="https://img.shields.io/badge/68_Skills-FF6B6B?style=for-the-badge&logo=bookstack&logoColor=white" alt="Skills" /><br><br>+ <img src="https://img.shields.io/badge/69_Skills-FF6B6B?style=for-the-badge&logo=bookstack&logoColor=white" alt="Skills" /><br><br><div align="left" style="font-size: 4px;">• 市場横断のマルチドメイン分析<br>• 自動ストラテジー/シグナル生成<br>@@ -106,7 +107,7 @@ Vibe-Tradingは、自然言語リクエストをグローバル市場向けの<img src="https://img.shields.io/badge/5_Data_Sources-FFD93D?style=for-the-badge&logo=bitcoin&logoColor=black" alt="Backtest" /><br><br><div align="left">• A株、HK/US株式、暗号資産、先物、FXに対応<br>- • 7つの市場エンジン: A株、US/HK株、暗号資産、中国先物、グローバル先物、FX<br>+ • 7つの市場エンジン + クロスマーケット複合エンジン(共有資金プール)<br>• 統計的検証: モンテカルロ、ブートストラップCI、ウォークフォワード<br>• 15以上のパフォーマンス指標と4種類のオプティマイザー</div>@@ -125,16 +126,16 @@ Vibe-Tradingは、自然言語リクエストをグローバル市場向けの</tr></table>-## 7カテゴリにわたる68スキル+## 7カテゴリにわたる69スキル-- 📊 68の金融特化スキルを7カテゴリに整理+- 📊 69の金融特化スキルを7カテゴリに整理- 🌐 伝統的市場から暗号・DeFiまで完全カバー- 🔬 データ取得からクオンツリサーチまでの包括的能力| Category | Skills | Examples ||----------|--------|----------|| Data Source | 6 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `ccxt` |-| Strategy | 16 | `strategy-generate`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |+| Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 15 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` || Crypto | 7 | `perp-funding-basis`, `liquidation-heatmap`, `stablecoin-flow`, `defi-yield`, `onchain-analysis` |@@ -457,7 +458,7 @@ ClawHubで閲覧: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills/vib<details><summary><b>OpenSpace — 自己進化スキル</b></summary>-全68金融スキルは[open-space.cloud](https://open-space.cloud)に公開され、OpenSpaceの自己進化エンジンで自律的に進化します。+全69金融スキルは[open-space.cloud](https://open-space.cloud)に公開され、OpenSpaceの自己進化エンジンで自律的に進化します。OpenSpaceで使うには、両方のMCPサーバーをエージェント設定に追加:@@ -479,7 +480,7 @@ OpenSpaceで使うには、両方のMCPサーバーをエージェント設定}```-OpenSpaceが全68スキルを自動検出し、auto-fix/auto-improve/コミュニティ共有を有効化。`search_skills("finance backtest")`でVibe-Tradingスキルを検索可能。+OpenSpaceが全69スキルを自動検出し、auto-fix/auto-improve/コミュニティ共有を有効化。`search_skills("finance backtest")`でVibe-Tradingスキルを検索可能。</details>@@ -500,7 +501,7 @@ Vibe-Trading/│ ├── src/│ │ ├── agent/ # ReActエージェントコア│ │ │ ├── loop.py # メイン推論ループ-│ │ │ ├── skills.py # スキルローダー(68 SKILL.md, 7カテゴリ)+│ │ │ ├── skills.py # スキルローダー(69 SKILL.md, 7カテゴリ)│ │ │ ├── tools.py # ツールオーケストレーション│ │ │ ├── context.py # システムプロンプトビルダー│ │ │ ├── memory.py # 実行メモリ / アーティファクトストア@@ -517,13 +518,13 @@ Vibe-Trading/│ │ │ ├── swarm_tool.py # スウォームチーム起動│ │ │ └── ... # ファイルI/O, bash, tasks など│ │ │-│ │ ├── skills/ # 7カテゴリに渡る68金融スキル (各SKILL.md)+│ │ ├── skills/ # 7カテゴリに渡る69金融スキル (各SKILL.md)│ │ ├── swarm/ # スウォームDAG実行エンジン│ │ ├── session/ # マルチターンチャットセッション管理│ │ └── providers/ # LLMプロバイダー抽象化│ ││ ├── backtest/ # バックテストエンジン-│ │ ├── engines/ # 7エンジン: china_a, global_equity, crypto, china_futures, global_futures, forex + options_portfolio+│ │ ├── engines/ # 7エンジン + クロスマーケット複合エンジン + options_portfolio│ │ ├── loaders/ # 5ソース: tushare, okx, yfinance, akshare, ccxt│ │ │ ├── base.py # DataLoader Protocol│ │ │ └── registry.py # レジストリ + 自動フォールバックチェーンdiff --git a/README_ko.md b/README_ko.mdindex 2d40acf3c..8a672bff0 100644--- a/README_ko.md+++ b/README_ko.md@@ -19,7 +19,7 @@<a href="https://pypi.org/project/vibe-trading-ai/"><img src="https://img.shields.io/pypi/v/vibe-trading-ai?style=flat&logo=pypi&logoColor=white" alt="PyPI"></a><a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow?style=flat" alt="License"></a><br>- <img src="https://img.shields.io/badge/Skills-68-orange" alt="Skills">+ <img src="https://img.shields.io/badge/Skills-69-orange" alt="Skills"><img src="https://img.shields.io/badge/Swarm_Presets-29-7C3AED" alt="Swarm"><img src="https://img.shields.io/badge/Tools-21-0F766E" alt="Tools"><img src="https://img.shields.io/badge/Data_Sources-5-2563EB" alt="Data Sources">@@ -51,6 +51,7 @@## 📰 뉴스+- **2026-04-13** 🌐 **크로스마켓 복합 백테스트**: 새로운 `CompositeEngine`으로 서로 다른 시장의 종목(예: A주 + 암호화폐)을 **공유 자금 풀**로 동시 백테스트 가능. T+1, 펀딩 수수료, 스왑 등 시장 규칙은 종목별로 적용, 시그널은 각 종목의 거래 캘린더에 맞춰 정렬. `source: "auto"`와 `["000001.SZ", "BTC-USDT"]` 같은 혼합 코드로 사용.- **2026-04-12** 🌍 **멀티 플랫폼 인디케이터 내보내기**: `/pine` 명령어로 **TradingView (Pine Script v6)**, **통달신/동화순/동방재부 (TDX 수식)**, **MetaTrader 5 (MQL5)** 3개 플랫폼에 한 번에 내보내기 — 국제 주식, 중국 A주, 글로벌 FX/CFD 시장을 커버. 하나의 명령어, 세 개 플랫폼.- **2026-04-11** 🛡️ **안정성 및 DX 개선**: `vibe-trading init` 대화형 .env 부트스트랩([#19](https://github.com/HKUDS/Vibe-Trading/pull/19)), 시작 시 LLM·데이터소스 프리플라이트 체크, 기본 데이터소스 빈 응답 시 런타임 폴백, 백테스트 엔진 데이터 검증 및 에러 격리 강화, 에이전트·Swarm 프롬프트에 현재 날짜/시간 주입. 커뮤니티 PR [#21](https://github.com/HKUDS/Vibe-Trading/pull/21)로 다국어 README(zh/ja/ko) 추가.- **2026-04-10** 📦 **v0.1.4**: Docker 빌드 수정([#8](https://github.com/HKUDS/Vibe-Trading/issues/8)), `web_search` MCP 도구 추가(총 17개), 의존성 및 MCP에 `akshare`/`ccxt` 추가. 11개 LLM 제공자(DeepSeek, Groq, Gemini, Ollama 등), 모든 튜닝 파라미터를 `.env`로 설정. `ml-strategy` 스킬 하드닝. PyPI와 ClawHub에 게시.@@ -81,7 +82,7 @@ Vibe-Trading은 AI 기반 멀티 에이전트 금융 워크스페이스로, 자<td align="center" width="25%" valign="top"><img src="assets/scene-research.png" height="150" alt="Research"/><br><h3>🔍 트레이딩용 DeepResearch</h3>- <img src="https://img.shields.io/badge/68_Skills-FF6B6B?style=for-the-badge&logo=bookstack&logoColor=white" alt="Skills" /><br><br>+ <img src="https://img.shields.io/badge/69_Skills-FF6B6B?style=for-the-badge&logo=bookstack&logoColor=white" alt="Skills" /><br><br><div align="left" style="font-size: 4px;">• 시장 전반을 아우르는 다중 도메인 분석<br>• 자동 전략 및 시그널 생성<br>@@ -106,7 +107,7 @@ Vibe-Trading은 AI 기반 멀티 에이전트 금융 워크스페이스로, 자<img src="https://img.shields.io/badge/5_Data_Sources-FFD93D?style=for-the-badge&logo=bitcoin&logoColor=black" alt="Backtest" /><br><br><div align="left">• A주, 홍콩/미국 주식, 크립토, 선물 및 FX<br>- • 7개 시장 엔진: A주, 미/홍콩 주식, 크립토, 중국 선물, 글로벌 선물, FX<br>+ • 7개 시장 엔진 + 크로스마켓 복합 엔진(공유 자금 풀)<br>• 통계 검증: 몬테카를로, Bootstrap CI, 워크포워드<br>• 15+ 성과 지표 및 4개 옵티마이저</div>@@ -125,16 +126,16 @@ Vibe-Trading은 AI 기반 멀티 에이전트 금융 워크스페이스로, 자</tr></table>-## 7개 카테고리에 걸친 68개 스킬+## 7개 카테고리에 걸친 69개 스킬-- 📊 7개 카테고리에 조직된 68개 금융 스킬+- 📊 7개 카테고리에 조직된 69개 금융 스킬- 🌐 전통 시장부터 크립토·DeFi까지 완전 커버리지- 🔬 데이터 소싱부터 정량 리서치까지 포괄적 기능| 카테고리 | 스킬 | 예시 ||----------|------|------|| Data Source | 6 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `ccxt` |-| Strategy | 16 | `strategy-generate`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |+| Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 15 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` || Crypto | 7 | `perp-funding-basis`, `liquidation-heatmap`, `stablecoin-flow`, `defi-yield`, `onchain-analysis` |@@ -324,7 +325,7 @@ vibe-trading serve # API 서버| Command | Description ||---------|-------------|| `/help` | 모든 명령 표시 |-| `/skills` | 68개 금융 스킬 목록 |+| `/skills` | 69개 금융 스킬 목록 || `/swarm` | 29개 스웜 팀 프리셋 목록 || `/swarm run <preset> [vars_json]` | 라이브 스트리밍으로 스웜 팀 실행 || `/swarm list` | 스웜 실행 이력 |@@ -458,7 +459,7 @@ ClawHub에서 보기: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills<details><summary><b>OpenSpace — 자가 진화 스킬</b></summary>-모든 68개 금융 스킬은 [open-space.cloud](https://open-space.cloud)에 게시되어 OpenSpace의 자가 진화 엔진을 통해 스스로 발전합니다.+모든 69개 금융 스킬은 [open-space.cloud](https://open-space.cloud)에 게시되어 OpenSpace의 자가 진화 엔진을 통해 스스로 발전합니다.OpenSpace와 함께 사용하려면 두 MCP 서버를 에이전트 설정에 추가하세요:@@ -480,7 +481,7 @@ OpenSpace와 함께 사용하려면 두 MCP 서버를 에이전트 설정에 추}```-OpenSpace는 모든 68개 스킬을 자동으로 탐지하여 자동 수정, 자동 개선, 커뮤니티 공유를 활성화합니다. OpenSpace 연결 에이전트에서 `search_skills("finance backtest")`로 Vibe-Trading 스킬을 검색하세요.+OpenSpace는 모든 69개 스킬을 자동으로 탐지하여 자동 수정, 자동 개선, 커뮤니티 공유를 활성화합니다. OpenSpace 연결 에이전트에서 `search_skills("finance backtest")`로 Vibe-Trading 스킬을 검색하세요.</details>@@ -501,7 +502,7 @@ Vibe-Trading/│ ├── src/│ │ ├── agent/ # ReAct 에이전트 코어│ │ │ ├── loop.py # 메인 추론 루프-│ │ │ ├── skills.py # 스킬 로더(68 SKILL.md, 7 카테고리)+│ │ │ ├── skills.py # 스킬 로더(69 SKILL.md, 7 카테고리)│ │ │ ├── tools.py # 도구 오케스트레이션│ │ │ ├── context.py # 시스템 프롬프트 빌더│ │ │ ├── memory.py # 실행 메모리 / 아티팩트 저장소@@ -518,13 +519,13 @@ Vibe-Trading/│ │ │ ├── swarm_tool.py # 스웜 팀 실행│ │ │ └── ... # 파일 I/O, bash, 태스크 등│ │ │-│ │ ├── skills/ # 7개 카테고리의 68개 금융 스킬(SKILL.md 각각)+│ │ ├── skills/ # 7개 카테고리의 69개 금융 스킬(SKILL.md 각각)│ │ ├── swarm/ # 스웜 DAG 실행 엔진│ │ ├── session/ # 멀티턴 채팅 세션 관리│ │ └── providers/ # LLM 제공자 추상화│ ││ ├── backtest/ # 백테스트 엔진-│ │ ├── engines/ # 7개 엔진: china_a, global_equity, crypto, china_futures, global_futures, forex + options_portfolio+│ │ ├── engines/ # 7개 엔진 + 크로스마켓 복합 엔진 + options_portfolio│ │ ├── loaders/ # 5개 소스: tushare, okx, yfinance, akshare, ccxt│ │ │ ├── base.py # DataLoader Protocol│ │ │ └── registry.py # 레지스트리 + 자동 폴백 체인diff --git a/README_zh.md b/README_zh.mdindex 012806769..44008fa66 100644--- a/README_zh.md+++ b/README_zh.md@@ -19,7 +19,7 @@<a href="https://pypi.org/project/vibe-trading-ai/"><img src="https://img.shields.io/pypi/v/vibe-trading-ai?style=flat&logo=pypi&logoColor=white" alt="PyPI"></a><a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow?style=flat" alt="License"></a><br>- <img src="https://img.shields.io/badge/Skills-68-orange" alt="Skills">+ <img src="https://img.shields.io/badge/Skills-69-orange" alt="Skills"><img src="https://img.shields.io/badge/Swarm_Presets-29-7C3AED" alt="Swarm"><img src="https://img.shields.io/badge/Tools-21-0F766E" alt="Tools"><img src="https://img.shields.io/badge/Data_Sources-5-2563EB" alt="Data Sources">@@ -51,6 +51,7 @@## 📰 新闻+- **2026-04-13** 🌐 **跨市场复合回测**:新增 `CompositeEngine`,支持在同一次回测中混合不同市场的标的(如 A 股 + 加密货币),共享资金池,各市场规则(T+1、资金费率、掉期)按标的独立执行,信号按各自交易日历对齐。使用 `source: "auto"` 配合混合代码如 `["000001.SZ", "BTC-USDT"]` 即可。包含波动率加权策略技能和日历日年化计算。- **2026-04-12** 🌍 **多平台指标导出**:`/pine` 命令现在一次性导出 **TradingView (Pine Script v6)**、**通达信/同花顺/东方财富 (TDX 公式)** 和 **MetaTrader 5 (MQL5)** 三个平台的指标代码 — 覆盖国际股票、中国 A 股和全球外汇/CFD 市场。一条命令,三大平台。- **2026-04-11** 🛡️ **可靠性与开发体验**:`vibe-trading init` 交互式 .env 引导([#19](https://github.com/HKUDS/Vibe-Trading/pull/19)),启动预检 LLM 与数据源连通性,主数据源返空时自动回退,回测引擎数据校验与错误隔离加固,Agent 与 Swarm 提示词注入当前日期时间。社区 PR [#21](https://github.com/HKUDS/Vibe-Trading/pull/21) 贡献多语言 README(zh/ja/ko)。- **2026-04-10** 📦 **v0.1.4**:修复 Docker 构建([#8](https://github.com/HKUDS/Vibe-Trading/issues/8)),新增 `web_search` MCP 工具(共 17 个),在依赖与 MCP 中加入 `akshare`/`ccxt`。支持 11 家 LLM 提供商(DeepSeek、Groq、Gemini、Ollama 等),全部调优参数可通过 `.env` 配置。加固 `ml-strategy` 技能。已发布至 PyPI 和 ClawHub。@@ -81,7 +82,7 @@ Vibe-Trading 是一个由 AI 驱动的多代理金融工作台,将自然语言<td align="center" width="25%" valign="top"><img src="assets/scene-research.png" height="150" alt="Research"/><br><h3>🔍 面向交易的深度研究</h3>- <img src="https://img.shields.io/badge/68_Skills-FF6B6B?style=for-the-badge&logo=bookstack&logoColor=white" alt="Skills" /><br><br>+ <img src="https://img.shields.io/badge/69_Skills-FF6B6B?style=for-the-badge&logo=bookstack&logoColor=white" alt="Skills" /><br><br><div align="left" style="font-size: 4px;">• 覆盖多市场的多领域分析<br>• 自动生成策略与信号<br>@@ -106,7 +107,7 @@ Vibe-Trading 是一个由 AI 驱动的多代理金融工作台,将自然语言<img src="https://img.shields.io/badge/5_Data_Sources-FFD93D?style=for-the-badge&logo=bitcoin&logoColor=black" alt="Backtest" /><br><br><div align="left">• A 股、港美股、加密、期货与外汇<br>- • 7 个市场引擎:A 股、美港股、加密、中国期货、全球期货、外汇<br>+ • 7 个市场引擎 + 跨市场复合引擎(共享资金池)<br>• 统计验证:蒙特卡洛、Bootstrap 置信区间、Walk-Forward<br>• 15+ 绩效指标与 4 种优化器</div>@@ -125,16 +126,16 @@ Vibe-Trading 是一个由 AI 驱动的多代理金融工作台,将自然语言</tr></table>-## 7 大类别中的 68 个技能+## 7 大类别中的 69 个技能-- 📊 68 个金融专长技能,划分 7 大类+- 📊 69 个金融专长技能,划分 7 大类- 🌐 覆盖传统市场到加密与 DeFi- 🔬 覆盖数据获取到量化研究的全链路能力| Category | Skills | Examples ||----------|--------|----------|| Data Source | 6 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `ccxt` |-| Strategy | 16 | `strategy-generate`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |+| Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 15 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` || Crypto | 7 | `perp-funding-basis`, `liquidation-heatmap`, `stablecoin-flow`, `defi-yield`, `onchain-analysis` |@@ -324,7 +325,7 @@ vibe-trading serve # API 服务器| Command | Description ||---------|-------------|| `/help` | 显示全部命令 |-| `/skills` | 列出 68 个金融技能 |+| `/skills` | 列出 69 个金融技能 || `/swarm` | 列出 29 个 swarm 团队预设 || `/swarm run <preset> [vars_json]` | 以流式输出运行一个 swarm 团队 || `/swarm list` | Swarm 运行历史 |@@ -457,7 +458,7 @@ npx clawhub@latest install vibe-trading --force<details><summary><b>OpenSpace — 自进化技能</b></summary>-全部 68 个金融技能已发布在 [open-space.cloud](https://open-space.cloud),并通过 OpenSpace 的自进化引擎自动演进。+全部 69 个金融技能已发布在 [open-space.cloud](https://open-space.cloud),并通过 OpenSpace 的自进化引擎自动演进。要在 OpenSpace 中使用,在代理配置中添加两个 MCP 服务器:@@ -479,7 +480,7 @@ npx clawhub@latest install vibe-trading --force}```-OpenSpace 会自动发现全部 68 个技能,支持自动修复、自动改进与社区共享。在任意连接 OpenSpace 的代理中通过 `search_skills("finance backtest")` 搜索 Vibe-Trading 技能。+OpenSpace 会自动发现全部 69 个技能,支持自动修复、自动改进与社区共享。在任意连接 OpenSpace 的代理中通过 `search_skills("finance backtest")` 搜索 Vibe-Trading 技能。</details>@@ -500,7 +501,7 @@ Vibe-Trading/│ ├── src/│ │ ├── agent/ # ReAct 代理核心│ │ │ ├── loop.py # 主推理循环-│ │ │ ├── skills.py # 技能加载器(68 个 SKILL.md,7 类)+│ │ │ ├── skills.py # 技能加载器(69 个 SKILL.md,7 类)│ │ │ ├── tools.py # 工具编排│ │ │ ├── context.py # 系统提示构建器│ │ │ ├── memory.py # 运行记忆 / artifact 存储@@ -517,13 +518,13 @@ Vibe-Trading/│ │ │ ├── swarm_tool.py # 启动 swarm 团队│ │ │ └── ... # 文件 I/O、bash、任务等│ │ │-│ │ ├── skills/ # 68 个金融技能(7 类,每个 SKILL.md)+│ │ ├── skills/ # 69 个金融技能(7 类,每个 SKILL.md)│ │ ├── swarm/ # Swarm DAG 执行引擎│ │ ├── session/ # 多轮对话管理│ │ └── providers/ # LLM 提供商抽象│ ││ ├── backtest/ # 回测引擎-│ │ ├── engines/ # 7 个引擎:china_a、global_equity、crypto、china_futures、global_futures、forex + options_portfolio+│ │ ├── engines/ # 7 个引擎 + 跨市场复合引擎 + options_portfolio│ │ ├── loaders/ # 5 个数据源:tushare、okx、yfinance、akshare、ccxt│ │ │ ├── base.py # DataLoader Protocol│ │ │ └── registry.py # 注册表 + 自动回退链diff --git a/agent/SKILL.md b/agent/SKILL.mdindex 0bd3c8c37..5bf8cacbe 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -1,7 +1,7 @@---name: vibe-tradingversion: 0.1.4-description: Professional finance research toolkit — backtesting (6 engines), factor analysis, options pricing, 68 finance skills, and 29 multi-agent swarm teams across 5 data sources (tushare, yfinance, okx, akshare, ccxt).+description: Professional finance research toolkit — backtesting (7 engines), factor analysis, options pricing, 69 finance skills, and 29 multi-agent swarm teams across 5 data sources (tushare, yfinance, okx, akshare, ccxt).dependencies:python: ">=3.11"pip:@@ -23,7 +23,7 @@ mcp:# Vibe-Trading-Professional finance research toolkit with AI-powered backtesting (6 engines), multi-agent teams, and 68 specialized skills.+Professional finance research toolkit with AI-powered backtesting (7 engines), multi-agent teams, and 69 specialized skills.## Setup@@ -53,7 +53,7 @@ Add to your agent's MCP config:### API Key Requirements-**16 of 17 MCP tools work with zero API keys.** After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, and all 68 skills are ready to use for HK/US equities and crypto.+**16 of 17 MCP tools work with zero API keys.** After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, and all 69 skills are ready to use for HK/US equities and crypto.| Feature | Key needed | When ||---------|-----------|------|@@ -64,7 +64,7 @@ Add to your agent's MCP config:## What You Can Do### Backtesting-Create and run quantitative strategies across 6 engines (ChinaA, GlobalEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 5 data sources:+Create and run quantitative strategies across 7 engines (ChinaA, GlobalEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 5 data sources:- **HK/US equities** via yfinance (free, no API key)- **Cryptocurrency** via OKX or CCXT/100+ exchanges (free, no API key)- **China A-shares** via Tushare (token) or AKShare (free fallback)@@ -105,7 +105,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.| Tool | Description | API Key ||------|-------------|---------|-| `list_skills` | List all 68 finance skills | None |+| `list_skills` | List all 69 finance skills | None || `load_skill` | Load full skill documentation | None || `backtest` | Run vectorized backtest engine | None* || `factor_analysis` | IC/IR analysis + layered backtest | None* |@@ -131,7 +131,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.pip install vibe-trading-ai```-That's it — no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `web_search`, and all 68 skills immediately.+That's it — no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `web_search`, and all 69 skills immediately.## Examplesdiff --git a/agent/backtest/engines/__init__.py b/agent/backtest/engines/__init__.pyindex 1ed9bad77..3b972fcca 100644--- a/agent/backtest/engines/__init__.py+++ b/agent/backtest/engines/__init__.py@@ -13,12 +13,17 @@ Wave 2:- GlobalFuturesEngine: International futures (CME/ICE/Eurex)- ForexEngine: FX spot/CFD (spread, swap, high leverage)+Wave 3:+ - CompositeEngine: Cross-market engine with shared capital pool+ - _market_hooks: Extracted on_bar logic (funding, liquidation, swap)+Inheritance:BaseEngine├── ChinaAEngine├── GlobalEquityEngine├── CryptoEngine├── ForexEngine+ ├── CompositeEngine (delegates to sub-engines as rule providers)└── FuturesBaseEngine├── ChinaFuturesEngine└── GlobalFuturesEnginediff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.pynew file mode 100644index 000000000..c41096568--- /dev/null+++ b/agent/backtest/engines/_market_hooks.py@@ -0,0 +1,180 @@+"""Extracted per-bar market hooks as pure functions.++Both the original engines (CryptoEngine, ForexEngine) and CompositeEngine+call these same functions. Zero duplication — one source of truth.+"""++from __future__ import annotations++from typing import Dict++import pandas as pd++from backtest.models import Position++# ── Crypto: OKX tiered maintenance margin table (simplified) ──++_TIER_TABLE = [+ (100_000, 0.004),+ (500_000, 0.006),+ (1_000_000, 0.01),+ (5_000_000, 0.02),+ (10_000_000, 0.05),+ (float("inf"), 0.10),+]++FUNDING_HOURS = {0, 8, 16}+++def _maintenance_rate(notional_usd: float) -> float:+ """Look up tiered maintenance margin rate."""+ for tier_max, rate in _TIER_TABLE:+ if notional_usd <= tier_max:+ return rate+ return _TIER_TABLE[-1][1]+++def calc_crypto_funding_fee(+ symbol: str,+ bar: pd.Series,+ timestamp: pd.Timestamp,+ positions: Dict[str, Position],+ funding_rate: float,+ applied_set: set,+ daily_done_set: set,+) -> float:+ """Calculate crypto funding fee for one symbol.++ Args:+ symbol: Instrument code.+ bar: Current bar data.+ timestamp: Bar timestamp.+ positions: Shared positions dict.+ funding_rate: Fixed rate per settlement.+ applied_set: (symbol, date, hour) dedup set — mutated.+ daily_done_set: (symbol, date) dedup set — mutated.++ Returns:+ Fee amount (positive = longs pay, negative = longs receive).+ """+ if not hasattr(timestamp, "date"):+ return 0.0++ current_date = timestamp.date()+ hour = timestamp.hour if hasattr(timestamp, "hour") else 0++ if hour in FUNDING_HOURS:+ key = (symbol, current_date, hour)+ if key in applied_set:+ return 0.0+ applied_set.add(key)+ else:+ day_key = (symbol, current_date)+ if day_key in daily_done_set:+ return 0.0+ daily_done_set.add(day_key)++ pos = positions.get(symbol)+ if pos is None:+ return 0.0++ mark_price = float(bar.get("close", pos.entry_price))+ notional = pos.size * mark_price+ return notional * funding_rate * pos.direction+++def check_crypto_liquidation(+ symbol: str,+ bar: pd.Series,+ positions: Dict[str, Position],+) -> bool:+ """Check if a crypto position should be liquidated.++ Args:+ symbol: Instrument code.+ bar: Current bar data.+ positions: Shared positions dict.++ Returns:+ True if liquidation should be triggered.+ Does NOT execute the liquidation -- caller handles that.+ """+ pos = positions.get(symbol)+ if pos is None or pos.leverage <= 1.0:+ return False++ mark_price = float(bar.get("close", pos.entry_price))+ margin = pos.size * pos.entry_price / pos.leverage+ unrealized = pos.direction * pos.size * (mark_price - pos.entry_price)++ notional = pos.size * mark_price+ maint_rate = _maintenance_rate(notional)+ maint_margin = notional * maint_rate++ return (margin + unrealized) <= maint_margin+++# ── Forex: swap tables ──++_SWAP_LONG: dict[str, float] = {+ "EUR/USD": -6.5, "GBP/USD": -3.0, "USD/JPY": 8.0, "USD/CHF": 4.0,+ "AUD/USD": -2.0, "USD/CAD": 2.0, "NZD/USD": -1.5,+}+_SWAP_SHORT: dict[str, float] = {+ "EUR/USD": 3.5, "GBP/USD": -1.0, "USD/JPY": -12.0, "USD/CHF": -8.0,+ "AUD/USD": -1.0, "USD/CAD": -5.0, "NZD/USD": -2.0,+}+++def _normalize_symbol(symbol: str) -> str:+ """Normalize forex symbol to 'XXX/YYY' format."""+ s = symbol.replace(".FX", "").replace(".", "").strip()+ if "/" in s:+ return s.upper()+ if len(s) == 6:+ return f"{s[:3]}/{s[3:]}".upper()+ return s.upper()+++def calc_forex_swap(+ symbol: str,+ timestamp: pd.Timestamp,+ positions: Dict[str, Position],+ lot_size: float,+ last_swap_dates: dict,+) -> float:+ """Calculate forex swap for one symbol.++ Args:+ symbol: Forex pair.+ timestamp: Bar timestamp.+ positions: Shared positions dict.+ lot_size: Standard lot size (e.g. 100_000).+ last_swap_dates: Per-symbol date tracking dict -- mutated.++ Returns:+ Swap amount (positive = credit, negative = debit).+ """+ if not hasattr(timestamp, "date"):+ return 0.0++ current_date = timestamp.date()+ if last_swap_dates.get(symbol) == current_date:+ return 0.0+ last_swap_dates[symbol] = current_date++ pos = positions.get(symbol)+ if pos is None:+ return 0.0++ pair = _normalize_symbol(symbol)+ lots = pos.size / lot_size++ if pos.direction == 1:+ swap_per_lot = _SWAP_LONG.get(pair, -1.0)+ else:+ swap_per_lot = _SWAP_SHORT.get(pair, -1.0)++ # Wednesday = triple swap (covers Sat+Sun)+ multiplier = 3.0 if timestamp.weekday() == 2 else 1.0+ return lots * swap_per_lot * multiplierdiff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex 8eb6c1f2d..122ddd9ae 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -29,6 +29,23 @@ from backtest.metrics import (from backtest.models import EquitySnapshot, Position, TradeRecord+# ─── Market detection (lightweight, for signal alignment only) ───++import re as _re++_CRYPTO_RE = _re.compile(r"^[A-Z]+-USDT$|^[A-Z]+/USDT$", _re.I)+_FOREX_RE = _re.compile(r"^[A-Z]{3}/[A-Z]{3}$|^[A-Z]{6}\.FX$")+++def _detect_market_for_align(code: str) -> str:+ """Lightweight market detection for ffill_limit calculation."""+ if _CRYPTO_RE.match(code):+ return "crypto"+ if _FOREX_RE.match(code):+ return "forex"+ return "equity"++# ─── Signal alignment (reused from daily_portfolio logic) ───@@ -62,7 +79,9 @@ def _align(close[c] = data_map[c]["close"].reindex(dates)# ffill with limit to avoid masking long suspensions (e.g. 3-week halt)- close = close.ffill(limit=5)+ # Cross-market needs larger limit (Chinese New Year can be 9-10 bars)+ ffill_limit = 10 if len({_detect_market_for_align(c) for c in codes}) > 1 else 5+ close = close.ffill(limit=ffill_limit)# Drop symbols that are entirely NaN (no data overlap with date range)all_nan_cols = [c for c in codes if close[c].isna().all()]@@ -75,8 +94,11 @@ def _align(pos = pd.DataFrame(0.0, index=dates, columns=codes)for c in codes:- raw = signal_map[c].reindex(dates).fillna(0.0).clip(-1.0, 1.0)- pos[c] = raw.shift(1).fillna(0.0)+ # Shift on each symbol's OWN trading calendar, then ffill to unified+ own_dates = data_map[c].index+ raw = signal_map[c].reindex(own_dates).fillna(0.0).clip(-1.0, 1.0)+ shifted = raw.shift(1).fillna(0.0)+ pos[c] = shifted.reindex(dates).ffill(limit=ffill_limit).fillna(0.0)ret = close.pct_change().fillna(0.0)diff --git a/agent/backtest/engines/composite.py b/agent/backtest/engines/composite.pynew file mode 100644index 000000000..e168b5895--- /dev/null+++ b/agent/backtest/engines/composite.py@@ -0,0 +1,217 @@+"""Composite cross-market backtest engine.++Manages a shared capital pool across multiple market engines.+Sub-engines are used as stateless "rule books" for market-specific+calculations (commission, slippage, lot rounding, etc.).+All state (capital, positions, trades) lives in CompositeEngine.+"""++from __future__ import annotations++import re+from typing import Dict, List++import pandas as pd++from backtest.engines.base import BaseEngine+from backtest.engines._market_hooks import (+ calc_crypto_funding_fee,+ check_crypto_liquidation,+ calc_forex_swap,+)+++# ── Market detection (same patterns as runner.py) ──++_MARKET_PATTERNS = [+ (re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "a_share"),+ (re.compile(r"^(51|15|56)\d{4}\.(SZ|SH)$", re.I), "a_share"),+ (re.compile(r"^[A-Z]+\.US$", re.I), "us_equity"),+ (re.compile(r"^\d{3,5}\.HK$", re.I), "hk_equity"),+ (re.compile(r"^[A-Z]+-USDT$", re.I), "crypto"),+ (re.compile(r"^[A-Z]+/USDT$", re.I), "crypto"),+ (re.compile(r"^[A-Za-z]{1,2}\d{3,4}\.(ZCE|DCE|SHFE|INE|CFFEX|GFEX)$", re.I), "futures"),+ (re.compile(r"^[A-Z]{2,4}[FGHJKMNQUVXZ]\d{1,2}$", re.I), "futures"),+ (re.compile(r"^[A-Z]{2,4}\d{4}$", re.I), "futures"),+ (re.compile(r"^[A-Z]{2,4}\.(CME|CBOT|NYMEX|COMEX|ICE|EUREX)$", re.I), "futures"),+ (re.compile(r"^[A-Z]{3}/[A-Z]{3}$"), "forex"),+ (re.compile(r"^[A-Z]{6}\.FX$"), "forex"),+]++_CHINA_EXCHANGES = {"CFFEX", "SHFE", "DCE", "ZCE", "INE", "GFEX"}+++def _detect_market(code: str) -> str:+ """Infer market type from symbol format."""+ for pattern, market in _MARKET_PATTERNS:+ if pattern.match(code):+ return market+ return "a_share"+++def _is_china_futures(code: str) -> bool:+ """Check if futures code belongs to a Chinese exchange."""+ parts = code.upper().split(".")+ return len(parts) == 2 and parts[1] in _CHINA_EXCHANGES+++def _build_rule_engines(config: dict, codes: List[str]) -> Dict[str, BaseEngine]:+ """Instantiate one sub-engine per market type detected in codes."""+ markets = {_detect_market(c) for c in codes}+ engines: Dict[str, BaseEngine] = {}++ for market in markets:+ if market == "a_share":+ from backtest.engines.china_a import ChinaAEngine+ engines["a_share"] = ChinaAEngine(config)+ elif market == "us_equity":+ from backtest.engines.global_equity import GlobalEquityEngine+ engines["us_equity"] = GlobalEquityEngine(config, market="us")+ elif market == "hk_equity":+ from backtest.engines.global_equity import GlobalEquityEngine+ engines["hk_equity"] = GlobalEquityEngine(config, market="hk")+ elif market == "crypto":+ from backtest.engines.crypto import CryptoEngine+ engines["crypto"] = CryptoEngine(config)+ elif market == "forex":+ from backtest.engines.forex import ForexEngine+ engines["forex"] = ForexEngine(config)+ elif market == "futures":+ china = any(+ _is_china_futures(c) for c in codes if _detect_market(c) == "futures"+ )+ if china:+ from backtest.engines.china_futures import ChinaFuturesEngine+ engines["futures"] = ChinaFuturesEngine(config)+ else:+ from backtest.engines.global_futures import GlobalFuturesEngine+ engines["futures"] = GlobalFuturesEngine(config)++ return engines+++class CompositeEngine(BaseEngine):+ """Cross-market engine with shared capital pool.++ Sub-engines are stateless rule providers. All positions, capital,+ and trades live here (inherited from BaseEngine).++ Args:+ config: Backtest configuration dict.+ codes: List of instrument codes spanning multiple markets.+ """++ def __init__(self, config: dict, codes: List[str]):+ super().__init__(config)++ # Build symbol -> market mapping+ self._symbol_market: Dict[str, str] = {c: _detect_market(c) for c in codes}++ # Build sub-engines (one per market type)+ self._rule_engines = _build_rule_engines(config, codes)++ # Crypto dedup state (owned by CompositeEngine, not sub-engine)+ self._funding_applied: set = set()+ self._funding_daily_done: set = set()++ # Forex dedup state+ self._last_swap_dates: dict = {}++ def _rule_for(self, symbol: str) -> BaseEngine:+ """Get the sub-engine that provides rules for this symbol."""+ market = self._symbol_market.get(symbol, "a_share")+ return self._rule_engines[market]++ # ── Stateless method dispatch ──++ def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:+ """Market-rule check with T+1 interceptor for A-shares."""+ market = self._symbol_market.get(symbol, "a_share")++ # T+1: intercept here because sub-engine has no access to shared positions+ if market == "a_share" and direction == 0:+ pos = self.positions.get(symbol)+ if pos is not None:+ bar_date = None+ if hasattr(bar, "name") and hasattr(bar.name, "date"):+ bar_date = bar.name.date()+ entry_date = (+ pos.entry_time.date()+ if hasattr(pos.entry_time, "date")+ else None+ )+ if bar_date and entry_date and bar_date == entry_date:+ return False++ # Delegate remaining checks (price limits, short-sell block, etc.)+ return self._rule_for(symbol).can_execute(symbol, direction, bar)++ def round_size(self, raw_size: float, price: float) -> float:+ """Delegate to active symbol's sub-engine."""+ return self._rule_for(self._active_symbol).round_size(raw_size, price)++ def calc_commission(+ self, size: float, price: float, direction: int, is_open: bool,+ ) -> float:+ """Delegate to active symbol's sub-engine."""+ return self._rule_for(self._active_symbol).calc_commission(+ size, price, direction, is_open,+ )++ def apply_slippage(self, price: float, direction: int) -> float:+ """Delegate to active symbol's sub-engine."""+ sub = self._rule_for(self._active_symbol)+ # ForexEngine needs _active_symbol set on the sub-engine+ sub._active_symbol = self._active_symbol+ return sub.apply_slippage(price, direction)++ # ── PnL / margin dispatch (route by symbol, not _active_symbol) ──++ def _calc_pnl(+ self, symbol: str, direction: int, size: float,+ entry_price: float, exit_price: float,+ ) -> float:+ return self._rule_for(symbol)._calc_pnl(+ symbol, direction, size, entry_price, exit_price,+ )++ def _calc_margin(+ self, symbol: str, size: float, price: float, leverage: float,+ ) -> float:+ return self._rule_for(symbol)._calc_margin(symbol, size, price, leverage)++ def _calc_raw_size(+ self, symbol: str, target_notional: float, price: float,+ ) -> float:+ return self._rule_for(symbol)._calc_raw_size(symbol, target_notional, price)++ # ── Stateful hooks (implemented directly, NO delegation) ──++ def on_bar(self, symbol: str, bar: pd.Series, timestamp: pd.Timestamp) -> None:+ """Per-bar hooks dispatched by market type."""+ market = self._symbol_market.get(symbol)++ if market == "crypto":+ crypto_sub = self._rule_engines["crypto"]+ fee = calc_crypto_funding_fee(+ symbol, bar, timestamp, self.positions,+ crypto_sub.funding_rate,+ self._funding_applied, self._funding_daily_done,+ )+ self.capital -= fee++ if check_crypto_liquidation(symbol, bar, self.positions):+ pos = self.positions.get(symbol)+ if pos is not None:+ mark_price = float(bar.get("close", pos.entry_price))+ liq_price = crypto_sub.apply_slippage(mark_price, -pos.direction)+ self._close_position(symbol, liq_price, timestamp, "liquidation")++ elif market == "forex":+ forex_sub = self._rule_engines["forex"]+ if forex_sub.swap_enabled:+ swap = calc_forex_swap(+ symbol, timestamp, self.positions,+ forex_sub.lot_size, self._last_swap_dates,+ )+ self.capital += swapdiff --git a/agent/backtest/engines/crypto.py b/agent/backtest/engines/crypto.pyindex b2c4cb0bc..def8dc3cd 100644--- a/agent/backtest/engines/crypto.py+++ b/agent/backtest/engines/crypto.py@@ -13,21 +13,10 @@ from __future__ import annotationsimport pandas as pdfrom backtest.engines.base import BaseEngine---# OKX tiered maintenance margin table (simplified)-# (max_notional_usd, maintenance_margin_rate)-_TIER_TABLE = [- (100_000, 0.004),- (500_000, 0.006),- (1_000_000, 0.01),- (5_000_000, 0.02),- (10_000_000, 0.05),- (float("inf"), 0.10),-]--# Funding fee settlement hours (UTC)-_FUNDING_HOURS = {0, 8, 16}+from backtest.engines._market_hooks import (+ calc_crypto_funding_fee,+ check_crypto_liquidation,+)class CryptoEngine(BaseEngine):@@ -70,80 +59,15 @@ class CryptoEngine(BaseEngine):def on_bar(self, symbol: str, bar: pd.Series, timestamp: pd.Timestamp) -> None:"""Crypto per-bar hooks: funding fee + liquidation check."""- self._apply_funding_fee(symbol, bar, timestamp)- self._check_liquidation(symbol, bar, timestamp)-- # ── Funding fee (exchange-enforced, every 8h) ──-- def _apply_funding_fee(- self, symbol: str, bar: pd.Series, timestamp: pd.Timestamp,- ) -> None:- """Deduct/credit funding fee at settlement hours.-- Positive rate: longs pay shorts. Negative rate: shorts pay longs.-- For intraday bars: applies at each 8h settlement (0/8/16 UTC).- For daily bars: applies once per calendar day regardless of hour.- Dedup is per-(symbol, date, hour) so multi-symbol portfolios work.- """- if not hasattr(timestamp, "date"):- return-- current_date = timestamp.date()- hour = timestamp.hour if hasattr(timestamp, "hour") else 0-- if hour in _FUNDING_HOURS:- key = (symbol, current_date, hour)- if key in self._funding_applied:- return- self._funding_applied.add(key)- else:- # Non-settlement hour (e.g. daily bar at 12:00 UTC)- # Apply once per day as approximation- day_key = (symbol, current_date)- if day_key in self._funding_daily_done:- return- self._funding_daily_done.add(day_key)-- pos = self.positions.get(symbol)- if pos is None:- return-- mark_price = float(bar.get("close", pos.entry_price))- notional = pos.size * mark_price- fee = notional * self.funding_rate * pos.direction+ fee = calc_crypto_funding_fee(+ symbol, bar, timestamp, self.positions,+ self.funding_rate, self._funding_applied, self._funding_daily_done,+ )self.capital -= fee- # ── Liquidation (exchange-enforced) ──-- def _check_liquidation(- self, symbol: str, bar: pd.Series, timestamp: pd.Timestamp,- ) -> None:- """Force-close when maintenance margin ratio drops to / below 100%."""- pos = self.positions.get(symbol)- if pos is None or pos.leverage <= 1.0:- return # spot has no liquidation-- mark_price = float(bar.get("close", pos.entry_price))- margin = pos.size * pos.entry_price / pos.leverage- unrealized = pos.direction * pos.size * (mark_price - pos.entry_price)-- # Maintenance margin rate (tiered)- notional = pos.size * mark_price- maint_rate = self._maintenance_rate(notional)- maint_margin = notional * maint_rate-- # Margin ratio = (margin + unrealized) / maint_margin- equity_in_pos = margin + unrealized- if equity_in_pos <= maint_margin:- # Liquidation: close at mark price with taker fee- liq_price = self.apply_slippage(mark_price, -pos.direction)- self._close_position(symbol, liq_price, timestamp, "liquidation")-- @staticmethod- def _maintenance_rate(notional_usd: float) -> float:- """Look up tiered maintenance margin rate."""- for tier_max, rate in _TIER_TABLE:- if notional_usd <= tier_max:- return rate- return _TIER_TABLE[-1][1]+ if check_crypto_liquidation(symbol, bar, self.positions):+ pos = self.positions.get(symbol)+ if pos is not None:+ mark_price = float(bar.get("close", pos.entry_price))+ liq_price = self.apply_slippage(mark_price, -pos.direction)+ self._close_position(symbol, liq_price, timestamp, "liquidation")diff --git a/agent/backtest/engines/forex.py b/agent/backtest/engines/forex.pyindex 0e9bd7ff3..f7ada0f45 100644--- a/agent/backtest/engines/forex.py+++ b/agent/backtest/engines/forex.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport pandas as pdfrom backtest.engines.base import BaseEngine+from backtest.engines._market_hooks import calc_forex_swap# ── Typical spreads in pips (1 pip = 0.0001 for most pairs, 0.01 for JPY) ──@@ -33,18 +34,6 @@ _SPREAD_PIPS: dict[str, float] = {}_DEFAULT_SPREAD_PIPS = 2.0-# ── Daily swap points (per standard lot, in account currency) ──-# Positive = receive, negative = pay. Varies by broker/rates; simplified table.--_SWAP_LONG: dict[str, float] = {- "EUR/USD": -6.5, "GBP/USD": -3.0, "USD/JPY": 8.0, "USD/CHF": 4.0,- "AUD/USD": -2.0, "USD/CAD": 2.0, "NZD/USD": -1.5,-}-_SWAP_SHORT: dict[str, float] = {- "EUR/USD": 3.5, "GBP/USD": -1.0, "USD/JPY": -12.0, "USD/CHF": -8.0,- "AUD/USD": -1.0, "USD/CAD": -5.0, "NZD/USD": -2.0,-}-# Standard lot sizeSTANDARD_LOT = 100_000@@ -149,41 +138,12 @@ class ForexEngine(BaseEngine):"""Apply daily swap/rollover at end of trading day."""if not self.swap_enabled:return- self._apply_swap(symbol, timestamp)+ swap = calc_forex_swap(+ symbol, timestamp, self.positions,+ self.lot_size, self._last_swap_dates,+ )+ self.capital += swapdef get_contract_multiplier(self, symbol: str) -> float:"""Forex: multiplier is 1.0 (size is in currency units)."""return 1.0-- # ── Swap (overnight rollover) ──-- def _apply_swap(self, symbol: str, timestamp: pd.Timestamp) -> None:- """Deduct/credit swap at daily rollover (once per calendar day).-- Triple swap on Wednesday (covers weekend).- """- if not hasattr(timestamp, "date"):- return-- current_date = timestamp.date()- if self._last_swap_dates.get(symbol) == current_date:- return- self._last_swap_dates[symbol] = current_date-- pos = self.positions.get(symbol)- if pos is None:- return-- pair = _normalize_symbol(symbol)- lots = pos.size / self.lot_size-- if pos.direction == 1:- swap_per_lot = _SWAP_LONG.get(pair, -1.0)- else:- swap_per_lot = _SWAP_SHORT.get(pair, -1.0)-- # Wednesday = triple swap (covers Sat+Sun)- multiplier = 3.0 if timestamp.weekday() == 2 else 1.0- swap = lots * swap_per_lot * multiplier-- self.capital += swapdiff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.pyindex dfdfb11f4..2d687da25 100644--- a/agent/backtest/metrics.py+++ b/agent/backtest/metrics.py@@ -147,7 +147,7 @@ def calc_metrics(equity_curve: pd.Series,trades: List[TradeRecord],initial_cash: float,- bars_per_year: int = 252,+ bars_per_year: Optional[int] = 252,bench_ret: Optional[pd.Series] = None,) -> Dict[str, Any]:"""Full set of performance metrics.@@ -156,7 +156,8 @@ def calc_metrics(equity_curve: Equity time series (index=timestamp, values=equity).trades: Completed round-trip trades.initial_cash: Starting capital.- bars_per_year: Bars per year for annualisation.+ bars_per_year: Bars per year for annualisation. None = auto-detect+ from equity curve dates (calendar-day method, for cross-market).bench_ret: Benchmark per-bar return series (optional).Returns:@@ -166,7 +167,15 @@ def calc_metrics(return _empty_metrics(initial_cash)n = len(equity_curve)- bpy = bars_per_year++ # Calendar-day annualization for cross-market (bars_per_year=None)+ if bars_per_year is None:+ first, last = equity_curve.index[0], equity_curve.index[-1]+ calendar_days = (last - first).days+ years = calendar_days / 365.25 if calendar_days > 0 else 1.0+ bpy = int(n / years) if years > 0 else 252+ else:+ bpy = bars_per_yearport_ret = equity_curve.pct_change().fillna(0.0)diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex 34a880267..e55b1dcaf 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -333,7 +333,12 @@ def main(run_dir: Path) -> None:# Annualization barseffective_source = _detect_primary_source(codes, source)from backtest.metrics import calc_bars_per_year- bars_per_year = calc_bars_per_year(interval, effective_source)+ # Cross-market: use calendar-day annualization (bars_per_year=None)+ market_types = {_detect_market(c) for c in codes}+ if len(market_types) > 1:+ bars_per_year = None+ else:+ bars_per_year = calc_bars_per_year(interval, effective_source)# Auto mode: wrap preloaded data in a dummy loaderif source == "auto":@@ -365,6 +370,11 @@ def _create_market_engine(source: str, config: dict, codes: List[str]):# Detect dominant market type from codesmarkets = {_detect_market(c) for c in codes} if codes else set()+ # Cross-market -> CompositeEngine+ if len(markets) > 1:+ from backtest.engines.composite import CompositeEngine+ return CompositeEngine(config, codes)+# Futures routing (Wave 2)if "futures" in markets:# Distinguish China vs global futures by exchange suffixdiff --git a/agent/src/skills/cross-market-strategy/SKILL.md b/agent/src/skills/cross-market-strategy/SKILL.mdnew file mode 100644index 000000000..8134fe856--- /dev/null+++ b/agent/src/skills/cross-market-strategy/SKILL.md@@ -0,0 +1,113 @@+---+name: cross-market-strategy+description: Write signal_engine.py for portfolios spanning multiple markets (A-shares + crypto, equity + forex, etc.)+category: strategy+---++## When to Use++When the user requests a backtest with codes from **different markets** — e.g. `["000001.SZ", "BTC-USDT"]` or `["AAPL.US", "EUR/USD", "600519.SH"]`.++The `CompositeEngine` handles calendar alignment, shared capital, and market rules automatically. The strategy only needs to output per-symbol signals.++## Key Concepts++### 1. Market Classification in generate()++Group symbols by market type and apply market-specific indicator parameters:++```python+def generate(self, data_map):+ groups = {}+ for code, df in data_map.items():+ market = self._detect_market(code)+ groups.setdefault(market, {})[code] = df++ signals = {}+ for market, market_data in groups.items():+ params = MARKET_PARAMS[market]+ for code, df in market_data.items():+ signals[code] = self._market_signal(df, params)+ return signals+```++### 2. Per-Market Parameter Tables++Different markets have very different dynamics. Using the same parameters everywhere produces poor results.++| Parameter | A-Share | Crypto | US Equity | Forex |+|-----------|---------|--------|-----------|-------|+| MA fast | 5 | 7 | 10 | 10 |+| MA slow | 20 | 25 | 50 | 30 |+| RSI period | 14 | 10 | 14 | 14 |+| Vol lookback | 20 | 14 | 20 | 20 |+| Typical daily vol | 1-2% | 3-8% | 1-2% | 0.3-0.8% |++### 3. Volatility-Adjusted Weights (Critical)++BTC daily vol ~ 5%, A-share daily vol ~ 1.5%. Without vol-adjustment, crypto eats the entire risk budget.++```python+def _vol_adjust(self, signals, data_map):+ vols = {}+ for code, df in data_map.items():+ ret = df["close"].pct_change().dropna()+ vols[code] = ret.rolling(20).std().iloc[-1] if len(ret) > 20 else ret.std()++ inv_vols = {c: 1.0 / (v + 1e-10) for c, v in vols.items()}+ total_inv = sum(inv_vols.values())++ adjusted = {}+ for code, sig in signals.items():+ weight = inv_vols[code] / total_inv * len(signals)+ adjusted[code] = (sig * weight).clip(-1.0, 1.0)+ return adjusted+```++### 4. Cross-Market Signal Patterns++1. **Momentum spillover**: BTC 7-day momentum as overlay for A-share tech sectors+2. **Risk-on/Risk-off**: USD/CNH rate + VIX proxy to reduce equity exposure+3. **Hedging**: Long A-shares + short crypto delta as tail hedge+4. **Correlation regime**: When rolling correlation > 0.6, reduce to single-market exposure; when < 0.2, maximize diversification++### 5. What the Engine Handles (Don't Worry About)++- **Trading calendar alignment**: signals are shifted on each symbol's own calendar, then ffill'd to unified dates+- **Market rules**: T+1 for A-shares, funding fees for crypto, swap for forex — all per-symbol+- **Capital allocation**: shared pool, strategy just sets target weights via signals+- **Commission/slippage**: dispatched to correct sub-engine per symbol++## config.json for Cross-Market++```json+{+ "source": "auto",+ "codes": ["000001.SZ", "BTC-USDT"],+ "start_date": "2024-01-01",+ "end_date": "2025-03-31",+ "interval": "1D",+ "initial_cash": 1000000,+ "engine": "daily"+}+```++- `source` **must** be `"auto"` for cross-market (routes each symbol to its loader)+- `extra_fields` should be `null` (not all markets support fundamentals)+- `leverage` defaults to 1.0 (CompositeEngine inherits from config)++## Market Detection Heuristics++| Pattern | Market |+|---------|--------|+| `000001.SZ`, `600519.SH` | A-share |+| `AAPL.US` | US equity |+| `700.HK` | HK equity |+| `BTC-USDT` | Crypto |+| `IF2406.CFFEX` | China futures |+| `ESZ4` | Global futures |+| `EUR/USD` | Forex |++## Supporting Files++- [example_signal_engine.py](example_signal_engine.py) — complete cross-market strategy examplediff --git a/agent/src/skills/cross-market-strategy/example_signal_engine.py b/agent/src/skills/cross-market-strategy/example_signal_engine.pynew file mode 100644index 000000000..4ea196bc9--- /dev/null+++ b/agent/src/skills/cross-market-strategy/example_signal_engine.py@@ -0,0 +1,80 @@+"""Cross-market strategy example: vol-adjusted dual-MA with per-market parameters.++Supports any combination of A-shares, crypto, US/HK equity, forex, and futures.+The CompositeEngine handles calendar alignment, market rules, and shared capital.+"""++import re++import numpy as np+import pandas as pd+++# Per-market indicator parameters+MARKET_PARAMS = {+ "a_share": {"ma_fast": 5, "ma_slow": 20, "vol_lookback": 20},+ "crypto": {"ma_fast": 7, "ma_slow": 25, "vol_lookback": 14},+ "us_equity": {"ma_fast": 10, "ma_slow": 50, "vol_lookback": 20},+ "hk_equity": {"ma_fast": 10, "ma_slow": 50, "vol_lookback": 20},+ "forex": {"ma_fast": 10, "ma_slow": 30, "vol_lookback": 20},+ "futures": {"ma_fast": 5, "ma_slow": 20, "vol_lookback": 20},+}++_MARKET_PATTERNS = [+ (re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "a_share"),+ (re.compile(r"^[A-Z]+\.US$", re.I), "us_equity"),+ (re.compile(r"^\d{3,5}\.HK$", re.I), "hk_equity"),+ (re.compile(r"^[A-Z]+-USDT$", re.I), "crypto"),+ (re.compile(r"^[A-Z]+/USDT$", re.I), "crypto"),+ (re.compile(r"^[A-Z]{3}/[A-Z]{3}$"), "forex"),+ (re.compile(r"^[A-Z]{6}\.FX$"), "forex"),+]+++class SignalEngine:+ def generate(self, data_map: dict) -> dict:+ # Step 1: raw signals per market+ raw_signals = {}+ for code, df in data_map.items():+ market = self._detect_market(code)+ params = MARKET_PARAMS.get(market, MARKET_PARAMS["a_share"])+ raw_signals[code] = self._market_signal(df, params)++ # Step 2: volatility-adjusted weights+ return self._vol_adjust(raw_signals, data_map)++ def _detect_market(self, code: str) -> str:+ for pattern, market in _MARKET_PATTERNS:+ if pattern.match(code):+ return market+ return "a_share"++ def _market_signal(self, df: pd.DataFrame, params: dict) -> pd.Series:+ close = df["close"]+ ma_fast = close.rolling(params["ma_fast"]).mean()+ ma_slow = close.rolling(params["ma_slow"]).mean()++ sig = pd.Series(0.0, index=df.index)+ sig[ma_fast > ma_slow] = 1.0+ sig[ma_fast < ma_slow] = -1.0+ return sig++ def _vol_adjust(self, signals: dict, data_map: dict) -> dict:+ vols = {}+ for code, df in data_map.items():+ ret = df["close"].pct_change().dropna()+ vols[code] = (+ ret.rolling(20).std().iloc[-1]+ if len(ret) > 20+ else ret.std()+ )++ inv_vols = {c: 1.0 / (v + 1e-10) for c, v in vols.items()}+ total_inv = sum(inv_vols.values())++ adjusted = {}+ n = len(signals)+ for code, sig in signals.items():+ weight = inv_vols[code] / total_inv * n+ adjusted[code] = (sig * weight).clip(-1.0, 1.0)+ return adjusteddiff --git a/agent/src/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.mdindex d6a130567..6ecdda9af 100644--- a/agent/src/skills/strategy-generate/SKILL.md+++ b/agent/src/skills/strategy-generate/SKILL.md@@ -183,6 +183,14 @@ If improvements are needed after evaluation, write `action_items`:- `"Add stop-loss: force close when loss exceeds 5%"`- `"Add volume filter in signal_engine.py: only trigger buy on high volume"`+## Cross-Market Strategies++When the user requests a backtest with codes from **different markets** (e.g. `["000001.SZ", "BTC-USDT"]`):+- Set `source: "auto"` in `config.json`+- The `CompositeEngine` handles calendar alignment, shared capital, and per-market rules automatically+- Use volatility-adjusted weights so high-vol assets (crypto) don't dominate the risk budget+- See the [cross-market-strategy](../cross-market-strategy/SKILL.md) skill for per-market parameters, vol-adjustment, and example code+## Supporting Files- [examples.md](examples.md) — example call sequencediff --git a/agent/tests/test_crypto_engine.py b/agent/tests/test_crypto_engine.pyindex 837ccbf83..1ddbbb71a 100644--- a/agent/tests/test_crypto_engine.py+++ b/agent/tests/test_crypto_engine.py@@ -14,7 +14,14 @@ from __future__ import annotationsimport pandas as pdimport pytest-from backtest.engines.crypto import CryptoEngine, _FUNDING_HOURS, _TIER_TABLE+from backtest.engines.crypto import CryptoEngine+from backtest.engines._market_hooks import (+ FUNDING_HOURS as _FUNDING_HOURS,+ _TIER_TABLE,+ calc_crypto_funding_fee,+ check_crypto_liquidation,+ _maintenance_rate,+)from backtest.models import Position@@ -131,7 +138,7 @@ class TestFundingFee:initial_capital = engine.capitalbar = _make_bar(close=60000.0)ts = pd.Timestamp("2025-01-01 08:00:00") # settlement hour- engine._apply_funding_fee("BTC-USDT", bar, ts)+ engine.on_bar("BTC-USDT", bar, ts)# Long pays: 1.0 × 60000 × 0.0001 × 1(long) = $6assert engine.capital == pytest.approx(initial_capital - 6.0)@@ -144,7 +151,7 @@ class TestFundingFee:initial_capital = engine.capitalbar = _make_bar(close=60000.0)ts = pd.Timestamp("2025-01-01 05:00:00") # not settlement hour- engine._apply_funding_fee("BTC-USDT", bar, ts)+ engine.on_bar("BTC-USDT", bar, ts)# Daily fallback: applies once even at non-settlement hourassert engine.capital == pytest.approx(initial_capital - 6.0)@@ -156,7 +163,7 @@ class TestFundingFee:initial_capital = engine.capitalbar = _make_bar(close=60000.0)ts = pd.Timestamp("2025-01-01 08:00:00")- engine._apply_funding_fee("BTC-USDT", bar, ts)+ engine.on_bar("BTC-USDT", bar, ts)# Short: direction=-1, fee = notional × rate × direction = negative → capital increasesassert engine.capital > initial_capital@@ -167,10 +174,10 @@ class TestFundingFee:)bar = _make_bar(close=60000.0)ts = pd.Timestamp("2025-01-01 08:00:00")- engine._apply_funding_fee("BTC-USDT", bar, ts)+ engine.on_bar("BTC-USDT", bar, ts)capital_after_first = engine.capital# Call again at same hour — should not deduct again- engine._apply_funding_fee("BTC-USDT", bar, ts)+ engine.on_bar("BTC-USDT", bar, ts)assert engine.capital == capital_after_firstdef test_no_funding_without_position(self) -> None:@@ -178,7 +185,7 @@ class TestFundingFee:initial_capital = engine.capitalbar = _make_bar()ts = pd.Timestamp("2025-01-01 08:00:00")- engine._apply_funding_fee("BTC-USDT", bar, ts)+ engine.on_bar("BTC-USDT", bar, ts)assert engine.capital == initial_capitaldef test_daily_bars_apply_each_day(self) -> None:@@ -191,17 +198,17 @@ class TestFundingFee:initial = engine.capital# Day 1- engine._apply_funding_fee("BTC-USDT", bar, pd.Timestamp("2025-01-01"))+ engine.on_bar("BTC-USDT", bar, pd.Timestamp("2025-01-01"))after_day1 = engine.capitalassert after_day1 < initial # fee deducted# Day 2 (same hour=0, different date)- engine._apply_funding_fee("BTC-USDT", bar, pd.Timestamp("2025-01-02"))+ engine.on_bar("BTC-USDT", bar, pd.Timestamp("2025-01-02"))after_day2 = engine.capitalassert after_day2 < after_day1 # fee deducted again# Day 3- engine._apply_funding_fee("BTC-USDT", bar, pd.Timestamp("2025-01-03"))+ engine.on_bar("BTC-USDT", bar, pd.Timestamp("2025-01-03"))after_day3 = engine.capitalassert after_day3 < after_day2 # fee deducted again@@ -222,9 +229,9 @@ class TestFundingFee:bar_eth = _make_bar(close=3000.0)ts = pd.Timestamp("2025-01-01 08:00:00")- engine._apply_funding_fee("BTC-USDT", bar_btc, ts)+ engine.on_bar("BTC-USDT", bar_btc, ts)after_btc = engine.capital- engine._apply_funding_fee("ETH-USDT", bar_eth, ts)+ engine.on_bar("ETH-USDT", bar_eth, ts)after_both = engine.capital# BTC: 1 × 60000 × 0.0001 = $6@@ -259,7 +266,7 @@ class TestLiquidation:# unrealized = -6000, equity = 0 → clearly liquidatedbar = _make_bar(close=54000.0)ts = pd.Timestamp("2025-01-02")- engine._check_liquidation("BTC-USDT", bar, ts)+ engine.on_bar("BTC-USDT", bar, ts)assert "BTC-USDT" not in engine.positionsassert len(engine.trades) == 1assert engine.trades[0].exit_reason == "liquidation"@@ -271,7 +278,7 @@ class TestLiquidation:)bar = _make_bar(close=65000.0)ts = pd.Timestamp("2025-01-02")- engine._check_liquidation("BTC-USDT", bar, ts)+ engine.on_bar("BTC-USDT", bar, ts)assert "BTC-USDT" in engine.positionsdef test_no_liquidation_for_spot(self) -> None:@@ -282,7 +289,7 @@ class TestLiquidation:)bar = _make_bar(close=30000.0) # 50% dropts = pd.Timestamp("2025-01-02")- engine._check_liquidation("BTC-USDT", bar, ts)+ engine.on_bar("BTC-USDT", bar, ts)assert "BTC-USDT" in engine.positionsdef test_short_liquidation(self) -> None:@@ -295,7 +302,7 @@ class TestLiquidation:# equity_in_pos = 6000 - 6500 = -$500 < 0 → liquidatedbar = _make_bar(close=66500.0)ts = pd.Timestamp("2025-01-02")- engine._check_liquidation("BTC-USDT", bar, ts)+ engine.on_bar("BTC-USDT", bar, ts)assert "BTC-USDT" not in engine.positions@@ -306,17 +313,17 @@ class TestLiquidation:class TestMaintenanceRate:def test_small_position(self) -> None:- assert CryptoEngine._maintenance_rate(50_000) == 0.004+ assert _maintenance_rate(50_000) == 0.004def test_medium_position(self) -> None:- assert CryptoEngine._maintenance_rate(300_000) == 0.006+ assert _maintenance_rate(300_000) == 0.006def test_large_position(self) -> None:- assert CryptoEngine._maintenance_rate(2_000_000) == 0.02+ assert _maintenance_rate(2_000_000) == 0.02def test_tier_boundaries(self) -> None:- assert CryptoEngine._maintenance_rate(100_000) == 0.004- assert CryptoEngine._maintenance_rate(100_001) == 0.006+ assert _maintenance_rate(100_000) == 0.004+ assert _maintenance_rate(100_001) == 0.006def test_maximum_tier(self) -> None:- assert CryptoEngine._maintenance_rate(100_000_000) == 0.10+ assert _maintenance_rate(100_000_000) == 0.10diff --git a/agent/tests/test_forex_engine.py b/agent/tests/test_forex_engine.pyindex 838024f9d..e8e3b5e77 100644--- a/agent/tests/test_forex_engine.py+++ b/agent/tests/test_forex_engine.py@@ -20,9 +20,9 @@ from backtest.engines.forex import (_normalize_symbol,_pip_value,_SPREAD_PIPS,- _SWAP_LONG,STANDARD_LOT,)+from backtest.engines._market_hooks import _SWAP_LONGfrom backtest.models import Position