Skip to content

"Vibe-Trading: Your Personal Trading Agent"

test: add 236 unit tests + CI pytest integration

warren618483de22b7d22
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index c4803f947..6f686882a 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -2,12 +2,12 @@ name: CI
on:
push:
- branches: [master]
+ branches: [main]
pull_request:
- branches: [master]
+ branches: [main]
jobs:
- build:
+ test:
runs-on: ubuntu-latest
timeout-minutes: 10
@@ -20,7 +20,7 @@ jobs:
cache: pip
- name: Install dependencies
- run: pip install -e .
+ run: pip install -e ".[dev]"
- name: Syntax check
run: |
@@ -32,6 +32,9 @@ jobs:
python -m py_compile src/tools/__init__.py
python -m py_compile backtest/runner.py
+ - name: Run tests
+ run: pytest --ignore=agent/tests/e2e_backtest --tb=short -q
+
- uses: actions/setup-node@v4
with:
node-version: "20"
diff --git a/.gitignore b/.gitignore
index 360ba4577..16984e30b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -35,9 +35,8 @@ data/overnight*.log
data/*.log
data/test_write.txt
agent/.pytest_tmp/
-agent/tests/e2e_swarm_results.json
agent/vibe_trading.egg-info/
agent/vibe_trading_ai.egg-info/
-agent/tests/
+agent/tests/e2e_backtest/
dist/
build/
diff --git a/agent/tests/__init__.py b/agent/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/agent/tests/conftest.py b/agent/tests/conftest.py
new file mode 100644
index 000000000..0c3d14c78
--- /dev/null
+++ b/agent/tests/conftest.py
@@ -0,0 +1,11 @@
+"""Shared fixtures and sys.path setup for all tests."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+# Ensure agent/ is on sys.path so imports like `backtest.*` and `src.*` work.
+AGENT_DIR = Path(__file__).resolve().parent.parent
+if str(AGENT_DIR) not in sys.path:
+ sys.path.insert(0, str(AGENT_DIR))
diff --git a/agent/tests/test_base_engine.py b/agent/tests/test_base_engine.py
new file mode 100644
index 000000000..da875321a
--- /dev/null
+++ b/agent/tests/test_base_engine.py
@@ -0,0 +1,232 @@
+"""Tests for BaseEngine shared logic: _align, _close_position, _calc_equity.
+
+Uses ChinaAEngine as a concrete implementation since BaseEngine is abstract.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.engines.base import BaseEngine, _align, _load_optimizer
+from backtest.engines.china_a import ChinaAEngine
+from backtest.models import Position
+
+
+# ---------------------------------------------------------------------------
+# _align: signal alignment and normalization
+# ---------------------------------------------------------------------------
+
+
+def _simple_data_and_signals():
+ """Build minimal data_map and signal_map for alignment tests."""
+ dates = pd.bdate_range("2025-01-01", periods=10)
+ df_a = pd.DataFrame(
+ {"close": np.linspace(10, 20, 10), "open": np.linspace(10, 20, 10)},
+ index=dates,
+ )
+ df_b = pd.DataFrame(
+ {"close": np.linspace(100, 110, 10), "open": np.linspace(100, 110, 10)},
+ index=dates,
+ )
+ data_map = {"A": df_a, "B": df_b}
+
+ sig_a = pd.Series(0.0, index=dates)
+ sig_a.iloc[3:] = 1.0
+ sig_b = pd.Series(0.0, index=dates)
+ sig_b.iloc[5:] = 1.0
+ signal_map = {"A": sig_a, "B": sig_b}
+
+ return data_map, signal_map, dates
+
+
+class TestAlign:
+ def test_output_shapes(self) -> None:
+ data_map, signal_map, dates = _simple_data_and_signals()
+ out_dates, close_df, pos_df, ret_df = _align(data_map, signal_map, ["A", "B"])
+ assert len(out_dates) == len(dates)
+ assert close_df.shape == (len(dates), 2)
+ assert pos_df.shape == (len(dates), 2)
+ assert ret_df.shape == (len(dates), 2)
+
+ def test_signal_shifted_by_one(self) -> None:
+ """Signal at bar i should produce position at bar i+1 (next-bar-open)."""
+ data_map, signal_map, dates = _simple_data_and_signals()
+ _, _, pos_df, _ = _align(data_map, signal_map, ["A", "B"])
+ # Signal A goes to 1.0 at index 3 → position should be 0 at index 3, non-zero at index 4
+ assert pos_df.at[dates[3], "A"] == 0.0
+ assert pos_df.at[dates[4], "A"] > 0.0
+
+ def test_positions_normalized(self) -> None:
+ """Sum of abs(weights) should be <= 1.0 per row."""
+ data_map, signal_map, dates = _simple_data_and_signals()
+ _, _, pos_df, _ = _align(data_map, signal_map, ["A", "B"])
+ row_sums = pos_df.abs().sum(axis=1)
+ assert (row_sums <= 1.0 + 1e-10).all()
+
+ def test_signals_clipped(self) -> None:
+ """Signals outside [-1, 1] should be clipped."""
+ dates = pd.bdate_range("2025-01-01", periods=5)
+ df = pd.DataFrame({"close": [100] * 5, "open": [100] * 5}, index=dates)
+ sig = pd.Series([0, 0, 2.0, -3.0, 0.5], index=dates)
+ data_map = {"X": df}
+ signal_map = {"X": sig}
+ _, _, pos_df, _ = _align(data_map, signal_map, ["X"])
+ # After shift, clipped values show up at indices 3 and 4
+ assert pos_df["X"].abs().max() <= 1.0 + 1e-10
+
+ def test_nan_signals_filled_zero(self) -> None:
+ dates = pd.bdate_range("2025-01-01", periods=5)
+ df = pd.DataFrame({"close": [100] * 5, "open": [100] * 5}, index=dates)
+ sig = pd.Series([np.nan, 1.0, np.nan, 0.5, np.nan], index=dates)
+ data_map = {"X": df}
+ signal_map = {"X": sig}
+ _, _, pos_df, _ = _align(data_map, signal_map, ["X"])
+ assert not pos_df.isna().any().any()
+
+ def test_close_ffill_bfill(self) -> None:
+ """Missing close prices should be forward/backward filled."""
+ dates = pd.bdate_range("2025-01-01", periods=5)
+ df = pd.DataFrame(
+ {"close": [100, np.nan, np.nan, 110, 115], "open": [100] * 5},
+ index=dates,
+ )
+ sig = pd.Series([0, 1, 1, 1, 0], index=dates)
+ _, close_df, _, _ = _align({"X": df}, {"X": sig}, ["X"])
+ assert not close_df.isna().any().any()
+
+ def test_with_optimizer(self) -> None:
+ """Optimizer callable gets applied."""
+ data_map, signal_map, dates = _simple_data_and_signals()
+
+ def dummy_optimizer(ret, pos, dates_arg):
+ return pos * 0.5 # halve everything
+
+ _, _, pos_df, _ = _align(data_map, signal_map, ["A", "B"], optimizer=dummy_optimizer)
+ # Positions should be smaller due to optimizer
+ _, _, pos_no_opt, _ = _align(data_map, signal_map, ["A", "B"])
+ assert pos_df.abs().sum().sum() <= pos_no_opt.abs().sum().sum() + 1e-10
+
+
+# ---------------------------------------------------------------------------
+# _load_optimizer
+# ---------------------------------------------------------------------------
+
+
+class TestLoadOptimizer:
+ def test_no_optimizer(self) -> None:
+ assert _load_optimizer({}) is None
+ assert _load_optimizer({"optimizer": ""}) is None
+
+ def test_valid_optimizer(self) -> None:
+ opt = _load_optimizer({"optimizer": "risk_parity"})
+ assert opt is not None and callable(opt)
+
+ def test_invalid_optimizer_returns_none(self) -> None:
+ opt = _load_optimizer({"optimizer": "nonexistent_module_xyz"})
+ assert opt is None
+
+
+# ---------------------------------------------------------------------------
+# _close_position: PnL calculation
+# ---------------------------------------------------------------------------
+
+
+class TestClosePosition:
+ def test_profitable_long(self) -> None:
+ engine = ChinaAEngine({"initial_cash": 1_000_000})
+ engine._bar_idx = 5
+ engine.positions["000001.SZ"] = Position(
+ "000001.SZ", 1, 15.0, pd.Timestamp("2025-01-02"), 1000.0, entry_bar_idx=0,
+ )
+ engine.capital = 985_000.0 # after buying
+ engine._close_position("000001.SZ", 16.0, pd.Timestamp("2025-01-10"), "signal")
+
+ assert "000001.SZ" not in engine.positions
+ assert len(engine.trades) == 1
+ t = engine.trades[0]
+ assert t.pnl == pytest.approx(1000.0) # 1000 × (16 - 15) = +1000
+ assert t.exit_reason == "signal"
+ assert t.holding_bars == 5
+
+ def test_losing_long(self) -> None:
+ engine = ChinaAEngine({"initial_cash": 1_000_000})
+ engine._bar_idx = 3
+ engine.positions["600519.SH"] = Position(
+ "600519.SH", 1, 1800.0, pd.Timestamp("2025-01-02"), 100.0, entry_bar_idx=0,
+ )
+ engine.capital = 820_000.0
+ engine._close_position("600519.SH", 1750.0, pd.Timestamp("2025-01-06"), "signal")
+
+ t = engine.trades[0]
+ assert t.pnl == pytest.approx(-5000.0) # 100 × (1750 - 1800) = -5000
+ assert t.direction == 1
+
+ def test_close_nonexistent_position_noop(self) -> None:
+ engine = ChinaAEngine({"initial_cash": 1_000_000})
+ engine._close_position("NOPE.SZ", 10.0, pd.Timestamp("2025-01-01"), "signal")
+ assert len(engine.trades) == 0
+
+ def test_capital_returned(self) -> None:
+ engine = ChinaAEngine({"initial_cash": 1_000_000})
+ engine._bar_idx = 1
+ engine.positions["000001.SZ"] = Position(
+ "000001.SZ", 1, 15.0, pd.Timestamp("2025-01-02"), 1000.0,
+ )
+ capital_before = 985_000.0
+ engine.capital = capital_before
+ engine._close_position("000001.SZ", 15.0, pd.Timestamp("2025-01-03"), "signal")
+ # Margin returned + 0 PnL - exit commission
+ assert engine.capital > capital_before # margin returned exceeds commission
+
+
+# ---------------------------------------------------------------------------
+# _calc_equity
+# ---------------------------------------------------------------------------
+
+
+class TestCalcEquity:
+ def test_no_positions(self) -> None:
+ engine = ChinaAEngine({"initial_cash": 1_000_000})
+ dates = pd.DatetimeIndex([pd.Timestamp("2025-01-02")])
+ close_df = pd.DataFrame({"X": [15.0]}, index=dates)
+ eq = engine._calc_equity(close_df, dates[0])
+ assert eq == 1_000_000.0
+
+ def test_with_unrealized_gain(self) -> None:
+ engine = ChinaAEngine({"initial_cash": 1_000_000})
+ engine.capital = 985_000.0
+ engine.positions["X"] = Position("X", 1, 15.0, pd.Timestamp("2025-01-02"), 1000.0)
+ dates = pd.DatetimeIndex([pd.Timestamp("2025-01-03")])
+ close_df = pd.DataFrame({"X": [16.0]}, index=dates)
+ eq = engine._calc_equity(close_df, dates[0])
+ # capital + margin + unrealized = 985000 + (1000×15/1) + (1×1000×(16-15)) = 985000 + 15000 + 1000 = 1001000
+ assert eq == pytest.approx(1_001_000.0)
+
+
+# ---------------------------------------------------------------------------
+# _safe_price
+# ---------------------------------------------------------------------------
+
+
+class TestSafePrice:
+ def test_returns_close_price(self) -> None:
+ dates = pd.DatetimeIndex([pd.Timestamp("2025-01-02")])
+ close_df = pd.DataFrame({"X": [15.5]}, index=dates)
+ assert BaseEngine._safe_price(close_df, dates[0], "X", 10.0) == 15.5
+
+ def test_fallback_on_missing_symbol(self) -> None:
+ dates = pd.DatetimeIndex([pd.Timestamp("2025-01-02")])
+ close_df = pd.DataFrame({"X": [15.5]}, index=dates)
+ assert BaseEngine._safe_price(close_df, dates[0], "MISSING", 10.0) == 10.0
+
+ def test_fallback_on_missing_timestamp(self) -> None:
+ dates = pd.DatetimeIndex([pd.Timestamp("2025-01-02")])
+ close_df = pd.DataFrame({"X": [15.5]}, index=dates)
+ assert BaseEngine._safe_price(close_df, pd.Timestamp("2025-06-01"), "X", 10.0) == 10.0
+
+ def test_fallback_on_nan(self) -> None:
+ dates = pd.DatetimeIndex([pd.Timestamp("2025-01-02")])
+ close_df = pd.DataFrame({"X": [np.nan]}, index=dates)
+ assert BaseEngine._safe_price(close_df, dates[0], "X", 10.0) == 10.0
diff --git a/agent/tests/test_china_a_engine.py b/agent/tests/test_china_a_engine.py
new file mode 100644
index 000000000..a895eb29a
--- /dev/null
+++ b/agent/tests/test_china_a_engine.py
@@ -0,0 +1,288 @@
+"""Tests for ChinaAEngine market rules.
+
+Validates:
+ - T+1 lock: can't sell shares bought today
+ - No short selling
+ - Price limit (涨跌停) enforcement
+ - 100-share lot rounding
+ - Commission structure (min ¥5, stamp tax sell-only, transfer fee)
+ - Slippage
+ - Price limit detection helper
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from backtest.engines.china_a import (
+ ChinaAEngine,
+ _bar_date,
+ _calc_pct_change,
+ _price_limit,
+)
+from backtest.models import Position
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_bar(
+ close: float = 15.0,
+ pre_close: float | None = None,
+ pct_chg: float | None = None,
+ trade_date: str | None = None,
+ open_: float | None = None,
+) -> pd.Series:
+ """Build a minimal bar Series for testing."""
+ d: dict = {"close": close, "open": open_ or close}
+ if pre_close is not None:
+ d["pre_close"] = pre_close
+ if pct_chg is not None:
+ d["pct_chg"] = pct_chg
+ if trade_date is not None:
+ d["trade_date"] = pd.Timestamp(trade_date)
+ return pd.Series(d)
+
+
+def _make_engine(**overrides) -> ChinaAEngine:
+ config = {"initial_cash": 1_000_000}
+ config.update(overrides)
+ return ChinaAEngine(config)
+
+
+# ---------------------------------------------------------------------------
+# can_execute: no short selling
+# ---------------------------------------------------------------------------
+
+
+class TestNoShortSelling:
+ def test_short_blocked(self) -> None:
+ engine = _make_engine()
+ bar = _make_bar()
+ assert engine.can_execute("000001.SZ", -1, bar) is False
+
+ def test_long_allowed(self) -> None:
+ engine = _make_engine()
+ bar = _make_bar()
+ assert engine.can_execute("000001.SZ", 1, bar) is True
+
+ def test_close_allowed_when_no_position(self) -> None:
+ engine = _make_engine()
+ bar = _make_bar()
+ assert engine.can_execute("000001.SZ", 0, bar) is True
+
+
+# ---------------------------------------------------------------------------
+# can_execute: T+1
+# ---------------------------------------------------------------------------
+
+
+class TestTPlusOne:
+ def test_sell_same_day_blocked(self) -> None:
+ engine = _make_engine()
+ # Simulate position bought today
+ engine.positions["000001.SZ"] = Position(
+ symbol="000001.SZ",
+ direction=1,
+ entry_price=15.0,
+ entry_time=pd.Timestamp("2025-06-10"),
+ size=100.0,
+ )
+ bar = _make_bar(trade_date="2025-06-10")
+ assert engine.can_execute("000001.SZ", 0, bar) is False
+
+ def test_sell_next_day_allowed(self) -> None:
+ engine = _make_engine()
+ engine.positions["000001.SZ"] = Position(
+ symbol="000001.SZ",
+ direction=1,
+ entry_price=15.0,
+ entry_time=pd.Timestamp("2025-06-10"),
+ size=100.0,
+ )
+ bar = _make_bar(trade_date="2025-06-11")
+ assert engine.can_execute("000001.SZ", 0, bar) is True
+
+ def test_sell_allowed_when_no_position(self) -> None:
+ engine = _make_engine()
+ bar = _make_bar(trade_date="2025-06-10")
+ assert engine.can_execute("000001.SZ", 0, bar) is True
+
+
+# ---------------------------------------------------------------------------
+# can_execute: price limits (涨跌停)
+# ---------------------------------------------------------------------------
+
+
+class TestPriceLimits:
+ def test_limit_up_buy_blocked(self) -> None:
+ """Mainboard +10% limit-up: can't buy."""
+ engine = _make_engine()
+ bar = _make_bar(close=16.5, pre_close=15.0) # +10%
+ assert engine.can_execute("000001.SZ", 1, bar) is False
+
+ def test_limit_down_sell_blocked(self) -> None:
+ """Mainboard -10% limit-down: can't sell."""
+ engine = _make_engine()
+ engine.positions["000001.SZ"] = Position(
+ "000001.SZ", 1, 15.0, pd.Timestamp("2025-06-09"), 100.0,
+ )
+ bar = _make_bar(close=13.5, pre_close=15.0, trade_date="2025-06-10")
+ assert engine.can_execute("000001.SZ", 0, bar) is False
+
+ def test_within_limit_allowed(self) -> None:
+ engine = _make_engine()
+ bar = _make_bar(close=15.5, pre_close=15.0) # +3.3%
+ assert engine.can_execute("000001.SZ", 1, bar) is True
+
+ def test_pct_chg_field_used(self) -> None:
+ """pct_chg in percentage points (tushare format)."""
+ engine = _make_engine()
+ bar = _make_bar(pct_chg=10.0) # 10% in tushare = +0.10
+ assert engine.can_execute("000001.SZ", 1, bar) is False
+
+ def test_chinext_20pct_limit(self) -> None:
+ """ChiNext (300xxx) has ±20% limit."""
+ engine = _make_engine()
+ bar = _make_bar(close=18.0, pre_close=15.0) # +20%
+ assert engine.can_execute("300750.SZ", 1, bar) is False
+
+ def test_chinext_within_limit(self) -> None:
+ engine = _make_engine()
+ bar = _make_bar(close=17.0, pre_close=15.0) # +13.3%
+ assert engine.can_execute("300750.SZ", 1, bar) is True
+
+
+# ---------------------------------------------------------------------------
+# round_size: 100-share lots
+# ---------------------------------------------------------------------------
+
+
+class TestRoundSize:
+ def test_exact_lots(self) -> None:
+ engine = _make_engine()
+ assert engine.round_size(300.0, 15.0) == 300
+
+ def test_rounds_down(self) -> None:
+ engine = _make_engine()
+ assert engine.round_size(350.0, 15.0) == 300
+ assert engine.round_size(199.0, 15.0) == 100
+ assert engine.round_size(99.0, 15.0) == 0
+
+ def test_zero_size(self) -> None:
+ engine = _make_engine()
+ assert engine.round_size(0.0, 15.0) == 0
+
+ def test_negative_clamps_to_zero(self) -> None:
+ engine = _make_engine()
+ assert engine.round_size(-50.0, 15.0) == 0
+
+
+# ---------------------------------------------------------------------------
+# calc_commission: fee structure
+# ---------------------------------------------------------------------------
+
+
+class TestCommission:
+ def test_minimum_commission(self) -> None:
+ """Small trades hit the ¥5 minimum."""
+ engine = _make_engine()
+ # 100 shares × ¥3 = ¥300 notional → 0.025% = ¥0.075 → min ¥5
+ comm = engine.calc_commission(100, 3.0, 1, is_open=True)
+ assert comm >= 5.0
+
+ def test_buy_no_stamp_tax(self) -> None:
+ """Buy side: no stamp tax."""
+ engine = _make_engine()
+ comm_buy = engine.calc_commission(1000, 15.0, 1, is_open=True)
+ comm_sell = engine.calc_commission(1000, 15.0, 1, is_open=False)
+ # Sell has stamp tax, buy doesn't → sell > buy
+ assert comm_sell > comm_buy
+
+ def test_stamp_tax_sell_only(self) -> None:
+ """Stamp tax: 0.05% on sell side only."""
+ engine = _make_engine()
+ size, price = 10000, 15.0
+ notional = size * price # 150,000
+ comm_sell = engine.calc_commission(size, price, 1, is_open=False)
+ # Stamp tax portion = 150000 × 0.0005 = ¥75
+ stamp_portion = notional * engine.stamp_tax
+ assert stamp_portion == pytest.approx(75.0, abs=0.01)
+ # Sell commission includes stamp tax
+ comm_buy = engine.calc_commission(size, price, 1, is_open=True)
+ assert comm_sell - comm_buy == pytest.approx(stamp_portion, abs=0.1)
+
+ def test_leverage_forced_one(self) -> None:
+ """A-share engine forces leverage=1."""
+ engine = _make_engine(leverage=10.0)
+ assert engine.default_leverage == 1.0
+
+
+# ---------------------------------------------------------------------------
+# apply_slippage
+# ---------------------------------------------------------------------------
+
+
+class TestSlippage:
+ def test_buy_slippage_increases_price(self) -> None:
+ engine = _make_engine()
+ assert engine.apply_slippage(100.0, 1) > 100.0
+
+ def test_sell_slippage_decreases_price(self) -> None:
+ engine = _make_engine()
+ assert engine.apply_slippage(100.0, -1) < 100.0
+
+ def test_custom_slippage_rate(self) -> None:
+ engine = _make_engine(slippage=0.005)
+ assert engine.apply_slippage(100.0, 1) == pytest.approx(100.5)
+
+
+# ---------------------------------------------------------------------------
+# Helper functions
+# ---------------------------------------------------------------------------
+
+
+class TestPriceLimit:
+ @pytest.mark.parametrize(
+ "symbol, expected",
+ [
+ ("000001.SZ", 0.10), # Mainboard
+ ("600519.SH", 0.10),
+ ("300750.SZ", 0.20), # ChiNext
+ ("688001.SH", 0.20), # STAR Market
+ ("830799.BJ", 0.30), # Beijing
+ ],
+ )
+ def test_price_limits(self, symbol: str, expected: float) -> None:
+ assert _price_limit(symbol) == expected
+
+
+class TestCalcPctChange:
+ def test_from_pct_chg_field(self) -> None:
+ bar = _make_bar(pct_chg=5.0)
+ assert _calc_pct_change(bar) == pytest.approx(0.05)
+
+ def test_from_close_and_pre_close(self) -> None:
+ bar = _make_bar(close=16.5, pre_close=15.0)
+ assert _calc_pct_change(bar) == pytest.approx(0.1)
+
+ def test_none_when_no_data(self) -> None:
+ bar = pd.Series({"close": 15.0})
+ assert _calc_pct_change(bar) is None
+
+
+class TestBarDate:
+ def test_from_trade_date_col(self) -> None:
+ bar = _make_bar(trade_date="2025-06-10")
+ assert _bar_date(bar) == pd.Timestamp("2025-06-10").date()
+
+ def test_from_index_name(self) -> None:
+ bar = pd.Series({"close": 15.0}, name=pd.Timestamp("2025-06-10"))
+ assert _bar_date(bar) == pd.Timestamp("2025-06-10").date()
+
+ def test_none_when_no_date(self) -> None:
+ bar = pd.Series({"close": 15.0})
+ assert _bar_date(bar) is None
diff --git a/agent/tests/test_crypto_engine.py b/agent/tests/test_crypto_engine.py
new file mode 100644
index 000000000..c8d9f178f
--- /dev/null
+++ b/agent/tests/test_crypto_engine.py
@@ -0,0 +1,269 @@
+"""Tests for CryptoEngine market rules.
+
+Validates:
+ - 24/7 execution (no direction/time restrictions)
+ - Fractional position sizing
+ - Maker/Taker fee separation
+ - Funding fee settlement (every 8 hours)
+ - Forced liquidation (maintenance margin check)
+ - Tiered maintenance margin rates
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from backtest.engines.crypto import CryptoEngine, _FUNDING_HOURS, _TIER_TABLE
+from backtest.models import Position
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_bar(close: float = 60000.0, open_: float | None = None) -> pd.Series:
+ return pd.Series({"close": close, "open": open_ or close})
+
+
+def _make_engine(**overrides) -> CryptoEngine:
+ config = {
+ "initial_cash": 100_000,
+ "leverage": 10.0,
+ "maker_rate": 0.0002,
+ "taker_rate": 0.0005,
+ "funding_rate": 0.0001,
+ }
+ config.update(overrides)
+ return CryptoEngine(config)
+
+
+# ---------------------------------------------------------------------------
+# can_execute: no restrictions
+# ---------------------------------------------------------------------------
+
+
+class TestCanExecute:
+ def test_long_allowed(self) -> None:
+ engine = _make_engine()
+ assert engine.can_execute("BTC-USDT", 1, _make_bar()) is True
+
+ def test_short_allowed(self) -> None:
+ engine = _make_engine()
+ assert engine.can_execute("BTC-USDT", -1, _make_bar()) is True
+
+ def test_close_allowed(self) -> None:
+ engine = _make_engine()
+ assert engine.can_execute("BTC-USDT", 0, _make_bar()) is True
+
+
+# ---------------------------------------------------------------------------
+# round_size: fractional
+# ---------------------------------------------------------------------------
+
+
+class TestRoundSize:
+ def test_fractional_preserved(self) -> None:
+ engine = _make_engine()
+ assert engine.round_size(0.123456, 60000.0) == 0.123456
+
+ def test_six_decimal_precision(self) -> None:
+ engine = _make_engine()
+ assert engine.round_size(0.1234567890, 60000.0) == pytest.approx(0.123457, abs=1e-7)
+
+ def test_negative_clamps_to_zero(self) -> None:
+ engine = _make_engine()
+ assert engine.round_size(-0.5, 60000.0) == 0.0
+
+
+# ---------------------------------------------------------------------------
+# calc_commission: maker/taker
+# ---------------------------------------------------------------------------
+
+
+class TestCommission:
+ def test_open_uses_taker(self) -> None:
+ engine = _make_engine(taker_rate=0.0005, maker_rate=0.0002)
+ comm = engine.calc_commission(1.0, 60000.0, 1, is_open=True)
+ # 1 BTC × $60000 × 0.0005 = $30
+ assert comm == pytest.approx(30.0)
+
+ def test_close_uses_maker(self) -> None:
+ engine = _make_engine(taker_rate=0.0005, maker_rate=0.0002)
+ comm = engine.calc_commission(1.0, 60000.0, 1, is_open=False)
+ # 1 BTC × $60000 × 0.0002 = $12
+ assert comm == pytest.approx(12.0)
+
+ def test_taker_higher_than_maker(self) -> None:
+ engine = _make_engine()
+ open_comm = engine.calc_commission(1.0, 60000.0, 1, is_open=True)
+ close_comm = engine.calc_commission(1.0, 60000.0, 1, is_open=False)
+ assert open_comm > close_comm
+
+
+# ---------------------------------------------------------------------------
+# apply_slippage
+# ---------------------------------------------------------------------------
+
+
+class TestSlippage:
+ def test_long_slippage_increases_price(self) -> None:
+ engine = _make_engine(slippage=0.001)
+ assert engine.apply_slippage(60000.0, 1) == pytest.approx(60060.0)
+
+ def test_short_slippage_decreases_price(self) -> None:
+ engine = _make_engine(slippage=0.001)
+ assert engine.apply_slippage(60000.0, -1) == pytest.approx(59940.0)
+
+
+# ---------------------------------------------------------------------------
+# Funding fee
+# ---------------------------------------------------------------------------
+
+
+class TestFundingFee:
+ def test_funding_deducted_at_settlement_hour(self) -> None:
+ engine = _make_engine(funding_rate=0.0001)
+ engine.positions["BTC-USDT"] = Position(
+ "BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ initial_capital = engine.capital
+ bar = _make_bar(close=60000.0)
+ ts = pd.Timestamp("2025-01-01 08:00:00") # settlement hour
+ engine._apply_funding_fee("BTC-USDT", bar, ts)
+ # Long pays: 1.0 × 60000 × 0.0001 × 1(long) = $6
+ assert engine.capital == pytest.approx(initial_capital - 6.0)
+
+ def test_no_funding_at_non_settlement_hour(self) -> None:
+ engine = _make_engine(funding_rate=0.0001)
+ engine.positions["BTC-USDT"] = Position(
+ "BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ initial_capital = engine.capital
+ bar = _make_bar(close=60000.0)
+ ts = pd.Timestamp("2025-01-01 05:00:00") # not settlement hour
+ engine._apply_funding_fee("BTC-USDT", bar, ts)
+ assert engine.capital == initial_capital
+
+ def test_short_receives_funding(self) -> None:
+ engine = _make_engine(funding_rate=0.0001)
+ engine.positions["BTC-USDT"] = Position(
+ "BTC-USDT", -1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ initial_capital = engine.capital
+ bar = _make_bar(close=60000.0)
+ ts = pd.Timestamp("2025-01-01 08:00:00")
+ engine._apply_funding_fee("BTC-USDT", bar, ts)
+ # Short: direction=-1, fee = notional × rate × direction = negative → capital increases
+ assert engine.capital > initial_capital
+
+ def test_no_double_settlement(self) -> None:
+ engine = _make_engine(funding_rate=0.0001)
+ engine.positions["BTC-USDT"] = Position(
+ "BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ bar = _make_bar(close=60000.0)
+ ts = pd.Timestamp("2025-01-01 08:00:00")
+ engine._apply_funding_fee("BTC-USDT", bar, ts)
+ capital_after_first = engine.capital
+ # Call again at same hour — should not deduct again
+ engine._apply_funding_fee("BTC-USDT", bar, ts)
+ assert engine.capital == capital_after_first
+
+ def test_no_funding_without_position(self) -> None:
+ engine = _make_engine()
+ initial_capital = engine.capital
+ bar = _make_bar()
+ ts = pd.Timestamp("2025-01-01 08:00:00")
+ engine._apply_funding_fee("BTC-USDT", bar, ts)
+ assert engine.capital == initial_capital
+
+ def test_funding_hours_correct(self) -> None:
+ assert _FUNDING_HOURS == {0, 8, 16}
+
+
+# ---------------------------------------------------------------------------
+# Liquidation
+# ---------------------------------------------------------------------------
+
+
+class TestLiquidation:
+ def test_liquidation_on_large_loss(self) -> None:
+ """Position wiped when equity drops below maintenance margin."""
+ engine = _make_engine(leverage=10.0)
+ engine.positions["BTC-USDT"] = Position(
+ "BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ # Margin = 1.0 × 60000 / 10 = $6000
+ # If price drops to 54500: unrealized = 1 × (54500 - 60000) = -$5500
+ # equity_in_pos = 6000 + (-5500) = $500
+ # Notional = 1 × 54500 = 54500, maint_rate(54500) = 0.004
+ # Maint margin = 54500 × 0.004 = $218
+ # $500 > $218 → no liquidation
+
+ # But if price drops to 54000:
+ # unrealized = -6000, equity = 0 → clearly liquidated
+ bar = _make_bar(close=54000.0)
+ ts = pd.Timestamp("2025-01-02")
+ engine._check_liquidation("BTC-USDT", bar, ts)
+ assert "BTC-USDT" not in engine.positions
+ assert len(engine.trades) == 1
+ assert engine.trades[0].exit_reason == "liquidation"
+
+ def test_no_liquidation_when_profitable(self) -> None:
+ engine = _make_engine(leverage=10.0)
+ engine.positions["BTC-USDT"] = Position(
+ "BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ bar = _make_bar(close=65000.0)
+ ts = pd.Timestamp("2025-01-02")
+ engine._check_liquidation("BTC-USDT", bar, ts)
+ assert "BTC-USDT" in engine.positions
+
+ def test_no_liquidation_for_spot(self) -> None:
+ """Spot (leverage=1) should never get liquidated."""
+ engine = _make_engine(leverage=1.0)
+ engine.positions["BTC-USDT"] = Position(
+ "BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=1.0,
+ )
+ bar = _make_bar(close=30000.0) # 50% drop
+ ts = pd.Timestamp("2025-01-02")
+ engine._check_liquidation("BTC-USDT", bar, ts)
+ assert "BTC-USDT" in engine.positions
+
+ def test_short_liquidation(self) -> None:
+ """Short position liquidated when price rises sharply."""
+ engine = _make_engine(leverage=10.0)
+ engine.positions["BTC-USDT"] = Position(
+ "BTC-USDT", -1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ # Margin = $6000, unrealized = -1 × 1 × (66500 - 60000) = -$6500
+ # equity_in_pos = 6000 - 6500 = -$500 < 0 → liquidated
+ bar = _make_bar(close=66500.0)
+ ts = pd.Timestamp("2025-01-02")
+ engine._check_liquidation("BTC-USDT", bar, ts)
+ assert "BTC-USDT" not in engine.positions
+
+
+# ---------------------------------------------------------------------------
+# Tiered maintenance margin
+# ---------------------------------------------------------------------------
+
+
+class TestMaintenanceRate:
+ def test_small_position(self) -> None:
+ assert CryptoEngine._maintenance_rate(50_000) == 0.004
+
+ def test_medium_position(self) -> None:
+ assert CryptoEngine._maintenance_rate(300_000) == 0.006
+
+ def test_large_position(self) -> None:
+ assert CryptoEngine._maintenance_rate(2_000_000) == 0.02
+
+ def test_tier_boundaries(self) -> None:
+ assert CryptoEngine._maintenance_rate(100_000) == 0.004
+ assert CryptoEngine._maintenance_rate(100_001) == 0.006
+
+ def test_maximum_tier(self) -> None:
+ assert CryptoEngine._maintenance_rate(100_000_000) == 0.10
diff --git a/agent/tests/test_global_equity_engine.py b/agent/tests/test_global_equity_engine.py
new file mode 100644
index 000000000..d6f62f558
--- /dev/null
+++ b/agent/tests/test_global_equity_engine.py
@@ -0,0 +1,175 @@
+"""Tests for GlobalEquityEngine (US / HK) market rules.
+
+Validates:
+ - US: zero commission, fractional shares, low slippage
+ - HK: stamp tax bilateral, 100-share lots, levies
+ - T+0 for both markets
+ - Both directions allowed
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from backtest.engines.global_equity import GlobalEquityEngine
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_bar(close: float = 180.0) -> pd.Series:
+ return pd.Series({"close": close, "open": close})
+
+
+def _us_engine(**overrides) -> GlobalEquityEngine:
+ config = {"initial_cash": 500_000}
+ config.update(overrides)
+ return GlobalEquityEngine(config, market="us")
+
+
+def _hk_engine(**overrides) -> GlobalEquityEngine:
+ config = {"initial_cash": 1_000_000}
+ config.update(overrides)
+ return GlobalEquityEngine(config, market="hk")
+
+
+# ---------------------------------------------------------------------------
+# can_execute: T+0 both directions
+# ---------------------------------------------------------------------------
+
+
+class TestCanExecute:
+ def test_us_long(self) -> None:
+ assert _us_engine().can_execute("AAPL.US", 1, _make_bar()) is True
+
+ def test_us_short(self) -> None:
+ assert _us_engine().can_execute("AAPL.US", -1, _make_bar()) is True
+
+ def test_us_close(self) -> None:
+ assert _us_engine().can_execute("AAPL.US", 0, _make_bar()) is True
+
+ def test_hk_long(self) -> None:
+ assert _hk_engine().can_execute("0700.HK", 1, _make_bar()) is True
+
+ def test_hk_short(self) -> None:
+ assert _hk_engine().can_execute("0700.HK", -1, _make_bar()) is True
+
+
+# ---------------------------------------------------------------------------
+# round_size: US fractional vs HK lots
+# ---------------------------------------------------------------------------
+
+
+class TestRoundSize:
+ def test_us_fractional(self) -> None:
+ engine = _us_engine()
+ assert engine.round_size(10.567, 180.0) == 10.57
+
+ def test_us_tiny_fraction(self) -> None:
+ engine = _us_engine()
+ assert engine.round_size(0.005, 180.0) == 0.01
+
+ def test_us_negative_clamps(self) -> None:
+ engine = _us_engine()
+ assert engine.round_size(-5.0, 180.0) == 0.0
+
+ def test_hk_100_share_lots(self) -> None:
+ engine = _hk_engine()
+ assert engine.round_size(350.0, 350.0) == 300
+ assert engine.round_size(99.0, 350.0) == 0
+ assert engine.round_size(500.0, 350.0) == 500
+
+ def test_hk_rounds_down(self) -> None:
+ engine = _hk_engine()
+ assert engine.round_size(199.0, 80.0) == 100
+
+
+# ---------------------------------------------------------------------------
+# calc_commission: US zero vs HK complex
+# ---------------------------------------------------------------------------
+
+
+class TestCommission:
+ def test_us_zero_commission(self) -> None:
+ engine = _us_engine()
+ comm = engine.calc_commission(100.0, 180.0, 1, is_open=True)
+ assert comm == 0.0
+
+ def test_us_zero_both_sides(self) -> None:
+ engine = _us_engine()
+ assert engine.calc_commission(100.0, 180.0, 1, is_open=True) == 0.0
+ assert engine.calc_commission(100.0, 180.0, 1, is_open=False) == 0.0
+
+ def test_hk_has_commission(self) -> None:
+ engine = _hk_engine()
+ comm = engine.calc_commission(1000, 350.0, 1, is_open=True)
+ assert comm > 0
+
+ def test_hk_stamp_tax_bilateral(self) -> None:
+ """HK stamp tax charged on both buy and sell."""
+ engine = _hk_engine()
+ comm_buy = engine.calc_commission(1000, 350.0, 1, is_open=True)
+ comm_sell = engine.calc_commission(1000, 350.0, 1, is_open=False)
+ # Both should be approximately equal (stamp tax bilateral)
+ assert comm_buy == pytest.approx(comm_sell, rel=0.01)
+
+ def test_hk_commission_components(self) -> None:
+ """Verify HK commission includes all components."""
+ engine = _hk_engine()
+ size, price = 1000, 350.0
+ notional = size * price # 350,000
+ comm = engine.calc_commission(size, price, 1, is_open=True)
+ # Expected components:
+ expected = (
+ notional * engine.hk_commission # broker ~¥52.5
+ + notional * engine.hk_stamp_tax # stamp ~¥350
+ + notional * engine.hk_levy # SFC+FRC ~¥19.8
+ + notional * engine.hk_settlement # CCASS ~¥7
+ )
+ assert comm == pytest.approx(expected, abs=0.01)
+
+
+# ---------------------------------------------------------------------------
+# apply_slippage: US low vs HK moderate
+# ---------------------------------------------------------------------------
+
+
+class TestSlippage:
+ def test_us_lower_slippage(self) -> None:
+ engine = _us_engine()
+ us_slipped = engine.apply_slippage(100.0, 1) - 100.0
+ hk_engine = _hk_engine()
+ hk_slipped = hk_engine.apply_slippage(100.0, 1) - 100.0
+ assert us_slipped < hk_slipped
+
+ def test_us_slippage_rate(self) -> None:
+ engine = _us_engine()
+ assert engine.apply_slippage(100.0, 1) == pytest.approx(100.05)
+
+ def test_hk_slippage_rate(self) -> None:
+ engine = _hk_engine()
+ assert engine.apply_slippage(100.0, 1) == pytest.approx(100.1)
+
+ def test_custom_slippage(self) -> None:
+ engine = GlobalEquityEngine(
+ {"initial_cash": 500_000, "slippage_us": 0.002}, market="us",
+ )
+ assert engine.apply_slippage(100.0, 1) == pytest.approx(100.2)
+
+
+# ---------------------------------------------------------------------------
+# Market parameter
+# ---------------------------------------------------------------------------
+
+
+class TestMarketParam:
+ def test_default_is_us(self) -> None:
+ engine = GlobalEquityEngine({"initial_cash": 100_000})
+ assert engine.market == "us"
+
+ def test_hk_market(self) -> None:
+ engine = GlobalEquityEngine({"initial_cash": 100_000}, market="hk")
+ assert engine.market == "hk"
diff --git a/agent/tests/test_llm.py b/agent/tests/test_llm.py
new file mode 100644
index 000000000..b5eb68ef0
--- /dev/null
+++ b/agent/tests/test_llm.py
@@ -0,0 +1,135 @@
+"""Tests for LLM provider mapping and JSON extraction."""
+
+from __future__ import annotations
+
+import os
+from unittest.mock import patch
+
+import pytest
+
+from src.providers.llm import _extract_balanced_json, _sync_provider_env
+
+
+# ---------------------------------------------------------------------------
+# _sync_provider_env
+# ---------------------------------------------------------------------------
+
+
+class TestSyncProviderEnv:
+ """Provider-specific env vars → OPENAI_* mapping."""
+
+ def _run_sync(self, env: dict[str, str]) -> dict[str, str]:
+ """Run _sync_provider_env with a clean env and return relevant keys."""
+ # Reset the dotenv guard so it doesn't skip
+ import src.providers.llm as llm_mod
+ llm_mod._dotenv_loaded = True # pretend already loaded
+
+ clean = {k: v for k, v in os.environ.items() if not k.startswith(("OPENAI_", "LANGCHAIN_", "DEEPSEEK_", "GROQ_", "OLLAMA_", "DASHSCOPE_"))}
+ clean.update(env)
+ with patch.dict(os.environ, clean, clear=True):
+ _sync_provider_env()
+ return {
+ "OPENAI_API_KEY": os.environ.get("OPENAI_API_KEY", ""),
+ "OPENAI_API_BASE": os.environ.get("OPENAI_API_BASE", ""),
+ "OPENAI_BASE_URL": os.environ.get("OPENAI_BASE_URL", ""),
+ }
+
+ def test_openai_default(self) -> None:
+ result = self._run_sync({
+ "OPENAI_API_KEY": "sk-test",
+ })
+ assert result["OPENAI_API_KEY"] == "sk-test"
+
+ def test_deepseek_provider(self) -> None:
+ result = self._run_sync({
+ "LANGCHAIN_PROVIDER": "deepseek",
+ "DEEPSEEK_API_KEY": "ds-key-123",
+ "DEEPSEEK_BASE_URL": "https://api.deepseek.com/v1",
+ })
+ assert result["OPENAI_API_KEY"] == "ds-key-123"
+ assert result["OPENAI_API_BASE"] == "https://api.deepseek.com/v1"
+
+ def test_groq_provider(self) -> None:
+ result = self._run_sync({
+ "LANGCHAIN_PROVIDER": "groq",
+ "GROQ_API_KEY": "gsk-test",
+ "GROQ_BASE_URL": "https://api.groq.com/openai/v1",
+ })
+ assert result["OPENAI_API_KEY"] == "gsk-test"
+ assert "groq" in result["OPENAI_API_BASE"]
+
+ def test_ollama_no_key_required(self) -> None:
+ result = self._run_sync({
+ "LANGCHAIN_PROVIDER": "ollama",
+ "OLLAMA_BASE_URL": "http://localhost:11434/v1",
+ })
+ # Ollama uses "ollama" as fallback key
+ assert result["OPENAI_API_KEY"] in ("ollama", "")
+ assert "localhost" in result["OPENAI_API_BASE"]
+
+ def test_qwen_alias_to_dashscope(self) -> None:
+ result = self._run_sync({
+ "LANGCHAIN_PROVIDER": "qwen",
+ "DASHSCOPE_API_KEY": "qwen-key",
+ "DASHSCOPE_BASE_URL": "https://dashscope.aliyuncs.com/v1",
+ })
+ assert result["OPENAI_API_KEY"] == "qwen-key"
+
+ def test_unknown_provider_falls_back_to_openai(self) -> None:
+ result = self._run_sync({
+ "LANGCHAIN_PROVIDER": "unknown_provider_xyz",
+ "OPENAI_API_KEY": "sk-fallback",
+ })
+ assert result["OPENAI_API_KEY"] == "sk-fallback"
+
+ def test_provider_key_fallback_to_openai_key(self) -> None:
+ """If provider-specific key is missing, fall back to OPENAI_API_KEY."""
+ result = self._run_sync({
+ "LANGCHAIN_PROVIDER": "deepseek",
+ "OPENAI_API_KEY": "sk-shared",
+ })
+ assert result["OPENAI_API_KEY"] == "sk-shared"
+
+
+# ---------------------------------------------------------------------------
+# _extract_balanced_json
+# ---------------------------------------------------------------------------
+
+
+class TestExtractBalancedJson:
+ def test_simple_json(self) -> None:
+ result = _extract_balanced_json('{"key": "value"}')
+ assert result == {"key": "value"}
+
+ def test_json_embedded_in_text(self) -> None:
+ text = 'Here is the config: {"a": 1, "b": 2} and some more text.'
+ result = _extract_balanced_json(text)
+ assert result == {"a": 1, "b": 2}
+
+ def test_nested_json(self) -> None:
+ text = '{"outer": {"inner": [1, 2, 3]}}'
+ result = _extract_balanced_json(text)
+ assert result["outer"]["inner"] == [1, 2, 3]
+
+ def test_escaped_quotes(self) -> None:
+ text = r'{"msg": "he said \"hello\""}'
+ result = _extract_balanced_json(text)
+ assert result is not None
+ assert "hello" in result["msg"]
+
+ def test_no_json(self) -> None:
+ assert _extract_balanced_json("no json here") is None
+
+ def test_empty_string(self) -> None:
+ assert _extract_balanced_json("") is None
+
+ def test_braces_in_strings(self) -> None:
+ text = '{"pattern": "if (x > 0) { return x; }"}'
+ result = _extract_balanced_json(text)
+ assert result is not None
+ assert "return x" in result["pattern"]
+
+ def test_multiple_objects_returns_first(self) -> None:
+ text = '{"a": 1} {"b": 2}'
+ result = _extract_balanced_json(text)
+ assert result == {"a": 1}
diff --git a/agent/tests/test_market_detection.py b/agent/tests/test_market_detection.py
new file mode 100644
index 000000000..f06fc648c
--- /dev/null
+++ b/agent/tests/test_market_detection.py
@@ -0,0 +1,145 @@
+"""Tests for runner market detection, source mapping, and code normalization."""
+
+from __future__ import annotations
+
+import pytest
+
+from backtest.runner import (
+ _detect_market,
+ _detect_source,
+ _group_codes_by_market,
+ _group_codes_by_source,
+ _normalize_codes,
+)
+
+
+# ---------------------------------------------------------------------------
+# _detect_market
+# ---------------------------------------------------------------------------
+
+
+class TestDetectMarket:
+ """Symbol pattern → market type mapping."""
+
+ @pytest.mark.parametrize(
+ "code, expected",
+ [
+ # A-share mainboard
+ ("000001.SZ", "a_share"),
+ ("600519.SH", "a_share"),
+ ("300750.SZ", "a_share"),
+ # A-share Beijing exchange
+ ("830799.BJ", "a_share"),
+ # A-share ETF
+ ("510300.SH", "a_share"),
+ ("159919.SZ", "a_share"),
+ ("560010.SH", "a_share"),
+ # US equity
+ ("AAPL.US", "us_equity"),
+ ("TSLA.US", "us_equity"),
+ ("NVDA.US", "us_equity"),
+ # HK equity
+ ("0700.HK", "hk_equity"),
+ ("9988.HK", "hk_equity"),
+ ("00005.HK", "hk_equity"),
+ # Crypto
+ ("BTC-USDT", "crypto"),
+ ("ETH-USDT", "crypto"),
+ ("BTC/USDT", "crypto"),
+ # Futures
+ ("IF2406.CFFEX", "futures"),
+ ("AU2412.SHFE", "futures"),
+ ("C2409.DCE", "futures"),
+ ("CF2409.ZCE", "futures"),
+ ("SC2406.INE", "futures"),
+ # Forex
+ ("EUR/USD", "forex"),
+ ("USD/JPY", "forex"),
+ ("EURUSD.FX", "forex"),
+ ],
+ )
+ def test_known_patterns(self, code: str, expected: str) -> None:
+ assert _detect_market(code) == expected
+
+ def test_case_insensitive(self) -> None:
+ assert _detect_market("000001.sz") == "a_share"
+ assert _detect_market("aapl.us") == "us_equity"
+ assert _detect_market("btc-usdt") == "crypto"
+
+ def test_unknown_defaults_to_a_share(self) -> None:
+ assert _detect_market("UNKNOWN") == "a_share"
+ assert _detect_market("random-string") == "a_share"
+
+
+# ---------------------------------------------------------------------------
+# _detect_source
+# ---------------------------------------------------------------------------
+
+
+class TestDetectSource:
+ """Market type → legacy source name."""
+
+ @pytest.mark.parametrize(
+ "code, expected_source",
+ [
+ ("000001.SZ", "tushare"),
+ ("AAPL.US", "yfinance"),
+ ("0700.HK", "yfinance"),
+ ("BTC-USDT", "okx"),
+ ("IF2406.CFFEX", "tushare"),
+ ("EUR/USD", "akshare"),
+ ],
+ )
+ def test_source_mapping(self, code: str, expected_source: str) -> None:
+ assert _detect_source(code) == expected_source
+
+
+# ---------------------------------------------------------------------------
+# _group_codes_by_market
+# ---------------------------------------------------------------------------
+
+
+class TestGroupCodes:
+ def test_mixed_codes(self) -> None:
+ codes = ["000001.SZ", "AAPL.US", "BTC-USDT", "0700.HK"]
+ groups = _group_codes_by_market(codes)
+ assert groups["a_share"] == ["000001.SZ"]
+ assert groups["us_equity"] == ["AAPL.US"]
+ assert groups["crypto"] == ["BTC-USDT"]
+ assert groups["hk_equity"] == ["0700.HK"]
+
+ def test_same_market(self) -> None:
+ codes = ["000001.SZ", "600519.SH"]
+ groups = _group_codes_by_market(codes)
+ assert groups["a_share"] == ["000001.SZ", "600519.SH"]
+ assert len(groups) == 1
+
+ def test_empty(self) -> None:
+ assert _group_codes_by_market([]) == {}
+
+ def test_group_by_source(self) -> None:
+ codes = ["000001.SZ", "AAPL.US"]
+ groups = _group_codes_by_source(codes)
+ assert "tushare" in groups
+ assert "yfinance" in groups
+
+
+# ---------------------------------------------------------------------------
+# _normalize_codes
+# ---------------------------------------------------------------------------
+
+
+class TestNormalizeCodes:
+ def test_okx_slash_to_hyphen(self) -> None:
+ assert _normalize_codes(["btc/usdt", "eth/usdt"], "okx") == [
+ "BTC-USDT",
+ "ETH-USDT",
+ ]
+
+ def test_ccxt_uppercase(self) -> None:
+ assert _normalize_codes(["btc-usdt"], "ccxt") == ["BTC-USDT"]
+
+ def test_non_crypto_unchanged(self) -> None:
+ codes = ["000001.SZ", "AAPL.US"]
+ assert _normalize_codes(codes, "tushare") == codes
+ assert _normalize_codes(codes, "yfinance") == codes
diff --git a/agent/tests/test_metrics.py b/agent/tests/test_metrics.py
new file mode 100644
index 000000000..bd4f14135
--- /dev/null
+++ b/agent/tests/test_metrics.py
@@ -0,0 +1,280 @@
+"""Tests for backtest metrics calculation.
+
+Validates:
+ - bars_per_year annualization
+ - win_rate_and_stats
+ - by_symbol_stats / by_exit_reason_stats
+ - calc_metrics (Sharpe, drawdown, Sortino, Calmar, etc.)
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.metrics import (
+ by_exit_reason_stats,
+ by_symbol_stats,
+ calc_bars_per_year,
+ calc_metrics,
+ win_rate_and_stats,
+)
+from backtest.models import TradeRecord
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _trade(
+ symbol: str = "X",
+ pnl: float = 100.0,
+ direction: int = 1,
+ exit_reason: str = "signal",
+ holding_bars: int = 5,
+) -> TradeRecord:
+ return TradeRecord(
+ symbol=symbol,
+ direction=direction,
+ entry_price=100.0,
+ exit_price=100.0 + pnl / 100,
+ entry_time=pd.Timestamp("2025-01-01"),
+ exit_time=pd.Timestamp("2025-01-06"),
+ size=100.0,
+ leverage=1.0,
+ pnl=pnl,
+ pnl_pct=pnl / 100,
+ exit_reason=exit_reason,
+ holding_bars=holding_bars,
+ commission=1.0,
+ )
+
+
+# ---------------------------------------------------------------------------
+# calc_bars_per_year
+# ---------------------------------------------------------------------------
+
+
+class TestBarsPerYear:
+ def test_daily_tushare(self) -> None:
+ assert calc_bars_per_year("1D", "tushare") == 252
+
+ def test_daily_okx(self) -> None:
+ assert calc_bars_per_year("1D", "okx") == 365
+
+ def test_minute_tushare(self) -> None:
+ # 252 trading days × 240 minutes/day = 60480
+ assert calc_bars_per_year("1m", "tushare") == 252 * 240
+
+ def test_hourly_okx(self) -> None:
+ # 365 days × 24 hours/day = 8760
+ assert calc_bars_per_year("1H", "okx") == 365 * 24
+
+ def test_unknown_source(self) -> None:
+ # Falls back to 252 trading days
+ assert calc_bars_per_year("1D", "unknown") == 252
+
+ def test_unknown_interval(self) -> None:
+ # Falls back to 1 bar/day
+ assert calc_bars_per_year("2H", "tushare") == 252
+
+
+# ---------------------------------------------------------------------------
+# win_rate_and_stats
+# ---------------------------------------------------------------------------
+
+
+class TestWinRateAndStats:
+ def test_all_winners(self) -> None:
+ trades = [_trade(pnl=100), _trade(pnl=200), _trade(pnl=50)]
+ stats = win_rate_and_stats(trades)
+ assert stats["win_rate"] == 1.0
+ assert stats["max_consecutive_loss"] == 0
+
+ def test_all_losers(self) -> None:
+ trades = [_trade(pnl=-100), _trade(pnl=-200)]
+ stats = win_rate_and_stats(trades)
+ assert stats["win_rate"] == 0.0
+ assert stats["max_consecutive_loss"] == 2
+
+ def test_mixed(self) -> None:
+ trades = [_trade(pnl=100), _trade(pnl=-50), _trade(pnl=200)]
+ stats = win_rate_and_stats(trades)
+ assert stats["win_rate"] == pytest.approx(2 / 3)
+ assert stats["max_consecutive_loss"] == 1
+
+ def test_profit_factor(self) -> None:
+ trades = [_trade(pnl=300), _trade(pnl=-100)]
+ stats = win_rate_and_stats(trades)
+ assert stats["profit_factor"] == pytest.approx(3.0)
+
+ def test_profit_loss_ratio(self) -> None:
+ trades = [_trade(pnl=200), _trade(pnl=-100)]
+ stats = win_rate_and_stats(trades)
+ assert stats["profit_loss_ratio"] == pytest.approx(2.0)
+
+ def test_empty_trades(self) -> None:
+ stats = win_rate_and_stats([])
+ assert stats["win_rate"] == 0.0
+ assert stats["profit_factor"] == 0.0
+
+ def test_consecutive_losses(self) -> None:
+ trades = [
+ _trade(pnl=100),
+ _trade(pnl=-10),
+ _trade(pnl=-20),
+ _trade(pnl=-30),
+ _trade(pnl=50),
+ _trade(pnl=-5),
+ ]
+ stats = win_rate_and_stats(trades)
+ assert stats["max_consecutive_loss"] == 3
+
+ def test_avg_holding_bars(self) -> None:
+ trades = [_trade(holding_bars=5), _trade(holding_bars=10), _trade(holding_bars=15)]
+ stats = win_rate_and_stats(trades)
+ assert stats["avg_holding_bars"] == 10.0
+
+
+# ---------------------------------------------------------------------------
+# by_symbol_stats
+# ---------------------------------------------------------------------------
+
+
+class TestBySymbolStats:
+ def test_single_symbol(self) -> None:
+ trades = [_trade("AAPL", 100), _trade("AAPL", -50)]
+ stats = by_symbol_stats(trades)
+ assert "AAPL" in stats
+ assert stats["AAPL"]["count"] == 2
+ assert stats["AAPL"]["total_pnl"] == 50.0
+ assert stats["AAPL"]["win_rate"] == 0.5
+
+ def test_multiple_symbols(self) -> None:
+ trades = [_trade("A", 100), _trade("B", -50), _trade("A", 200)]
+ stats = by_symbol_stats(trades)
+ assert stats["A"]["count"] == 2
+ assert stats["B"]["count"] == 1
+
+ def test_empty(self) -> None:
+ assert by_symbol_stats([]) == {}
+
+
+# ---------------------------------------------------------------------------
+# by_exit_reason_stats
+# ---------------------------------------------------------------------------
+
+
+class TestByExitReasonStats:
+ def test_single_reason(self) -> None:
+ trades = [_trade(exit_reason="signal", pnl=100), _trade(exit_reason="signal", pnl=-50)]
+ stats = by_exit_reason_stats(trades)
+ assert stats["signal"]["count"] == 2
+ assert stats["signal"]["total_pnl"] == 50.0
+
+ def test_multiple_reasons(self) -> None:
+ trades = [
+ _trade(exit_reason="signal", pnl=100),
+ _trade(exit_reason="liquidation", pnl=-500),
+ _trade(exit_reason="end_of_backtest", pnl=50),
+ ]
+ stats = by_exit_reason_stats(trades)
+ assert len(stats) == 3
+ assert stats["liquidation"]["total_pnl"] == -500.0
+
+ def test_empty(self) -> None:
+ assert by_exit_reason_stats([]) == {}
+
+
+# ---------------------------------------------------------------------------
+# calc_metrics
+# ---------------------------------------------------------------------------
+
+
+class TestCalcMetrics:
+ def _flat_equity(self) -> pd.Series:
+ """Equity that stays flat at 1M (zero return)."""
+ dates = pd.bdate_range("2025-01-01", periods=252)
+ return pd.Series(1_000_000.0, index=dates)
+
+ def _growing_equity(self) -> pd.Series:
+ """Equity that grows linearly from 1M to 1.2M (20% return)."""
+ dates = pd.bdate_range("2025-01-01", periods=252)
+ return pd.Series(np.linspace(1_000_000, 1_200_000, 252), index=dates)
+
+ def _declining_equity(self) -> pd.Series:
+ """Equity that declines from 1M to 800K (-20%)."""
+ dates = pd.bdate_range("2025-01-01", periods=252)
+ return pd.Series(np.linspace(1_000_000, 800_000, 252), index=dates)
+
+ def test_total_return(self) -> None:
+ eq = self._growing_equity()
+ m = calc_metrics(eq, [], 1_000_000, 252)
+ assert m["total_return"] == pytest.approx(0.2, rel=0.01)
+
+ def test_negative_return(self) -> None:
+ eq = self._declining_equity()
+ m = calc_metrics(eq, [], 1_000_000, 252)
+ assert m["total_return"] < 0
+
+ def test_max_drawdown_negative(self) -> None:
+ eq = self._declining_equity()
+ m = calc_metrics(eq, [], 1_000_000, 252)
+ assert m["max_drawdown"] < 0
+
+ def test_flat_equity_zero_return(self) -> None:
+ eq = self._flat_equity()
+ m = calc_metrics(eq, [], 1_000_000, 252)
+ assert m["total_return"] == pytest.approx(0.0)
+
+ def test_sharpe_positive_for_growth(self) -> None:
+ eq = self._growing_equity()
+ m = calc_metrics(eq, [], 1_000_000, 252)
+ assert m["sharpe"] > 0
+
+ def test_trade_count(self) -> None:
+ eq = self._growing_equity()
+ trades = [_trade(pnl=100), _trade(pnl=-50)]
+ m = calc_metrics(eq, trades, 1_000_000, 252)
+ assert m["trade_count"] == 2
+ assert m["win_rate"] == 0.5
+
+ def test_benchmark_comparison(self) -> None:
+ eq = self._growing_equity()
+ dates = eq.index
+ bench_ret = pd.Series(0.0004, index=dates) # ~10% annual
+ m = calc_metrics(eq, [], 1_000_000, 252, bench_ret=bench_ret)
+ assert m["benchmark_return"] > 0
+ assert "excess_return" in m
+ assert "information_ratio" in m
+
+ def test_empty_equity(self) -> None:
+ m = calc_metrics(pd.Series(dtype=float), [], 1_000_000, 252)
+ assert m["final_value"] == 1_000_000
+ assert m["total_return"] == 0
+
+ def test_final_value(self) -> None:
+ eq = self._growing_equity()
+ m = calc_metrics(eq, [], 1_000_000, 252)
+ assert m["final_value"] == pytest.approx(1_200_000, rel=0.01)
+
+ def test_sortino_positive_for_growth(self) -> None:
+ eq = self._growing_equity()
+ m = calc_metrics(eq, [], 1_000_000, 252)
+ assert m["sortino"] > 0
+
+ def test_calmar_positive_for_drawdown(self) -> None:
+ """Growing equity with a dip should have positive Calmar."""
+ dates = pd.bdate_range("2025-01-01", periods=100)
+ values = np.concatenate([
+ np.linspace(1_000_000, 900_000, 30), # dip
+ np.linspace(900_000, 1_200_000, 70), # recovery
+ ])
+ eq = pd.Series(values, index=dates)
+ m = calc_metrics(eq, [], 1_000_000, 252)
+ assert m["max_drawdown"] < 0
+ # Calmar = annual_return / |max_drawdown|
+ if m["annual_return"] > 0:
+ assert m["calmar"] > 0
diff --git a/agent/tests/test_models.py b/agent/tests/test_models.py
new file mode 100644
index 000000000..f301b7bb9
--- /dev/null
+++ b/agent/tests/test_models.py
@@ -0,0 +1,89 @@
+"""Tests for backtest data models (Position, TradeRecord, EquitySnapshot)."""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from backtest.models import EquitySnapshot, Position, TradeRecord
+
+
+class TestPosition:
+ def test_creation(self) -> None:
+ pos = Position(
+ symbol="AAPL.US",
+ direction=1,
+ entry_price=150.0,
+ entry_time=pd.Timestamp("2025-01-02"),
+ size=100.0,
+ )
+ assert pos.symbol == "AAPL.US"
+ assert pos.direction == 1
+ assert pos.leverage == 1.0 # default
+
+ def test_frozen(self) -> None:
+ pos = Position(
+ symbol="AAPL.US",
+ direction=1,
+ entry_price=150.0,
+ entry_time=pd.Timestamp("2025-01-02"),
+ size=100.0,
+ )
+ with pytest.raises(AttributeError):
+ pos.size = 200.0 # type: ignore[misc]
+
+ def test_leverage_default(self) -> None:
+ pos = Position("BTC-USDT", -1, 60000.0, pd.Timestamp("2025-01-01"), 0.5)
+ assert pos.leverage == 1.0
+
+ def test_leverage_custom(self) -> None:
+ pos = Position("BTC-USDT", -1, 60000.0, pd.Timestamp("2025-01-01"), 0.5, leverage=10.0)
+ assert pos.leverage == 10.0
+
+
+class TestTradeRecord:
+ def test_creation(self) -> None:
+ trade = TradeRecord(
+ symbol="000001.SZ",
+ direction=1,
+ entry_price=15.0,
+ exit_price=16.0,
+ entry_time=pd.Timestamp("2025-01-02"),
+ exit_time=pd.Timestamp("2025-01-10"),
+ size=1000.0,
+ leverage=1.0,
+ pnl=1000.0,
+ pnl_pct=0.0667,
+ exit_reason="signal",
+ holding_bars=6,
+ commission=12.5,
+ )
+ assert trade.pnl == 1000.0
+ assert trade.exit_reason == "signal"
+
+ def test_frozen(self) -> None:
+ trade = TradeRecord(
+ "X", 1, 10.0, 11.0,
+ pd.Timestamp("2025-01-01"), pd.Timestamp("2025-01-02"),
+ 100.0, 1.0, 100.0, 0.1, "signal", 1, 0.0,
+ )
+ with pytest.raises(AttributeError):
+ trade.pnl = 999.0 # type: ignore[misc]
+
+
+class TestEquitySnapshot:
+ def test_creation(self) -> None:
+ snap = EquitySnapshot(
+ timestamp=pd.Timestamp("2025-06-15"),
+ capital=900_000.0,
+ unrealized=50_000.0,
+ equity=950_000.0,
+ positions=3,
+ )
+ assert snap.equity == 950_000.0
+ assert snap.positions == 3
+
+ def test_frozen(self) -> None:
+ snap = EquitySnapshot(pd.Timestamp("2025-01-01"), 1e6, 0.0, 1e6, 0)
+ with pytest.raises(AttributeError):
+ snap.capital = 0.0 # type: ignore[misc]
diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.py
new file mode 100644
index 000000000..a357dce2d
--- /dev/null
+++ b/agent/tests/test_registry.py
@@ -0,0 +1,179 @@
+"""Tests for loader registry and fallback chain logic."""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+import pandas as pd
+import pytest
+
+from backtest.loaders.base import DataLoaderProtocol, NoAvailableSourceError
+from backtest.loaders.registry import (
+ FALLBACK_CHAINS,
+ LOADER_REGISTRY,
+ get_loader_cls_with_fallback,
+ register,
+ resolve_loader,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers — fake loaders
+# ---------------------------------------------------------------------------
+
+
+class _FakeAvailableLoader:
+ name = "fake_available"
+ markets = {"a_share"}
+ requires_auth = False
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {}
+
+
+class _FakeUnavailableLoader:
+ name = "fake_unavailable"
+ markets = {"a_share"}
+ requires_auth = True
+
+ def is_available(self) -> bool:
+ return False
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {}
+
+
+class _FakeCryptoLoader:
+ name = "fake_crypto"
+ markets = {"crypto"}
+ requires_auth = False
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {}
+
+
+# ---------------------------------------------------------------------------
+# @register decorator
+# ---------------------------------------------------------------------------
+
+
+class TestRegisterDecorator:
+ def test_register_adds_to_registry(self) -> None:
+ # Use a patched registry to avoid polluting global state
+ with patch.dict(LOADER_REGISTRY, {}, clear=True):
+ register(_FakeAvailableLoader)
+ assert "fake_available" in LOADER_REGISTRY
+ assert LOADER_REGISTRY["fake_available"] is _FakeAvailableLoader
+
+ def test_register_returns_class_unchanged(self) -> None:
+ with patch.dict(LOADER_REGISTRY, {}, clear=True):
+ result = register(_FakeAvailableLoader)
+ assert result is _FakeAvailableLoader
+
+
+# ---------------------------------------------------------------------------
+# Protocol conformance
+# ---------------------------------------------------------------------------
+
+
+class TestProtocol:
+ def test_fake_loader_satisfies_protocol(self) -> None:
+ assert isinstance(_FakeAvailableLoader(), DataLoaderProtocol)
+
+ def test_missing_method_fails_protocol(self) -> None:
+ class BadLoader:
+ name = "bad"
+
+ assert not isinstance(BadLoader(), DataLoaderProtocol)
+
+
+# ---------------------------------------------------------------------------
+# FALLBACK_CHAINS
+# ---------------------------------------------------------------------------
+
+
+class TestFallbackChains:
+ def test_all_expected_markets_present(self) -> None:
+ expected = {"a_share", "us_equity", "hk_equity", "crypto", "futures", "fund", "macro", "forex"}
+ assert expected == set(FALLBACK_CHAINS.keys())
+
+ def test_chains_are_non_empty(self) -> None:
+ for market, chain in FALLBACK_CHAINS.items():
+ assert len(chain) > 0, f"Fallback chain for {market} is empty"
+
+
+# ---------------------------------------------------------------------------
+# resolve_loader
+# ---------------------------------------------------------------------------
+
+
+class TestResolveLoader:
+ def test_returns_first_available(self) -> None:
+ with patch.dict(LOADER_REGISTRY, {
+ "fake_unavailable": _FakeUnavailableLoader,
+ "fake_available": _FakeAvailableLoader,
+ }, clear=True):
+ with patch.dict(FALLBACK_CHAINS, {
+ "a_share": ["fake_unavailable", "fake_available"],
+ }):
+ loader = resolve_loader("a_share")
+ assert loader.name == "fake_available"
+
+ def test_raises_when_none_available(self) -> None:
+ with patch.dict(LOADER_REGISTRY, {
+ "fake_unavailable": _FakeUnavailableLoader,
+ }, clear=True):
+ with patch.dict(FALLBACK_CHAINS, {
+ "a_share": ["fake_unavailable"],
+ }):
+ with pytest.raises(NoAvailableSourceError):
+ resolve_loader("a_share")
+
+ def test_unknown_market_raises(self) -> None:
+ with patch.dict(LOADER_REGISTRY, {}, clear=True):
+ with pytest.raises(NoAvailableSourceError):
+ resolve_loader("martian_stocks")
+
+
+# ---------------------------------------------------------------------------
+# get_loader_cls_with_fallback
+# ---------------------------------------------------------------------------
+
+
+class TestGetLoaderWithFallback:
+ def test_returns_requested_if_available(self) -> None:
+ with patch.dict(LOADER_REGISTRY, {
+ "fake_available": _FakeAvailableLoader,
+ }, clear=True):
+ cls = get_loader_cls_with_fallback("fake_available")
+ assert cls is _FakeAvailableLoader
+
+ def test_falls_back_when_unavailable(self) -> None:
+ with patch.dict(LOADER_REGISTRY, {
+ "fake_unavailable": _FakeUnavailableLoader,
+ "fake_available": _FakeAvailableLoader,
+ }, clear=True):
+ with patch.dict(FALLBACK_CHAINS, {
+ "a_share": ["fake_unavailable", "fake_available"],
+ }):
+ cls = get_loader_cls_with_fallback("fake_unavailable")
+ assert cls is _FakeAvailableLoader
+
+ def test_unknown_source_raises(self) -> None:
+ with patch.dict(LOADER_REGISTRY, {}, clear=True):
+ with pytest.raises(NoAvailableSourceError):
+ get_loader_cls_with_fallback("nonexistent")
+
+ def test_no_fallback_raises(self) -> None:
+ with patch.dict(LOADER_REGISTRY, {
+ "fake_unavailable": _FakeUnavailableLoader,
+ }, clear=True):
+ with patch.dict(FALLBACK_CHAINS, {"a_share": ["fake_unavailable"]}):
+ with pytest.raises(NoAvailableSourceError):
+ get_loader_cls_with_fallback("fake_unavailable")
diff --git a/agent/tests/test_risk_parity.py b/agent/tests/test_risk_parity.py
new file mode 100644
index 000000000..7427839b8
--- /dev/null
+++ b/agent/tests/test_risk_parity.py
@@ -0,0 +1,98 @@
+"""Tests for risk parity optimizer."""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.optimizers.risk_parity import RiskParityOptimizer
+
+
+class TestRiskParityCalcWeights:
+ """Unit tests for the core weight calculation."""
+
+ def test_equal_vol_gives_equal_weight(self) -> None:
+ """Assets with identical volatility → equal weights."""
+ n = 3
+ vol = 0.02
+ cov = np.eye(n) * vol**2
+ opt = RiskParityOptimizer()
+ w = opt._calc_weights({"cov": cov})
+ np.testing.assert_allclose(w, np.ones(n) / n, atol=1e-6)
+
+ def test_weights_sum_to_one(self) -> None:
+ rng = np.random.default_rng(42)
+ n = 5
+ A = rng.standard_normal((100, n))
+ cov = np.cov(A.T)
+ opt = RiskParityOptimizer()
+ w = opt._calc_weights({"cov": cov})
+ assert abs(w.sum() - 1.0) < 1e-10
+
+ def test_weights_nonnegative(self) -> None:
+ rng = np.random.default_rng(7)
+ n = 4
+ A = rng.standard_normal((100, n))
+ cov = np.cov(A.T)
+ opt = RiskParityOptimizer()
+ w = opt._calc_weights({"cov": cov})
+ assert np.all(w >= -1e-12)
+
+ def test_higher_vol_gets_lower_weight(self) -> None:
+ """Asset with higher volatility should get lower weight."""
+ cov = np.diag([0.01, 0.04]) # vol = 0.1 vs 0.2
+ opt = RiskParityOptimizer()
+ w = opt._calc_weights({"cov": cov})
+ assert w[0] > w[1], "Lower-vol asset should have higher weight"
+
+ def test_zero_vol_fallback(self) -> None:
+ """Zero volatility → equal weight fallback."""
+ cov = np.zeros((3, 3))
+ opt = RiskParityOptimizer()
+ w = opt._calc_weights({"cov": cov})
+ np.testing.assert_allclose(w, np.ones(3) / 3, atol=1e-10)
+
+ def test_single_asset(self) -> None:
+ cov = np.array([[0.04]])
+ opt = RiskParityOptimizer()
+ w = opt._calc_weights({"cov": cov})
+ np.testing.assert_allclose(w, [1.0], atol=1e-10)
+
+ def test_empty_portfolio(self) -> None:
+ cov = np.empty((0, 0))
+ opt = RiskParityOptimizer()
+ w = opt._calc_weights({"cov": cov})
+ assert len(w) == 0
+
+
+class TestRiskParityOptimize:
+ """Integration test for the module-level optimize function."""
+
+ def test_optimize_preserves_sign(self) -> None:
+ """Optimizer should preserve signal direction (long/short)."""
+ dates = pd.bdate_range("2025-01-01", periods=100)
+ codes = ["A", "B"]
+ rng = np.random.default_rng(42)
+ ret = pd.DataFrame(rng.normal(0, 0.02, (100, 2)), index=dates, columns=codes)
+ pos = pd.DataFrame(0.0, index=dates, columns=codes)
+ # A is long, B is short after lookback period
+ pos.iloc[60:, 0] = 1.0
+ pos.iloc[60:, 1] = -1.0
+
+ opt = RiskParityOptimizer(lookback=60)
+ result = opt.optimize(ret, pos, dates)
+
+ # After lookback, signs should be preserved
+ assert (result.iloc[61:, 0] >= 0).all(), "A should remain long"
+ assert (result.iloc[61:, 1] <= 0).all(), "B should remain short"
+
+ def test_single_asset_unchanged(self) -> None:
+ """Optimizer with 1 asset returns input unchanged."""
+ dates = pd.bdate_range("2025-01-01", periods=100)
+ ret = pd.DataFrame(np.random.default_rng(1).normal(0, 0.02, (100, 1)), index=dates, columns=["A"])
+ pos = pd.DataFrame(1.0, index=dates, columns=["A"])
+
+ opt = RiskParityOptimizer(lookback=60)
+ result = opt.optimize(ret, pos, dates)
+ pd.testing.assert_frame_equal(result, pos)
diff --git a/agent/tests/test_skills.py b/agent/tests/test_skills.py
new file mode 100644
index 000000000..2e34fd287
--- /dev/null
+++ b/agent/tests/test_skills.py
@@ -0,0 +1,157 @@
+"""Tests for skill loading, frontmatter parsing, and category grouping."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from src.agent.skills import Skill, SkillsLoader, _parse_frontmatter
+
+
+# ---------------------------------------------------------------------------
+# _parse_frontmatter
+# ---------------------------------------------------------------------------
+
+
+class TestParseFrontmatter:
+ def test_basic(self) -> None:
+ text = "---\nname: test-skill\ndescription: A test\n---\nBody here."
+ meta, body = _parse_frontmatter(text)
+ assert meta["name"] == "test-skill"
+ assert meta["description"] == "A test"
+ assert body == "Body here."
+
+ def test_category_field(self) -> None:
+ text = "---\nname: foo\ncategory: strategy\n---\nContent"
+ meta, body = _parse_frontmatter(text)
+ assert meta["category"] == "strategy"
+
+ def test_boolean_values(self) -> None:
+ text = "---\nname: foo\nactive: true\narchived: false\n---\nBody"
+ meta, _ = _parse_frontmatter(text)
+ assert meta["active"] is True
+ assert meta["archived"] is False
+
+ def test_list_values(self) -> None:
+ text = "---\nname: foo\ntags: [a, b, c]\n---\nBody"
+ meta, _ = _parse_frontmatter(text)
+ assert meta["tags"] == ["a", "b", "c"]
+
+ def test_empty_list(self) -> None:
+ text = "---\nname: foo\ntags: []\n---\nBody"
+ meta, _ = _parse_frontmatter(text)
+ assert meta["tags"] == []
+
+ def test_no_frontmatter(self) -> None:
+ text = "Just plain text, no frontmatter."
+ meta, body = _parse_frontmatter(text)
+ assert meta == {}
+ assert body == text.strip()
+
+ def test_multiline_body(self) -> None:
+ text = "---\nname: x\n---\nLine 1\nLine 2\nLine 3"
+ _, body = _parse_frontmatter(text)
+ assert "Line 1" in body
+ assert "Line 3" in body
+
+
+# ---------------------------------------------------------------------------
+# Skill dataclass
+# ---------------------------------------------------------------------------
+
+
+class TestSkill:
+ def test_defaults(self) -> None:
+ s = Skill(name="test")
+ assert s.category == "other"
+ assert s.description == ""
+ assert s.body == ""
+ assert s.metadata == {}
+
+ def test_load_support_file_no_dir(self) -> None:
+ s = Skill(name="test")
+ assert s.load_support_file("missing.md") is None
+
+ def test_load_support_file(self, tmp_path: Path) -> None:
+ (tmp_path / "extra.md").write_text("extra content", encoding="utf-8")
+ s = Skill(name="test", dir_path=tmp_path)
+ assert s.load_support_file("extra.md") == "extra content"
+
+ def test_load_support_file_missing(self, tmp_path: Path) -> None:
+ s = Skill(name="test", dir_path=tmp_path)
+ assert s.load_support_file("nope.md") is None
+
+
+# ---------------------------------------------------------------------------
+# SkillsLoader
+# ---------------------------------------------------------------------------
+
+
+class TestSkillsLoader:
+ @pytest.fixture()
+ def skills_dir(self, tmp_path: Path) -> Path:
+ """Create a minimal skills directory with 3 skills in 2 categories."""
+ for name, cat, desc in [
+ ("alpha", "strategy", "Alpha strategy"),
+ ("beta", "data-source", "Beta source"),
+ ("gamma", "strategy", "Gamma strategy"),
+ ]:
+ d = tmp_path / name
+ d.mkdir()
+ (d / "SKILL.md").write_text(
+ f"---\nname: {name}\ncategory: {cat}\ndescription: {desc}\n---\nBody of {name}.",
+ encoding="utf-8",
+ )
+ return tmp_path
+
+ def test_loads_all_skills(self, skills_dir: Path) -> None:
+ loader = SkillsLoader(skills_dir)
+ assert len(loader.skills) == 3
+
+ def test_category_assignment(self, skills_dir: Path) -> None:
+ loader = SkillsLoader(skills_dir)
+ cats = {s.name: s.category for s in loader.skills}
+ assert cats["alpha"] == "strategy"
+ assert cats["beta"] == "data-source"
+
+ def test_get_descriptions_grouped(self, skills_dir: Path) -> None:
+ loader = SkillsLoader(skills_dir)
+ desc = loader.get_descriptions()
+ # data-source comes before strategy in _CATEGORY_ORDER
+ ds_pos = desc.index("data-source")
+ st_pos = desc.index("strategy")
+ assert ds_pos < st_pos
+
+ def test_get_descriptions_contains_all(self, skills_dir: Path) -> None:
+ loader = SkillsLoader(skills_dir)
+ desc = loader.get_descriptions()
+ assert "alpha" in desc
+ assert "beta" in desc
+ assert "gamma" in desc
+
+ def test_get_content_existing(self, skills_dir: Path) -> None:
+ loader = SkillsLoader(skills_dir)
+ content = loader.get_content("alpha")
+ assert '<skill name="alpha">' in content
+ assert "Body of alpha" in content
+
+ def test_get_content_missing(self, skills_dir: Path) -> None:
+ loader = SkillsLoader(skills_dir)
+ content = loader.get_content("nonexistent")
+ assert "Error" in content
+ assert "nonexistent" in content
+
+ def test_empty_dir(self, tmp_path: Path) -> None:
+ loader = SkillsLoader(tmp_path)
+ assert loader.skills == []
+ assert loader.get_descriptions() == "(no skills)"
+
+ def test_dir_without_skill_md_skipped(self, tmp_path: Path) -> None:
+ (tmp_path / "empty_skill").mkdir()
+ loader = SkillsLoader(tmp_path)
+ assert len(loader.skills) == 0
+
+ def test_nonexistent_dir(self, tmp_path: Path) -> None:
+ loader = SkillsLoader(tmp_path / "nope")
+ assert loader.skills == []
diff --git a/pyproject.toml b/pyproject.toml
index c66075730..effd0387d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -72,6 +72,20 @@ include = ["src*", "backtest*"]
[tool.setuptools.data-files]
"config/swarm" = ["agent/config/swarm/*.yaml"]
+[project.optional-dependencies]
+dev = [
+ "pytest>=7.0",
+ "pytest-cov>=4.0",
+]
+
+[tool.pytest.ini_options]
+testpaths = ["agent/tests"]
+pythonpath = ["agent"]
+markers = [
+ "unit: Unit tests (fast, no network)",
+ "integration: Integration tests (may need network)",
+]
+
[tool.ruff]
target-version = "py311"
line-length = 120