Skip to content

"Vibe-Trading: Your Personal Trading Agent"

Merge PR #2071: add BYMA rules with declared tick versions and correct resale eligibility

Haozhe Wue0955ffaaf98
diff --cc agent/backtest/engines/argentina_equity.py
index 000000000,c9920f54d..50bf3a117
mode 000000,100644..100644
--- a/agent/backtest/engines/argentina_equity.py
+++ b/agent/backtest/engines/argentina_equity.py
@@@ -1,0 -1,695 +1,941 @@@
+ """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.
++ - Normal settlement is not a holding-period restriction: acquired shares
++ may be resold before settlement. CEDEAR credit-date restrictions still
++ bind both signal exits and terminal liquidation.
+ - 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:
++ - Ticks: a declared Circular 3569 table version/panel, or a fixed tick
++ (rounded against the trader). No panel membership or effective date is
++ inferred. 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);
++Declare ``ar_tick_table`` as ``2024-07-04``, ``2025-09-08-leader`` or
++``2025-09-08-general`` (or an instrument-specific ``tick_table`` / ``tick_size``).
++Select the table and panel applicable to the simulated window; split a window
++when its rule changes. Local shares need no kind entry (Yahoo 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")
++_TICK_TABLES = {
++ "2024-07-04": (_TICK_BANDS, _TICK_ABOVE),
++ "2025-09-08-leader": (
++ tuple(
++ (Decimal(p), Decimal(t))
++ for p, t in (
++ ("1", ".001"),
++ ("5", ".005"),
++ ("50", ".01"),
++ ("100", ".10"),
++ ("500", ".25"),
++ ("1000", ".50"),
++ ("2500", "1"),
++ ("5000", "2.5"),
++ ("10000", "5"),
++ ("25000", "10"),
++ ("50000", "20"),
++ )
++ ),
++ Decimal("25"),
++ ),
++ "2025-09-08-general": (
++ tuple(
++ (Decimal(p), Decimal(t))
++ for p, t in (
++ ("1", ".001"),
++ ("5", ".005"),
++ ("10", ".01"),
++ ("25", ".05"),
++ ("50", ".10"),
++ ("100", ".20"),
++ ("400", ".50"),
++ ("800", "1"),
++ ("1000", "2.5"),
++ ("5000", "5"),
++ ("10000", "10"),
++ ("25000", "25"),
++ )
++ ),
++ Decimal("50"),
++ ),
++}
+
+ # 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:
++def equity_tick(price: Decimal, table: str = "2024-07-04") -> Decimal:
++ """Minimum price change at *price* under an explicitly selected table."""
++ bands, above = _TICK_TABLES[table]
++ for upper, tick in bands:
+ if price <= upper:
+ return tick
- return _TICK_ABOVE
++ return 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'")
++ 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)"
++ provenance.setdefault(
++ "tick_size",
++ (
++ f"declared table {info.get('tick_table')}"
++ 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")
++ 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)
++ 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,
- })
++ 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]
++ 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)
++ 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):
++ if config.get("leverage", 1.0) != 1.0:
++ raise ValueError("ArgentinaEquityEngine is cash-only; leverage must be 1")
+ 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'.")
++ 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.tick_table = config.get("ar_tick_table")
++ if self.tick_table is not None and self.tick_table not in _TICK_TABLES:
++ raise ValueError(f"ar_tick_table must be one of {tuple(_TICK_TABLES)}")
+ 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"
++ 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"
++ 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.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,
++ "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))
++ 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)
++ )
++ for name, value in (
++ ("ar_max_cedear_move", self.max_cedear_move),
++ ("ar_max_share_move", self.max_share_move),
++ ):
++ if not math.isfinite(value) or not 0 < value < 1:
++ raise ValueError(f"{name} must be finite and between 0 and 1")
+
+ # ── 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]:
++ 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)
++ symbol,
++ {
++ **({"tick_table": self.tick_table} if self.tick_table else {}),
++ **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.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)
++ 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")
++ "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
++ 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")
++ + (
++ "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"]))
++ 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)
++ 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:
++ 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
++ 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)))
++ 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
++ tick = (
++ info["tick_size"] or equity_tick(slipped * scale, info["tick_table"])
++ ) / 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."""
++
++def argentina_sell_allowed(
++ state: BaseEngine, rules: ArgentinaEquityEngine, symbol: str, timestamp: Any
++) -> bool:
++ """Acquired shares may be resold; additional certificates must be credited."""
+ 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"]):
++ 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:
++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)
++ 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."""
++def argentina_can_execute(
++ state: BaseEngine,
++ rules: ArgentinaEquityEngine,
++ symbol: str,
++ direction: int,
++ bar: pd.Series,
++) -> bool:
++ """Long only, a traded bar, and CEDEAR credit protection 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):
++ 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)
++ 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))
++ 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),
- })
++ 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]:
++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]")
++ tick = (
++ f"declared table {info['tick_table']}"
++ 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]")
++ 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_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_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_terminal_equity_basis": (
++ "credit-restricted 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:
++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)
++ 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")
++ 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.')
++ 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"}]}}. Declare ar_tick_table or per-instrument tick_table/tick_size. Local shares need no kind 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:
++ parsed_tick = Decimal(str(info["tick_size"]))
++ if not parsed_tick.is_finite() or not parsed_tick > 0:
+ raise ArithmeticError
+ except (ValueError, ArithmeticError):
- problems.append(f"{symbol}.tick_size must be a positive number (omit it for BYMA bands)")
++ problems.append(
++ f"{symbol}.tick_size must be a positive number (omit it for BYMA bands)"
++ )
++ elif require and info.get("tick_table") not in _TICK_TABLES:
++ problems.append(
++ f"{symbol}: declare tick_size, tick_table or global ar_tick_table from {tuple(_TICK_TABLES)}; panel membership and historical tick rules are not inferred"
++ )
++ if info.get("tick_table") is not None and info["tick_table"] not in _TICK_TABLES:
++ problems.append(f"{symbol}.tick_table must be one of {tuple(_TICK_TABLES)}")
+ 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
++ 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")
++ 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")
++ 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'")
++ problems.append(
++ f"{symbol}: price_series must be 'adjusted' or 'unadjusted'"
++ )
+ break
+ previous = effective
+ return problems
diff --cc agent/backtest/runner.py
index 414435398,7bb1fa94a..9d29b1e06
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@@ -1816,14 -1819,13 +1819,14 @@@ def _select_market_engine(source: 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,
++ # currency, lot, tick and dated CEDEAR ratios), reporting observed-session
++ # settlement as an approximation rather than an official 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 --cc agent/src/skills/strategy-generate/SKILL.md
index cf323450d,97b2dbcca..a231fe56c
--- a/agent/src/skills/strategy-generate/SKILL.md
+++ b/agent/src/skills/strategy-generate/SKILL.md
@@@ -167,8 -167,8 +167,9 @@@ Self-check after writing `signal_engine
- `artifact_id`: optional. Set it only when the run benches an artifact registered with `sdm_register`; the backtest then records its metrics in that artifact's bench history. `bench_type` (`"initial"` / `"periodic"` / `"manual"`, default `"manual"`) states whether the run counts towards decay monitoring, which reads only `initial` and `periodic` runs. Omit both for exploratory runs.
- `initial_cash`: default 1,000,000
- `commission`: default 0.1%
+- Crypto: `commission` sets both fee sides unless `maker_rate` / `taker_rate` explicitly override that side. Bare spot pairs such as `BTC-USDT` do not pay funding by default. `-PERP`, `-SWAP`, CCXT settled contract codes and strict perpetual mode retain funding; a nonzero explicit `funding_rate` also opts a bare pair into a perpetual proxy assumption. `crypto_funding_pnl` in metrics reports the signed funding actually applied, separately from trade P&L.
- `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).
++- Argentina (BYMA `.BA` codes, e.g. `"YPFD.BA"`): use `"source": "yahoo"` and keep `"engine": "daily"`; `.BA` codes select the BYMA engine. Local shares can take their kind from Yahoo's descriptor (ARS, one-share lots as an assumption). Declare `ar_tick_table` as `"2024-07-04"`, `"2025-09-08-leader"` (leader panel / CEDEARs) or `"2025-09-08-general"`, or an instrument-specific `tick_table` / positive `tick_size`. These are explicit rule assumptions: choose the applicable table/panel for the window and split runs across rule changes; panel membership and effective dates are not inferred. `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. Settlement is not a ban on reselling acquired shares; CEDEAR credit dates still restrict exits, including terminal liquidation. `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 --cc agent/tests/test_argentina_backtests.py
index 000000000,cf9a41702..e10ad1248
mode 000000,100644..100644
--- a/agent/tests/test_argentina_backtests.py
+++ b/agent/tests/test_argentina_backtests.py
@@@ -1,0 -1,196 +1,307 @@@
+ """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"}
++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('''
++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 = [
++ 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 = 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))
++ 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
++ 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}
++ return {
++ "source": "yahoo",
++ "codes": codes,
++ "start_date": start,
++ "end_date": end,
++ "initial_cash": 1_000_000,
++ "commission": 0.001,
++ "engine": "daily",
++ "ar_tick_table": "2024-07-04",
++ **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")
++ 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 (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)
+
+
+ @pytest.mark.parametrize("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)
++ 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 ("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["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 (
++ 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"}]}
++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})
++ 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 (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")
++ 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
++ 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)
++ 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"):
++ 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})
+
+
+ @pytest.mark.parametrize("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)}
++ 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
++ 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"]))
++ 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 --cc agent/tests/test_argentina_equity_engine.py
index 000000000,84898653b..548b78f4e
mode 000000,100644..100644
--- a/agent/tests/test_argentina_equity_engine.py
+++ b/agent/tests/test_argentina_equity_engine.py
@@@ -1,0 -1,248 +1,440 @@@
+ """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"}]
++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 = 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)
++ 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 = ArgentinaEquityEngine(
++ {
++ "initial_cash": 1000,
++ "ar_tick_table": "2024-07-04",
++ **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"},
- }})
++ 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"'):
++ 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"
++ 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")])
++
++ "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 = _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
++ 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)
++ 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
+
+
+ @pytest.mark.parametrize("day,lag", [("2024-05-20", 2), ("2024-06-03", 1)])
-def test_shares_wait_for_their_settlement_session(day, lag):
++def test_normal_settlement_does_not_forbid_reselling_acquired_shares(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)
++ assert argentina_sell_allowed(engine, engine, "YPFD.BA", pd.Timestamp(day))
+
+
-def test_a_scale_in_restarts_the_hold():
++def test_a_scale_in_does_not_freeze_the_position():
+ 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.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"))
++ assert 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
++ 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
++ 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)
++ 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 = _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"))
++ 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):
++def test_terminal_close_can_sell_acquired_shares_before_settlement(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
++ 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", "close"]
++ assert metrics["ar_unliquidated_position_count"] == 0
++ assert engine.equity_snapshots[-1].positions == 0
++
++
++def test_terminal_close_preserves_the_cedear_credit_window(tmp_path):
++ days = ["2025-03-17", "2025-03-18", "2025-03-19"]
++ instrument = {
++ **CEDEAR,
++ "ratio_history": [
++ {"effective_date": "2020-01-02", "ratio": "10"},
++ {
++ "effective_date": "2025-03-19",
++ "ratio": "20",
++ "credit_date": "2025-03-21",
++ },
++ ],
++ }
++ engine = _engine({"SYN.BA": instrument})
++
++ class Loader:
++ def fetch(self, *args, **kwargs):
++ return {"SYN.BA": _bars(days, [100.0, 100.0, 50.0])}
++
++ class Signal:
++ def generate(self, data_map):
++ return {"SYN.BA": pd.Series(0.8, index=data_map["SYN.BA"].index)}
++
++ metrics = engine.run_backtest(
++ {
++ "codes": ["SYN.BA"],
++ "start_date": days[0],
++ "end_date": days[-1],
++ "initial_cash": 1000,
++ "position_adjustment": "hold",
++ "source": "local",
++ },
++ Loader(),
++ Signal(),
++ tmp_path,
++ )
++ assert [f.action for f in engine.fill_records] == ["open"]
+ assert metrics["ar_unliquidated_position_count"] == 1
+ assert engine.equity_snapshots[-1].positions == 1
++ assert metrics["final_value"] == pytest.approx(1000)
++
++
++ "table,price,tick",
++ [
++ ("2025-09-08-leader", "10.01", ".01"),
++ ("2025-09-08-leader", "1000.01", "1"),
++ ("2025-09-08-leader", "50000.01", "25"),
++ ("2025-09-08-general", "100.01", ".50"),
++ ("2025-09-08-general", "800.01", "2.5"),
++ ("2025-09-08-general", "50000", "50"),
++ ],
++)
++def test_versioned_tick_tables(table, price, tick):
++ assert equity_tick(Decimal(price), table) == Decimal(tick)
++
++
++def test_tick_table_is_declared_instead_of_guessing_panel_or_history():
++ frames = {"YPFD.BA": _bars(["2025-10-01"], [100.0])}
++ with pytest.raises(ValueError, match="tick_table"):
++ _engine(ar_tick_table=None).prepare_market_data(frames)
++ engine = _engine({"YPFD.BA": {**SHARE, "tick_size": "0.5"}}, ar_tick_table=None)
++ engine.prepare_market_data(frames)
++ engine._active_symbol = "YPFD.BA"
++ engine._bar_ts = pd.Timestamp("2025-10-01")
++ assert engine.apply_slippage(100.1, 1) == 100.5
++
++
[email protected]("value", ["NaN", "Infinity", "0", "-1"])
++def test_tick_must_be_positive_and_finite(value):
++ with pytest.raises(ValueError, match="tick_size"):
++ _engine({"YPFD.BA": {**SHARE, "tick_size": value}})
++
++
++def test_no_leverage_or_nonfinite_discontinuity_threshold():
++ with pytest.raises(ValueError, match="leverage"):
++ _engine(leverage=2)
++ for value in (float("nan"), float("inf"), 0, 1):
++ with pytest.raises(ValueError, match="ar_max_share_move"):
++ _engine(ar_max_share_move=value)
+
+
+ # ── 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)])
++
++ "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
++ 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"}]
++ 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"]
++ 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