"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(backtest): composable weight constraints for any optimizer (#818)
Yufeng He97083c618b01
diff --git a/agent/backtest/constraints.py b/agent/backtest/constraints.pynew file mode 100644index 000000000..e7a0e6ad4--- /dev/null+++ b/agent/backtest/constraints.py@@ -0,0 +1,205 @@+"""Composable weight constraints applied on top of any optimizer.++Portfolio Studio step 2 (#456): per-name cap, per-name floor, and per-group+exposure caps that work with every optimizer, not only the bounds baked into+``turnover_aware``. Configured via ``constraints`` in config.json::++ "constraints": [+ {"type": "max_weight", "cap": 0.25},+ {"type": "min_weight", "floor": 0.02},+ {"type": "group_exposure",+ "groups": {"AAPL": "tech", "MSFT": "tech", "XOM": "energy"},+ "caps": {"tech": 0.6}}+ ]++The layer runs on the optimizer's output frame (signed weights, one row per+rebalance date). Magnitudes are adjusted and signs are preserved, so+long/short books work too. Constraints apply in config order, and the layer+only acts on names that are already active: it reshapes allocations, it+never opens or closes positions. Off by default, so existing configs behave+exactly as before.+"""++from __future__ import annotations++from typing import Any, Dict, List, Mapping, Sequence++import numpy as np+import pandas as pd++_EPS = 1e-9+_TOL = 1e-12+_MAX_PASSES = 50+++def _bounded_fraction(value: Any, name: str) -> float:+ """Validate a (0, 1] fraction from config, rejecting bools and junk."""+ if isinstance(value, (bool, np.bool_)):+ raise ValueError(f"{name} must be numeric, not boolean")+ try:+ v = float(value)+ except (TypeError, ValueError) as exc:+ raise ValueError(f"{name} must be numeric") from exc+ if not np.isfinite(v) or not 0.0 < v <= 1.0:+ raise ValueError(f"{name} must be finite and in (0, 1]")+ return v+++class MaxWeight:+ """Per-name cap with pro-rata redistribution of the clipped excess.++ Clipped weight is handed to the names still under the cap, in+ proportion to their current size, until everything fits. When the cap+ cannot hold the book (n_active * cap < gross), every name lands on the+ cap and gross exposure shrinks accordingly.+ """++ def __init__(self, cap: float) -> None:+ self.cap = cap++ def apply(self, w: np.ndarray, codes: Sequence[str]) -> np.ndarray:+ del codes # per-name rule, codes unused+ w = w.astype(float).copy()+ for _ in range(_MAX_PASSES):+ over = w > self.cap + _TOL+ if not over.any():+ break+ excess = float((w[over] - self.cap).sum())+ w[over] = self.cap+ room = w < self.cap - _TOL+ base = float(w[room].sum())+ if not room.any() or base <= _TOL:+ break+ w[room] += w[room] / base * excess+ return w+++class MinWeight:+ """Per-name floor: active names below ``floor`` are lifted to it.++ The lift is funded pro-rata by the names above the floor (each gives+ up weight in proportion to how far it sits above the floor), so gross+ exposure is preserved. If the book cannot fund the floor+ (floor * n_active > gross), the date degrades to equal weights.+ """++ def __init__(self, floor: float) -> None:+ self.floor = floor++ def apply(self, w: np.ndarray, codes: Sequence[str]) -> np.ndarray:+ del codes+ w = w.astype(float).copy()+ for _ in range(_MAX_PASSES):+ below = (w > _EPS) & (w < self.floor - _TOL)+ if not below.any():+ break+ need = float((self.floor - w[below]).sum())+ above = w > self.floor + _TOL+ avail = float((w[above] - self.floor).sum())+ if avail <= _TOL:+ n = len(w)+ return np.full(n, w.sum() / n) if n else w+ w[below] = self.floor+ w[above] -= (w[above] - self.floor) / avail * need+ return w+++class GroupExposure:+ """Cap the summed weight of each configured group.++ A group over its cap is scaled down pro-rata; the freed exposure is+ not redistributed (pushing it elsewhere could break another group's+ cap), so gross exposure shrinks by the clipped amount. Names absent+ from ``groups`` are unconstrained.+ """++ def __init__(self, groups: Mapping[str, str], caps: Mapping[str, float]) -> None:+ self.groups: Dict[str, str] = dict(groups)+ self.caps: Dict[str, float] = dict(caps)++ def apply(self, w: np.ndarray, codes: Sequence[str]) -> np.ndarray:+ w = w.astype(float).copy()+ for group, cap in self.caps.items():+ idx = [i for i, c in enumerate(codes) if self.groups.get(c) == group]+ if not idx:+ continue+ total = float(w[idx].sum())+ if total > cap + _TOL:+ w[idx] *= cap / total+ return w+++_TYPES = ("max_weight", "min_weight", "group_exposure")+++def _build_constraint(spec: Mapping[str, Any]) -> Any:+ if not isinstance(spec, Mapping):+ raise ValueError(f"constraint spec must be a mapping, got {type(spec).__name__}")+ kind = spec.get("type")+ if kind == "max_weight":+ if "cap" not in spec:+ raise ValueError("max_weight constraint requires 'cap'")+ return MaxWeight(_bounded_fraction(spec["cap"], "max_weight cap"))+ if kind == "min_weight":+ if "floor" not in spec:+ raise ValueError("min_weight constraint requires 'floor'")+ return MinWeight(_bounded_fraction(spec["floor"], "min_weight floor"))+ if kind == "group_exposure":+ groups = spec.get("groups")+ caps = spec.get("caps")+ if not isinstance(groups, Mapping) or not groups:+ raise ValueError("group_exposure constraint requires a non-empty 'groups' mapping")+ if any(not isinstance(c, str) or not isinstance(g, str) for c, g in groups.items()):+ raise ValueError("groups must map string asset codes to string group names")+ if not isinstance(caps, Mapping) or not caps:+ raise ValueError("group_exposure constraint requires a non-empty 'caps' mapping")+ unknown = set(caps) - set(groups.values())+ if unknown:+ raise ValueError(+ "caps reference groups with no mapped assets: " + ", ".join(sorted(unknown))+ )+ return GroupExposure(+ groups,+ {g: _bounded_fraction(c, f"cap for group {g!r}") for g, c in caps.items()},+ )+ raise ValueError(+ f"unknown constraint type {kind!r}; expected one of {', '.join(_TYPES)}"+ )+++def load_constraints(config: Mapping[str, Any]) -> List[Any]:+ """Build the constraint list from ``config['constraints']`` (empty if unset)."""+ raw = config.get("constraints")+ if raw in (None, []):+ return []+ if not isinstance(raw, list):+ raise ValueError("constraints must be a list of constraint specs")+ return [_build_constraint(spec) for spec in raw]+++def apply_constraints_frame(+ frame: pd.DataFrame, constraints: Sequence[Any]+) -> pd.DataFrame:+ """Apply constraints row by row to a signed weight frame.++ Args:+ frame: Optimizer output (dates x codes), signed weights.+ constraints: Constraint objects from ``load_constraints``.++ Returns:+ Adjusted frame with signs preserved and zero rows/cells untouched.+ """+ if not constraints:+ return frame+ out = frame.copy()+ for dt in frame.index:+ row = frame.loc[dt]+ codes = [c for c in row.index if abs(row[c]) > _EPS]+ if not codes:+ continue+ signs = np.sign(row[codes].to_numpy(dtype=float))+ mags = np.abs(row[codes].to_numpy(dtype=float))+ for con in constraints:+ mags = con.apply(mags, codes)+ out.loc[dt, codes] = signs * mags+ return outdiff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex 0b66f1900..7e424872a 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -23,6 +23,7 @@ from typing import Any, Callable, Dict, List, Optionalimport numpy as npimport pandas as pd+from backtest.constraints import apply_constraints_frame, load_constraintsfrom backtest.loaders.rsshub_events import (FeedSpec,RSSHubEventProvider,@@ -239,16 +240,25 @@ def _load_optimizer(config: Dict[str, Any]) -> Optional[Callable]:Optimizer callable, or None."""opt_name = config.get("optimizer")+ constraints = load_constraints(config)if not opt_name:+ if constraints:+ print("[WARN] 'constraints' only act on optimizer output, "+ "set 'optimizer' to use them; ignoring")return Noneopt_params = config.get("optimizer_params") or {}try:mod = importlib.import_module(f"backtest.optimizers.{opt_name}")- return lambda ret, pos, dates: mod.optimize(ret, pos, dates, **opt_params)except (ImportError, AttributeError) as e:print(f"[WARN] Failed to load optimizer '{opt_name}': {e}, falling back to equal weight")return None+ def optimize(ret: pd.DataFrame, pos: pd.DataFrame, dates: pd.DatetimeIndex) -> pd.DataFrame:+ out = mod.optimize(ret, pos, dates, **opt_params)+ return apply_constraints_frame(out, constraints)++ return optimize+def _normalise_fundamental_fields(config: Dict[str, Any]) -> dict[str, list[str]]:"""Read the optional statement-table field map from backtest config."""diff --git a/agent/tests/test_constraints.py b/agent/tests/test_constraints.pynew file mode 100644index 000000000..884703899--- /dev/null+++ b/agent/tests/test_constraints.py@@ -0,0 +1,210 @@+"""Tests for the composable weight-constraint layer (Portfolio Studio step 2)."""++from __future__ import annotations++import numpy as np+import pandas as pd+import pytest++from backtest.constraints import (+ GroupExposure,+ MaxWeight,+ MinWeight,+ apply_constraints_frame,+ load_constraints,+)+++def _frame(rows: dict, codes=("A", "B", "C", "D")) -> pd.DataFrame:+ """Build a signed weight frame from {date: [w...]} shorthand."""+ dates = pd.bdate_range("2025-01-01", periods=len(rows))+ data = [rows[k] for k in sorted(rows)]+ return pd.DataFrame(data, index=dates, columns=list(codes))+++class TestMaxWeight:+ def test_clip_and_redistribute_pro_rata(self) -> None:+ w = MaxWeight(0.4).apply(np.array([0.7, 0.2, 0.1]), ["A", "B", "C"])+ assert w[0] == pytest.approx(0.4)+ # excess 0.3 goes to B and C in proportion 2:1+ assert w[1] == pytest.approx(0.2 + 0.3 * 2 / 3)+ assert w[2] == pytest.approx(0.1 + 0.3 * 1 / 3)+ assert w.sum() == pytest.approx(1.0)++ def test_redistribution_can_trigger_second_pass(self) -> None:+ w = MaxWeight(0.34).apply(np.array([0.8, 0.15, 0.05]), ["A", "B", "C"])+ assert np.all(w <= 0.34 + 1e-12)+ assert w.sum() == pytest.approx(1.0)++ def test_infeasible_cap_shrinks_gross(self) -> None:+ # 3 names at cap 0.2 can hold at most 0.6 of the book+ w = MaxWeight(0.2).apply(np.array([0.6, 0.3, 0.1]), ["A", "B", "C"])+ assert np.all(w == pytest.approx(0.2))+ assert w.sum() == pytest.approx(0.6)++ def test_noop_when_under_cap(self) -> None:+ src = np.array([0.3, 0.3, 0.4])+ w = MaxWeight(0.5).apply(src, ["A", "B", "C"])+ np.testing.assert_allclose(w, src)+++class TestMinWeight:+ def test_lift_funded_by_largest(self) -> None:+ w = MinWeight(0.1).apply(np.array([0.85, 0.1, 0.05]), ["A", "B", "C"])+ assert w[2] == pytest.approx(0.1)+ assert w[1] == pytest.approx(0.1)+ assert w[0] == pytest.approx(0.8)+ assert w.sum() == pytest.approx(1.0)++ def test_infeasible_floor_degrades_to_equal(self) -> None:+ w = MinWeight(0.4).apply(np.array([0.5, 0.3, 0.2]), ["A", "B", "C"])+ np.testing.assert_allclose(w, np.full(3, 1.0 / 3.0))++ def test_zero_stays_zero(self) -> None:+ # handled at frame level, but the constraint itself must not invent weight+ w = MinWeight(0.2).apply(np.array([0.9, 0.1, 0.0]), ["A", "B", "C"])+ assert w[2] == pytest.approx(0.0)+++class TestGroupExposure:+ def test_violating_group_scaled_pro_rata(self) -> None:+ con = GroupExposure({"A": "tech", "B": "tech", "C": "energy"}, {"tech": 0.5})+ w = con.apply(np.array([0.4, 0.3, 0.3]), ["A", "B", "C"])+ assert w[0] + w[1] == pytest.approx(0.5)+ assert w[0] / w[1] == pytest.approx(0.4 / 0.3)+ assert w[2] == pytest.approx(0.3)++ def test_compliant_group_untouched(self) -> None:+ con = GroupExposure({"A": "tech", "B": "tech"}, {"tech": 0.9})+ src = np.array([0.3, 0.2, 0.5])+ w = con.apply(src, ["A", "B", "C"])+ np.testing.assert_allclose(w, src)++ def test_unmapped_codes_unconstrained(self) -> None:+ con = GroupExposure({"A": "tech"}, {"tech": 0.3})+ w = con.apply(np.array([0.4, 0.6]), ["A", "OTHER"])+ assert w[0] == pytest.approx(0.3)+ assert w[1] == pytest.approx(0.6)+++class TestLoadConstraints:+ def test_empty_by_default(self) -> None:+ assert load_constraints({}) == []+ assert load_constraints({"constraints": []}) == []++ def test_unknown_type_rejected(self) -> None:+ with pytest.raises(ValueError, match="unknown constraint type"):+ load_constraints({"constraints": [{"type": "nonsense"}]})++ def test_cap_validation(self) -> None:+ for bad in (0, -0.1, 1.5, True, "big", float("nan")):+ with pytest.raises(ValueError):+ load_constraints({"constraints": [{"type": "max_weight", "cap": bad}]})++ def test_missing_keys_rejected(self) -> None:+ with pytest.raises(ValueError, match="requires 'cap'"):+ load_constraints({"constraints": [{"type": "max_weight"}]})+ with pytest.raises(ValueError, match="requires 'floor'"):+ load_constraints({"constraints": [{"type": "min_weight"}]})++ def test_group_caps_must_reference_mapped_groups(self) -> None:+ with pytest.raises(ValueError, match="no mapped assets"):+ load_constraints({+ "constraints": [{+ "type": "group_exposure",+ "groups": {"A": "tech"},+ "caps": {"energy": 0.5},+ }]+ })++ def test_constraints_not_a_list_rejected(self) -> None:+ with pytest.raises(ValueError, match="must be a list"):+ load_constraints({"constraints": {"type": "max_weight", "cap": 0.3}})+++class TestApplyFrame:+ def test_signs_preserved(self) -> None:+ frame = _frame({"2025-01-01": [0.7, -0.2, 0.1, 0.0]})+ out = apply_constraints_frame(frame, load_constraints({+ "constraints": [{"type": "max_weight", "cap": 0.4}]+ }))+ assert out.iloc[0]["A"] == pytest.approx(0.4)+ assert out.iloc[0]["B"] < 0+ assert out.iloc[0]["C"] > 0+ assert out.iloc[0]["D"] == 0.0+ # gross exposure preserved through redistribution+ assert out.abs().sum(axis=1).iloc[0] == pytest.approx(1.0)++ def test_config_order_applies(self) -> None:+ frame = _frame({"2025-01-01": [0.5, 0.4, 0.1, 0.0]})+ cons = load_constraints({+ "constraints": [+ {"type": "max_weight", "cap": 0.45},+ {"type": "group_exposure", "groups": {"A": "x", "B": "x"}, "caps": {"x": 0.7}},+ ]+ })+ out = apply_constraints_frame(frame, cons)+ assert out.iloc[0]["A"] <= 0.45 + 1e-12+ assert out.iloc[0]["A"] + out.iloc[0]["B"] == pytest.approx(0.7)++ def test_empty_constraints_identity(self) -> None:+ frame = _frame({"2025-01-01": [0.5, -0.3, 0.2, 0.0]})+ out = apply_constraints_frame(frame, [])+ pd.testing.assert_frame_equal(out, frame)++ def test_per_date_independence(self) -> None:+ frame = _frame({+ "2025-01-01": [0.9, 0.1, 0.0, 0.0],+ "2025-01-02": [0.2, 0.2, 0.6, 0.0],+ })+ out = apply_constraints_frame(frame, load_constraints({+ "constraints": [{"type": "max_weight", "cap": 0.5}]+ }))+ assert out.iloc[0]["A"] == pytest.approx(0.5)+ assert out.iloc[1]["C"] == pytest.approx(0.5)++ def test_idempotent(self) -> None:+ frame = _frame({"2025-01-01": [0.7, 0.2, 0.1, 0.0]})+ cons = load_constraints({+ "constraints": [+ {"type": "max_weight", "cap": 0.4},+ {"type": "min_weight", "floor": 0.1},+ ]+ })+ once = apply_constraints_frame(frame, cons)+ twice = apply_constraints_frame(once, cons)+ pd.testing.assert_frame_equal(once, twice)+++class TestEngineWiring:+ """The layer composes onto whatever optimizer the config selects."""++ def test_load_optimizer_applies_constraints(self) -> None:+ from backtest.engines.base import _load_optimizer++ n_days, n_assets = 120, 4+ rng = np.random.default_rng(0)+ dates = pd.bdate_range("2025-01-01", periods=n_days)+ codes = [f"A{i}" for i in range(n_assets)]+ ret = pd.DataFrame(+ rng.normal(0.001, 0.02, (n_days, n_assets)), index=dates, columns=codes+ )+ pos = pd.DataFrame(1.0, index=dates, columns=codes)++ config = {+ "optimizer": "equal_volatility",+ "constraints": [{"type": "max_weight", "cap": 0.4}],+ }+ opt_fn = _load_optimizer(config)+ out = opt_fn(ret, pos, dates)+ active_rows = out.index[out.abs().sum(axis=1) > 0]+ assert len(active_rows) > 0+ for dt in active_rows:+ assert (out.loc[dt].abs() <= 0.4 + 1e-9).all()++ def test_constraints_without_optimizer_warns_and_passes(self, capsys) -> None:+ from backtest.engines.base import _load_optimizer++ config = {"constraints": [{"type": "max_weight", "cap": 0.4}]}+ assert _load_optimizer(config) is None+ assert "constraints" in capsys.readouterr().out