Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): buy the benchmark at the first evaluated open, as the strategy is

Haozhe Wu8172827ec537
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 918821eac..cbf9b3ca5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,25 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Fixed
+
+#### Backtest runner, engines and metrics
+
+- **A benchmark is bought at the first evaluated open, the way the strategy
+ is**. Both start from cash before the first evaluated bar, and the engine
+ fills the strategy at a bar's open. The equal-weight basket ran instead from
+ each bar's previous close, so with a warm-up boundary (`evaluation_start_date`
+ or `warmup_bars`) it was credited with the move from the last warm-up close;
+ a declared external benchmark started at the first evaluated close and missed
+ that bar's move. Both now buy at the first evaluated open (each basket symbol
+ at its first traded open in the window, or that bar's close when it has no
+ usable open) and hold to the last close, so a fully invested strategy differs
+ from buy-and-hold on the first bar only by its costs. On a 20/60 SMA run on
+ AAPL.US over 2024-01-02..2025-12-31 the basket moves from 42.54% to 46.64%,
+ excess return from 22.53% to 18.43% and the information ratio from 0.236 to
+ 0.172; strategy metrics are unchanged. Runs without a warm-up boundary also
+ move, by the first bar's open-to-close.
+
## [0.1.19] — 2026-11-05
Rolls up 299 commits / 116 merged pull requests since 0.1.18, plus 21
diff --git a/README.md b/README.md
index 855ec5da5..e85ac28df 100644
--- a/README.md
+++ b/README.md
@@ -59,6 +59,7 @@
- **2026-11-05** 🚀 **v0.1.19 released** ([Release notes](https://github.com/HKUDS/Vibe-Trading/releases/tag/v0.1.19), `pip install -U vibe-trading-ai`): research that outlives the chat — save versioned research artifacts with their evidence and revise them, reuse backtests from earlier turns and sessions, and edit a research goal in place. New opt-ins: a five-minute A-share paper simulation, and Gildata financial queries, stock screening and Shannon portfolio diagnosis (QVeris is removed; an existing `GILDATA_TOKEN` alone now enables nothing). Also Argentina (BYMA) backtests, Parallel web search, Codex OAuth model discovery, and both 0.1.18 regressions fixed. 116 merged pull requests plus 21 landed through maintainer commits, from 26 contributors ([CHANGELOG](CHANGELOG.md)).
**Fixed today:** a backtest reports the benchmark it actually evaluated, long/short books get a risk x-ray, GTJA alpha 17 stays missing while its inputs warm up, the Shannon panel speaks all eleven UI languages, and two reviewed contributor fixes that had not landed are in ([#2042](https://github.com/HKUDS/Vibe-Trading/pull/2042) TTM sums across a missing quarter, [#1985](https://github.com/HKUDS/Vibe-Trading/pull/1985) 3:2 split detection). Thanks [@rudycelekli](https://github.com/rudycelekli), [@he-yufeng](https://github.com/he-yufeng), [@Jackzigen](https://github.com/Jackzigen), [@Shizoqua](https://github.com/Shizoqua), [@cgycorey](https://github.com/cgycorey), [@dajiaohuang](https://github.com/dajiaohuang), [@zeus229](https://github.com/zeus229), [@alexwan02](https://github.com/alexwan02), [@BHhhh-123](https://github.com/BHhhh-123), [@remote-controlled-man](https://github.com/remote-controlled-man), [@shadowinlife](https://github.com/shadowinlife), [@TWJxi](https://github.com/TWJxi), [@lishuanghong1989-netizen](https://github.com/lishuanghong1989-netizen), [@TerryF7](https://github.com/TerryF7), [@davidalmeida90](https://github.com/davidalmeida90), [@DrDLyuan](https://github.com/DrDLyuan), [@goatyyc](https://github.com/goatyyc), [@hnq-ai](https://github.com/hnq-ai), [@kadyrbekovhamit-cyber](https://github.com/kadyrbekovhamit-cyber), [@MetaAviator](https://github.com/MetaAviator), [@octo-patch](https://github.com/octo-patch), [@RowanAldean](https://github.com/RowanAldean), [@VectorPeak](https://github.com/VectorPeak), [@wavebyrd](https://github.com/wavebyrd) and [@yufengsika](https://github.com/yufengsika)!
+ **On main after the release (next pip release):** backtest benchmarks are bought at the first evaluated open, as the strategy is, instead of from the last warm-up close; excess return no longer includes that move (AAPL 20/60 SMA example: 22.5% → 18.4%).
- **2026-11-04** 📊 **Gildata financial queries, stock screening and Shannon portfolio diagnosis** — Screen stocks by market cap and retrieve their half-year revenue in one request, or inspect portfolio factor exposures and each holding’s contribution to volatility. All nine Gildata features are opt-in, including for existing token holders. Free data sources never fall back to Gildata. [#2117](https://github.com/HKUDS/Vibe-Trading/pull/2117) · [#2118](https://github.com/HKUDS/Vibe-Trading/pull/2118) · [#2119](https://github.com/HKUDS/Vibe-Trading/pull/2119)
Also clarified next-bar backtest fills, fixed false Swarm timeouts on Unicode heartbeats and sped up research artifact deduplication. [#2137](https://github.com/HKUDS/Vibe-Trading/pull/2137) · [#2155](https://github.com/HKUDS/Vibe-Trading/pull/2155) · [#2159](https://github.com/HKUDS/Vibe-Trading/pull/2159)
diff --git a/README_ar.md b/README_ar.md
index 9ae117e87..d8c1d3169 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -59,6 +59,7 @@
- **2026-11-05** 🚀 **صدور v0.1.19** ([ملاحظات الإصدار](https://github.com/HKUDS/Vibe-Trading/releases/tag/v0.1.19), `pip install -U vibe-trading-ai`): أبحاث تبقى بعد انتهاء المحادثة: احفظ نسخًا مؤرخة من الأبحاث مع أدلتها ونقّحها، وأعد استخدام الاختبارات التاريخية من الأدوار والجلسات السابقة، وعدّل هدف البحث في مكانه. ميزات اختيارية جديدة: محاكاة تجريبية لأسهم A بخطوات خمس دقائق، والاستعلامات المالية وفرز الأسهم عبر Gildata وتشخيص المحافظ عبر Shannon (أُزيل QVeris، ولم يعد وجود `GILDATA_TOKEN` وحده يفعّل أي ميزة). وأيضًا اختبارات تاريخية لسوق الأرجنتين (BYMA)، والبحث في الويب عبر Parallel، واكتشاف النماذج عبر Codex OAuth، وإصلاح التراجعين اللذين ظهرا في 0.1.18. ‏116 طلب سحب مدموجًا، إضافة إلى 21 دخلت عبر إيداعات المشرفين، من 26 مساهمًا ([CHANGELOG](CHANGELOG.md)).
**إصلاحات اليوم:** يعرض الاختبار التاريخي المؤشر المرجعي الذي قيّمه فعلًا، وتحصل المحافظ الطويلة/القصيرة على فحص المخاطر (risk x-ray)، ويبقى عامل GTJA رقم 17 فارغًا ما دامت مدخلاته في فترة الإحماء، وتتوفر لوحة Shannon بلغات الواجهة الإحدى عشرة، ودخل إصلاحان من المساهمين كانا قد رُوجعا ولم يُدمجا ([#2042](https://github.com/HKUDS/Vibe-Trading/pull/2042) مجاميع TTM التي تمتد عبر ربع سنة مفقود، [#1985](https://github.com/HKUDS/Vibe-Trading/pull/1985) رصد تجزئة الأسهم بنسبة 3:2). شكرًا لـ [@rudycelekli](https://github.com/rudycelekli)، [@he-yufeng](https://github.com/he-yufeng)، [@Jackzigen](https://github.com/Jackzigen)، [@Shizoqua](https://github.com/Shizoqua)، [@cgycorey](https://github.com/cgycorey)، [@dajiaohuang](https://github.com/dajiaohuang)، [@zeus229](https://github.com/zeus229)، [@alexwan02](https://github.com/alexwan02)، [@BHhhh-123](https://github.com/BHhhh-123)، [@remote-controlled-man](https://github.com/remote-controlled-man)، [@shadowinlife](https://github.com/shadowinlife)، [@TWJxi](https://github.com/TWJxi)، [@lishuanghong1989-netizen](https://github.com/lishuanghong1989-netizen)، [@TerryF7](https://github.com/TerryF7)، [@davidalmeida90](https://github.com/davidalmeida90)، [@DrDLyuan](https://github.com/DrDLyuan)، [@goatyyc](https://github.com/goatyyc)، [@hnq-ai](https://github.com/hnq-ai)، [@kadyrbekovhamit-cyber](https://github.com/kadyrbekovhamit-cyber)، [@MetaAviator](https://github.com/MetaAviator)، [@octo-patch](https://github.com/octo-patch)، [@RowanAldean](https://github.com/RowanAldean)، [@VectorPeak](https://github.com/VectorPeak)، [@wavebyrd](https://github.com/wavebyrd) و[@yufengsika](https://github.com/yufengsika)!
+ **أُصلح على main بعد الإصدار (يصل في إصدار pip التالي):** يُشترى معيار المقارنة في الاختبار الرجعي الآن عند سعر افتتاح أول شريط مُقيَّم، كما تُنفَّذ الاستراتيجية، بدلًا من آخر سعر إغلاق في فترة الإحماء؛ ولم يعد العائد الزائد يتضمن هذه الحركة (مثال AAPL بمتوسطي 20/60: من 22.5% إلى 18.4%).
- **2026-11-04** 📊 **الاستعلامات المالية وفرز الأسهم عبر Gildata وتشخيص المحافظ عبر Shannon** — يمكن باستعلام واحد عرض أكبر ثلاثة أسهم من حيث القيمة السوقية وإيراداتها نصف السنوية. يعرض Shannon تعرّض المحفظة لعشرة عوامل ومساهمة كل مركز في تقلّباتها. تتطلب كل ميزة من الميزات التسع تفعيلًا منفصلًا حتى مع وجود رمز وصول محفوظ. لا ينتقل النظام إلى Gildata تلقائيًا إذا تعذّر جلب البيانات من المصادر المجانية. [#2117](https://github.com/HKUDS/Vibe-Trading/pull/2117) · [#2118](https://github.com/HKUDS/Vibe-Trading/pull/2118) · [#2119](https://github.com/HKUDS/Vibe-Trading/pull/2119)
يوضح دليل الاختبار التاريخي أن الإشارة تُنفّذ عند افتتاح الشمعة التالية. كما صُحّح رصد انتهاء مهلة مهام Swarm وتسارع التحقق من تكرار الأبحاث. [#2137](https://github.com/HKUDS/Vibe-Trading/pull/2137) · [#2155](https://github.com/HKUDS/Vibe-Trading/pull/2155) · [#2159](https://github.com/HKUDS/Vibe-Trading/pull/2159)
diff --git a/README_es.md b/README_es.md
index db3a6a63f..4de08640b 100644
--- a/README_es.md
+++ b/README_es.md
@@ -59,6 +59,7 @@
- **2026-11-05** 🚀 **Publicada la v0.1.19** ([Notas de la versión](https://github.com/HKUDS/Vibe-Trading/releases/tag/v0.1.19), `pip install -U vibe-trading-ai`): investigación que sobrevive al chat: guarda investigaciones versionadas con su evidencia y revísalas, reutiliza backtests de turnos y sesiones anteriores y edita un objetivo de investigación sin empezar de cero. Nuevas funciones opcionales: una simulación de acciones A en pasos de cinco minutos y las consultas financieras, la selección de acciones y el diagnóstico de cartera Shannon de Gildata (se retira QVeris; un `GILDATA_TOKEN` existente ya no activa nada por sí solo). Además: backtests de Argentina (BYMA), búsqueda web con Parallel, descubrimiento de modelos con OAuth de Codex y corrección de las dos regresiones de la 0.1.18. 116 pull requests fusionados más 21 incorporados mediante commits de los mantenedores, de 26 contribuidores ([CHANGELOG](CHANGELOG.md)).
**Corregido hoy:** el backtest informa del índice de referencia que realmente evaluó, las carteras largo/corto tienen radiografía de riesgo, el alfa 17 de GTJA queda vacío mientras sus datos de entrada completan el periodo de calentamiento, el panel Shannon está disponible en los once idiomas de la interfaz y entran dos correcciones revisadas de colaboradores que no se habían incorporado ([#2042](https://github.com/HKUDS/Vibe-Trading/pull/2042) sumas TTM que abarcaban un trimestre ausente, [#1985](https://github.com/HKUDS/Vibe-Trading/pull/1985) detección de desdoblamientos 3:2). ¡Gracias a [@rudycelekli](https://github.com/rudycelekli), [@he-yufeng](https://github.com/he-yufeng), [@Jackzigen](https://github.com/Jackzigen), [@Shizoqua](https://github.com/Shizoqua), [@cgycorey](https://github.com/cgycorey), [@dajiaohuang](https://github.com/dajiaohuang), [@zeus229](https://github.com/zeus229), [@alexwan02](https://github.com/alexwan02), [@BHhhh-123](https://github.com/BHhhh-123), [@remote-controlled-man](https://github.com/remote-controlled-man), [@shadowinlife](https://github.com/shadowinlife), [@TWJxi](https://github.com/TWJxi), [@lishuanghong1989-netizen](https://github.com/lishuanghong1989-netizen), [@TerryF7](https://github.com/TerryF7), [@davidalmeida90](https://github.com/davidalmeida90), [@DrDLyuan](https://github.com/DrDLyuan), [@goatyyc](https://github.com/goatyyc), [@hnq-ai](https://github.com/hnq-ai), [@kadyrbekovhamit-cyber](https://github.com/kadyrbekovhamit-cyber), [@MetaAviator](https://github.com/MetaAviator), [@octo-patch](https://github.com/octo-patch), [@RowanAldean](https://github.com/RowanAldean), [@VectorPeak](https://github.com/VectorPeak), [@wavebyrd](https://github.com/wavebyrd) y [@yufengsika](https://github.com/yufengsika)!
+ **Corregido en main tras el lanzamiento (llegará en la próxima versión de pip):** el benchmark del backtest ahora se compra a la apertura de la primera barra evaluada, como la estrategia, en lugar de partir del último cierre del calentamiento; el exceso de rentabilidad ya no incluye ese movimiento (ejemplo AAPL SMA 20/60: 22,5 % → 18,4 %).
- **2026-11-04** 📊 **Consultas financieras, selección de acciones y diagnóstico de cartera Shannon con Gildata** — Una consulta permite obtener las tres acciones de mayor capitalización y sus ingresos semestrales. Shannon muestra la exposición de la cartera a diez factores y la contribución de cada posición a la volatilidad. Las nueve funciones requieren activación individual, incluso con un token guardado. Si fallan las fuentes gratuitas, el sistema no recurre a Gildata. [#2117](https://github.com/HKUDS/Vibe-Trading/pull/2117) · [#2118](https://github.com/HKUDS/Vibe-Trading/pull/2118) · [#2119](https://github.com/HKUDS/Vibe-Trading/pull/2119)
También se aclaró la ejecución de señales en la apertura de la siguiente vela, se corrigieron falsos vencimientos de tareas Swarm y se agilizó la detección de investigaciones duplicadas. [#2137](https://github.com/HKUDS/Vibe-Trading/pull/2137) · [#2155](https://github.com/HKUDS/Vibe-Trading/pull/2155) · [#2159](https://github.com/HKUDS/Vibe-Trading/pull/2159)
diff --git a/README_id.md b/README_id.md
index d25244bf7..8cdde4a2e 100644
--- a/README_id.md
+++ b/README_id.md
@@ -59,6 +59,7 @@
- **2026-11-05** 🚀 **v0.1.19 dirilis** ([Catatan rilis](https://github.com/HKUDS/Vibe-Trading/releases/tag/v0.1.19), `pip install -U vibe-trading-ai`): riset yang bertahan melampaui obrolan — simpan artefak riset berversi beserta buktinya lalu revisi, gunakan kembali backtest dari giliran dan sesi sebelumnya, dan sunting tujuan riset di tempat. Fitur opsional baru: simulasi saham A per lima menit, serta kueri keuangan, seleksi saham, dan diagnosis portofolio Shannon dari Gildata (QVeris dihapus; `GILDATA_TOKEN` yang sudah ada kini tidak lagi mengaktifkan apa pun dengan sendirinya). Juga backtest Argentina (BYMA), pencarian web Parallel, penemuan model lewat Codex OAuth, dan perbaikan kedua regresi 0.1.18. 116 pull request digabung ditambah 21 yang masuk lewat commit maintainer, dari 26 kontributor ([CHANGELOG](CHANGELOG.md)).
**Diperbaiki hari ini:** backtest melaporkan tolok ukur yang benar-benar dievaluasinya, portofolio long/short mendapat risk x-ray, alfa GTJA 17 tetap kosong selama inputnya masih dalam masa pemanasan, panel Shannon tersedia dalam kesebelas bahasa antarmuka, dan dua perbaikan kontributor yang sudah ditinjau tetapi belum masuk kini disertakan ([#2042](https://github.com/HKUDS/Vibe-Trading/pull/2042) jumlah TTM yang melintasi kuartal yang hilang, [#1985](https://github.com/HKUDS/Vibe-Trading/pull/1985) deteksi pemecahan saham 3:2). Terima kasih [@rudycelekli](https://github.com/rudycelekli), [@he-yufeng](https://github.com/he-yufeng), [@Jackzigen](https://github.com/Jackzigen), [@Shizoqua](https://github.com/Shizoqua), [@cgycorey](https://github.com/cgycorey), [@dajiaohuang](https://github.com/dajiaohuang), [@zeus229](https://github.com/zeus229), [@alexwan02](https://github.com/alexwan02), [@BHhhh-123](https://github.com/BHhhh-123), [@remote-controlled-man](https://github.com/remote-controlled-man), [@shadowinlife](https://github.com/shadowinlife), [@TWJxi](https://github.com/TWJxi), [@lishuanghong1989-netizen](https://github.com/lishuanghong1989-netizen), [@TerryF7](https://github.com/TerryF7), [@davidalmeida90](https://github.com/davidalmeida90), [@DrDLyuan](https://github.com/DrDLyuan), [@goatyyc](https://github.com/goatyyc), [@hnq-ai](https://github.com/hnq-ai), [@kadyrbekovhamit-cyber](https://github.com/kadyrbekovhamit-cyber), [@MetaAviator](https://github.com/MetaAviator), [@octo-patch](https://github.com/octo-patch), [@RowanAldean](https://github.com/RowanAldean), [@VectorPeak](https://github.com/VectorPeak), [@wavebyrd](https://github.com/wavebyrd) dan [@yufengsika](https://github.com/yufengsika)!
+ **Diperbaiki di main setelah rilis (masuk rilis pip berikutnya):** benchmark backtest kini dibeli pada harga pembukaan bar evaluasi pertama, sama seperti strategi, bukan dari harga penutupan terakhir masa pemanasan; excess return tidak lagi memuat pergerakan itu (contoh AAPL SMA 20/60: 22,5% → 18,4%).
- **2026-11-04** 📊 **Kueri keuangan, seleksi saham, dan diagnosis portofolio Shannon dengan Gildata** — Satu kueri dapat menampilkan tiga saham dengan kapitalisasi pasar terbesar beserta pendapatan semesterannya. Shannon menunjukkan eksposur portofolio terhadap sepuluh faktor dan kontribusi tiap posisi terhadap volatilitas. Kesembilan fitur harus diaktifkan satu per satu, termasuk jika token sudah tersimpan. Jika sumber gratis gagal, sistem tidak beralih ke Gildata. [#2117](https://github.com/HKUDS/Vibe-Trading/pull/2117) · [#2118](https://github.com/HKUDS/Vibe-Trading/pull/2118) · [#2119](https://github.com/HKUDS/Vibe-Trading/pull/2119)
Panduan backtest kini menjelaskan bahwa sinyal dieksekusi pada harga pembukaan bar berikutnya. Deteksi batas waktu Swarm juga diperbaiki dan pemeriksaan duplikat riset dipercepat. [#2137](https://github.com/HKUDS/Vibe-Trading/pull/2137) · [#2155](https://github.com/HKUDS/Vibe-Trading/pull/2155) · [#2159](https://github.com/HKUDS/Vibe-Trading/pull/2159)
diff --git a/README_ja.md b/README_ja.md
index 88bb407c7..004b096d0 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -59,6 +59,7 @@
- **2026-11-05** 🚀 **v0.1.19 リリース**([リリースノート](https://github.com/HKUDS/Vibe-Trading/releases/tag/v0.1.19)、`pip install -U vibe-trading-ai`):チャットが終わっても残る調査へ。根拠付きの調査記録をバージョンごとに保存・改訂でき、以前のターンやセッションのバックテストを再利用でき、調査目標をその場で編集できます。新しいオプトイン機能:中国A株の5分刻みペーパーシミュレーション、Gildata の財務照会・銘柄抽出と Shannon のポートフォリオ診断(QVeris は削除。既存の `GILDATA_TOKEN` だけでは何も有効になりません)。ほかにアルゼンチン(BYMA)のバックテスト、Parallel ウェブ検索、Codex OAuth のモデル検出を追加し、0.1.18 の回帰 2 件をどちらも修正しました。マージ済みプルリクエスト 116 件に加え、メンテナーのコミット経由で取り込まれたものが 21 件あり、貢献者は 26 人です([CHANGELOG](CHANGELOG.md))。
**本日の修正:** バックテストは実際に評価したベンチマークを報告し、ロング・ショートのポートフォリオにもリスク分析(risk x-ray)が付きます。GTJA alpha 17 は入力のウォームアップ中は欠損のまま保たれ、Shannon パネルは UI の 11 言語すべてに対応しました。レビュー済みで未取り込みだった貢献者の修正 2 件も取り込みました([#2042](https://github.com/HKUDS/Vibe-Trading/pull/2042) 欠損四半期をまたぐ TTM 合計の修正、[#1985](https://github.com/HKUDS/Vibe-Trading/pull/1985) 3:2 株式分割の検出)。[@rudycelekli](https://github.com/rudycelekli)、[@he-yufeng](https://github.com/he-yufeng)、[@Jackzigen](https://github.com/Jackzigen)、[@Shizoqua](https://github.com/Shizoqua)、[@cgycorey](https://github.com/cgycorey)、[@dajiaohuang](https://github.com/dajiaohuang)、[@zeus229](https://github.com/zeus229)、[@alexwan02](https://github.com/alexwan02)、[@BHhhh-123](https://github.com/BHhhh-123)、[@remote-controlled-man](https://github.com/remote-controlled-man)、[@shadowinlife](https://github.com/shadowinlife)、[@TWJxi](https://github.com/TWJxi)、[@lishuanghong1989-netizen](https://github.com/lishuanghong1989-netizen)、[@TerryF7](https://github.com/TerryF7)、[@davidalmeida90](https://github.com/davidalmeida90)、[@DrDLyuan](https://github.com/DrDLyuan)、[@goatyyc](https://github.com/goatyyc)、[@hnq-ai](https://github.com/hnq-ai)、[@kadyrbekovhamit-cyber](https://github.com/kadyrbekovhamit-cyber)、[@MetaAviator](https://github.com/MetaAviator)、[@octo-patch](https://github.com/octo-patch)、[@RowanAldean](https://github.com/RowanAldean)、[@VectorPeak](https://github.com/VectorPeak)、[@wavebyrd](https://github.com/wavebyrd)、[@yufengsika](https://github.com/yufengsika) に感謝します!
+ **リリース後に main で修正(次の pip リリースに含まれます):** バックテストのベンチマークは、戦略と同じく評価期間最初の足の始値で買うようになり、ウォームアップ最後の終値からは計算しなくなりました。超過リターンにはその値動きが含まれなくなります(AAPL 20/60 SMA の例:22.5% → 18.4%)。
- **2026-11-04** 📊 **Gildataの財務照会・銘柄抽出とShannonのポートフォリオ診断** — 時価総額上位3銘柄とその半期売上高を一度に取得できます。Shannonでは10因子へのエクスポージャーと各銘柄のポートフォリオ変動への寄与を確認できます。9機能はトークン登録済みでも個別に有効化する必要があります。無料ソースからGildataへの自動切り替えはありません。 [#2117](https://github.com/HKUDS/Vibe-Trading/pull/2117) · [#2118](https://github.com/HKUDS/Vibe-Trading/pull/2118) · [#2119](https://github.com/HKUDS/Vibe-Trading/pull/2119)
バックテストの約定が次の足の始値になることを明記し、Swarmのタイムアウト誤判定を修正しました。研究資料の重複チェックも高速化しました。 [#2137](https://github.com/HKUDS/Vibe-Trading/pull/2137) · [#2155](https://github.com/HKUDS/Vibe-Trading/pull/2155) · [#2159](https://github.com/HKUDS/Vibe-Trading/pull/2159)
diff --git a/README_ko.md b/README_ko.md
index 8247d835b..c3fdd1f55 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -59,6 +59,7 @@
- **2026-11-05** 🚀 **v0.1.19 출시**([릴리스 노트](https://github.com/HKUDS/Vibe-Trading/releases/tag/v0.1.19), `pip install -U vibe-trading-ai`): 대화가 끝나도 남는 리서치 — 근거를 담은 연구 기록을 버전별로 저장하고 수정하며, 이전 턴과 세션의 백테스트를 재사용하고, 연구 목표를 그 자리에서 편집할 수 있습니다. 새 옵트인 기능: A주 5분 단위 모의 거래 시뮬레이션, Gildata 재무 조회·종목 선별 및 Shannon 포트폴리오 진단(QVeris는 제거되었고, 기존 `GILDATA_TOKEN`만으로는 아무 기능도 켜지지 않습니다). 또한 아르헨티나(BYMA) 백테스트, Parallel 웹 검색, Codex OAuth 모델 탐색을 추가하고 0.1.18의 회귀 두 건을 모두 수정했습니다. 병합된 풀 리퀘스트 116개와 메인테이너 커밋으로 반영된 21개이며 기여자는 26명입니다([CHANGELOG](CHANGELOG.md)).
**오늘의 수정:** 백테스트가 실제로 평가한 벤치마크를 보고하고, 롱숏 포트폴리오에도 위험 분석(risk x-ray)을 제공합니다. GTJA alpha 17은 입력이 워밍업되는 동안 결측으로 유지되고, Shannon 패널은 11개 UI 언어를 모두 지원합니다. 검토를 마쳤지만 반영되지 않았던 기여자 수정 두 건도 반영했습니다([#2042](https://github.com/HKUDS/Vibe-Trading/pull/2042) 결측 분기를 건너뛰는 TTM 합계 수정, [#1985](https://github.com/HKUDS/Vibe-Trading/pull/1985) 3:2 주식 분할 감지). [@rudycelekli](https://github.com/rudycelekli), [@he-yufeng](https://github.com/he-yufeng), [@Jackzigen](https://github.com/Jackzigen), [@Shizoqua](https://github.com/Shizoqua), [@cgycorey](https://github.com/cgycorey), [@dajiaohuang](https://github.com/dajiaohuang), [@zeus229](https://github.com/zeus229), [@alexwan02](https://github.com/alexwan02), [@BHhhh-123](https://github.com/BHhhh-123), [@remote-controlled-man](https://github.com/remote-controlled-man), [@shadowinlife](https://github.com/shadowinlife), [@TWJxi](https://github.com/TWJxi), [@lishuanghong1989-netizen](https://github.com/lishuanghong1989-netizen), [@TerryF7](https://github.com/TerryF7), [@davidalmeida90](https://github.com/davidalmeida90), [@DrDLyuan](https://github.com/DrDLyuan), [@goatyyc](https://github.com/goatyyc), [@hnq-ai](https://github.com/hnq-ai), [@kadyrbekovhamit-cyber](https://github.com/kadyrbekovhamit-cyber), [@MetaAviator](https://github.com/MetaAviator), [@octo-patch](https://github.com/octo-patch), [@RowanAldean](https://github.com/RowanAldean), [@VectorPeak](https://github.com/VectorPeak), [@wavebyrd](https://github.com/wavebyrd), [@yufengsika](https://github.com/yufengsika)에게 감사드립니다!
+ **릴리스 후 main에서 수정(다음 pip 릴리스에 포함):** 백테스트 벤치마크는 전략과 같이 평가 구간 첫 봉의 시가에 매수하며, 더 이상 워밍업 마지막 종가에서 계산하지 않습니다. 초과 수익에 그 움직임이 더 이상 포함되지 않습니다(AAPL 20/60 SMA 예: 22.5% → 18.4%).
- **2026-11-04** 📊 **Gildata 재무 조회·종목 선별 및 Shannon 포트폴리오 진단** — 시가총액 상위 세 종목과 반기 매출을 한 번에 조회할 수 있습니다. Shannon은 포트폴리오의 10개 요인 노출도와 각 보유 종목의 변동성 기여도를 보여 줍니다. 저장된 토큰이 있어도 아홉 기능을 각각 켜야 합니다. 무료 소스 조회가 실패해도 Gildata로 자동 전환하지 않습니다. [#2117](https://github.com/HKUDS/Vibe-Trading/pull/2117) · [#2118](https://github.com/HKUDS/Vibe-Trading/pull/2118) · [#2119](https://github.com/HKUDS/Vibe-Trading/pull/2119)
백테스트 신호가 다음 봉의 시가에 체결된다는 점을 명시하고 Swarm의 시간 초과 오판을 수정했으며 연구 자료 중복 검사 속도를 높였습니다. [#2137](https://github.com/HKUDS/Vibe-Trading/pull/2137) · [#2155](https://github.com/HKUDS/Vibe-Trading/pull/2155) · [#2159](https://github.com/HKUDS/Vibe-Trading/pull/2159)
diff --git a/README_zh.md b/README_zh.md
index 375313348..8719d9aaf 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -59,6 +59,7 @@
- **2026-11-05** 🚀 **v0.1.19 发布**([发布说明](https://github.com/HKUDS/Vibe-Trading/releases/tag/v0.1.19),`pip install -U vibe-trading-ai`):研究不再随对话结束而消失——带证据的研究记录可按版本保存并修订,之前轮次和会话中的回测可直接复用,研究目标可原地编辑。新增可选功能:A 股五分钟模拟交易,以及聚源综合问数、智能选股与香农持仓诊断(QVeris 已移除;仅有 `GILDATA_TOKEN` 不再开启任何功能)。另有阿根廷(BYMA)回测、Parallel 网页搜索、Codex OAuth 模型发现,并修复了 0.1.18 的两个回归问题。共 116 个合并的 PR,另有 21 个经维护者提交合入,来自 26 位贡献者([CHANGELOG](CHANGELOG.md))。
**今日修复:** 回测报告其实际评估的基准;多空组合也能生成风险透视(risk x-ray);GTJA alpha 17 在输入预热期间保持缺失;香农面板支持全部 11 种界面语言;另合入两项已审阅但尚未落地的贡献者修复([#2042](https://github.com/HKUDS/Vibe-Trading/pull/2042) TTM 求和不再跨越缺失季度,[#1985](https://github.com/HKUDS/Vibe-Trading/pull/1985) 3:2 拆股识别)。感谢 [@rudycelekli](https://github.com/rudycelekli), [@he-yufeng](https://github.com/he-yufeng), [@Jackzigen](https://github.com/Jackzigen), [@Shizoqua](https://github.com/Shizoqua), [@cgycorey](https://github.com/cgycorey), [@dajiaohuang](https://github.com/dajiaohuang), [@zeus229](https://github.com/zeus229), [@alexwan02](https://github.com/alexwan02), [@BHhhh-123](https://github.com/BHhhh-123), [@remote-controlled-man](https://github.com/remote-controlled-man), [@shadowinlife](https://github.com/shadowinlife), [@TWJxi](https://github.com/TWJxi), [@lishuanghong1989-netizen](https://github.com/lishuanghong1989-netizen), [@TerryF7](https://github.com/TerryF7), [@davidalmeida90](https://github.com/davidalmeida90), [@DrDLyuan](https://github.com/DrDLyuan), [@goatyyc](https://github.com/goatyyc), [@hnq-ai](https://github.com/hnq-ai), [@kadyrbekovhamit-cyber](https://github.com/kadyrbekovhamit-cyber), [@MetaAviator](https://github.com/MetaAviator), [@octo-patch](https://github.com/octo-patch), [@RowanAldean](https://github.com/RowanAldean), [@VectorPeak](https://github.com/VectorPeak), [@wavebyrd](https://github.com/wavebyrd) 和 [@yufengsika](https://github.com/yufengsika)!
+ **发版后已在 main 上修复(随下个 pip 版本发布):** 回测基准改为在评估期第一根 K 线的开盘价买入,与策略的成交方式一致,不再从热身期最后一根收盘价起算;超额收益不再包含这段涨跌(AAPL 20/60 均线例子:22.5% → 18.4%)。
- **2026-11-04** 📊 **聚源综合问数、智能选股与香农持仓诊断** — 可以一次查出市值前三的股票及其半年营收,也可以查看组合的十因子风格暴露和各持仓对波动的贡献。聚源九项功能默认全关,已有 Token 也需逐项开启。免费数据源查不到时不会自动转用聚源。 [#2117](https://github.com/HKUDS/Vibe-Trading/pull/2117) · [#2118](https://github.com/HKUDS/Vibe-Trading/pull/2118) · [#2119](https://github.com/HKUDS/Vibe-Trading/pull/2119)
同日明确了回测信号在下一根 K 线开盘成交的约定,修复了特殊换行符导致 Swarm 任务被误判为超时的问题,并加快了研究资料查重。 [#2137](https://github.com/HKUDS/Vibe-Trading/pull/2137) · [#2155](https://github.com/HKUDS/Vibe-Trading/pull/2155) · [#2159](https://github.com/HKUDS/Vibe-Trading/pull/2159)
diff --git a/agent/backtest/benchmark.py b/agent/backtest/benchmark.py
index 42797ced8..5d8aa26af 100644
--- a/agent/backtest/benchmark.py
+++ b/agent/backtest/benchmark.py
@@ -9,13 +9,14 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Optional
+import numpy as np
import pandas as pd
from backtest.engines._market_hooks import matched_market, strip_local_prefix
from backtest.loaders.base import resample_bars, source_interval
from backtest.loaders.registry import is_no_network_fallback_source
from backtest.loaders.yfinance_loader import DataLoader as YfinanceLoader
-from backtest.metrics import bar_returns, buy_and_hold_return
+from backtest.metrics import bar_returns, buy_and_hold_return, entry_returns
# -------------------------------------------------------------------
@@ -44,6 +45,7 @@ class BenchmarkResult:
ret_series: pd.Series # per-bar returns, index = timestamps
total_ret: float # total return over the FETCHED period
close: pd.Series # benchmark closes, index = timestamps
+ open: Optional[pd.Series] = None # benchmark opens, same index
def total_return_over(self, dates: pd.DatetimeIndex) -> Optional[float]:
"""Return the buy-and-hold return restricted to ``dates``.
@@ -54,9 +56,12 @@ class BenchmarkResult:
the short window against a benchmark measured over the long one is the
mismatched-window error the warm-up boundary exists to prevent (#1240).
- Computed as a price relative rather than the compounded product of
- ``ret_series``, which is the only form that stays honest once a price
- series contains a non-positive prior close (#872).
+ The position is bought at the open of the first benchmark bar inside
+ the window, the price the engine fills the strategy at (see
+ ``metrics.entry_returns``), or at that bar's close when it has no
+ usable open. Computed as a price relative rather than the compounded
+ product of ``ret_series``, which is the only form that stays honest
+ once a price series contains a non-positive prior close (#872).
Args:
dates: The evaluated bar index.
@@ -68,7 +73,31 @@ class BenchmarkResult:
window = self.close.reindex(dates).dropna()
if len(window) < 2:
return None
- return buy_and_hold_return(window)
+ entry = self._entry_open(window.index[0])
+ if entry is None:
+ return buy_and_hold_return(window)
+ last = float(window.iloc[-1])
+ return last / entry - 1.0 if np.isfinite(last) else None
+
+ def returns_over(self, dates: pd.DatetimeIndex) -> pd.Series:
+ """Per-bar returns of the same position on the evaluated bar index.
+
+ Args:
+ dates: The evaluated bar index.
+
+ Returns:
+ Returns on ``dates`` whose compounded total equals
+ :meth:`total_return_over` while prices are positive.
+ """
+ close = self.close.reindex(dates)
+ opens = self.open.reindex(dates) if self.open is not None else None
+ return entry_returns(close, opens, label=f"benchmark {self.ticker}")
+
+ def _entry_open(self, timestamp: Any) -> Optional[float]:
+ if self.open is None or timestamp not in self.open.index:
+ return None
+ value = float(self.open.loc[timestamp])
+ return value if np.isfinite(value) and value > 0 else None
def resolve_benchmark(
@@ -133,8 +162,9 @@ def resolve_benchmark(
if total is None:
return None
+ opens = bench_df["open"].reindex(close.index) if "open" in bench_df.columns else None
return BenchmarkResult(
- ticker=ticker, ret_series=ret_series, total_ret=total, close=close
+ ticker=ticker, ret_series=ret_series, total_ret=total, close=close, open=opens
)
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index 3b7e462b4..42ed58ccc 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -44,6 +44,7 @@ from backtest.metrics import (
by_symbol_stats,
calc_fill_turnover_series,
calc_metrics,
+ entry_returns,
period_returns,
)
from backtest.models import EquitySnapshot, FillRecord, Position, TradeRecord
@@ -367,6 +368,35 @@ def _align(
return dates, close, close_val, pos, ret
+def _basket_entry_returns(
+ close_df: pd.DataFrame, data_map: Dict[str, pd.DataFrame], codes: List[str],
+) -> pd.DataFrame:
+ """Per-symbol returns of the equal-weight basket over the evaluated bars.
+
+ Each symbol is bought at the open of its first traded bar in the window
+ (``metrics.entry_returns``) and marked on the same close matrix the
+ strategy is valued against.
+
+ Args:
+ close_df: Evaluated close matrix from ``_align``.
+ data_map: code -> raw OHLCV DataFrame.
+ codes: Basket symbols, columns of ``close_df``.
+
+ Returns:
+ DataFrame of per-bar returns shaped like ``close_df[codes]``.
+ """
+ columns = {}
+ for code in codes:
+ frame = data_map[code]
+ index = frame.index if frame.index.unit == "ns" else frame.index.as_unit("ns")
+ raw = frame.set_axis(index).reindex(close_df.index)
+ opens = raw["open"] if "open" in raw.columns else None
+ columns[code] = entry_returns(
+ close_df[code], opens, raw["close"].notna(), label=f"benchmark basket {code}",
+ )
+ return pd.DataFrame(columns, index=close_df.index)
+
+
def _load_optimizer(config: Dict[str, Any]) -> Optional[Callable]:
"""Dynamically load an optimizer function from config.
@@ -1027,7 +1057,11 @@ class BaseEngine(ABC):
[s.equity for s in self.equity_snapshots],
index=[s.timestamp for s in self.equity_snapshots],
)
- bench_ret = ret_df.mean(axis=1) if ret_df.shape[1] > 0 else pd.Series(0.0, index=dates)
+ # ret_df runs from each bar's previous close, so its first evaluated row
+ # starts at the last warm-up close. The basket instead buys each symbol
+ # at its first traded open in the window, as the strategy can.
+ basket_ret = _basket_entry_returns(close_df, data_map, list(ret_df.columns))
+ bench_ret = basket_ret.mean(axis=1) if basket_ret.shape[1] > 0 else pd.Series(0.0, index=dates)
from backtest.benchmark import default_benchmark, resolve_benchmark
basket_codes = list(ret_df.columns)
@@ -1048,7 +1082,7 @@ class BaseEngine(ABC):
)
window_return = result.total_return_over(dates) if result is not None else None
if result is not None and window_return is not None:
- bench_ret = bar_returns(result.close.reindex(dates), label=f"benchmark {result.ticker}")
+ bench_ret = result.returns_over(dates)
benchmark_metadata = {
"benchmark_kind": "external", "benchmark_label": result.ticker,
"benchmark_ticker": result.ticker, "benchmark_return": window_return,
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
index 81acba6ef..80e37928f 100644
--- a/agent/backtest/metrics.py
+++ b/agent/backtest/metrics.py
@@ -312,6 +312,49 @@ def bar_returns(close: Any, *, label: str = "") -> Any:
return ret.replace([np.inf, -np.inf], np.nan).fillna(0.0)
+def entry_returns(
+ close: pd.Series,
+ open_: Optional[pd.Series] = None,
+ traded: Optional[pd.Series] = None,
+ *,
+ label: str = "",
+) -> pd.Series:
+ """Per-bar returns of a position bought at the first traded bar's open.
+
+ A benchmark starts from cash at the same moment the strategy does, before
+ the first evaluated bar opens, and the earliest price it can buy at is that
+ bar's open -- the price the engine itself fills the strategy at. Grading it
+ from the previous close credits it with a move it could not have held
+ (with a warm-up boundary that close is a warm-up bar), and grading it from
+ the first close drops a move the strategy did hold.
+
+ Args:
+ close: Closes over the evaluated window; may carry a price through a
+ short gap.
+ open_: Opens on the same index. ``None``, NaN or a non-positive open
+ means the position is bought at that bar's close instead.
+ traded: Bars on which the instrument actually traded; defaults to
+ ``close.notna()``. The first of them is the entry bar.
+ label: Name for the non-positive-price warning in ``bar_returns``.
+
+ Returns:
+ Returns on ``close``'s index: 0.0 before the entry bar,
+ ``close / open - 1`` on it, then ``bar_returns`` from its close on.
+ """
+ ret = bar_returns(close, label=label)
+ traded = close.notna() if traded is None else traded.reindex(close.index).fillna(False).astype(bool)
+ if not traded.any():
+ return ret * 0.0
+ entry = int(np.argmax(traded.to_numpy()))
+ ret.iloc[:entry + 1] = 0.0
+ if open_ is not None:
+ entry_open = float(open_.reindex(close.index).iloc[entry])
+ entry_close = float(close.iloc[entry])
+ if np.isfinite(entry_open) and entry_open > 0 and np.isfinite(entry_close):
+ ret.iloc[entry] = entry_close / entry_open - 1.0
+ return ret
+
+
def buy_and_hold_return(close: Any) -> Optional[float]:
"""Total buy-and-hold return as a price relative, not a compounded product.
diff --git a/agent/src/skills/backtest-diagnose/SKILL.md b/agent/src/skills/backtest-diagnose/SKILL.md
index 35a75c868..abdbbc0e2 100644
--- a/agent/src/skills/backtest-diagnose/SKILL.md
+++ b/agent/src/skills/backtest-diagnose/SKILL.md
@@ -35,7 +35,7 @@ Use this skill when a user reports that a backtest failed, raised an error, or p
2. **Late trades** (first trade occurs more than 2 years after the backtest start): data-filtering bug. The lookback window may be too long, or the initial data segment may have been dropped. Shorten the window or check whether `dropna` is too aggressive.
3. **Capital utilization < 50%** (mostly in cash): position-sizing bug. Signal triggers may be too sparse, or the position-sizing logic may be wrong.
4. **Open position at the end** (a position still exists when the backtest ends): exit-timing bug. Forced liquidation may be missing, or exit logic does not cover the final segment.
-5. **Unexpected excess return**: check `benchmark_label` in the run metrics and the warnings in `run_card.json`. An omitted benchmark uses the evaluated symbols’ equal-weight returns. Set `"benchmark": "auto"` to request a market reference, or supply an explicit ticker. If no common default applies or the reference lacks usable data, the run records the equal-weight fallback.
+5. **Unexpected excess return**: check `benchmark_label` in the run metrics and the warnings in `run_card.json`. An omitted benchmark uses the evaluated symbols’ equal-weight returns. Set `"benchmark": "auto"` to request a market reference, or supply an explicit ticker. If no common default applies or the reference lacks usable data, the run records the equal-weight fallback. Either benchmark is bought at the open of the first evaluated bar (each basket symbol at its first traded open), the price the engine fills the strategy at, and held to the last close, so a fully invested strategy differs from buy-and-hold on that bar only by its costs.
### Data Errors
diff --git a/agent/tests/test_benchmark_warmup_basis.py b/agent/tests/test_benchmark_warmup_basis.py
new file mode 100644
index 000000000..b47236f90
--- /dev/null
+++ b/agent/tests/test_benchmark_warmup_basis.py
@@ -0,0 +1,149 @@
+"""A benchmark is bought at the window's first traded open, like the strategy.
+
+Both start from cash before the first evaluated bar opens, and the engine
+fills the strategy at a bar's open. The equal-weight basket used to run from
+the previous close: with a warm-up boundary that is a warm-up bar, a price no
+position could have been opened at. A declared external benchmark started at
+the first evaluated close instead, dropping the first bar's move the strategy
+did hold. On a 20/60 SMA run over AAPL.US the basket read 42.54% where
+buy-and-hold from the first open was 46.6%, so excess return was overstated.
+"""
+
+from __future__ import annotations
+
+import json
+
+import numpy as np
+import pandas as pd
+import pytest
+
+import backtest.runner as runner
+from backtest.benchmark import BenchmarkResult
+from backtest.metrics import entry_returns
+
+_DATES = pd.bdate_range("2026-01-05", periods=5)
+_STOCK_OPEN = [99.0, 108.0, 115.0, 128.0, 139.0]
+_STOCK_CLOSE = [100.0, 110.0, 120.0, 130.0, 140.0]
+_BENCH_OPEN = [190.0, 215.0, 230.0, 245.0, 290.0]
+_BENCH_CLOSE = [200.0, 220.0, 240.0, 250.0, 300.0]
+# Bars 0-1 are warm-up; the window opens at 115 / 230 and closes at 140 / 300.
+_EVALUATION_START = str(_DATES[2].date())
+
+
+def _bars(opens: list[float], closes: list[float], dates=_DATES) -> pd.DataFrame:
+ return pd.DataFrame(
+ {"open": opens, "high": closes, "low": opens, "close": closes, "volume": [1_000.0] * len(closes)},
+ index=dates,
+ ).rename_axis("date")
+
+
+def _run(tmp_path, monkeypatch, *, benchmark=None, warmup=True, frames=None, codes=("AAPL.US",)):
+ from backtest.loaders import local_loader
+
+ frames = frames or {
+ "AAPL.US": _bars(_STOCK_OPEN, _STOCK_CLOSE),
+ "SPY.US": _bars(_BENCH_OPEN, _BENCH_CLOSE),
+ }
+ sources = []
+ for symbol, frame in frames.items():
+ path = tmp_path / f"{symbol}.csv"
+ frame.to_csv(path)
+ sources.append({"symbol": symbol, "type": "csv", "path": str(path)})
+ bridge = tmp_path / "bridge.json"
+ bridge.write_text(json.dumps({"sources": sources}))
+ monkeypatch.setattr(local_loader, "_CONFIG_PATH", bridge)
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))
+ monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "0")
+
+ class _NoNetwork:
+ def fetch(self, *args, **kwargs):
+ return {}
+
+ monkeypatch.setattr("backtest.benchmark.YfinanceLoader", _NoNetwork)
+ run = tmp_path / "run"
+ (run / "code").mkdir(parents=True)
+ (run / "code/signal_engine.py").write_text(
+ "class SignalEngine:\n"
+ " def generate(self, data_map):\n"
+ " return {code: frame['close'] * 0 for code, frame in data_map.items()}\n"
+ )
+ config = {
+ "codes": list(codes), "source": "local", "initial_cash": 100_000,
+ "start_date": str(_DATES[0].date()), "end_date": str(_DATES[-1].date()),
+ }
+ if warmup:
+ config["evaluation_start_date"] = _EVALUATION_START
+ if benchmark:
+ config["benchmark"] = benchmark
+ (run / "config.json").write_text(json.dumps(config))
+ runner.main(run)
+ card = json.loads((run / "run_card.json").read_text())
+ equity = pd.read_csv(run / "artifacts" / "equity.csv")
+ return card["metrics"], equity
+
+
+def test_equal_weight_basket_buys_at_the_first_evaluated_open(tmp_path, monkeypatch):
+ metrics, equity = _run(tmp_path, monkeypatch)
+
+ assert metrics["benchmark_kind"] == "equal_weight"
+ # From the warm-up close it was 140 / 110 - 1, from the first close 140 / 120 - 1.
+ assert metrics["benchmark_return"] == pytest.approx(140 / 115 - 1, abs=1e-6)
+ assert equity["timestamp"].iloc[0] == _EVALUATION_START
+ assert equity["benchmark_equity"].iloc[0] == pytest.approx(100_000 * 120 / 115)
+ # The flat strategy earns nothing, so its excess is minus the benchmark.
+ assert metrics["excess_return"] == pytest.approx(-(140 / 115 - 1), abs=1e-6)
+
+
+def test_external_benchmark_buys_at_its_first_evaluated_open(tmp_path, monkeypatch):
+ metrics, equity = _run(tmp_path, monkeypatch, benchmark="SPY.US")
+
+ assert metrics["benchmark_kind"] == "external"
+ assert metrics["benchmark_return"] == pytest.approx(300 / 230 - 1, abs=1e-6)
+ assert equity["benchmark_equity"].iloc[0] == pytest.approx(100_000 * 240 / 230)
+ assert equity["benchmark_equity"].iloc[-1] == pytest.approx(100_000 * 300 / 230)
+
+
+def test_without_a_warm_up_boundary_the_basket_buys_at_the_first_open(tmp_path, monkeypatch):
+ metrics, equity = _run(tmp_path, monkeypatch, warmup=False)
+
+ assert metrics["benchmark_return"] == pytest.approx(140 / 99 - 1, abs=1e-6)
+ assert equity["benchmark_equity"].iloc[0] == pytest.approx(100_000 * 100 / 99)
+
+
+def test_a_symbol_halted_on_the_first_bar_enters_at_its_first_traded_open(tmp_path, monkeypatch):
+ halted_dates = _DATES.delete(2) # MSFT.US has no bar on the first evaluated day
+ frames = {
+ "AAPL.US": _bars(_STOCK_OPEN, _STOCK_CLOSE),
+ "MSFT.US": _bars([49.0, 50.0, 64.0, 70.0], [50.0, 55.0, 65.0, 72.0], dates=halted_dates),
+ }
+ metrics, equity = _run(tmp_path, monkeypatch, frames=frames, codes=("AAPL.US", "MSFT.US"))
+
+ aapl = [120 / 115 - 1, 130 / 120 - 1, 140 / 130 - 1]
+ # MSFT is not bought at its carried warm-up close (55) but at 64, its first open.
+ msft = [0.0, 65 / 64 - 1, 72 / 65 - 1]
+ expected = np.prod([1 + (a + m) / 2 for a, m in zip(aapl, msft)]) - 1
+ assert metrics["benchmark_return"] == pytest.approx(expected, abs=1e-6)
+
+
+def test_entry_falls_back_to_the_close_without_a_usable_open():
+ close = pd.Series([10.0, 11.0, 12.1], index=_DATES[:3])
+
+ for opens in (None, pd.Series([np.nan, 9.0, 9.0], index=_DATES[:3]), pd.Series([0.0, 9.0, 9.0], index=_DATES[:3])):
+ ret = entry_returns(close, opens)
+ assert ret.tolist() == pytest.approx([0.0, 0.1, 0.1])
+
+ assert entry_returns(pd.Series([np.nan, np.nan], index=_DATES[:2])).tolist() == [0.0, 0.0]
+
+
+def test_external_total_and_per_bar_returns_agree():
+ result = BenchmarkResult(
+ ticker="SPY.US", ret_series=pd.Series(dtype=float), total_ret=0.0,
+ close=pd.Series(_BENCH_CLOSE, index=_DATES), open=pd.Series(_BENCH_OPEN, index=_DATES),
+ )
+ window = _DATES[2:]
+
+ total = result.total_return_over(window)
+ per_bar = result.returns_over(window)
+
+ assert total == pytest.approx(300 / 230 - 1)
+ assert (1 + per_bar).prod() - 1 == pytest.approx(total)
diff --git a/guides/news.md b/guides/news.md
index 548c9c5ef..191425824 100644
--- a/guides/news.md
+++ b/guides/news.md
@@ -4,6 +4,7 @@
- **2026-11-05** 🚀 **v0.1.19 released** ([Release notes](https://github.com/HKUDS/Vibe-Trading/releases/tag/v0.1.19), `pip install -U vibe-trading-ai`): research that outlives the chat — save versioned research artifacts with their evidence and revise them, reuse backtests from earlier turns and sessions, and edit a research goal in place. New opt-ins: a five-minute A-share paper simulation, and Gildata financial queries, stock screening and Shannon portfolio diagnosis (QVeris is removed; an existing `GILDATA_TOKEN` alone now enables nothing). Also Argentina (BYMA) backtests, Parallel web search, Codex OAuth model discovery, and both 0.1.18 regressions fixed. 116 merged pull requests plus 21 landed through maintainer commits, from 26 contributors ([CHANGELOG](../CHANGELOG.md)).
**Fixed today:** a backtest reports the benchmark it actually evaluated, long/short books get a risk x-ray, GTJA alpha 17 stays missing while its inputs warm up, the Shannon panel speaks all eleven UI languages, and two reviewed contributor fixes that had not landed are in ([#2042](https://github.com/HKUDS/Vibe-Trading/pull/2042) TTM sums across a missing quarter, [#1985](https://github.com/HKUDS/Vibe-Trading/pull/1985) 3:2 split detection). Thanks [@rudycelekli](https://github.com/rudycelekli), [@he-yufeng](https://github.com/he-yufeng), [@Jackzigen](https://github.com/Jackzigen), [@Shizoqua](https://github.com/Shizoqua), [@cgycorey](https://github.com/cgycorey), [@dajiaohuang](https://github.com/dajiaohuang), [@zeus229](https://github.com/zeus229), [@alexwan02](https://github.com/alexwan02), [@BHhhh-123](https://github.com/BHhhh-123), [@remote-controlled-man](https://github.com/remote-controlled-man), [@shadowinlife](https://github.com/shadowinlife), [@TWJxi](https://github.com/TWJxi), [@lishuanghong1989-netizen](https://github.com/lishuanghong1989-netizen), [@TerryF7](https://github.com/TerryF7), [@davidalmeida90](https://github.com/davidalmeida90), [@DrDLyuan](https://github.com/DrDLyuan), [@goatyyc](https://github.com/goatyyc), [@hnq-ai](https://github.com/hnq-ai), [@kadyrbekovhamit-cyber](https://github.com/kadyrbekovhamit-cyber), [@MetaAviator](https://github.com/MetaAviator), [@octo-patch](https://github.com/octo-patch), [@RowanAldean](https://github.com/RowanAldean), [@VectorPeak](https://github.com/VectorPeak), [@wavebyrd](https://github.com/wavebyrd) and [@yufengsika](https://github.com/yufengsika)!
+ **On main after the release (next pip release):** backtest benchmarks are bought at the first evaluated open, as the strategy is, instead of from the last warm-up close; excess return no longer includes that move (AAPL 20/60 SMA example: 22.5% → 18.4%).
- **2026-11-04** 📊 **Gildata financial queries, stock screening and Shannon portfolio diagnosis** — Screen stocks by market cap and retrieve their half-year revenue in one request, or inspect portfolio factor exposures and each holding’s contribution to volatility. All nine Gildata features are opt-in, including for existing token holders. Free data sources never fall back to Gildata. [#2117](https://github.com/HKUDS/Vibe-Trading/pull/2117) · [#2118](https://github.com/HKUDS/Vibe-Trading/pull/2118) · [#2119](https://github.com/HKUDS/Vibe-Trading/pull/2119)
Also clarified next-bar backtest fills, fixed false Swarm timeouts on Unicode heartbeats and sped up research artifact deduplication. [#2137](https://github.com/HKUDS/Vibe-Trading/pull/2137) · [#2155](https://github.com/HKUDS/Vibe-Trading/pull/2155) · [#2159](https://github.com/HKUDS/Vibe-Trading/pull/2159)