Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(backtest): add ArgentinaEquity engine for BYMA shares and CEDEARs

zeus229fe61c62d91a8
diff --git a/README.md b/README.md
index 9cdabb9d3..f998b36af 100644
--- a/README.md
+++ b/README.md
@@ -843,7 +843,7 @@ Run `vibe-trading alpha list` to browse, `vibe-trading alpha show <id>` for form
</details>
<details>
-<summary><b>Backtest Engines</b> <sub>11 engines + options portfolio, cross-market composite</sub></summary>
+<summary><b>Backtest Engines</b> <sub>12 engines + options portfolio, cross-market composite</sub></summary>
| Engine | Market | Notes |
|--------|--------|-------|
@@ -853,6 +853,7 @@ Run `vibe-trading alpha list` to browse, `vibe-trading alpha show <id>` for form
| **KoreaEquity** | Korea (KRX: KOSPI/KOSDAQ) | long-only, ±30% band judged at execution time on the unified tick grid, 2026 0.20% transaction tax |
| **VietnamEquity** | Vietnam (HOSE) | long-only, T+2 settlement hold, ±7% band on the 10/50/100-VND tick grid, 100-share lots, 0.1% sell-side tax |
| **BrazilEquity** | Brazil (B3) | BRL, B3 trading + settlement fees, configurable broker fee, 1- or 100-share lots, R$0.01 tick, shorting allowed |
+| **ArgentinaEquity** | Argentina (BYMA) | ARS, long-only, T+2 → T+1 (2024-05-27) counted on observed sessions, same-session sale netting, CEDEAR ratio changes reconciled from declared history, BYMA tick bands |
| **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |
| **ChinaFutures** · **GlobalFutures** | futures | margin, contract multipliers |
| **Forex** | FX / metals | via the `mt5` loader (local terminal) or the hosted `tickerall` loader (no terminal, any OS) |
@@ -2339,7 +2340,7 @@ Vibe-Trading/
│ │ └── providers/ # LLM provider abstraction
│ │
│ └── backtest/ # Backtest engines
-│ ├── engines/ # 10 engines + composite cross-market engine + options_portfolio
+│ ├── engines/ # 11 engines + composite cross-market engine + options_portfolio
│ ├── loaders/ # 29 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, qveris, india_broker, tickerall, gildata, b3_cotahist
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + auto-fallback chains
diff --git a/README_ar.md b/README_ar.md
index f47b08f3a..4ae4c01de 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -717,7 +717,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
</details>
<details>
-<summary><b>محرّكات الاختبار الرجعي</b> <sub>11 محرّكات + محفظة خيارات، ومركّب عبر الأسواق</sub></summary>
+<summary><b>محرّكات الاختبار الرجعي</b> <sub>12 محرّكات + محفظة خيارات، ومركّب عبر الأسواق</sub></summary>
| المحرّك | السوق | ملاحظات |
|--------|-------|---------|
@@ -727,6 +727,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
| **KoreaEquity** | كوريا (KRX: KOSPI/KOSDAQ) | شراء فقط، ونطاق ±30% يُحكم عليه لحظة التنفيذ على شبكة الخطوة السعرية الموحّدة، وضريبة تداول 0.20% لعام 2026 |
| **VietnamEquity** | فيتنام (HOSE) | شراء فقط، واحتجاز تسوية T+2، ونطاق ±7% على شبكة الخطوة السعرية 10/50/100 دونغ، ولوت 100 سهم، وضريبة 0.1% على البيع |
| **BrazilEquity** | Brazil (B3) | BRL, B3 trading + settlement fees, configurable broker fee, 1- or 100-share lots, R$0.01 tick, shorting allowed |
+| **ArgentinaEquity** | Argentina (BYMA) | ARS, long-only, T+2 → T+1 (2024-05-27) counted on observed sessions, same-session sale netting, CEDEAR ratio changes reconciled from declared history, BYMA tick bands |
| **Crypto** | crypto فوري / عقود USD-M الدائمة | تسويات التمويل، وفصل سعر التنفيذ عن سعر العلامة |
| **ChinaFutures** · **GlobalFutures** | العقود الآجلة | الهامش، ومضاعِفات العقد |
| **Forex** | FX / المعادن | عبر مُحمّل `mt5` |
@@ -1776,7 +1777,7 @@ Vibe-Trading/
│ │ └── providers/ # LLM provider abstraction
│ │
│ └── backtest/ # Backtest engines
-│ ├── engines/ # 10 engines + composite cross-market engine + options_portfolio
+│ ├── engines/ # 11 engines + composite cross-market engine + options_portfolio
│ ├── loaders/ # 29 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, qveris, india_broker, tickerall, gildata, b3_cotahist
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + auto-fallback chains
diff --git a/README_es.md b/README_es.md
index 1c34b35fc..b221390bb 100644
--- a/README_es.md
+++ b/README_es.md
@@ -723,7 +723,7 @@ Ejecuta `vibe-trading alpha list` para explorar, `vibe-trading alpha show <id>`
</details>
<details>
-<summary><b>Motores de Backtest</b> <sub>11 motores + cartera de opciones, composite cross-market</sub></summary>
+<summary><b>Motores de Backtest</b> <sub>12 motores + cartera de opciones, composite cross-market</sub></summary>
| Motor | Mercado | Notas |
|--------|--------|-------|
@@ -732,6 +732,7 @@ Ejecuta `vibe-trading alpha list` para explorar, `vibe-trading alpha show <id>`
| **IndiaEquity** | India (NSE/BSE) | T+1, bandas de circuito, pila de costos STT / stamp / SEBI / GST basada en configuración |
| **KoreaEquity** | Corea (KRX: KOSPI/KOSDAQ) | solo largo, banda de ±30% evaluada en el momento de ejecución sobre la malla de ticks unificada, impuesto de transacción del 0.20% en 2026 |
| **BrazilEquity** | Brazil (B3) | BRL, B3 trading + settlement fees, configurable broker fee, 1- or 100-share lots, R$0.01 tick, shorting allowed |
+| **ArgentinaEquity** | Argentina (BYMA) | ARS, long-only, T+2 → T+1 (2024-05-27) counted on observed sessions, same-session sale netting, CEDEAR ratio changes reconciled from declared history, BYMA tick bands |
| **Crypto** | spot cripto / perps USD-M | liquidaciones de funding, división ejecución/mark |
| **ChinaFutures** · **GlobalFutures** | futuros | margen, multiplicadores de contrato |
| **Forex** | FX / metales | vía el loader `mt5` |
@@ -1864,7 +1865,7 @@ Vibe-Trading/
│ │ └── providers/ # Abstracción de proveedores LLM
│ │
│ └── backtest/ # Motores de backtest
-│ ├── engines/ # 10 motores + motor compuesto multi-mercado + options_portfolio
+│ ├── engines/ # 11 motores + motor compuesto multi-mercado + options_portfolio
│ ├── loaders/ # 29 fuentes: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, qveris, india_broker, tickerall, gildata, b3_cotahist
│ │ ├── base.py # Protocolo DataLoader
│ │ └── registry.py # Registro + cadenas de fallback automáticas
diff --git a/README_id.md b/README_id.md
index 641511aa9..98db1abf6 100644
--- a/README_id.md
+++ b/README_id.md
@@ -883,7 +883,7 @@ Jalankan `vibe-trading alpha list` untuk menjelajah, `vibe-trading alpha show <i
</details>
<details>
-<summary><b>Engine Backtest</b> <sub>11 engine + portofolio opsi, komposit lintas market</sub></summary>
+<summary><b>Engine Backtest</b> <sub>12 engine + portofolio opsi, komposit lintas market</sub></summary>
| Engine | Market | Catatan |
|--------|--------|-------|
@@ -893,6 +893,7 @@ Jalankan `vibe-trading alpha list` untuk menjelajah, `vibe-trading alpha show <i
| **KoreaEquity** | Korea (KRX: KOSPI/KOSDAQ) | long-only, ±30% band judged at execution time on the unified tick grid, 2026 0.20% transaction tax |
| **VietnamEquity** | Vietnam (HOSE) | long-only, T+2 settlement hold, ±7% band on the 10/50/100-VND tick grid, 100-share lots, 0.1% sell-side tax |
| **BrazilEquity** | Brazil (B3) | BRL, B3 trading + settlement fees, configurable broker fee, 1- or 100-share lots, R$0.01 tick, shorting allowed |
+| **ArgentinaEquity** | Argentina (BYMA) | ARS, long-only, T+2 → T+1 (2024-05-27) counted on observed sessions, same-session sale netting, CEDEAR ratio changes reconciled from declared history, BYMA tick bands |
| **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |
| **ChinaFutures** · **GlobalFutures** | futures | margin, contract multipliers |
| **Forex** | FX / metals | via the `mt5` loader (local terminal) or the hosted `tickerall` loader (no terminal, any OS) |
@@ -2109,7 +2110,7 @@ Vibe-Trading/
│ │ └── providers/ # LLM provider abstraction
│ │
│ └── backtest/ # Backtest engines
-│ ├── engines/ # 10 engines + composite cross-market engine + options_portfolio
+│ ├── engines/ # 11 engines + composite cross-market engine + options_portfolio
│ ├── loaders/ # 29 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, qveris, india_broker, tickerall, gildata, b3_cotahist
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + auto-fallback chains
diff --git a/README_ja.md b/README_ja.md
index f84a7f9c2..8698f2194 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -717,7 +717,7 @@ Paper-vs-live is a **structural per-broker runtime guard** (account-id format, h
</details>
<details>
-<summary><b>Backtest Engines</b> <sub>11 engines + options portfolio, cross-market composite</sub></summary>
+<summary><b>Backtest Engines</b> <sub>12 engines + options portfolio, cross-market composite</sub></summary>
| Engine | Market | Notes |
|--------|--------|-------|
@@ -727,6 +727,7 @@ Paper-vs-live is a **structural per-broker runtime guard** (account-id format, h
| **KoreaEquity** | 韓国(KRX:KOSPI/KOSDAQ) | ロングオンリー、統一呼値グリッド上で ±30% 制限値幅を約定時点に判定、2026 年 0.20% の証券取引税 |
| **VietnamEquity** | ベトナム(HOSE) | ロングオンリー、T+2 決済ホールド、10/50/100 ドンの呼値グリッド上で ±7% 制限値幅、100 株単元、売却側 0.1% 課税 |
| **BrazilEquity** | Brazil (B3) | BRL, B3 trading + settlement fees, configurable broker fee, 1- or 100-share lots, R$0.01 tick, shorting allowed |
+| **ArgentinaEquity** | Argentina (BYMA) | ARS, long-only, T+2 → T+1 (2024-05-27) counted on observed sessions, same-session sale netting, CEDEAR ratio changes reconciled from declared history, BYMA tick bands |
| **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |
| **ChinaFutures** · **GlobalFutures** | futures | margin, contract multipliers |
| **Forex** | FX / metals | via the `mt5` loader |
@@ -1784,7 +1785,7 @@ Vibe-Trading/
│ │ └── providers/ # LLM プロバイダー抽象化
│ │
│ └── backtest/ # バックテストエンジン
-│ ├── engines/ # 10 エンジン + クロスマーケット composite engine + options_portfolio
+│ ├── engines/ # 11 エンジン + クロスマーケット composite engine + options_portfolio
│ ├── loaders/ # 29 ソース: tushare、okx、nobitex、wallex、binance、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、pykrx、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp、longbridge、mt5、qveris、india_broker、tickerall、gildata, b3_cotahist
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + 自動フォールバックチェーン
diff --git a/README_ko.md b/README_ko.md
index d97cc479a..a11693939 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -717,7 +717,7 @@ Paper-vs-live는 **구조적 브로커별 런타임 가드**(account-id 형식,
</details>
<details>
-<summary><b>백테스트 엔진</b> <sub>11개 엔진 + 옵션 포트폴리오, 크로스마켓 composite</sub></summary>
+<summary><b>백테스트 엔진</b> <sub>12개 엔진 + 옵션 포트폴리오, 크로스마켓 composite</sub></summary>
| Engine | Market | Notes |
|--------|--------|-------|
@@ -727,6 +727,7 @@ Paper-vs-live는 **구조적 브로커별 런타임 가드**(account-id 형식,
| **KoreaEquity** | 한국 (KRX: KOSPI/KOSDAQ) | 롱 온리, 통합 호가 단위에서 ±30% 가격제한폭을 체결 시점에 판정, 2026년 0.20% 증권거래세 |
| **VietnamEquity** | 베트남 (HOSE) | 롱 온리, T+2 결제 보유, 10/50/100 VND 호가 단위에서 ±7% 가격제한폭, 100주 단위, 매도측 0.1% 세금 |
| **BrazilEquity** | Brazil (B3) | BRL, B3 trading + settlement fees, configurable broker fee, 1- or 100-share lots, R$0.01 tick, shorting allowed |
+| **ArgentinaEquity** | Argentina (BYMA) | ARS, long-only, T+2 → T+1 (2024-05-27) counted on observed sessions, same-session sale netting, CEDEAR ratio changes reconciled from declared history, BYMA tick bands |
| **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |
| **ChinaFutures** · **GlobalFutures** | futures | margin, contract multipliers |
| **Forex** | FX / metals | via the `mt5` loader |
@@ -1781,7 +1782,7 @@ Vibe-Trading/
│ │ └── providers/ # LLM provider abstraction
│ │
│ └── backtest/ # Backtest engines
-│ ├── engines/ # 10 engines + composite cross-market engine + options_portfolio
+│ ├── engines/ # 11 engines + composite cross-market engine + options_portfolio
│ ├── loaders/ # 29 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, qveris, india_broker, tickerall, gildata, b3_cotahist
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + auto-fallback chains
diff --git a/README_zh.md b/README_zh.md
index d9e3861f5..35872cc6a 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -730,7 +730,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
</details>
<details>
-<summary><b>Backtest Engines</b> <sub>11 个引擎 + options portfolio,跨市场 composite</sub></summary>
+<summary><b>Backtest Engines</b> <sub>12 个引擎 + options portfolio,跨市场 composite</sub></summary>
| 引擎 | 市场 | 说明 |
|------|------|------|
@@ -740,6 +740,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
| **KoreaEquity** | 韩国(KRX:KOSPI/KOSDAQ) | 只做多,统一最小价位网格上于成交时刻判定 ±30% 涨跌停,2026 年 0.20% 证券交易税 |
| **VietnamEquity** | 越南(HOSE) | 只做多,T+2 交收锁定,10/50/100 越南盾最小价位网格上 ±7% 涨跌停,100 股整手,0.1% 卖出方税 |
| **BrazilEquity** | Brazil (B3) | BRL, B3 trading + settlement fees, configurable broker fee, 1- or 100-share lots, R$0.01 tick, shorting allowed |
+| **ArgentinaEquity** | Argentina (BYMA) | ARS, long-only, T+2 → T+1 (2024-05-27) counted on observed sessions, same-session sale netting, CEDEAR ratio changes reconciled from declared history, BYMA tick bands |
| **Crypto** | 加密现货 / USD-M 永续 | 资金费结算、成交价/标记价分离 |
| **ChinaFutures** · **GlobalFutures** | 期货 | 保证金、合约乘数 |
| **Forex** | 外汇 / 贵金属 | 经 `mt5` loader |
@@ -1779,7 +1780,7 @@ Vibe-Trading/
│ │ └── providers/ # LLM provider 抽象层
│ │
│ └── backtest/ # 回测引擎
-│ ├── engines/ # 10 个引擎 + 跨市场 composite 引擎 + options_portfolio
+│ ├── engines/ # 11 个引擎 + 跨市场 composite 引擎 + options_portfolio
│ ├── loaders/ # 29 个数据源:tushare、okx、nobitex、wallex、binance、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、pykrx、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp、longbridge、mt5、qveris、india_broker、tickerall、gildata, b3_cotahist
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + 自动 fallback 链路
diff --git a/agent/backtest/engines/argentina_equity.py b/agent/backtest/engines/argentina_equity.py
new file mode 100644
index 000000000..c9920f54d
--- /dev/null
+++ b/agent/backtest/engines/argentina_equity.py
@@ -0,0 +1,695 @@
+"""Argentina equity (BYMA) backtest engine: local shares and CEDEARs (``.BA``).
+
+Market rules modelled:
+ - Long only, no leverage. One ARS cash pool (USD ``D`` lines are rejected by
+ the loaders' ARS contract).
+ - Yahoo emits flat zero-volume bars on exchange holidays; a date on which no
+ loaded instrument traded is dropped, and a zero-volume bar is never a fill.
+ - Normal settlement ("contado normal") is T+2 for trades before 2024-05-27
+ and T+1 from that date. It is counted in **observed trading sessions**: the
+ bars of the run on which at least one loaded instrument traded. Days with
+ no trades in the loaded data (holidays) never count. This approximates the
+ official calendar; settlement dates are not official dates, and a
+ settlement that falls after the last loaded bar is reported as
+ ``beyond_loaded_data`` rather than guessed.
+ - A sale funds a purchase settling on the same or a later session (a same-bar
+ sale always does: BaseEngine's default netting); proceeds that settle
+ later are not available, so money is never used twice.
+ - Shares bought are not sold before their settlement session (the whole
+ position waits for its newest lot, as for HOSE); the end-of-backtest close
+ obeys the same rule and keeps an unsettled position open, valued.
+ - CEDEAR ratio changes are not adjusted by Yahoo (AAPL.BA halves on
+ 2024-01-24, ratio 10:1 -> 20:1, while the holder's position doubles). Each
+ declared change inside the window is checked against the observed price
+ step and earlier bars are restated in post-change units, exactly as a
+ split adjustment would; an ambiguous step, or a large one-bar move with no
+ declared change, fails closed; before the change one real certificate is ``new/old``
+ units, which sets the lot and the tick. A position held through the
+ ex-date is sold only by a trade whose earliest possible settlement (counted
+ on weekdays) reaches the declared ``credit_date`` of the extra certificates.
+ - Ticks: BYMA Circular 3569 price bands (rounded against the trader). Lots:
+ one share unless declared (an assumption; the circular sets no number).
+
+Costs are simulation inputs, never official tariffs: ``ar_brokerage_rate``
+(defaults to the generic ``commission``), ``ar_exchange_fee_rate``,
+``ar_fixed_fee`` per order and ``ar_slippage`` (all default 0).
+
+Config ``ar_instruments`` (optional) declares metadata per symbol::
+
+ {"YPFD.BA": {"kind": "share"},
+ "AAPL.BA": {"kind": "cedear", "underlying": "AAPL",
+ "ratio_history": [{"effective_date": "2010-06-24", "ratio": "10"},
+ {"effective_date": "2024-01-24", "ratio": "20",
+ "credit_date": "2024-01-26"}]}}
+
+Local shares need no entry (their kind comes from Yahoo's descriptor);
+CEDEARs must be declared. Every resolved value is labelled in the
+``ar_data_basis`` metric and ``artifacts/byma_preparation.json``.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+from datetime import date, datetime, timedelta
+from decimal import ROUND_CEILING, ROUND_FLOOR, Decimal
+from pathlib import Path
+from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Tuple
+
+import pandas as pd
+
+from backtest.engines.base import BaseEngine
+
+# ── price basis and instrument metadata ──
+
+PRICE_COLUMNS = ("open", "high", "low", "close")
+
+# One-bar moves larger than these, with no declared ratio change, are treated as
+# unit discontinuities rather than market moves. Shares get a wider band: BYMA
+# sessions have moved ~47% (2019-08-12) while an unadjusted 4:1 split moves 75%.
+DEFAULT_MAX_CEDEAR_MOVE = 0.4
+DEFAULT_MAX_SHARE_MOVE = 0.75
+# How far an observed ratio step may sit from the expected factor.
+DEFAULT_RATIO_TOLERANCE = 0.2
+
+# BYMA Circular 3569, "Reglas de Negocio en el Segmento PPT Operaciones de
+# Contado", annex version 2024-07-04: minimum price change for equities
+# (CEDEARs included) by price band.
+TICK_SOURCE = "BYMA Circular 3569 annex v2024-07-04"
+_TICK_BANDS: Tuple[Tuple[Decimal, Decimal], ...] = (
+ (Decimal("1"), Decimal("0.001")),
+ (Decimal("5"), Decimal("0.005")),
+ (Decimal("10"), Decimal("0.01")),
+ (Decimal("50"), Decimal("0.05")),
+ (Decimal("100"), Decimal("0.10")),
+ (Decimal("250"), Decimal("0.25")),
+ (Decimal("500"), Decimal("0.50")),
+ (Decimal("1000"), Decimal("1.00")),
+ (Decimal("5000"), Decimal("5.00")),
+ (Decimal("10000"), Decimal("10.00")),
+ (Decimal("50000"), Decimal("25.00")),
+)
+_TICK_ABOVE = Decimal("50.00")
+
+# Yahoo truncates shortName at 31 characters, which can cut a "CEDEAR" marker.
+_SHORT_NAME_LIMIT = 31
+_CEDEAR_MARKER = re.compile(r"\bCEDEARS?\b", re.I)
+_TRUNCATED_MARKER = re.compile(r"\bC(E(D(E(A(R)?)?)?)?)?$", re.I)
+
+
+def equity_tick(price: Decimal) -> Decimal:
+ """Minimum price change of a BYMA equity quoted at *price*."""
+ for upper, tick in _TICK_BANDS:
+ if price <= upper:
+ return tick
+ return _TICK_ABOVE
+
+
+def classify_short_name(short_name: Optional[str]) -> Tuple[Optional[str], str]:
+ """``("share" | "cedear" | None, evidence)`` from Yahoo's shortName."""
+ name = (short_name or "").strip()
+ if not name:
+ return None, "no Yahoo descriptor"
+ if _CEDEAR_MARKER.search(name):
+ return "cedear", f"Yahoo shortName {name!r} names a CEDEAR"
+ if len(name) >= _SHORT_NAME_LIMIT or _TRUNCATED_MARKER.search(name):
+ return None, f"Yahoo shortName {name!r} may be truncated"
+ return "share", f"Yahoo shortName {name!r} has no CEDEAR marker"
+
+
+def yahoo_short_name(symbol: str) -> Optional[str]:
+ """Yahoo's shortName through the existing quote-summary client, or None."""
+ from backtest.loaders import yahoo_client
+
+ try:
+ summary = yahoo_client.get_quote_summary(symbol, ["quoteType"])
+ except Exception: # noqa: BLE001 - an unreachable descriptor is "unknown"
+ return None
+ quote = summary.get("quoteType") if isinstance(summary, dict) else None
+ name = quote.get("shortName") if isinstance(quote, dict) else None
+ return name if isinstance(name, str) else None
+
+
+def resolve_instrument(
+ symbol: str,
+ declared: Optional[Mapping[str, Any]],
+ describe: Callable[[str], Optional[str]],
+) -> Tuple[dict, Dict[str, str], List[str]]:
+ """Complete one instrument: ``(metadata, provenance, problems)``.
+
+ Declared fields win. A missing ``kind`` is taken from Yahoo only when it
+ names a local share; a CEDEAR needs its declared ratio history.
+ """
+ info = dict(declared or {})
+ provenance = {key: "declared" for key in info}
+ problems: List[str] = []
+ if "kind" not in info:
+ kind, evidence = classify_short_name(describe(symbol))
+ if kind == "share":
+ info["kind"] = "share"
+ provenance["kind"] = f"vendor ({evidence})"
+ elif kind == "cedear":
+ problems.append(
+ f"{symbol}: {evidence}; declare ar_instruments.{symbol} with "
+ "kind='cedear', underlying and ratio_history [{effective_date, ratio, "
+ "credit_date for changes inside the backtest}]"
+ )
+ else:
+ problems.append(f"{symbol}: {evidence}; declare ar_instruments.{symbol}.kind "
+ "as 'share' or 'cedear'")
+ info.setdefault("lot_size", 1)
+ provenance.setdefault("lot_size", "assumption (one share per order)")
+ provenance.setdefault("tick_size", TICK_SOURCE if info.get("tick_size") is None else "declared")
+ provenance["currency"] = "ARS (.BA pool, checked against the loader's declared currency)"
+ return info, provenance, problems
+
+
+def validate_frame(frame: pd.DataFrame, symbol: str) -> None:
+ """Require OHLCV columns and an ARS quote the loader declared."""
+ missing = [c for c in (*PRICE_COLUMNS, "volume") if c not in frame.columns]
+ if missing:
+ raise ValueError(f"{symbol}: BYMA bars need columns {missing}")
+ declared = frame.attrs.get("quote_currency")
+ if declared != "ARS":
+ raise ValueError(
+ f"{symbol}: BYMA backtests book in ARS but the source declared "
+ f"{declared or 'no quote currency'}"
+ )
+ if not isinstance(frame.index, pd.DatetimeIndex) or frame.index.has_duplicates:
+ raise ValueError(f"{symbol}: BYMA bars need a unique DatetimeIndex")
+
+
+def traded_dates(frames: Iterable[pd.DataFrame]) -> set:
+ """Dates on which at least one loaded instrument traded (volume > 0)."""
+ dates: set = set()
+ for frame in frames:
+ volume = pd.to_numeric(frame["volume"], errors="coerce")
+ dates.update(ts.normalize() for ts, v in volume.items() if v > 0)
+ return dates
+
+
+def _traded(frame: pd.DataFrame) -> pd.DataFrame:
+ return frame[pd.to_numeric(frame["volume"], errors="coerce") > 0]
+
+
+def _near(observed: float, target: float, tolerance: float) -> bool:
+ return abs(math.log(observed / target)) <= math.log1p(tolerance)
+
+
+def reconcile_ratio_changes(
+ frame: pd.DataFrame,
+ symbol: str,
+ ratio_history: Iterable[Mapping[str, Any]],
+ *,
+ tolerance: float = DEFAULT_RATIO_TOLERANCE,
+) -> Tuple[pd.DataFrame, List[dict]]:
+ """Put every in-window CEDEAR ratio change on one adjusted unit basis.
+
+ A change from ``old`` to ``new`` CEDEARs per underlying share moves an
+ unadjusted series by ``old/new`` across the effective date and an adjusted
+ one by ~1. The close-to-close move between the last traded bar before and
+ the first traded bar on/after the date must match exactly one of them
+ (and the entry's optional ``price_series`` declaration). Unadjusted
+ evidence rescales earlier OHLC by ``old/new`` and volume by the inverse.
+ """
+ entries = list(ratio_history)
+ events: List[dict] = []
+ if frame.empty or len(entries) < 2:
+ return frame, events
+ first, last = frame.index[0].date(), frame.index[-1].date()
+ adjusted = frame.copy()
+ traded = _traded(frame)
+ for previous, entry in zip(entries, entries[1:]):
+ effective = date.fromisoformat(str(entry["effective_date"]))
+ if not first < effective <= last:
+ continue
+ old, new = float(previous["ratio"]), float(entry["ratio"])
+ factor = old / new
+ before = traded[traded.index.date < effective]
+ after = traded[traded.index.date >= effective]
+ if before.empty or after.empty:
+ raise ValueError(f"{symbol}: ratio change on {effective} cannot be verified; "
+ "no traded bar on both sides of it")
+ observed = float(after["close"].iloc[0]) / float(before["close"].iloc[-1])
+ unadjusted, already = _near(observed, factor, tolerance), _near(observed, 1.0, tolerance)
+ declared = entry.get("price_series")
+ if declared == "unadjusted":
+ ok = unadjusted and not already
+ elif declared == "adjusted":
+ ok = already and not unadjusted
+ else:
+ ok = unadjusted != already
+ if not ok:
+ raise ValueError(
+ f"{symbol}: ratio change {old:g}->{new:g} on {effective} is not provable "
+ f"from prices (observed move x{observed:.3f}; unadjusted would be "
+ f"x{factor:.3f}, adjusted ~x1)"
+ )
+ if unadjusted:
+ earlier = adjusted.index.date < effective
+ for column in PRICE_COLUMNS:
+ adjusted.loc[earlier, column] = adjusted.loc[earlier, column] * factor
+ adjusted.loc[earlier, "volume"] = adjusted.loc[earlier, "volume"] / factor
+ events.append({
+ "symbol": symbol, "effective_date": str(effective),
+ "credit_date": str(entry["credit_date"]) if entry.get("credit_date") else None,
+ "old_ratio": old, "new_ratio": new, "observed_move": round(observed, 6),
+ "rescaled_prior_bars": unadjusted,
+ })
+ return adjusted, events
+
+
+def discontinuities(frame: pd.DataFrame, max_move: float) -> List[str]:
+ """Dates where consecutive traded closes move by more than *max_move*."""
+ closes = _traded(frame)["close"].astype(float)
+ if len(closes) < 2:
+ return []
+ moves = closes / closes.shift(1)
+ limit = math.log(1.0 / (1.0 - max_move))
+ return [str(ts.date()) for ts, move in moves.iloc[1:].items() if abs(math.log(move)) > limit]
+
+
+# ── settlement ──
+
+#: First trade date of T+1 normal settlement on BYMA (T+2 before).
+T1_FROM = date(2024, 5, 27)
+_OPENING = ("open", "increase")
+_SALES = ("reduce", "close")
+
+
+def normal_cash_lag(trade_date: date) -> int:
+ """Settlement lag in sessions for a normal-cash trade on *trade_date*."""
+ return 1 if trade_date >= T1_FROM else 2
+
+
+def _day(value: Any) -> Optional[date]:
+ if type(value) is date:
+ return value
+ if isinstance(value, (datetime, pd.Timestamp)) and not pd.isna(value):
+ return value.date()
+ return None
+
+
+def _add_weekdays(day: date, count: int) -> date:
+ while count > 0:
+ day += timedelta(days=1)
+ if day.weekday() < 5:
+ count -= 1
+ return day
+
+
+def _settlement_bar(fill: Any) -> int:
+ return int(fill.bar_idx) + normal_cash_lag(_day(fill.timestamp))
+
+
+def _net_proceeds(fill: Any) -> float:
+ return abs(float(fill.signed_quantity)) * float(fill.execution_price) - float(fill.fee)
+
+
+class ArgentinaEquityEngine(BaseEngine):
+ """BYMA cash-equity engine (shares and CEDEARs); see the module docstring."""
+
+ def __init__(self, config: dict):
+ config = {**config, "leverage": 1.0} # cash equity: no leverage
+ super().__init__(config)
+ if config.get("allow_short"):
+ raise ValueError("ArgentinaEquityEngine is long-only; remove 'allow_short'.")
+ declared = config.get("ar_instruments") or {}
+ if not isinstance(declared, dict):
+ raise ValueError("ar_instruments must be an object keyed by .BA symbol")
+ problems: List[str] = []
+ self._declared: Dict[str, dict] = {}
+ for symbol, info in declared.items():
+ if not isinstance(info, dict):
+ problems.append(f"{symbol}: metadata must be an object")
+ continue
+ problems.extend(_field_problems(symbol, info))
+ self._declared[symbol.upper()] = dict(info)
+ if problems:
+ raise ValueError(_config_error(problems))
+ self.instruments: Dict[str, dict] = {}
+ self.provenance: Dict[str, dict] = {}
+ self.ratio_adjustments: List[dict] = []
+ self.dropped_no_trade_dates: List[str] = []
+ self.slippage_rate = _rate(config.get("ar_slippage", 0.0), "ar_slippage")
+ if "ar_brokerage_rate" in config:
+ self.brokerage_rate, source = _rate(config["ar_brokerage_rate"], "ar_brokerage_rate"), "ar_brokerage_rate"
+ elif config.get("commission") is not None:
+ self.brokerage_rate, source = _rate(config["commission"], "commission"), "commission"
+ else:
+ self.brokerage_rate, source = 0.0, "none configured"
+ self.exchange_fee_rate = _rate(config.get("ar_exchange_fee_rate", 0.0), "ar_exchange_fee_rate")
+ self.fixed_fee = _rate(config.get("ar_fixed_fee", 0.0), "ar_fixed_fee")
+ self.fee_basis = {
+ "brokerage_rate": self.brokerage_rate, "brokerage_source": source,
+ "exchange_fee_rate": self.exchange_fee_rate, "fixed_fee": self.fixed_fee,
+ "slippage": self.slippage_rate,
+ "note": "simulation inputs, not an official BYMA or broker tariff",
+ }
+ self.max_cedear_move = float(config.get("ar_max_cedear_move", DEFAULT_MAX_CEDEAR_MOVE))
+ self.max_share_move = float(config.get("ar_max_share_move", DEFAULT_MAX_SHARE_MOVE))
+
+ # ── metadata and data ──
+
+ @staticmethod
+ def describe_instrument(symbol: str) -> Optional[str]:
+ """Vendor descriptor used to tell a local share from a CEDEAR."""
+ return yahoo_short_name(symbol)
+
+ def _instrument(self, symbol: str) -> dict:
+ try:
+ return self.instruments[symbol.upper()]
+ except KeyError:
+ raise ValueError(f"{symbol}: unregistered BYMA instrument") from None
+
+ def prepare_market_data(self, data_map: Dict[str, pd.DataFrame]) -> Dict[str, pd.DataFrame]:
+ """Resolve metadata, keep traded sessions, put CEDEAR prices on one unit basis."""
+ problems: List[str] = []
+ for symbol in data_map:
+ if not symbol.upper().endswith(".BA"):
+ problems.append(f"{symbol}: expected a .BA listing")
+ continue
+ info, provenance, gaps = resolve_instrument(
+ symbol, self._declared.get(symbol.upper()), self.describe_instrument)
+ gaps = gaps or _field_problems(symbol, info, require=True)
+ problems.extend(gaps)
+ if not gaps:
+ tick = info.get("tick_size")
+ self.instruments[symbol.upper()] = {**info, "tick_size": None if tick is None else Decimal(str(tick))}
+ self.provenance[symbol.upper()] = provenance
+ if problems:
+ raise ValueError(_config_error(problems))
+ for symbol, frame in data_map.items():
+ validate_frame(frame, symbol)
+ sessions = traded_dates(data_map.values())
+ prepared: Dict[str, pd.DataFrame] = {}
+ dropped: set = set()
+ self.ratio_adjustments = []
+ for symbol, frame in data_map.items():
+ attrs = dict(frame.attrs)
+ keep = frame.index.normalize().isin(sessions)
+ dropped.update(str(ts.date()) for ts in frame.index[~keep])
+ frame = frame[keep]
+ info = self._instrument(symbol)
+ if info["kind"] == "cedear":
+ frame, events = reconcile_ratio_changes(
+ frame, symbol, info["ratio_history"], tolerance=DEFAULT_RATIO_TOLERANCE)
+ missing = [e["effective_date"] for e in events if not e["credit_date"]]
+ if missing:
+ raise ValueError(
+ f"{symbol}: ratio change(s) on {', '.join(missing)} need the depositary "
+ "credit_date of the additional certificates")
+ self.ratio_adjustments.extend(events)
+ limit = self.max_cedear_move if info["kind"] == "cedear" else self.max_share_move
+ jumps = discontinuities(frame, limit)
+ if jumps:
+ raise ValueError(
+ f"{symbol}: unexplained price discontinuities on {', '.join(jumps[:5])}; "
+ + ("declare the CEDEAR ratio change in ratio_history"
+ if info["kind"] == "cedear" else "use a split-adjusted source")
+ + " or exclude the window")
+ frame.attrs.update(attrs)
+ prepared[symbol] = frame
+ self.dropped_no_trade_dates = sorted(dropped)
+ return prepared
+
+ # ── market rules ──
+
+ def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:
+ return argentina_can_execute(self, self, symbol, direction, bar)
+
+ def available_cash(self, timestamp: pd.Timestamp) -> float:
+ return argentina_available_cash(self, self, timestamp)
+
+ def can_liquidate_at_end(self, symbol: str, timestamp: pd.Timestamp) -> bool:
+ return argentina_sell_allowed(self, self, symbol, timestamp)
+
+ def unit_scale(self, symbol: str, timestamp: Any) -> Decimal:
+ """Adjusted units per real certificate on *timestamp* (``new/old`` before a change)."""
+ today = _day(timestamp)
+ scale = Decimal(1)
+ if today is None:
+ return scale
+ for event in self.ratio_adjustments:
+ if event["symbol"].upper() == symbol.upper() and date.fromisoformat(event["effective_date"]) > today:
+ scale *= Decimal(str(event["new_ratio"])) / Decimal(str(event["old_ratio"]))
+ return scale
+
+ def round_size(self, raw_size: float, price: float) -> float:
+ """Whole real lots: before a ratio change one lot spans ``new/old`` units."""
+ info = self._instrument(self._active_symbol)
+ if not math.isfinite(raw_size) or raw_size <= 0:
+ return 0.0
+ lot = Decimal(info["lot_size"]) * self.unit_scale(self._active_symbol, self._bar_ts)
+ return float((Decimal(repr(raw_size)) / lot).to_integral_value(rounding=ROUND_FLOOR) * lot)
+
+ def calc_commission(self, size: float, price: float, direction: int, is_open: bool) -> float:
+ notional = size * price
+ if not math.isfinite(notional) or notional <= 0:
+ return 0.0
+ return notional * (self.brokerage_rate + self.exchange_fee_rate) + self.fixed_fee
+
+ def apply_slippage(self, price: float, direction: int) -> float:
+ """Slip against the trader, then snap to the BYMA tick of the real price."""
+ info = self._instrument(self._active_symbol)
+ if not math.isfinite(price) or price <= 0:
+ raise ValueError("BYMA execution price must be positive and finite")
+ side = 1 if direction == 1 else -1
+ slipped = Decimal(str(price)) * (Decimal(1) + side * Decimal(str(self.slippage_rate)))
+ scale = self.unit_scale(self._active_symbol, self._bar_ts)
+ tick = (info["tick_size"] or equity_tick(slipped * scale)) / scale
+ rounding = ROUND_CEILING if side > 0 else ROUND_FLOOR
+ return float((slipped / tick).to_integral_value(rounding=rounding) * tick)
+
+ # ── reporting ──
+
+ def _engine_diagnostics(self) -> Dict[str, Any]:
+ return argentina_diagnostics(self, self)
+
+ def _write_artifacts(self, run_dir, *args, **kwargs) -> None:
+ super()._write_artifacts(run_dir, *args, **kwargs)
+ write_byma_artifacts(run_dir, self, self)
+
+
+# ── state/rules helpers (shared with CompositeEngine, like hose_can_execute) ──
+
+def argentina_sell_allowed(state: BaseEngine, rules: ArgentinaEquityEngine, symbol: str, timestamp: Any) -> bool:
+ """Settled shares and credited certificates: the BYMA sell rule."""
+ today = _day(timestamp)
+ if today is None or symbol not in state.positions:
+ return False
+ openings = []
+ for fill in reversed(getattr(state, "fill_records", ()) or ()):
+ if fill.symbol != symbol:
+ continue
+ if fill.action == "close":
+ break
+ if fill.action in _OPENING:
+ openings.append(fill)
+ if not openings:
+ return False
+ newest = openings[0]
+ if int(state._bar_idx) < _settlement_bar(newest):
+ return False
+ first_open = min(_day(f.timestamp) for f in openings)
+ earliest = _add_weekdays(today, normal_cash_lag(today))
+ for event in rules.ratio_adjustments:
+ if event["symbol"].upper() != symbol.upper() or not event["credit_date"]:
+ continue
+ ex = date.fromisoformat(event["effective_date"])
+ if first_open < ex <= today and earliest < date.fromisoformat(event["credit_date"]):
+ return False
+ return True
+
+
+def argentina_available_cash(state: BaseEngine, rules: ArgentinaEquityEngine, timestamp: Any) -> float:
+ """Cash for a purchase now: capital less sales settling after its session."""
+ today = _day(timestamp)
+ if today is None:
+ raise ValueError("BYMA buying power requires a session timestamp")
+ due = int(state._bar_idx) + normal_cash_lag(today)
+ later = sum(_net_proceeds(f) for f in state.fill_records
+ if f.action in _SALES and _settlement_bar(f) > due)
+ return state.capital - later
+
+
+def argentina_can_execute(state: BaseEngine, rules: ArgentinaEquityEngine, symbol: str,
+ direction: int, bar: pd.Series) -> bool:
+ """Long only, a traded bar, and settled/credited shares for a sale."""
+ rules._instrument(symbol)
+ if direction not in (0, 1):
+ return False
+ try:
+ price, volume = float(bar.get("close")), float(bar.get("volume"))
+ except (TypeError, ValueError):
+ return False
+ if not (math.isfinite(price) and price > 0 and math.isfinite(volume) and volume > 0):
+ return False # a zero-volume bar is a stale print, not an executable price
+ return direction == 1 or argentina_sell_allowed(state, rules, symbol, bar.name)
+
+
+def byma_cash_ledger(state: BaseEngine) -> List[dict]:
+ """Per-fill cash reconciliation replayed from the engine's own fills."""
+ dates = [snap.timestamp for snap in state.equity_snapshots]
+ cash = float(state.initial_capital)
+ rows: List[dict] = []
+ for index, fill in enumerate(state.fill_records):
+ qty = float(fill.signed_quantity)
+ notional = abs(qty) * float(fill.execution_price)
+ fee = float(fill.fee)
+ due = _settlement_bar(fill)
+ buying_power = None
+ if qty > 0:
+ later = sum(_net_proceeds(f) for f in state.fill_records[:index]
+ if f.action in _SALES and _settlement_bar(f) > due)
+ buying_power = cash - later
+ cash += -(notional + fee) if qty > 0 else notional - fee
+ unsettled = sum(_net_proceeds(f) for f in state.fill_records[:index + 1]
+ if f.action in _SALES and _settlement_bar(f) > int(fill.bar_idx))
+ within = due < len(dates)
+ rows.append({
+ "timestamp": str(_day(fill.timestamp)), "code": fill.symbol,
+ "side": "buy" if qty > 0 else "sell", "qty": abs(qty),
+ "notional": round(notional, 6), "fee": round(fee, 6),
+ "total_cost": round(notional + fee, 6) if qty > 0 else "",
+ "net_proceeds": round(notional - fee, 6) if qty < 0 else "",
+ "cash_flow": round(-(notional + fee) if qty > 0 else notional - fee, 6),
+ "cash_after": round(cash, 6),
+ "settlement_date": str(_day(dates[due])) if within else "",
+ "settlement_basis": "observed_sessions" if within else "beyond_loaded_data",
+ "buying_power_before": "" if buying_power is None else round(buying_power, 6),
+ "unsettled_sale_proceeds_after": round(unsettled, 6),
+ })
+ return rows
+
+
+def argentina_diagnostics(state: BaseEngine, rules: ArgentinaEquityEngine) -> Dict[str, Any]:
+ """Run facts: what the figures rest on and what terminal equity contains."""
+ if not state.equity_snapshots:
+ return {}
+ last_bar = len(state.equity_snapshots) - 1
+ fills = state.fill_records
+ retained = state.unliquidated_positions
+ parts = []
+ for symbol, info in sorted(rules.instruments.items()):
+ prov = rules.provenance.get(symbol, {})
+ tick = TICK_SOURCE if info["tick_size"] is None else str(info["tick_size"])
+ parts.append(f"{symbol}: kind={info['kind']} [{prov.get('kind', 'declared')}], "
+ f"lot={info['lot_size']} [{prov.get('lot_size')}], tick={tick}")
+ parts.append("settlement: T+2 (T+1 from 2024-05-27) counted in observed trading sessions "
+ "[approximation, not an official calendar]")
+ fee = rules.fee_basis
+ parts.append(f"costs: brokerage {fee['brokerage_rate']:.4%} ({fee['brokerage_source']}), "
+ f"exchange {fee['exchange_fee_rate']:.4%}, fixed {fee['fixed_fee']:g}, "
+ f"slippage {fee['slippage']:.4%} [assumptions]")
+ return {
+ "settlement_currency": "ARS",
+ "ar_data_basis": "; ".join(parts),
+ "ar_net_pnl": round(state.equity_snapshots[-1].equity - state.initial_capital, 6),
+ "ar_total_fees": round(sum(float(f.fee) for f in fills), 6),
+ "ar_buy_fees": round(sum(float(f.fee) for f in fills if f.signed_quantity > 0), 6),
+ "ar_sell_fees": round(sum(float(f.fee) for f in fills if f.signed_quantity < 0), 6),
+ "ar_unsettled_sale_receivable_at_end": round(sum(
+ _net_proceeds(f) for f in fills if f.action in _SALES and _settlement_bar(f) > last_bar), 6),
+ "ar_unliquidated_position_count": len(retained),
+ "ar_terminal_equity_basis": ("unsettled positions marked net of estimated exit costs"
+ if retained else "all positions liquidated at the last close"),
+ "ar_cedear_ratio_adjustments": list(rules.ratio_adjustments),
+ "ar_metadata_provenance": dict(rules.provenance),
+ "ar_fee_basis": dict(fee),
+ "ar_dropped_no_trade_dates": len(rules.dropped_no_trade_dates),
+ }
+
+
+def write_byma_artifacts(run_dir: Any, state: BaseEngine, rules: ArgentinaEquityEngine) -> None:
+ """``artifacts/cash_ledger.csv`` and ``artifacts/byma_preparation.json``."""
+ out = Path(run_dir) / "artifacts"
+ out.mkdir(parents=True, exist_ok=True)
+ columns = ["timestamp", "code", "side", "qty", "notional", "fee", "total_cost", "net_proceeds",
+ "cash_flow", "cash_after", "settlement_date", "settlement_basis",
+ "buying_power_before", "unsettled_sale_proceeds_after"]
+ pd.DataFrame(byma_cash_ledger(state), columns=columns).to_csv(out / "cash_ledger.csv", index=False)
+ diagnostics = argentina_diagnostics(state, rules)
+ diagnostics["ar_unliquidated_positions"] = list(state.unliquidated_positions)
+ diagnostics["ar_dropped_no_trade_dates"] = list(rules.dropped_no_trade_dates)
+ (out / "byma_preparation.json").write_text(
+ json.dumps(diagnostics, indent=2, ensure_ascii=False, default=str) + "\n", encoding="utf-8")
+
+
+# ── configuration ──
+
+def _rate(value: Any, key: str) -> float:
+ try:
+ parsed = float(value)
+ except (TypeError, ValueError):
+ raise ValueError(f"{key} must be a finite nonnegative number") from None
+ if not math.isfinite(parsed) or parsed < 0:
+ raise ValueError(f"{key} must be a finite nonnegative number")
+ return parsed
+
+
+def _config_error(problems: List[str]) -> str:
+ lines = "\n".join(f"- {p}" for p in problems)
+ return (f"BYMA backtest configuration incomplete:\n{lines}\n"
+ 'Example: "ar_instruments": {"YPFD.BA": {"kind": "share"}, "AAPL.BA": {"kind": '
+ '"cedear", "underlying": "AAPL", "ratio_history": [{"effective_date": "YYYY-MM-DD", '
+ '"ratio": "20", "credit_date": "YYYY-MM-DD"}]}}. Local shares need no entry; '
+ 'do not set "engine": .BA codes select the BYMA engine.')
+
+
+def _iso(value: Any) -> Optional[date]:
+ try:
+ parsed = date.fromisoformat(str(value))
+ except ValueError:
+ return None
+ return parsed if parsed.isoformat() == str(value) else None
+
+
+def _field_problems(symbol: str, info: dict, *, require: bool = False) -> List[str]:
+ """Validate declared fields; with *require*, also report missing essentials."""
+ problems: List[str] = []
+ kind = info.get("kind")
+ if kind not in (None, "share", "cedear"):
+ problems.append(f"{symbol}.kind must be 'share' or 'cedear' (got {kind!r})")
+ elif require and kind is None:
+ problems.append(f"{symbol}.kind is required ('share' or 'cedear')")
+ if info.get("currency", "ARS") != "ARS":
+ problems.append(f"{symbol}.currency: only ARS lines are supported")
+ lot = info.get("lot_size", 1)
+ if isinstance(lot, bool) or not isinstance(lot, int) or lot < 1:
+ problems.append(f"{symbol}.lot_size must be a positive integer")
+ if info.get("tick_size") is not None:
+ try:
+ if not Decimal(str(info["tick_size"])) > 0:
+ raise ArithmeticError
+ except (ValueError, ArithmeticError):
+ problems.append(f"{symbol}.tick_size must be a positive number (omit it for BYMA bands)")
+ if kind == "cedear":
+ if not info.get("underlying"):
+ problems.append(f"{symbol}.underlying is required for a CEDEAR")
+ history = info.get("ratio_history")
+ if not isinstance(history, list) or not history:
+ problems.append(f"{symbol}.ratio_history (dated CEDEAR ratios) is required")
+ return problems
+ previous: Optional[date] = None
+ for item in history:
+ effective = _iso(item.get("effective_date")) if isinstance(item, dict) else None
+ try:
+ ratio = Decimal(str(item["ratio"]))
+ except (KeyError, TypeError, ValueError, ArithmeticError):
+ ratio = Decimal(0)
+ credit = item.get("credit_date") if isinstance(item, dict) else None
+ if (effective is None or not ratio.is_finite() or ratio <= 0
+ or (previous is not None and effective <= previous)):
+ problems.append(f"{symbol}.ratio_history needs increasing ISO effective_date "
+ "and positive ratio entries")
+ break
+ if credit is not None and (_iso(credit) is None or _iso(credit) < effective):
+ problems.append(f"{symbol}: credit_date must be an ISO date on/after effective_date")
+ break
+ if item.get("price_series") not in (None, "adjusted", "unadjusted"):
+ problems.append(f"{symbol}: price_series must be 'adjusted' or 'unadjusted'")
+ break
+ previous = effective
+ return problems
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index 4918add46..61acfe55d 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -577,7 +577,52 @@ class BaseEngine(ABC):
# metrics instead of only to a subclass that overrode the hook.
self.plan_rejections: Counter = Counter()
self._bar_idx: int = 0
+ self._bar_ts: Optional[pd.Timestamp] = None # session being executed
self._active_symbol: str = "" # set by _rebalance/_close_position for subclass use
+ # Positions the terminal close was not allowed to sell (see
+ # can_liquidate_at_end). Empty for every market that keeps the default.
+ self.unliquidated_positions: List[Dict[str, Any]] = []
+
+ def available_cash(self, timestamp: pd.Timestamp) -> float:
+ """Spendable funds for an order at timestamp, without changing equity.
+
+ Default preserves legacy immediate-settlement capital across markets.
+ Markets with unsettled receivables may override this hook.
+ """
+ return self.capital
+
+ def projected_reduction_buying_power(
+ self, reductions: list, timestamp: pd.Timestamp,
+ ) -> float:
+ """Incremental buying power from planned closes on this bar.
+
+ Default is the legacy immediate-credit behavior. Settlement-based
+ markets can return zero so a sale never finances a same-bar purchase.
+ """
+ return sum(order.capital_credit for order in reductions)
+
+ def prepare_market_data(
+ self, data_map: Dict[str, pd.DataFrame],
+ ) -> Dict[str, pd.DataFrame]:
+ """Validate or normalize loaded bars before signals see them.
+
+ Default returns the frames untouched, so every market keeps its
+ loader output. A market whose source data needs a documented unit
+ convention (e.g. a depositary-receipt ratio change) overrides this;
+ running before signal generation keeps signals and fills on the
+ same price basis.
+ """
+ return data_map
+
+ def can_liquidate_at_end(self, symbol: str, timestamp: pd.Timestamp) -> bool:
+ """Whether the terminal forced close may sell *symbol* on the last bar.
+
+ Default True keeps the legacy behavior of every market. A market whose
+ securities cannot be sold before settlement overrides this so the
+ end-of-backtest close does not bypass the rule that gates signal exits.
+ Positions it refuses stay open and are valued, not traded.
+ """
+ return True
# ── Market rule interface (subclass must implement) ──
@@ -928,6 +973,7 @@ class BaseEngine(ABC):
sys.exit(1)
data_map = _maybe_enrich_fundamentals(data_map, config)
data_map = _maybe_enrich_events(data_map, config)
+ data_map = self.prepare_market_data(data_map)
# 2. Generate signals
signal_map = signal_engine.generate(data_map)
@@ -1235,6 +1281,7 @@ class BaseEngine(ABC):
for i, ts in enumerate(dates):
self._bar_idx = i
+ self._bar_ts = ts
stop_run = self.before_rebalance_bar(ts, data_map, codes)
execute_targets = execution_dates is None or ts in execution_dates
@@ -1323,7 +1370,7 @@ class BaseEngine(ABC):
return result
planned = _plans(1.0, observe=True)
- if sum(order.cost for order in planned) > self.capital + 1e-9:
+ if sum(order.cost for order in planned) > self.available_cash(ts) + 1e-9:
# The trial plans of the search are not findings: one starved
# open used to be booked as a zero_size rejection on every
# bisection step (#1470). The sleeve that leaves the basket is
@@ -1338,7 +1385,7 @@ class BaseEngine(ABC):
for _ in range(50):
mid = (low + high) / 2.0
candidate = _plans(mid, observe=False)
- if sum(order.cost for order in candidate) <= self.capital + 1e-9:
+ if sum(order.cost for order in candidate) <= self.available_cash(ts) + 1e-9:
low, fitting = mid, candidate
else:
high = mid
@@ -1398,6 +1445,8 @@ class BaseEngine(ABC):
if len(dates) > 0:
_last_row = min(self._bar_idx, len(dates) - 1)
last_ts = dates[_last_row]
+ self.unliquidated_positions = []
+ retained_value = 0.0
for c in list(self.positions.keys()):
pos = self.positions[c]
mark_price = self._safe_price(
@@ -1407,23 +1456,46 @@ class BaseEngine(ABC):
)
self._active_symbol = c
exit_price = self.apply_slippage(mark_price, -pos.direction)
+ if not self.can_liquidate_at_end(c, last_ts):
+ # The market's sell rule (e.g. unsettled securities) also
+ # binds the terminal close: keep the position open and
+ # value it at what a close would net, without booking a
+ # trade the rules would not have allowed.
+ proceeds = self._close_proceeds(pos, exit_price)
+ retained_value += proceeds
+ self.unliquidated_positions.append({
+ "symbol": c,
+ "size": pos.size,
+ "entry_price": pos.entry_price,
+ "mark_price": mark_price,
+ "estimated_exit_price": exit_price,
+ "estimated_net_proceeds": proceeds,
+ })
+ continue
self._close_position(c, exit_price, last_ts, "end_of_backtest")
# The final snapshot feeds metrics and artifacts. Replace its
# pre-liquidation mark with post-liquidation cash so terminal
# slippage and exit commission are reflected in reported equity.
if self.equity_snapshots:
+ terminal_equity = self.capital + retained_value
self.equity_snapshots[-1] = EquitySnapshot(
timestamp=last_ts,
capital=self.capital,
- unrealized=0.0,
- equity=self.capital,
- positions=0,
+ unrealized=terminal_equity - self.capital - sum(
+ self._calc_margin(p.symbol, p.size, p.entry_price, p.leverage)
+ for p in self.positions.values()
+ ),
+ equity=terminal_equity,
+ positions=len(self.positions),
)
if self.actual_position_snapshots:
- self.actual_position_snapshots[-1] = (
- last_ts, {code: 0.0 for code in codes}
- )
+ final_weights = {code: 0.0 for code in codes}
+ if self.positions and self.equity_snapshots[-1].equity > 1e-12:
+ final_weights = self._actual_weights(
+ close_df, last_ts, codes, self.equity_snapshots[-1].equity
+ )
+ self.actual_position_snapshots[-1] = (last_ts, final_weights)
# Clean up temporary instance attributes
self._close_arr = None
@@ -1557,7 +1629,7 @@ class BaseEngine(ABC):
if target_dir != 0 and symbol not in self.positions:
order = self._plan_open_order(symbol, target_weight, df, ts, equity)
- if order is not None and order.cost <= self.capital + 1e-9:
+ if order is not None and order.cost <= self.available_cash(ts) + 1e-9:
self._execute_open_order(order, ts)
def _plan_open_order(
@@ -1803,15 +1875,15 @@ class BaseEngine(ABC):
reductions.append(self._plan_reduction(before, target_size, price))
projected_capital = (
- self.capital
- + sum(order.capital_credit for order in reductions)
+ self.available_cash(ts)
+ + self.projected_reduction_buying_power(reductions, ts)
- sum(order.cost for order in opens)
)
self._validate_rebalance_values(projected_capital)
if projected_capital < -1e-9:
fitted = self._fit_rebalance_opens(opens, reductions, ts)
if fitted is None:
- if sum(order.capital_credit for order in reductions) < 0:
+ if self.projected_reduction_buying_power(reductions, ts) < 0:
# The reductions themselves consume cash (a close whose loss
# exceeds its margin): no dropping of opens repairs that, so
# the bar aborts atomically as #1274 decided.
@@ -1868,10 +1940,10 @@ class BaseEngine(ABC):
(#1274), and otherwise — cash was already below zero — drops every
open and still runs the reductions (#1542).
"""
- released = sum(order.capital_credit for order in reductions)
+ released = self.projected_reduction_buying_power(reductions, ts)
def _fits(candidate: list[_OpenOrder]) -> bool:
- projected = self.capital + released - sum(order.cost for order in candidate)
+ projected = self.available_cash(ts) + released - sum(order.cost for order in candidate)
self._validate_rebalance_values(projected)
return projected >= -1e-9
@@ -1970,7 +2042,7 @@ class BaseEngine(ABC):
before = self.positions[order.symbol]
if order.direction != before.direction:
raise ValueError("position increase direction must match the open position")
- if order.cost > self.capital + 1e-7:
+ if order.cost > self.available_cash(ts) + 1e-7:
raise RuntimeError(
f"planned order for {order.symbol} exceeds available capital"
)
@@ -2068,7 +2140,7 @@ class BaseEngine(ABC):
def _execute_open_order(self, order: _OpenOrder, ts: pd.Timestamp) -> None:
"""Commit a previously priced opening order."""
- if order.cost > self.capital + 1e-7:
+ if order.cost > self.available_cash(ts) + 1e-7:
raise RuntimeError(
f"planned order for {order.symbol} exceeds available capital"
)
@@ -2138,6 +2210,19 @@ class BaseEngine(ABC):
frame.index.name = "timestamp"
return frame
+ def _close_proceeds(self, pos: Position, exit_price: float) -> float:
+ """Capital a close at *exit_price* would return, without closing.
+
+ Mirrors the credit in ``_close_position`` (margin + pnl - exit
+ commission) so a position valued this way is worth exactly what the
+ close would have booked.
+ """
+ self._active_symbol = pos.symbol
+ pnl = self._calc_pnl(pos.symbol, pos.direction, pos.size, pos.entry_price, exit_price)
+ margin = self._calc_margin(pos.symbol, pos.size, pos.entry_price, pos.leverage)
+ exit_comm = self.calc_commission(pos.size, exit_price, pos.direction, is_open=False)
+ return margin + pnl - exit_comm
+
def _close_position(
self,
symbol: str,
diff --git a/agent/backtest/engines/composite.py b/agent/backtest/engines/composite.py
index b74a45625..4a13791ce 100644
--- a/agent/backtest/engines/composite.py
+++ b/agent/backtest/engines/composite.py
@@ -51,10 +51,8 @@ def _build_rule_engines(config: dict, codes: List[str]) -> Dict[str, BaseEngine]
from backtest.engines.vietnam_equity import VietnamEquityEngine
engines["vietnam_equity"] = VietnamEquityEngine(config)
elif market == "ar_equity":
- raise ValueError(
- "Argentina .BA market data is supported, but Argentina backtest "
- "execution rules are not modeled yet"
- )
+ from backtest.engines.argentina_equity import ArgentinaEquityEngine
+ engines["ar_equity"] = ArgentinaEquityEngine(config)
elif market == "br_equity":
from backtest.engines.brazil_equity import BrazilEquityEngine
engines["br_equity"] = BrazilEquityEngine(config)
@@ -136,6 +134,17 @@ class CompositeEngine(BaseEngine):
# Build symbol -> market mapping
self._symbol_market: Dict[str, str] = {c: _detect_market(c) for c in codes}
+ # BYMA buying power, sell eligibility and terminal liquidation read the
+ # whole pool's fill ledger against one ARS settlement calendar; another
+ # market's fills in that ledger would be settled by BYMA's rules.
+ markets = set(self._symbol_market.values())
+ if "ar_equity" in markets and len(markets) > 1:
+ raise ValueError(
+ "Argentina .BA codes cannot share a composite pool with other "
+ f"markets ({', '.join(sorted(markets - {'ar_equity'}))}): BYMA "
+ "settlement cash and certificate rules apply to the whole ledger"
+ )
+
# Build sub-engines (one per market type)
self._rule_engines = _build_rule_engines(config, codes)
@@ -147,6 +156,7 @@ class CompositeEngine(BaseEngine):
self._last_swap_dates: dict = {}
self._run_interval = str(config.get("interval", "1D"))
+ self._ar_rules = self._rule_engines.get("ar_equity")
def run_backtest(self, config: dict, *args, **kwargs):
"""Run the pipeline, refusing a code set that spans currencies.
@@ -180,8 +190,14 @@ class CompositeEngine(BaseEngine):
"""
by_market = {
market: details for market, engine in self._rule_engines.items()
- if (details := engine._engine_diagnostics())
+ if market != "ar_equity" and (details := engine._engine_diagnostics())
}
+ if self._ar_rules is not None:
+ from backtest.engines.argentina_equity import argentina_diagnostics
+
+ # The rule book holds no fills; the pool's ledger is evaluated.
+ if details := argentina_diagnostics(self, self._ar_rules):
+ by_market["ar_equity"] = details
if not by_market:
return {}
result: Dict[str, Any] = {"market_diagnostics": by_market}
@@ -203,6 +219,34 @@ class CompositeEngine(BaseEngine):
engine = next(iter(self._rule_engines.values()))
return engine
+ # ── BYMA state/rules hooks (pool ledger evaluated by the rule book) ──
+
+ def _write_artifacts(self, run_dir, *args, **kwargs) -> None:
+ super()._write_artifacts(run_dir, *args, **kwargs)
+ if self._ar_rules is not None:
+ from backtest.engines.argentina_equity import write_byma_artifacts
+
+ write_byma_artifacts(run_dir, self, self._ar_rules)
+
+ def prepare_market_data(self, data_map):
+ if self._ar_rules is None:
+ return super().prepare_market_data(data_map)
+ return self._ar_rules.prepare_market_data(data_map)
+
+ def available_cash(self, timestamp: pd.Timestamp) -> float:
+ if self._ar_rules is None:
+ return super().available_cash(timestamp)
+ from backtest.engines.argentina_equity import argentina_available_cash
+
+ return argentina_available_cash(self, self._ar_rules, timestamp)
+
+ def can_liquidate_at_end(self, symbol: str, timestamp: pd.Timestamp) -> bool:
+ if self._symbol_market.get(symbol) != "ar_equity" or self._ar_rules is None:
+ return super().can_liquidate_at_end(symbol, timestamp)
+ from backtest.engines.argentina_equity import argentina_sell_allowed
+
+ return argentina_sell_allowed(self, self._ar_rules, symbol, timestamp)
+
# ── Stateless method dispatch ──
def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:
@@ -235,6 +279,11 @@ class CompositeEngine(BaseEngine):
return india_can_execute(self, sub, symbol, direction, bar)
+ if market == "ar_equity" and self._ar_rules is not None:
+ from backtest.engines.argentina_equity import argentina_can_execute
+
+ return argentina_can_execute(self, self._ar_rules, symbol, direction, bar)
+
# Delegate remaining checks (price limits, short-sell block, etc.)
return self._rule_for(symbol).can_execute(symbol, direction, bar)
@@ -246,6 +295,7 @@ class CompositeEngine(BaseEngine):
# sub-engine instance keeps whatever symbol last synced it, so it
# must be refreshed on every dispatch, not just in apply_slippage.
sub._active_symbol = self._active_symbol
+ sub._bar_ts = self._bar_ts
return sub.round_size(raw_size, price)
def calc_commission(
@@ -260,6 +310,7 @@ class CompositeEngine(BaseEngine):
"""Delegate to active symbol's sub-engine."""
sub = self._rule_for(self._active_symbol)
sub._active_symbol = self._active_symbol
+ sub._bar_ts = self._bar_ts
return sub.apply_slippage(price, direction)
# ── PnL / margin dispatch (route by symbol, not _active_symbol) ──
diff --git a/agent/backtest/loaders/yfinance_loader.py b/agent/backtest/loaders/yfinance_loader.py
index c239a559b..acb280919 100644
--- a/agent/backtest/loaders/yfinance_loader.py
+++ b/agent/backtest/loaders/yfinance_loader.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import logging
from collections import defaultdict
+from collections.abc import Mapping
from typing import Dict, List, Optional, Union
import pandas as pd
@@ -110,7 +111,8 @@ def _declared_currency(symbol: str) -> Optional[str]:
meta = yf.Ticker(symbol).history_metadata
except Exception: # noqa: BLE001 — a metadata probe failure is not data
return None
- currency = meta.get("currency") if isinstance(meta, dict) else None
+ # yfinance>=1.x returns a lazy HistoryMetadata Mapping, not a dict.
+ currency = meta.get("currency") if isinstance(meta, Mapping) else None
return currency if isinstance(currency, str) and currency else None
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index 414435398..7bb1fa94a 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -161,7 +161,10 @@ class BacktestConfigSchema(BaseModel):
@classmethod
def valid_engine(cls, v: str) -> str:
if v not in _VALID_ENGINES:
- raise ValueError(f"unsupported engine {v!r}, must be one of {_VALID_ENGINES}")
+ raise ValueError(
+ f"unsupported engine {v!r}, must be one of {_VALID_ENGINES}; market rule "
+ "engines (e.g. BYMA for .BA codes) are selected from `codes`, keep 'daily'"
+ )
return v
@field_validator("source")
@@ -1816,14 +1819,13 @@ def _select_market_engine(source: str, config: dict, codes: List[str]):
if "br_equity" in markets:
from backtest.engines.brazil_equity import BrazilEquityEngine
return BrazilEquityEngine(config)
- # Argentina market-data routing is supported, but BYMA execution rules
- # are not modeled yet. Fail closed instead of silently applying US/crypto
- # commissions, lot sizes, settlement, or short-selling assumptions.
+ # Argentina (BYMA) routing — same reason as India. The engine itself
+ # fails closed without declared instrument metadata (share/CEDEAR, quote
+ # currency, lot, tick, dated CEDEAR ratios) and a settlement calendar,
+ # rather than applying US/crypto lot, settlement or shorting defaults.
if "ar_equity" in markets:
- raise ValueError(
- "Argentina .BA market data is supported, but Argentina backtest "
- "execution rules are not modeled yet"
- )
+ from backtest.engines.argentina_equity import ArgentinaEquityEngine
+ return ArgentinaEquityEngine(config)
# Index symbols (^SPX, ^FTSE, ...) — priced like a US/global-listed
# instrument (GlobalEquityEngine, US rules) and never the China/crypto
diff --git a/agent/src/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.md
index cdeddbba1..97b2dbcca 100644
--- a/agent/src/skills/strategy-generate/SKILL.md
+++ b/agent/src/skills/strategy-generate/SKILL.md
@@ -168,6 +168,7 @@ Self-check after writing `signal_engine.py`:
- `initial_cash`: default 1,000,000
- `commission`: default 0.1%
- `hk_lot_sizes`: optional, Hong Kong only — `{"00700.HK": 100, "02800.HK": 500}`. HK board lots are set per issuer, so without this table every HK order is rounded to 100 shares and a name whose real lot is smaller than its target trades zero times. Codes match with or without leading zeros. Every symbol with no configured lot size uses 100 shares and is listed under `lot_assumptions` in the metrics, including runs without a table. Reports must identify these as assumptions rather than verified exchange lots.
+- Argentina (BYMA `.BA` codes, e.g. `"YPFD.BA"`): use `"source": "yahoo"` and keep `"engine": "daily"`; `.BA` codes select the BYMA engine. Local shares need no extra keys (kind from Yahoo's descriptor, ARS, one-share lots as an assumption, BYMA Circular 3569 ticks). `commission` is the brokerage rate; `ar_exchange_fee_rate`, `ar_fixed_fee` and `ar_slippage` add costs. Settlement is T+2 (T+1 from 2024-05-27) counted in observed trading sessions, an approximation rather than an official calendar; `artifacts/cash_ledger.csv` reports each fill's cash flow and settlement session (`beyond_loaded_data` past the last bar). **CEDEARs** (e.g. `"AAPL.BA"`) must be declared: `"ar_instruments": {"AAPL.BA": {"kind": "cedear", "underlying": "AAPL", "ratio_history": [{"effective_date": "YYYY-MM-DD", "ratio": "20", "credit_date": "YYYY-MM-DD"}]}}`, with ratios from the issuer's notices. A `BYMA backtest configuration incomplete` error lists every missing key at once: ask the user for them rather than guessing. Report the `ar_data_basis` metric's labels (declared / vendor / assumption).
- `validation`: optional statistical validation after backtest completes. Omit to skip. Example:
```json
"validation": {
diff --git a/agent/tests/test_argentina_backtests.py b/agent/tests/test_argentina_backtests.py
new file mode 100644
index 000000000..cf9a41702
--- /dev/null
+++ b/agent/tests/test_argentina_backtests.py
@@ -0,0 +1,196 @@
+"""End-to-end BYMA backtests through runner.main: YPFD buy-and-hold, YPFD/GGAL
+rotation, AAPL.BA across its 2024 CEDEAR ratio change, and composite parity.
+
+Synthetic bars on real 2024 BYMA sessions (holidays are simply absent, as in
+the loaders' output once placeholder bars are dropped); the Yahoo descriptor
+is stubbed; no network.
+"""
+
+from __future__ import annotations
+
+import csv
+import io
+import json
+import textwrap
+from contextlib import redirect_stdout
+
+import pandas as pd
+import pytest
+
+from backtest import runner
+from backtest.engines.argentina_equity import ArgentinaEquityEngine
+from backtest.engines.composite import CompositeEngine
+
+HOLIDAYS_2024 = {"2024-01-01", "2024-02-12", "2024-02-13", "2024-03-28", "2024-03-29",
+ "2024-04-01", "2024-04-02", "2024-05-01", "2024-06-17", "2024-06-20",
+ "2024-06-21", "2024-07-09"}
+NAMES = {"YPFD.BA": "YPF SOCIEDAD ANONIMA", "GGAL.BA": "GRUPO FINANCIERO GALICIA SA"}
+HOLD = textwrap.dedent('''
+ import pandas as pd
+
+
+ class SignalEngine:
+ def generate(self, data_map):
+ return {c: pd.Series(0.95, index=d.index) for c, d in data_map.items()}
+''')
+ROTATE = textwrap.dedent('''
+ import pandas as pd
+
+
+ class SignalEngine:
+ """YPFD until the 2024-08-01 session, GGAL from then on."""
+
+ def generate(self, data_map):
+ out = {}
+ for code, df in data_map.items():
+ nxt = pd.Series(df.index, index=df.index).shift(-1).fillna(df.index[-1])
+ on_ggal = nxt >= pd.Timestamp("2024-08-01")
+ weight = on_ggal if code == "GGAL.BA" else ~on_ggal
+ out[code] = weight.astype(float) * 0.95
+ return out
+''')
+
+
+def _frame(start, end, base, drift=0.0, ex=None, factor=1.0, placeholders=()):
+ days = [d for d in pd.bdate_range(start, end) if d.strftime("%Y-%m-%d") not in HOLIDAYS_2024]
+ days = sorted(set(days) | {pd.Timestamp(p) for p in placeholders})
+ rows = []
+ for i, day in enumerate(days):
+ close = round(base * (1 + drift) ** i * (1 + 0.004 * ((i * 7) % 5 - 2)), 2)
+ if ex is not None and day >= pd.Timestamp(ex):
+ close = round(close * factor, 2)
+ volume = 0.0 if day.strftime("%Y-%m-%d") in placeholders else 80_000.0
+ rows.append((day, round(close * 0.998, 2), close, volume))
+ frame = pd.DataFrame({"open": [r[1] for r in rows], "high": [r[2] * 1.01 for r in rows],
+ "low": [r[2] * 0.99 for r in rows], "close": [r[2] for r in rows],
+ "volume": [r[3] for r in rows]}, index=pd.DatetimeIndex([r[0] for r in rows]))
+ frame.attrs["quote_currency"] = "ARS"
+ return frame
+
+
+def _run(tmp_path, monkeypatch, config, frames, signal=HOLD):
+ class Loader:
+ name = "yahoo"
+
+ def fetch(self, codes, *args, **kwargs):
+ out = {}
+ for code in codes:
+ out[code] = frames[code].copy()
+ out[code].attrs = dict(frames[code].attrs)
+ return out
+
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))
+ monkeypatch.delenv("VIBE_TRADING_DATA_CACHE", raising=False)
+ monkeypatch.setattr(runner, "_get_loader", lambda source: Loader)
+ monkeypatch.setattr(ArgentinaEquityEngine, "describe_instrument", staticmethod(NAMES.get))
+ run_dir = tmp_path / "run"
+ (run_dir / "code").mkdir(parents=True)
+ (run_dir / "config.json").write_text(json.dumps(config), encoding="utf-8")
+ (run_dir / "code" / "signal_engine.py").write_text(signal, encoding="utf-8")
+ out = io.StringIO()
+ with redirect_stdout(out):
+ runner.main(run_dir)
+ printed = out.getvalue()
+ ledger = list(csv.DictReader((run_dir / "artifacts" / "cash_ledger.csv").open()))
+ prep = json.loads((run_dir / "artifacts" / "byma_preparation.json").read_text())
+ return json.loads(printed[printed.index("{"):]), ledger, prep, run_dir
+
+
+def _config(codes, start, end, **extra):
+ return {"source": "yahoo", "codes": codes, "start_date": start, "end_date": end,
+ "initial_cash": 1_000_000, "commission": 0.001, "engine": "daily", **extra}
+
+
+def _closes_on_cash(ledger, metrics):
+ cash = 1_000_000.0
+ for row in ledger:
+ cash += float(row["cash_flow"])
+ assert abs(float(row["fee"]) - float(row["notional"]) * 0.001) < 1e-6
+ assert cash == pytest.approx(float(ledger[-1]["cash_after"]))
+ assert cash == pytest.approx(metrics["final_value"])
+
+
+def test_ypfd_buy_and_hold_minimal_config(tmp_path, monkeypatch):
+ frame = _frame("2024-06-03", "2024-09-30", 26000.0, 0.001, placeholders={"2024-06-20"})
+ config = _config(["YPFD.BA"], "2024-06-01", "2024-09-30", position_adjustment="hold")
+ metrics, ledger, prep, _ = _run(tmp_path, monkeypatch, config, {"YPFD.BA": frame})
+ assert metrics["trade_count"] == 1 and metrics["settlement_currency"] == "ARS"
+ buy, sell = ledger
+ assert (buy["timestamp"], buy["settlement_date"]) == ("2024-06-04", "2024-06-05") # T+1
+ assert (sell["timestamp"], sell["settlement_basis"]) == ("2024-09-30", "beyond_loaded_data")
+ assert sell["settlement_date"] == "" # never a guessed date
+ assert prep["ar_metadata_provenance"]["YPFD.BA"]["kind"].startswith("vendor")
+ assert "observed trading sessions [approximation" in metrics["ar_data_basis"]
+ assert prep["ar_dropped_no_trade_dates"] == ["2024-06-20"] # holiday placeholder
+ _closes_on_cash(ledger, metrics)
+
+
[email protected]("mode", ["hold", "rebalance"])
+def test_ypfd_ggal_rotation_nets_the_same_session_sale(tmp_path, monkeypatch, mode):
+ frames = {"YPFD.BA": _frame("2024-06-03", "2024-09-30", 2900.0, -0.002),
+ "GGAL.BA": _frame("2024-06-03", "2024-09-30", 3500.0, 0.004)}
+ config = _config(["YPFD.BA", "GGAL.BA"], "2024-06-01", "2024-09-30", position_adjustment=mode)
+ metrics, ledger, _, _ = _run(tmp_path, monkeypatch, config, frames, ROTATE)
+ by_side = [(r["timestamp"], r["code"], r["side"]) for r in ledger]
+ assert ("2024-08-01", "YPFD.BA", "sell") in by_side and ("2024-08-01", "GGAL.BA", "buy") in by_side
+ sale = next(r for r in ledger if r["timestamp"] == "2024-08-01" and r["side"] == "sell")
+ buy = next(r for r in ledger if r["timestamp"] == "2024-08-01" and r["side"] == "buy")
+ assert sale["settlement_date"] == buy["settlement_date"] == "2024-08-02"
+ previous_cash = float(ledger[ledger.index(sale) - 1]["cash_after"])
+ assert float(buy["buying_power_before"]) == pytest.approx(previous_cash + float(sale["net_proceeds"]))
+ assert float(buy["total_cost"]) <= float(buy["buying_power_before"])
+ assert float(buy["total_cost"]) > previous_cash # funded by the sale, not by settled cash alone
+ assert min(float(r["cash_after"]) for r in ledger) >= -1e-6
+ _closes_on_cash(ledger, metrics)
+
+
+AAPL = {"kind": "cedear", "underlying": "AAPL", "ratio_history": [
+ {"effective_date": "2010-06-24", "ratio": "10"},
+ {"effective_date": "2024-01-24", "ratio": "20", "credit_date": "2024-01-26"}]}
+
+
+def test_aapl_ratio_change_books_no_artificial_loss(tmp_path, monkeypatch):
+ frame = _frame("2024-01-02", "2024-03-27", 25000.0, 0.0, ex="2024-01-24", factor=0.5)
+ config = _config(["AAPL.BA"], "2024-01-02", "2024-03-27", position_adjustment="hold",
+ ar_instruments={"AAPL.BA": AAPL})
+ metrics, ledger, prep, run_dir = _run(tmp_path, monkeypatch, config, {"AAPL.BA": frame})
+ buy, sell = ledger
+ assert (buy["timestamp"], buy["settlement_date"]) == ("2024-01-03", "2024-01-05") # T+2
+ assert float(buy["qty"]) % 2 == 0 # whole real certificates before the change
+ assert (sell["timestamp"], sell["settlement_basis"]) == ("2024-03-27", "beyond_loaded_data")
+ adj = prep["ar_cedear_ratio_adjustments"][0]
+ assert adj["rescaled_prior_bars"] is True and adj["credit_date"] == "2024-01-26"
+ equity = pd.read_csv(run_dir / "artifacts" / "equity.csv", index_col=0)["equity"]
+ assert abs(equity.loc["2024-01-24"] / equity.loc["2024-01-23"] - 1) < 0.05 # no -50% step
+ _closes_on_cash(ledger, metrics)
+
+
+def test_aapl_without_the_ratio_change_fails_closed(tmp_path, monkeypatch):
+ frame = _frame("2024-01-02", "2024-03-27", 25000.0, 0.0, ex="2024-01-24", factor=0.5)
+ instrument = {**AAPL, "ratio_history": AAPL["ratio_history"][:1]}
+ config = _config(["AAPL.BA"], "2024-01-02", "2024-03-27", ar_instruments={"AAPL.BA": instrument})
+ with pytest.raises(ValueError, match="unexplained price discontinuities on 2024-01-24"):
+ _run(tmp_path, monkeypatch, config, {"AAPL.BA": frame})
+
+
[email protected]("mode", ["hold", "rebalance"])
+def test_composite_matches_the_standalone_engine(tmp_path, monkeypatch, mode):
+ monkeypatch.setattr(ArgentinaEquityEngine, "describe_instrument", staticmethod(NAMES.get))
+ frames = {"YPFD.BA": _frame("2024-06-03", "2024-09-30", 2900.0, -0.002),
+ "GGAL.BA": _frame("2024-06-03", "2024-09-30", 3500.0, 0.004)}
+ codes = ["YPFD.BA", "GGAL.BA"]
+ config = _config(codes, "2024-06-01", "2024-09-30", position_adjustment=mode)
+
+ class Loader:
+ def fetch(self, codes, *a, **k):
+ return {c: frames[c].copy() for c in codes}
+
+ namespace: dict = {}
+ exec(compile(ROTATE, "signal_engine.py", "exec"), namespace) # noqa: S102 - test fixture
+ results = []
+ for engine in (ArgentinaEquityEngine(config), CompositeEngine(config, codes)):
+ with redirect_stdout(io.StringIO()):
+ metrics = engine.run_backtest(config, Loader(), namespace["SignalEngine"](), tmp_path / type(engine).__name__)
+ results.append(([(f.symbol, f.action, str(f.timestamp.date()), f.signed_quantity, f.fee)
+ for f in engine.fill_records], metrics["total_return"]))
+ assert results[0] == results[1]
diff --git a/agent/tests/test_argentina_equity_engine.py b/agent/tests/test_argentina_equity_engine.py
new file mode 100644
index 000000000..84898653b
--- /dev/null
+++ b/agent/tests/test_argentina_equity_engine.py
@@ -0,0 +1,248 @@
+"""BYMA engine rules: configuration, units, settlement in sessions, netting,
+terminal close, CEDEAR credit window and price basis. Synthetic data only."""
+
+from __future__ import annotations
+
+from datetime import date
+from decimal import Decimal
+from types import SimpleNamespace
+
+import pandas as pd
+import pytest
+
+from backtest.engines.argentina_equity import (
+ classify_short_name,
+ discontinuities,
+ equity_tick,
+ reconcile_ratio_changes,
+)
+from backtest.engines.argentina_equity import (
+ ArgentinaEquityEngine,
+ argentina_available_cash,
+ argentina_sell_allowed,
+ normal_cash_lag,
+)
+
+SHARE = {"kind": "share"}
+RATIO = [{"effective_date": "2010-06-24", "ratio": "10"},
+ {"effective_date": "2024-01-24", "ratio": "20", "credit_date": "2024-01-26"}]
+CEDEAR = {"kind": "cedear", "underlying": "AAPL", "ratio_history": RATIO}
+
+
+def _bars(days, closes, volume=1000.0):
+ frame = pd.DataFrame({"open": closes, "high": closes, "low": closes, "close": closes,
+ "volume": [volume] * len(days)}, index=pd.DatetimeIndex(days))
+ frame.attrs["quote_currency"] = "ARS"
+ return frame
+
+
+def _fill(symbol, action, bar_idx, day, qty, price=100.0, fee=0.0):
+ return SimpleNamespace(symbol=symbol, action=action, bar_idx=bar_idx,
+ timestamp=pd.Timestamp(day), signed_quantity=qty,
+ execution_price=price, fee=fee)
+
+
+def _engine(instruments=None, **config):
+ engine = ArgentinaEquityEngine({"initial_cash": 1000, **config,
+ "ar_instruments": instruments or {"YPFD.BA": SHARE}})
+ engine.describe_instrument = lambda symbol: None
+ return engine
+
+
+def _prepared(instruments, frames, **config):
+ engine = _engine(instruments, **config)
+ engine.prepare_market_data(frames)
+ return engine
+
+
+# ── configuration ──
+
+def test_configuration_problems_are_reported_together():
+ with pytest.raises(ValueError) as err:
+ ArgentinaEquityEngine({"ar_instruments": {
+ "YPFD.BA": {"kind": "acciones", "lot_size": 0},
+ "AAPL.BA": {"kind": "cedear"},
+ "GGALD.BA": {"kind": "share", "currency": "USD"},
+ }})
+ message = str(err.value)
+ for expected in ("YPFD.BA.kind must be", "YPFD.BA.lot_size must be", "AAPL.BA.underlying is required",
+ "AAPL.BA.ratio_history", "GGALD.BA.currency: only ARS", 'do not set "engine"'):
+ assert expected in message
+
+
+def test_long_only_and_cost_validation():
+ with pytest.raises(ValueError, match="long-only"):
+ ArgentinaEquityEngine({"allow_short": True})
+ with pytest.raises(ValueError, match="finite nonnegative"):
+ ArgentinaEquityEngine({"ar_fixed_fee": -1})
+
+
+def test_generic_commission_is_the_brokerage_rate_unless_declared():
+ assert ArgentinaEquityEngine({"commission": 0.001}).fee_basis["brokerage_source"] == "commission"
+ engine = ArgentinaEquityEngine({"commission": 0.001, "ar_brokerage_rate": 0.002})
+ assert engine.brokerage_rate == 0.002
+ assert ArgentinaEquityEngine({}).fee_basis["brokerage_source"] == "none configured"
+
+
+def test_undeclared_cedear_and_unknown_kind_fail_closed():
+ days = ["2024-06-03", "2024-06-04"]
+ engine = ArgentinaEquityEngine({})
+ engine.describe_instrument = lambda s: "APPLE INC CEDEAR(REPR 1/20 SHR)"
+ with pytest.raises(ValueError, match="names a CEDEAR"):
+ engine.prepare_market_data({"AAPL.BA": _bars(days, [1.0, 1.0])})
+ engine.describe_instrument = lambda s: "STATE ST SPDR S&P 500 ETF TR CE"
+ with pytest.raises(ValueError, match="may be truncated"):
+ engine.prepare_market_data({"SPY.BA": _bars(days, [1.0, 1.0])})
+
+
+# ── units ──
+
[email protected]("price,tick", [("1", "0.001"), ("1.01", "0.005"), ("250", "0.25"),
+ ("26000", "25.00"), ("50000.01", "50.00")])
+def test_tick_bands(price, tick):
+ assert equity_tick(Decimal(price)) == Decimal(tick)
+
+
+def test_lots_and_ticks_are_real_certificates_before_a_ratio_change():
+ days = ["2024-01-22", "2024-01-23", "2024-01-24", "2024-01-25"]
+ engine = _prepared({"AAPL.BA": CEDEAR}, {"AAPL.BA": _bars(days, [25000.0, 25000.0, 12500.0, 12500.0])})
+ engine._active_symbol = "AAPL.BA"
+ engine._bar_ts = pd.Timestamp("2024-01-23")
+ assert engine.round_size(9.9, 12500.0) == 8.0 # 4 real certificates = 8 units
+ assert engine.apply_slippage(12500.15, 1) == pytest.approx(12512.5) # real tick 25 / 2
+ engine._bar_ts = pd.Timestamp("2024-01-24")
+ assert engine.round_size(9.9, 12500.0) == 9.0
+ assert engine.calc_commission(8, 12500.0, 1, True) == engine.calc_commission(4, 25000.0, 1, True)
+
+
+# ── settlement in observed sessions ──
+
+def test_settlement_lag_switches_to_t1_on_2024_05_27():
+ assert normal_cash_lag(date(2024, 5, 24)) == 2
+ assert normal_cash_lag(date(2024, 5, 27)) == 1
+
+
[email protected]("day,lag", [("2024-05-20", 2), ("2024-06-03", 1)])
+def test_shares_wait_for_their_settlement_session(day, lag):
+ engine = _engine()
+ engine.positions["YPFD.BA"] = object()
+ engine.fill_records = [_fill("YPFD.BA", "open", 5, day, 10)]
+ for bars_later in range(lag + 1):
+ engine._bar_idx = 5 + bars_later
+ assert argentina_sell_allowed(engine, engine, "YPFD.BA", pd.Timestamp(day)) is (bars_later >= lag)
+
+
+def test_a_scale_in_restarts_the_hold():
+ engine = _engine()
+ engine.positions["YPFD.BA"] = object()
+ engine.fill_records = [_fill("YPFD.BA", "open", 0, "2024-06-03", 10),
+ _fill("YPFD.BA", "increase", 3, "2024-06-06", 5)]
+ engine._bar_idx = 3
+ assert not argentina_sell_allowed(engine, engine, "YPFD.BA", pd.Timestamp("2024-06-06"))
+ engine._bar_idx = 4
+ assert argentina_sell_allowed(engine, engine, "YPFD.BA", pd.Timestamp("2024-06-07"))
+
+
+def test_buying_power_excludes_only_sales_settling_after_the_purchase():
+ engine = _engine()
+ engine.capital = 2000.0
+ # T+2 sale on bar 4 (settles bar 6); a T+1 purchase on bar 5 settles bar 6: usable.
+ engine.fill_records = [_fill("YPFD.BA", "close", 4, "2024-05-24", -10)]
+ engine._bar_idx = 5
+ assert argentina_available_cash(engine, engine, pd.Timestamp("2024-05-27")) == 2000.0
+ # A T+1 sale and a T+1 purchase on the same bar settle together: usable.
+ engine._bar_idx = 3
+ engine.fill_records = [_fill("YPFD.BA", "close", 3, "2024-06-03", -10, fee=1.0)]
+ assert argentina_available_cash(engine, engine, pd.Timestamp("2024-06-03")) == 2000.0
+ # A sale settling on bar 5 cannot fund a purchase settling on bar 4.
+ engine.fill_records = [_fill("YPFD.BA", "close", 3, "2024-05-23", -10, fee=1.0)]
+ assert argentina_available_cash(engine, engine, pd.Timestamp("2024-06-03")) == pytest.approx(2000 - 999)
+
+
+def test_credit_window_holds_a_position_through_the_ex_date():
+ """Synthetic T+1-era change (not an official event): ex Wed 2025-03-19,
+ credit Fri 03-21. An ex-date sale's earliest settlement is 03-20: held."""
+ engine = _engine({"SYN.BA": {**CEDEAR, "ratio_history": [
+ {"effective_date": "2020-01-02", "ratio": "10"},
+ {"effective_date": "2025-03-19", "ratio": "20", "credit_date": "2025-03-21"}]}})
+ engine.ratio_adjustments = [{"symbol": "SYN.BA", "effective_date": "2025-03-19",
+ "credit_date": "2025-03-21", "old_ratio": 10.0, "new_ratio": 20.0}]
+ engine.positions["SYN.BA"] = object()
+ engine.fill_records = [_fill("SYN.BA", "open", 0, "2025-03-17", 10)]
+ engine._bar_idx = 2
+ assert not argentina_sell_allowed(engine, engine, "SYN.BA", pd.Timestamp("2025-03-19"))
+ engine._bar_idx = 3
+ assert argentina_sell_allowed(engine, engine, "SYN.BA", pd.Timestamp("2025-03-20"))
+
+
+def test_terminal_close_keeps_an_unsettled_position_open(tmp_path):
+ days = ["2024-06-03", "2024-06-04"]
+ engine = _engine()
+
+ class Loader:
+ def fetch(self, *a, **k):
+ return {"YPFD.BA": _bars(days, [100.0, 100.0])}
+
+ class Signal:
+ def generate(self, data_map):
+ return {"YPFD.BA": pd.Series([1.0, 1.0], index=data_map["YPFD.BA"].index)}
+
+ import io
+ from contextlib import redirect_stdout
+ with redirect_stdout(io.StringIO()):
+ metrics = engine.run_backtest({"codes": ["YPFD.BA"], "start_date": days[0], "end_date": days[-1],
+ "initial_cash": 1000, "source": "local"}, Loader(), Signal(), tmp_path)
+ assert [f.action for f in engine.fill_records] == ["open"] # bought 06-04, no same-day exit
+ assert metrics["ar_unliquidated_position_count"] == 1
+ assert engine.equity_snapshots[-1].positions == 1
+
+
+# ── price basis ──
+
[email protected]("name,kind", [("YPF SOCIEDAD ANONIMA", "share"),
+ ("APPLE INC CEDEAR(REPR 1/20 SHR)", "cedear"),
+ ("STATE ST SPDR S&P 500 ETF TR CE", None), (None, None)])
+def test_vendor_classification(name, kind):
+ assert classify_short_name(name)[0] == kind
+
+
+def test_ratio_change_rescaling_and_ambiguity():
+ days = ["2024-01-22", "2024-01-23", "2024-01-24", "2024-01-25"]
+ raw = _bars(days, [25000.0, 25000.0, 12500.0, 12500.0])
+ adjusted, events = reconcile_ratio_changes(raw, "AAPL.BA", RATIO)
+ assert events[0]["rescaled_prior_bars"] and adjusted["close"].tolist() == [12500.0] * 4
+ _, again = reconcile_ratio_changes(adjusted, "AAPL.BA", RATIO)
+ assert not again[0]["rescaled_prior_bars"]
+ with pytest.raises(ValueError, match="not provable"):
+ reconcile_ratio_changes(raw, "AAPL.BA", [RATIO[0], {**RATIO[1], "price_series": "adjusted"}])
+ small = [RATIO[0], {"effective_date": "2024-01-24", "ratio": "11", "credit_date": "2024-01-26"}]
+ with pytest.raises(ValueError, match="not provable"):
+ reconcile_ratio_changes(_bars(days, [100.0] * 4), "AAPL.BA", small)
+
+
+def test_discontinuity_bands_allow_real_crashes_but_not_unadjusted_splits():
+ days = ["2019-08-08", "2019-08-09", "2019-08-12"]
+ assert discontinuities(_bars(days, [174.55, 174.55, 92.4]), 0.75) == []
+ assert discontinuities(_bars(days, [8000.0, 8000.0, 800.0]), 0.75) == ["2019-08-12"]
+
+
+def test_currency_must_be_declared_ars():
+ frame = _bars(["2024-06-03"], [1.0])
+ frame.attrs = {}
+ with pytest.raises(ValueError, match="no quote currency"):
+ _engine().prepare_market_data({"YPFD.BA": frame})
+
+
+def test_only_dates_nobody_traded_are_dropped():
+ days = ["2024-06-19", "2024-06-20", "2024-06-24"]
+ ypfd = _bars(days, [100.0, 100.0, 101.0])
+ ypfd.loc["2024-06-20", "volume"] = 0.0 # holiday placeholder
+ ggal = _bars(days, [50.0, 50.0, 51.0])
+ ggal.loc["2024-06-20", "volume"] = 0.0
+ ggal.loc["2024-06-24", "volume"] = 0.0 # illiquid on an open day
+ engine = _engine({"YPFD.BA": SHARE, "GGAL.BA": SHARE})
+ prepared = engine.prepare_market_data({"YPFD.BA": ypfd, "GGAL.BA": ggal})
+ assert engine.dropped_no_trade_dates == ["2024-06-20"]
+ assert list(prepared["GGAL.BA"].index.strftime("%Y-%m-%d")) == ["2024-06-19", "2024-06-24"]
+ stale = prepared["GGAL.BA"].loc["2024-06-24"]
+ assert not engine.can_execute("GGAL.BA", 1, stale) # zero volume: not executable
diff --git a/agent/tests/test_argentina_market_routing.py b/agent/tests/test_argentina_market_routing.py
index 68029e680..898aaf744 100644
--- a/agent/tests/test_argentina_market_routing.py
+++ b/agent/tests/test_argentina_market_routing.py
@@ -32,6 +32,12 @@ def test_argentina_fallback_chain_is_yahoo_first() -> None:
assert FALLBACK_CHAINS["ar_equity"] == ["yahoo", "yfinance", "local"]
-def test_argentina_backtest_fails_closed_until_execution_rules_exist() -> None:
- with pytest.raises(ValueError, match="Argentina backtest execution rules are not modeled"):
- _create_market_engine("yahoo", {}, ["GGAL.BA"])
+def test_argentina_backtest_routes_to_the_byma_engine() -> None:
+ from backtest.engines.argentina_equity import ArgentinaEquityEngine
+
+ assert isinstance(_create_market_engine("yahoo", {}, ["GGAL.BA"]), ArgentinaEquityEngine)
+
+
+def test_ba_codes_cannot_share_a_composite_pool_with_other_markets() -> None:
+ with pytest.raises(ValueError, match="cannot share a composite pool"):
+ _create_market_engine("yahoo", {}, ["GGAL.BA", "AAPL.US"])
diff --git a/agent/tests/test_yfinance_declared_currency.py b/agent/tests/test_yfinance_declared_currency.py
new file mode 100644
index 000000000..f4a756612
--- /dev/null
+++ b/agent/tests/test_yfinance_declared_currency.py
@@ -0,0 +1,72 @@
+"""yfinance's declared-currency probe must read the metadata Mapping it returns.
+
+yfinance 1.x (1.7.0 is the locked version) returns ``history_metadata`` as a
+lazy ``HistoryMetadata`` Mapping, not a dict. The probe used to require a
+dict, so every LSE/BYMA/TSX symbol read as "no currency" and the yfinance
+path rejected them all. Existing loader tests stub ``_declared_currency``
+itself, which is why that went unseen.
+"""
+
+from collections.abc import Mapping
+
+import pandas as pd
+import pytest
+
+import backtest.loaders.yfinance_loader as yfl
+
+
+class _LazyMetadata(Mapping):
+ """Stand-in for yfinance.scrapers.history.HistoryMetadata."""
+
+ def __init__(self, data):
+ self._data = data
+
+ def __getitem__(self, key):
+ return self._data[key]
+
+ def __iter__(self):
+ return iter(self._data)
+
+ def __len__(self):
+ return len(self._data)
+
+
+class _Ticker:
+ metadata: Mapping = _LazyMetadata({})
+
+ def __init__(self, symbol):
+ self.symbol = symbol
+
+ @property
+ def history_metadata(self):
+ return self.metadata
+
+
[email protected]("currency", ["ARS", "GBp", "CAD"])
+def test_declared_currency_reads_a_non_dict_mapping(monkeypatch, currency):
+ monkeypatch.setattr(_Ticker, "metadata", _LazyMetadata({"currency": currency}))
+ monkeypatch.setattr(yfl.yf, "Ticker", _Ticker)
+ assert yfl._declared_currency("YPFD.BA") == currency
+
+
[email protected]("metadata", [_LazyMetadata({}), _LazyMetadata({"currency": ""}), None, "ARS"])
+def test_missing_or_unusable_currency_is_still_none(monkeypatch, metadata):
+ monkeypatch.setattr(_Ticker, "metadata", metadata)
+ monkeypatch.setattr(yfl.yf, "Ticker", _Ticker)
+ assert yfl._declared_currency("YPFD.BA") is None
+
+
+def test_byma_fetch_succeeds_with_mapping_metadata(monkeypatch):
+ monkeypatch.delenv("VIBE_TRADING_DATA_CACHE", raising=False)
+ index = pd.DatetimeIndex(["2024-05-27", "2024-05-28"])
+ bars = pd.DataFrame(
+ {"Open": [1.0, 2.0], "High": [1.0, 2.0], "Low": [1.0, 2.0],
+ "Close": [1.0, 2.0], "Volume": [10, 20]},
+ index=index,
+ )
+ monkeypatch.setattr(yfl, "_download_history", lambda *a, **k: bars.copy())
+ monkeypatch.setattr(_Ticker, "metadata", _LazyMetadata({"currency": "ARS"}))
+ monkeypatch.setattr(yfl.yf, "Ticker", _Ticker)
+ frame = yfl.DataLoader().fetch(["YPFD.BA"], "2024-05-27", "2024-05-28")["YPFD.BA"]
+ assert frame.attrs["quote_currency"] == "ARS"
+ assert list(frame["close"]) == [1.0, 2.0]