Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(backtest): size HK orders on each symbol's own board lot

alex46d528cd676e
diff --git a/agent/backtest/engines/global_equity.py b/agent/backtest/engines/global_equity.py
index b7ae6ffce..8237d1874 100644
--- a/agent/backtest/engines/global_equity.py
+++ b/agent/backtest/engines/global_equity.py
@@ -9,7 +9,7 @@ Market rules:
HK:
- T+0, long/short allowed
- Stamp tax 0.1% bilateral + levies
- - Lot-size rounding (simplified to 100 shares)
+ - Board-lot rounding per symbol from ``hk_lot_sizes``; 100 shares otherwise
- Higher slippage than US
Canada (TSX / TSX Venture):
- Same-session round trips and long/short orders supported
@@ -28,13 +28,34 @@ India (NSE/BSE) is handled by the dedicated ``backtest.engines.india_equity``
from __future__ import annotations
+import logging
import math
from decimal import Decimal, ROUND_HALF_UP
+from typing import Any
import pandas as pd
from backtest.engines.base import BaseEngine
+logger = logging.getLogger(__name__)
+
+#: Board lot used for an HK symbol the run has no lot size for.
+_DEFAULT_HK_BOARD_LOT = 100
+
+
+def _hk_lot_key(symbol: Any) -> str:
+ """Normalise an HK symbol so ``00700.HK``, ``0700.HK`` and ``700.hk`` match.
+
+ Args:
+ symbol: Symbol as written in config or carried by the data.
+
+ Returns:
+ Upper-cased symbol in the loaders' four-digit spelling (``0700.HK``);
+ five-digit codes such as ``80700.HK`` keep all five digits.
+ """
+ head, sep, tail = str(symbol).strip().upper().partition(".")
+ return f"{head.lstrip('0').zfill(4)}{sep}{tail}"
+
class GlobalEquityEngine(BaseEngine):
"""US / HK / Canada / UK equity engine selected by *market*.
@@ -46,6 +67,11 @@ class GlobalEquityEngine(BaseEngine):
- hk_commission: default 0.00015 (万1.5)
- hk_levy: default 0.0000565 (SFC + FRC)
- hk_settlement: default 0.00002 (CCASS)
+ - hk_lot_sizes: ``{symbol: board lot}``. HK board lots are set per
+ issuer, so a flat 100 mis-sizes most names. When the table is given,
+ any HK symbol missing from it falls back to 100 and is reported in
+ the run metrics under ``lot_assumptions``. Without the table every HK
+ symbol uses 100, as before.
- slippage_ca: defaults to slippage_us
- ca_commission: broker commission rate, default 0.0
- slippage_uk: defaults to slippage_us
@@ -67,6 +93,11 @@ class GlobalEquityEngine(BaseEngine):
self.hk_commission: float = config.get("hk_commission", 0.00015)
self.hk_levy: float = config.get("hk_levy", 0.0000565)
self.hk_settlement: float = config.get("hk_settlement", 0.00002)
+ self.hk_lot_sizes: dict[str, int] = {
+ _hk_lot_key(k): int(v)
+ for k, v in (config.get("hk_lot_sizes") or {}).items()
+ }
+ self.lot_assumptions: dict[str, int] = {}
# Canada defaults. Commission varies by broker, so the model exposes a
# rate instead of inventing an exchange-wide charge.
self.slippage_ca: float = config.get("slippage_ca", self.slippage_us)
@@ -83,8 +114,50 @@ class GlobalEquityEngine(BaseEngine):
"""Allow same-session trading in both directions for every market."""
return True
+ def _hk_board_lot(self, symbol: str) -> int:
+ """Return the board lot for one HK symbol.
+
+ A symbol the configured table does not cover is sized on the default
+ lot, which looks exactly like data in the output, so the miss is
+ recorded and the run can state which lot sizes were assumed.
+
+ Args:
+ symbol: HK symbol of the order being sized.
+
+ Returns:
+ The configured board lot, or the default lot when none applies.
+ """
+ key = _hk_lot_key(symbol) if symbol else "<no active symbol>"
+ lot = self.hk_lot_sizes.get(key, 0)
+ if lot > 0:
+ return lot
+ if self.hk_lot_sizes and key not in self.lot_assumptions:
+ self.lot_assumptions[key] = _DEFAULT_HK_BOARD_LOT
+ logger.warning(
+ "HK symbol %r has no usable hk_lot_sizes entry; sizing it on "
+ "the default %d-share lot (reported under lot_assumptions).",
+ key,
+ _DEFAULT_HK_BOARD_LOT,
+ )
+ return _DEFAULT_HK_BOARD_LOT
+
+ def _engine_diagnostics(self) -> dict[str, Any]:
+ """Report every HK symbol this run sized on the default board lot."""
+ if not self.lot_assumptions:
+ return {}
+ return {
+ "lot_assumptions": [
+ {"symbol": symbol, "field": "board_lot", "value": lot}
+ for symbol, lot in sorted(self.lot_assumptions.items())
+ ]
+ }
+
def round_size(self, raw_size: float, price: float) -> float:
- """US: fractional; HK: 100-share lots; Canada/UK: whole shares.
+ """US: fractional; HK: per-symbol board lots; Canada/UK: whole shares.
+
+ HK sizing reads the lot of ``self._active_symbol``, which the base
+ engine sets before every sizing call, so the signature stays the same
+ across engines.
TSX and TSXV accept odd and mixed lots through dedicated facilities,
so forcing every order to a board lot would reject valid retail trades.
@@ -92,7 +165,8 @@ class GlobalEquityEngine(BaseEngine):
the whole-share floor.
"""
if self.market == "hk":
- return max(int(raw_size / 100) * 100, 0)
+ lot = self._hk_board_lot(self._active_symbol)
+ return max(int(raw_size / lot) * lot, 0)
if self.market in {"ca", "uk"}:
return float(math.floor(max(raw_size, 0.0)))
return round(max(raw_size, 0.0), 2)
diff --git a/agent/src/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.md
index fd1bb8132..37a63df51 100644
--- a/agent/src/skills/strategy-generate/SKILL.md
+++ b/agent/src/skills/strategy-generate/SKILL.md
@@ -158,6 +158,7 @@ Self-check after writing `signal_engine.py`:
- `rebalance_tolerance`: drift band around the target, as a fraction of it, used only under `"rebalance"`. A resize executes once the held weight has moved further than this from its target; a **changed** target breaches any sane band on its own, so target changes always execute. Default `0.0` means no band, and then the resize test is decided by the slippage width alone — measured on a constant 20% target over 60 bars, `0.0` produced 60 fills, `0.02` produced 12, and `0.05` produced 5 while the weight never left 0.21. Use `rebalance_mask`, not tolerance, to express a strategy's execution cadence. `0.05` is a reasonable starting point, not a recommendation with evidence behind it — it is your modelling choice and the report records the value the run used.
- `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. A symbol missing from a supplied table is sized on 100 shares and listed under `lot_assumptions` in the metrics, so the report says which lots were assumed.
- `validation`: optional statistical validation after backtest completes. Omit to skip. Example:
```json
"validation": {
diff --git a/agent/tests/test_global_equity_hk_lot_sizes.py b/agent/tests/test_global_equity_hk_lot_sizes.py
new file mode 100644
index 000000000..cf17889e2
--- /dev/null
+++ b/agent/tests/test_global_equity_hk_lot_sizes.py
@@ -0,0 +1,129 @@
+"""HK board lots are set per issuer, so ``round_size`` must not assume 100.
+
+A flat 100-share lot mis-sizes most HK names, and quietly: a target smaller
+than one assumed lot rounds to zero and the symbol simply never trades. The
+symbols and lot sizes below are synthetic.
+"""
+
+from __future__ import annotations
+
+import logging
+
+import pandas as pd
+import pytest
+
+from backtest.engines.global_equity import GlobalEquityEngine
+
+LOTS = {"00001.HK": 20, "00002.HK": 100, "00003.HK": 5000}
+LOGGER = "backtest.engines.global_equity"
+
+
+def _engine(
+ lots: dict[str, int] | None = LOTS,
+ market: str = "hk",
+ initial_cash: float = 1_000_000,
+) -> GlobalEquityEngine:
+ config: dict = {"initial_cash": initial_cash}
+ if lots is not None:
+ config["hk_lot_sizes"] = lots
+ return GlobalEquityEngine(config, market=market)
+
+
+def _sized(engine: GlobalEquityEngine, symbol: str, raw: float) -> float:
+ engine._active_symbol = symbol
+ return engine.round_size(raw, price=10.0)
+
+
+ ("symbol", "raw", "expected"),
+ [
+ ("00001.HK", 99, 80), # lot 20: four lots, where a 100 grid gives 0
+ ("00001.HK", 19, 0), # below one real lot
+ ("00002.HK", 250, 200), # lot 100 unchanged
+ ("00003.HK", 12_345, 10_000), # lot 5000
+ ],
+)
+def test_round_size_uses_the_symbols_own_lot(
+ symbol: str, raw: float, expected: float
+) -> None:
+ assert _sized(_engine(), symbol, raw) == expected
+
+
[email protected]("written", ["1.HK", "0001.HK", " 00001.hk "])
+def test_table_keys_match_however_the_code_is_padded(written: str) -> None:
+ engine = _engine({written: 20})
+
+ assert _sized(engine, "00001.HK", 99) == 80
+ assert _sized(engine, "1.HK", 99) == 80
+ assert engine.lot_assumptions == {}
+
+
+def test_unlisted_symbol_falls_back_and_reaches_the_metrics(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ engine = _engine()
+
+ with caplog.at_level(logging.WARNING, logger=LOGGER):
+ assert _sized(engine, "00009.HK", 250) == 200
+ assert _sized(engine, "00009.HK", 350) == 300
+
+ assert engine._engine_diagnostics() == {
+ "lot_assumptions": [{"symbol": "0009.HK", "field": "board_lot", "value": 100}]
+ }
+ assert sum("0009.HK" in r.getMessage() for r in caplog.records) == 1
+
+
+def test_non_positive_lot_is_treated_as_missing() -> None:
+ engine = _engine({"00001.HK": 0})
+
+ assert _sized(engine, "00001.HK", 250) == 200
+ assert engine.lot_assumptions == {"0001.HK": 100}
+
+
+def test_without_a_table_sizing_and_output_are_unchanged(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ engine = _engine(lots=None)
+
+ with caplog.at_level(logging.WARNING, logger=LOGGER):
+ assert _sized(engine, "00001.HK", 99) == 0
+ assert _sized(engine, "00002.HK", 250) == 200
+
+ assert engine._engine_diagnostics() == {}
+ assert not caplog.records
+
+
+def test_non_hk_markets_ignore_the_table() -> None:
+ us = _engine(market="us")
+ ca = _engine(market="ca")
+
+ assert _sized(us, "AAPL", 59.4321) == 59.43
+ assert _sized(ca, "SHOP.TO", 59.9) == 59.0
+ assert us._engine_diagnostics() == {} and ca._engine_diagnostics() == {}
+
+
+def test_a_rebalance_fills_each_symbol_on_its_own_lot() -> None:
+ """Through the engine's own sizing path, not just ``round_size``."""
+ engine = _engine({"00001.HK": 20, "00002.HK": 500}, initial_cash=100_000)
+ dates = pd.date_range("2026-01-05", periods=2, freq="B")
+ prices = {"00001.HK": [300.0, 300.0], "00002.HK": [3.0, 3.0]}
+ data_map = {
+ symbol: pd.DataFrame({"open": values, "close": values}, index=dates)
+ for symbol, values in prices.items()
+ }
+ weights = pd.DataFrame(
+ {"00001.HK": [0.0, 0.1], "00002.HK": [0.0, 0.1]}, index=dates
+ )
+
+ engine._execute_bars(
+ dates, data_map, pd.DataFrame(prices, index=dates), weights, list(prices)
+ )
+
+ opened = {
+ fill.symbol: abs(fill.signed_quantity)
+ for fill in engine.fill_records
+ if fill.action == "open"
+ }
+ assert opened["00001.HK"] > 0 and opened["00001.HK"] % 20 == 0
+ assert opened["00002.HK"] > 0 and opened["00002.HK"] % 500 == 0
+ assert engine.lot_assumptions == {}