"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): size short positions by their own expected return
Lanre Shittucd653b52b364
diff --git a/agent/backtest/optimizers/base.py b/agent/backtest/optimizers/base.pyindex 5c76e05a2..ab90c9644 100644--- a/agent/backtest/optimizers/base.py+++ b/agent/backtest/optimizers/base.py@@ -70,6 +70,13 @@ class BaseOptimizer(ABC):if len(window) < max(self.lookback // 2, 5):continue+ signs = np.array([np.sign(pos.at[dt, c]) for c in active])+ # Exposed for subclasses (e.g. mean-variance style optimizers)+ # that need the direction of the position actually being sized,+ # not just its unsigned covariance/volatility structure -- a+ # short's expected return is -1 * the asset's raw drift, not the+ # raw drift itself.+ self._active_signs = signsctx = self._build_context(window, active)if ctx is None:continue@@ -79,8 +86,7 @@ class BaseOptimizer(ABC):continuefor j, c in enumerate(active):- sign = np.sign(pos.at[dt, c])- result.at[dt, c] = sign * weights[j]+ result.at[dt, c] = signs[j] * weights[j]return resultdiff --git a/agent/backtest/optimizers/mean_variance.py b/agent/backtest/optimizers/mean_variance.pyindex a54bb3cf9..0fe763df0 100644--- a/agent/backtest/optimizers/mean_variance.py+++ b/agent/backtest/optimizers/mean_variance.py@@ -18,8 +18,17 @@ class MeanVarianceOptimizer(BaseOptimizer):def _build_context(self, window: pd.DataFrame, active: List[str]) -> "Dict[str, Any] | None":- """Mean vector and covariance."""- mu = window.mean().values+ """Mean vector and covariance.++ ``mu`` is the expected return of the position actually being sized+ (``sign(pos) * raw asset drift``), not the raw asset drift -- a+ short's expected return is the negative of the asset's own drift.+ Without this, a strong short candidate (very negative raw drift)+ scores as a bad "long" in the Sharpe objective below and is starved+ of capital relative to a weak short (near-zero drift).+ """+ signs = self._active_signs+ mu = signs * window.mean().valuescov = window.cov().valuesif np.isnan(cov).any() or np.isnan(mu).any():return Nonediff --git a/agent/backtest/optimizers/turnover_aware.py b/agent/backtest/optimizers/turnover_aware.pyindex ad97d5a66..a5afdcb53 100644--- a/agent/backtest/optimizers/turnover_aware.py+++ b/agent/backtest/optimizers/turnover_aware.py@@ -95,8 +95,16 @@ class TurnoverAwareOptimizer(BaseOptimizer):def _build_context(self, window: pd.DataFrame, active: List[str]) -> "Dict[str, Any] | None":- """Mean vector, covariance, and active codes for the current window."""- mu = window.mean().values+ """Mean vector, covariance, and active codes for the current window.++ ``mu`` is the expected return of the position actually being sized+ (``sign(pos) * raw asset drift``), not the raw asset drift -- see+ ``MeanVarianceOptimizer._build_context`` for the same fix and its+ rationale; this optimizer's ``objective`` has the identical+ ``w @ mu`` return term.+ """+ signs = self._active_signs+ mu = signs * window.mean().valuescov = window.cov().valuesif np.isnan(cov).any() or np.isnan(mu).any():return Nonediff --git a/agent/tests/test_mean_variance_optimizer.py b/agent/tests/test_mean_variance_optimizer.pynew file mode 100644index 000000000..18d13bb19--- /dev/null+++ b/agent/tests/test_mean_variance_optimizer.py@@ -0,0 +1,79 @@+"""Tests for the mean-variance (max Sharpe) optimizer."""++from __future__ import annotations++import numpy as np+import pandas as pd++from backtest.optimizers.mean_variance import MeanVarianceOptimizer+++class TestMeanVarianceOptimize:+ """Integration tests 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)+ pos.iloc[60:, 0] = 1.0+ pos.iloc[60:, 1] = -1.0++ opt = MeanVarianceOptimizer(lookback=60)+ result = opt.optimize(ret, pos, dates)++ assert (result.iloc[61:, 0] >= 0).all(), "A should remain long"+ assert (result.iloc[61:, 1] <= 0).all(), "B should remain short"++ def test_strong_short_sized_above_weak_short(self) -> None:+ """A short with a strongly negative drift is a better short than one+ with near-zero drift, so it must receive more capital, not less.++ Regression: mu was the raw unsigned asset drift, so a strong short+ (very negative raw mu) scored as a bad "long" in the Sharpe+ objective and was starved of capital relative to a weak short+ (near-zero raw mu) -- sizing was inverted for the short book.+ """+ dates = pd.bdate_range("2025-01-01", periods=140)+ codes = ["WEAK", "STRONG"]+ rng = np.random.default_rng(7)+ weak_ret = rng.normal(-0.0005, 0.01, 140)+ strong_ret = rng.normal(-0.02, 0.01, 140)+ ret = pd.DataFrame({"WEAK": weak_ret, "STRONG": strong_ret}, index=dates)++ pos = pd.DataFrame(0.0, index=dates, columns=codes)+ pos.iloc[120:, 0] = -1.0+ pos.iloc[120:, 1] = -1.0++ opt = MeanVarianceOptimizer(lookback=120)+ result = opt.optimize(ret, pos, dates)+ last = result.iloc[-1]++ assert abs(last["STRONG"]) > abs(last["WEAK"])++ def test_single_asset_unchanged(self) -> None:+ 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 = MeanVarianceOptimizer(lookback=60)+ result = opt.optimize(ret, pos, dates)+ pd.testing.assert_frame_equal(result, pos)++ def test_result_weights_on_simplex(self) -> None:+ dates = pd.bdate_range("2025-01-01", periods=100)+ codes = ["A", "B", "C"]+ rng = np.random.default_rng(3)+ ret = pd.DataFrame(rng.normal(0, 0.02, (100, 3)), index=dates, columns=codes)+ pos = pd.DataFrame(1.0, index=dates, columns=codes)++ opt = MeanVarianceOptimizer(lookback=60)+ result = opt.optimize(ret, pos, dates)+ last = result.iloc[-1].values+ assert abs(abs(last).sum() - 1.0) < 1e-6diff --git a/agent/tests/test_turnover_aware_optimizer.py b/agent/tests/test_turnover_aware_optimizer.pyindex 44f05e633..7c8ad477d 100644--- a/agent/tests/test_turnover_aware_optimizer.py+++ b/agent/tests/test_turnover_aware_optimizer.py@@ -120,6 +120,26 @@ class TestTurnoverAwareOptimize:assert (result.iloc[61:, 0] >= 0).all()assert (result.iloc[61:, 1] <= 0).all()+ def test_strong_short_sized_above_weak_short(self) -> None:+ """Regression: mu was the raw unsigned asset drift, so a strong short+ (very negative raw mu) scored as a bad "long" in the mean-variance+ utility term and was starved of capital relative to a weak short+ (near-zero raw mu) -- sizing was inverted for the short book."""+ dates = pd.bdate_range("2025-01-01", periods=140)+ codes = ["WEAK", "STRONG"]+ rng = np.random.default_rng(7)+ weak_ret = rng.normal(-0.0005, 0.01, 140)+ strong_ret = rng.normal(-0.02, 0.01, 140)+ ret = pd.DataFrame({"WEAK": weak_ret, "STRONG": strong_ret}, index=dates)++ pos = pd.DataFrame(0.0, index=dates, columns=codes)+ pos.iloc[120:, 0] = -1.0+ pos.iloc[120:, 1] = -1.0++ result = optimize(ret, pos, dates, lookback=120, turnover_penalty=0.0)+ last = result.iloc[-1]+ assert abs(last["STRONG"]) > abs(last["WEAK"])+def test_short_window_and_nan_do_not_raise(self) -> None:ret, pos, dates = _sample_data(n_days=80)ret.iloc[10:20, 0] = np.nan