Skip to content

"Vibe-Trading: Your Personal Trading Agent"

13.1 KB
Raw Blame
"""Global futures backtest engine (CME / ICE / Eurex).

Market rules:
  - Nearly 24x5 (CME Globex: Sun 17:00 - Fri 16:00 CT, daily pause 16:00-17:00)
  - Margin: initial + maintenance (exchange-set per contract)
  - Limit up/down: dynamic for equity index, fixed for commodities
  - Contract multiplier: per-product (ES=$50/pt, CL=$1000/bbl, GC=$100/oz)
  - Commission: per-contract ($1-3 per side typical)
  - Minimum unit: 1 contract
  - Roll/expiry: not modeled (assumes continuous front-month data)
"""

from __future__ import annotations

import logging
import re
from typing import Any, Dict, Mapping, TypeVar

import pandas as pd

from backtest.engines.china_a import _blocked_by_limit
from backtest.engines._market_hooks import strip_local_prefix
from backtest.engines.futures_base import FuturesBaseEngine

logger = logging.getLogger(__name__)

_T = TypeVar("_T")


# ── Contract multiplier (USD per point / per unit) ──

_MULTIPLIER: dict[str, float] = {
    # Equity index (CME)
    "ES": 50, "NQ": 20, "YM": 5, "RTY": 50,
    # Micro equity index
    "MES": 5, "MNQ": 2, "MYM": 0.5, "M2K": 5,
    # Energy (NYMEX)
    "CL": 1000, "NG": 10000, "RB": 42000, "HO": 42000,
    # Metals (COMEX)
    "GC": 100, "SI": 5000, "HG": 25000, "PL": 50, "PA": 100,
    # Micro metals
    "MGC": 10, "SIL": 1000,
    # Grains (CBOT)
    "ZC": 50, "ZS": 50, "ZW": 50, "ZM": 100, "ZL": 600, "ZR": 2000,
    # Bonds (CBOT)
    "ZB": 1000, "ZN": 1000, "ZF": 1000, "ZT": 2000,
    # Currencies (CME)
    "6E": 125000, "6J": 12500000, "6B": 62500, "6A": 100000, "6C": 100000,
    # Softs (ICE)
    "KC": 375, "SB": 1120, "CC": 10, "CT": 500, "OJ": 150,
    # Livestock (CME)
    "LE": 400, "HE": 400, "GF": 500,
    # Eurex
    "FESX": 10, "FDAX": 25, "FGBL": 1000,
}

#: Multiplier used when a product is absent from ``_MULTIPLIER``. It is ES's
#: own value, so an unlisted contract is priced as though it were an E-mini
#: future; the run records every such fallback under ``pricing_assumptions``.
_DEFAULT_MULTIPLIER = 50

# ── Margin per contract (approximate USD, initial margin) ──
# Reference table — future use for margin-call checks. Not yet consumed.

_MARGIN_PER_CONTRACT: dict[str, float] = {
    # Equity index
    "ES": 12650, "NQ": 17600, "YM": 8800, "RTY": 6600,
    "MES": 1265, "MNQ": 1760,
    # Energy
    "CL": 6270, "NG": 3300,
    # Metals
    "GC": 9950, "SI": 11000, "HG": 4400, "PL": 3300,
    "MGC": 995,
    # Grains
    "ZC": 1650, "ZS": 2200, "ZW": 1925,
    # Bonds
    "ZB": 4400, "ZN": 2200, "ZF": 1375,
    # Currencies
    "6E": 2475, "6J": 3300, "6B": 2750,
}

# ── Price limit (fraction of prev settlement) ──

_PRICE_LIMIT: dict[str, float] = {
    # Equity index: 7% (Level 1), simplified to single level
    "ES": 0.07, "NQ": 0.07, "YM": 0.07, "RTY": 0.07,
    "MES": 0.07, "MNQ": 0.07, "MYM": 0.07, "M2K": 0.07,
    # Energy: varies, typically ~$10-15 for CL
    # Not easily expressed as %, skip for most commodities
}

# ── Per-contract commission (USD, one side) ──

_COMMISSION_PER_CONTRACT: dict[str, float] = {
    "ES": 2.25, "NQ": 2.25, "YM": 2.25, "RTY": 2.25,
    "MES": 0.62, "MNQ": 0.62, "MYM": 0.62, "M2K": 0.62,
    "CL": 2.25, "NG": 2.25,
    "GC": 2.25, "SI": 2.25, "HG": 2.25,
    "MGC": 0.62,
    "ZC": 2.25, "ZS": 2.25, "ZW": 2.25,
    "ZB": 1.52, "ZN": 1.52, "ZF": 1.02,
    "6E": 2.25, "6J": 2.25, "6B": 2.25,
}
_DEFAULT_COMMISSION = 2.50


_MONTH_CODES = set("FGHJKMNQUVXZ")

# Every listed product, longest first: _extract_product resolves a symbol
# against this table BEFORE falling back to shape regexes, because the shapes
# alone are ambiguous. Three ways they fail: a digit inside the letters (M2K,
# M2KZ4) that no letters-only group can span, a product whose own last letter
# doubles as a month code (MYM, FESX, FDAX -> "MY" + M + 2503), and a product
# that is a prefix of another (SI vs SIL). Longest-match-first settles all
# three; a product NOT in this table still falls through to the regexes.
_KNOWN_PRODUCTS = frozenset(_MULTIPLIER)
_PRODUCTS_LONGEST_FIRST = tuple(sorted(_KNOWN_PRODUCTS, key=len, reverse=True))

#: Contract suffix left after stripping a listed product: a month code plus a
#: 1-4 digit year (Z4, F25, M2025), or a bare YYMM (2503).
_CONTRACT_SUFFIX_RE = re.compile(r"^(?:[FGHJKMNQUVXZ]\d{1,4}|\d{4})$")


def _listed_product_prefix(code: str) -> str | None:
    """Longest listed product that ``code`` starts with, if the rest is a
    contract suffix.

    Returns:
        The product code, or ``None`` when no listed product explains
        ``code`` (the caller then falls back to the shape regexes).
    """
    for product in _PRODUCTS_LONGEST_FIRST:
        if code.startswith(product) and _CONTRACT_SUFFIX_RE.match(code[len(product):]):
            return product
    return None


def _extract_product(symbol: str) -> str:
    """Extract product code from futures symbol.

    Handles CME conventions:
      - Product + month-code + year:  ESZ4, CLF25, GCM2025
      - Product + YYMM:              CL2412, NQ2503
      - Product.exchange:            ES.CME
      - Bare product:                ES

    CME currency futures (6E, 6J, 6B, 6A, 6C) start with a digit, so the
    product group also accepts a single leading digit followed by one
    letter (e.g. 6EZ4 -> 6E), on top of the plain 2-4 letter form.

    Shape alone is ambiguous, so a listed product always wins first:
    MYM2503 parses just as well as "MY" + June + year 2503 as it does as
    MYM + YYMM 2503, and M2K / M2KZ4 cannot be split by a letters-only
    group at all. ``_listed_product_prefix`` resolves both, longest match
    first (so SILZ4 is micro silver, not SI). Only a product missing from
    the multiplier table falls through to the shape regexes below.

    Args:
        symbol: Futures symbol string.

    Returns:
        Product code (e.g. 'ES', 'CL', 'GC', '6E', 'M2K').
    """
    code = strip_local_prefix(symbol).split(".")[0].upper()
    if code.endswith("=F"):
        # Yahoo's explicit continuous-contract suffix already identifies the
        # complete product, including digit-bearing names such as M2K/M6E.
        return code[:-2]

    if code in _KNOWN_PRODUCTS:
        return code

    listed = _listed_product_prefix(code)
    if listed is not None:
        return listed

    # Pattern 1: product + month-code + year (ESZ4, CLF25, GCM2025, 6EZ4)
    m = re.match(r"([A-Z0-9]{1,5})([FGHJKMNQUVXZ])(\d{1,4})$", code)
    if m:
        return m.group(1)

    # Pattern 2: product + YYMM (NQ2503, CL2412, 6EH25)
    m = re.match(r"([A-Z0-9]{1,5})(\d{4})$", code)
    if m:
        return m.group(1)

    # Pattern 3: bare product or fallback
    m = re.fullmatch(r"[A-Z0-9]{1,5}", code)
    return m.group(0) if m else code


class GlobalFuturesEngine(FuturesBaseEngine):
    """International futures engine (CME/CBOT/NYMEX/COMEX/ICE/Eurex).

    Config keys:
      - slippage: default 0.0003
      - commission_per_contract: override, default varies by product

    A product absent from the multiplier or commission table is not an error:
    it is silently priced on a generic constant (50, ES's own multiplier, and
    $2.50). The run reports every such fallback under ``pricing_assumptions``
    so a default cannot pass for data (#1393's failure class). Sizing is the
    same kind of assumption with no product table to look it up in, so the
    fixed leverage default is recorded there too, under product ``"*"``.
    """

    def __init__(self, config: dict):
        # Leverage: most futures have 5-15% margin → 7-20x leverage.
        # Price is unknown at init, so use a reasonable fixed default.
        # User can override via config["leverage"].
        # (product, field) -> the generic constant this run was priced on. A
        # product missing from a table does not fail, it silently takes a
        # default, so the run has to say which numbers were assumed rather
        # than looked up. Recording only: this recorder changes no value.
        self._pricing_defaults: dict[tuple[str, str], Any] = {}
        if "leverage" in config:
            leverage = config["leverage"]
        else:
            # Sizing has no product table: 10.0 is assumed, not looked up.
            leverage = 10.0
            self._pricing_defaults[("*", "leverage")] = leverage
        config = {**config, "leverage": leverage}
        super().__init__(config)
        # Futures bands come off the previous settlement, not the previous close.
        self.base_price_fields = ("pre_settle", "pre_close")
        self.slippage_rate: float = config.get("slippage", 0.0003)
        self._comm_override = config.get("commission_per_contract")

    def _priced(
        self,
        table: Mapping[str, _T],
        product: str,
        default: _T,
        field: str,
    ) -> _T:
        """Look a product up, recording the miss when it falls back.

        A product absent from one of the tables is priced on a generic
        constant that looks exactly like data in the output -- for example an
        unlisted contract is sized on ES's multiplier of 50. This returns the
        same value the plain ``table.get(product, default)`` returned before
        and additionally remembers the miss, so the run can state which of its
        numbers were assumed.

        Args:
            table: One of the product tables in this module.
            product: Product code as ``_extract_product`` spells it.
            default: The generic constant used when the product is absent.
            field: Name of the field, as reported in ``pricing_assumptions``.

        Returns:
            The table entry, or ``default`` when the product is not listed.
        """
        if product in table:
            return table[product]
        key = (product, field)
        if key not in self._pricing_defaults:
            self._pricing_defaults[key] = default
            logger.warning(
                "Global futures product %r has no %s entry; pricing it on the "
                "generic default %r. The backtest reports this under "
                "pricing_assumptions.",
                product,
                field,
                default,
            )
        return default

    def _engine_diagnostics(self) -> Dict[str, Any]:
        """Report every table lookup this run priced on a generic default."""
        if not self._pricing_defaults:
            return {}
        return {
            "pricing_assumptions": [
                {"product": product, "field": field, "value": value}
                for (product, field), value in sorted(self._pricing_defaults.items())
            ]
        }

    def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:
        """Global futures: T+0, both directions, limit checks for equity index.

        Args:
            symbol: Futures symbol.
            direction: 1 (long), -1 (short), 0 (close).
            bar: Current bar data.

        Returns:
            True if allowed.
        """
        product = _extract_product(symbol)
        limit = _PRICE_LIMIT.get(product)
        if limit is None:
            return True  # no price limit for most commodities

        # Tested at execution time (see _blocked_by_limit).
        pos = self.positions.get(symbol) if direction == 0 else None
        if pos is None and direction == 0:
            return True
        return not _blocked_by_limit(
            self,
            symbol,
            direction,
            bar,
            limit,
            position_direction=pos.direction if pos is not None else None,
        )

    def round_size(self, raw_size: float, price: float) -> float:
        """Integer contracts, minimum 1."""
        return max(int(raw_size), 0)

    def calc_commission(self, size: float, price: float, _direction: int, is_open: bool) -> float:
        """Per-contract fixed commission (uses _active_symbol for product lookup).

        ``_direction`` is unused — reserved for future borrow/financing
        asymmetry on short positions.
        """
        if self._comm_override is not None:
            return size * self._comm_override
        return self.calc_commission_for_symbol(self._active_symbol, size, price, is_open)

    def calc_commission_for_symbol(
        self, symbol: str, size: float, price: float, is_open: bool,
    ) -> float:
        """Symbol-aware commission.

        Args:
            symbol: Futures code.
            size: Number of contracts.
            price: Execution price (unused — fixed per-lot).
            is_open: Opening or closing.

        Returns:
            Commission in USD.
        """
        product = _extract_product(symbol)
        rate = self._priced(
            _COMMISSION_PER_CONTRACT, product, _DEFAULT_COMMISSION, "commission"
        )
        return size * rate

    def apply_slippage(self, price: float, direction: int) -> float:
        """Slippage model for liquid global futures."""
        return price * (1 + direction * self.slippage_rate)

    def get_contract_multiplier(self, symbol: str) -> float:
        """Product-specific contract multiplier."""
        product = _extract_product(symbol)
        return float(
            self._priced(
                _MULTIPLIER, product, _DEFAULT_MULTIPLIER, "contract_multiplier"
            )
        )


# ── Helpers ──