Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(risk): complete monthly history and turnover lifecycle guards

Haozhe Wu3ee353f71917
diff --git a/agent/backtest/optimizers/base.py b/agent/backtest/optimizers/base.py
index 3a04cd636..a7775c470 100644
--- a/agent/backtest/optimizers/base.py
+++ b/agent/backtest/optimizers/base.py
@@ -58,7 +58,10 @@ class BaseOptimizer(ABC):
result = pos.copy()
for i, dt in enumerate(dates):
active = [c for c in codes if abs(pos.at[dt, c]) > 1e-9]
- if not active or i < self.lookback:
+ if i < self.lookback:
+ continue
+ if not active:
+ self._on_passthrough_allocation(result.loc[dt])
continue
# Signals are executed at the decision bar's open. ``ret[dt]``
@@ -68,6 +71,7 @@ class BaseOptimizer(ABC):
history = ret.loc[ret.index < dt, active]
window = history.tail(self.lookback)
if len(window) < max(self.lookback // 2, 5):
+ self._on_passthrough_allocation(result.loc[dt])
continue
signs = np.array([np.sign(pos.at[dt, c]) for c in active])
@@ -83,6 +87,7 @@ class BaseOptimizer(ABC):
signed = window.mul(pd.Series(signs, index=window.columns), axis=1)
ctx = self._build_context(signed, active)
if ctx is None:
+ self._on_passthrough_allocation(result.loc[dt])
continue
# Stateful optimizers need the direction as well as the signed
@@ -90,6 +95,7 @@ class BaseOptimizer(ABC):
ctx["position_signs"] = signs
weights = self._calc_weights(ctx)
if weights is None or len(weights) != len(active):
+ self._on_passthrough_allocation(result.loc[dt])
continue
for j, c in enumerate(active):
@@ -101,6 +107,13 @@ class BaseOptimizer(ABC):
# Hooks
# ------------------------------------------------------------------
+ def _on_passthrough_allocation(self, allocation: pd.Series) -> None:
+ """Observe a post-warmup allocation retained without optimization.
+
+ Args:
+ allocation: Signed output allocation for the current decision date.
+ """
+
def _build_context(
self, window: pd.DataFrame, active: List[str]
) -> "Dict[str, Any] | None":
diff --git a/agent/backtest/optimizers/turnover_aware.py b/agent/backtest/optimizers/turnover_aware.py
index d5b82418f..dc3d1f110 100644
--- a/agent/backtest/optimizers/turnover_aware.py
+++ b/agent/backtest/optimizers/turnover_aware.py
@@ -132,6 +132,14 @@ class TurnoverAwareOptimizer(BaseOptimizer):
)
return super().optimize(ret, pos, dates)
+ def _on_passthrough_allocation(self, allocation: pd.Series) -> None:
+ """Record retained allocations so the next penalty uses current holdings.
+
+ Args:
+ allocation: Signed output allocation, including cash liquidations.
+ """
+ self._record_turnover(allocation.index.tolist(), allocation.to_numpy(dtype=float))
+
def _build_context(
self, window: pd.DataFrame, active: List[str]
) -> "Dict[str, Any] | None":
diff --git a/agent/src/tools/portfolio_risk_tool.py b/agent/src/tools/portfolio_risk_tool.py
index 95113e2ff..f18d7a523 100644
--- a/agent/src/tools/portfolio_risk_tool.py
+++ b/agent/src/tools/portfolio_risk_tool.py
@@ -17,7 +17,7 @@ from typing import Any, Callable, Mapping
import pandas as pd
from backtest.metrics import calc_bars_per_year
-from backtest.risk_xray import PERIODS_PER_YEAR, compute_risk_xray
+from backtest.risk_xray import MIN_HISTORY_DAYS, PERIODS_PER_YEAR, compute_risk_xray
from src.agent.tools import BaseTool
from src.market_data import fetch_market_data
@@ -39,7 +39,7 @@ class PortfolioRiskXrayTool(BaseTool):
name = "portfolio_risk_xray"
description = (
"Portfolio risk x-ray: given symbols (and optional weights), fetch "
- "recent daily closes through the data fallback chain and compute "
+ "recent closes through the data fallback chain and compute "
"concentration (HHI/effective N), annualized volatility, max drawdown, "
"historical VaR/expected shortfall, diversification ratio, and "
"correlation/beta. Long-only; weights are renormalized when they do "
@@ -60,7 +60,10 @@ class PortfolioRiskXrayTool(BaseTool):
},
"start_date": {
"type": "string",
- "description": "YYYY-MM-DD. Defaults to one year before end_date.",
+ "description": (
+ "YYYY-MM-DD. Defaults to one year before end_date; monthly "
+ "bars use enough calendar months to meet the minimum history."
+ ),
},
"end_date": {
"type": "string",
@@ -103,9 +106,11 @@ class PortfolioRiskXrayTool(BaseTool):
raise ValueError(f"too many symbols ({len(symbols)}); cap is {_MAX_SYMBOLS}")
weights = self._parse_weights(kwargs.get("weights"), symbols)
- start_date, end_date = self._parse_dates(kwargs.get("start_date"), kwargs.get("end_date"))
source = str(kwargs.get("source") or "auto")
- interval = str(kwargs.get("interval") or "1D")
+ interval = str(kwargs.get("interval") or "1D").strip()
+ start_date, end_date = self._parse_dates(
+ kwargs.get("start_date"), kwargs.get("end_date"), interval
+ )
raw = self._fetch(
codes=symbols,
@@ -158,17 +163,22 @@ class PortfolioRiskXrayTool(BaseTool):
return {sym: raw[sym] for sym in symbols}
@staticmethod
- def _parse_dates(start_raw: Any, end_raw: Any) -> tuple[str, str]:
+ def _parse_dates(
+ start_raw: Any, end_raw: Any, interval: str = "1D"
+ ) -> tuple[str, str]:
end = (
datetime.strptime(end_raw, "%Y-%m-%d").date()
if isinstance(end_raw, str) and end_raw
else datetime.now(timezone.utc).date()
)
- start = (
- datetime.strptime(start_raw, "%Y-%m-%d").date()
- if isinstance(start_raw, str) and start_raw
- else end - timedelta(days=_DEFAULT_LOOKBACK_DAYS)
- )
+ if isinstance(start_raw, str) and start_raw:
+ start = datetime.strptime(start_raw, "%Y-%m-%d").date()
+ elif interval == "1M":
+ # Keep the same minimum sample gate for every interval. Include an
+ # extra calendar month so a partial boundary month is not needed.
+ start = (pd.Timestamp(end) - pd.DateOffset(months=MIN_HISTORY_DAYS + 1)).date()
+ else:
+ start = end - timedelta(days=_DEFAULT_LOOKBACK_DAYS)
if start >= end:
raise ValueError(f"start_date {start} must be before end_date {end}")
return start.isoformat(), end.isoformat()
diff --git a/agent/tests/quantlib/test_options_iv_price_tolerance.py b/agent/tests/quantlib/test_options_iv_price_tolerance.py
index 4a0784028..2afc129f4 100644
--- a/agent/tests/quantlib/test_options_iv_price_tolerance.py
+++ b/agent/tests/quantlib/test_options_iv_price_tolerance.py
@@ -9,8 +9,18 @@ from src.quantlib.options import bs_price, implied_volatility
@pytest.mark.parametrize("scale", [1.0, 100.0, 10000.0])
def test_implied_volatility_fallback_reprices_within_absolute_tolerance(
- scale: float,
+ scale: float, monkeypatch: pytest.MonkeyPatch,
) -> None:
+ import src.quantlib.options as options
+
+ real_brentq = options.brentq
+ calls = []
+
+ def solve(*args, **kwargs):
+ calls.append(kwargs)
+ return real_brentq(*args, **kwargs)
+
+ monkeypatch.setattr(options, "brentq", solve)
spot, strike, maturity, rate, volatility = (
100.0 * scale,
150.0 * scale,
@@ -21,5 +31,17 @@ def test_implied_volatility_fallback_reprices_within_absolute_tolerance(
quote = bs_price(spot, strike, maturity, rate, volatility)
tolerance = 1e-6
implied = implied_volatility(quote, spot, strike, maturity, rate, tol=tolerance)
+ assert len(calls) == 1
assert math.isfinite(implied)
assert abs(bs_price(spot, strike, maturity, rate, implied) - quote) < tolerance
+
+
+def test_fallback_rejects_a_candidate_outside_price_tolerance(monkeypatch) -> None:
+ import src.quantlib.options as options
+
+ quote = bs_price(100.0, 150.0, 1.0, 0.05, 0.2)
+ inaccurate = 0.2001
+ assert abs(bs_price(100.0, 150.0, 1.0, 0.05, inaccurate) - quote) > 1e-6
+ monkeypatch.setattr(options, "brentq", lambda *args, **kwargs: inaccurate)
+ result = implied_volatility(quote, 100.0, 150.0, 1.0, 0.05)
+ assert math.isnan(result)
diff --git a/agent/tests/test_portfolio_risk_calendar_bars.py b/agent/tests/test_portfolio_risk_calendar_bars.py
index 3c1fd320c..c3c4ba4d7 100644
--- a/agent/tests/test_portfolio_risk_calendar_bars.py
+++ b/agent/tests/test_portfolio_risk_calendar_bars.py
@@ -51,3 +51,65 @@ def test_public_tool_annualizes_calendar_bars(
assert vol["daily_vol"] > 0
observed_vol = pd.Series(closes).pct_change(fill_method=None).dropna().std(ddof=1)
assert vol["annualized_vol"] == pytest.approx(observed_vol * math.sqrt(annual_bars))
+
+
+def local_price_file(tmp_path, monkeypatch):
+ from backtest.loaders import base, local_loader
+ from src.market_data import fetch_market_data
+
+ dates = pd.bdate_range("2020-01-01", "2026-01-31")
+ close = 100 * np.cumprod(1 + np.resize([0.002, -0.001, 0.0005, -0.0015], len(dates)))
+ path = tmp_path / "calendar-prices.csv"
+ pd.DataFrame(
+ {"date": dates, "open": close, "high": close, "low": close,
+ "close": close, "volume": 100}
+ ).to_csv(path, index=False)
+ monkeypatch.setattr(base, "loader_cache_enabled", lambda: False)
+ monkeypatch.setattr(
+ local_loader, "_load_config",
+ lambda: {"sources": [{"symbol": "AAA.US", "type": "csv", "path": str(path)}]},
+ )
+
+ def fetch(**kwargs):
+ # Exercise real CSV filtering, the shared market-data resampler and
+ # public tool shaping while keeping all data local to the fixture.
+ return fetch_market_data(
+ **kwargs, loader_resolver=lambda source: local_loader.DataLoader
+ )
+
+ return PortfolioRiskXrayTool(data_fetcher=fetch)
+
+
[email protected]("end_date", ["2024-02-29", "2025-01-15", "2025-01-31"])
+def test_monthly_default_range_supplies_enough_real_resampled_bars(
+ local_price_file, end_date: str
+) -> None:
+ result = json.loads(local_price_file.execute(
+ symbols=["AAA.US"], source="local", interval="1M", end_date=end_date
+ ))
+ assert result["status"] == "ok", result
+ assert result["data"]["inputs"]["aligned_days"] >= 30
+ assert result["data"]["volatility"]["annualized_vol"] == pytest.approx(
+ result["data"]["volatility"]["daily_vol"] * math.sqrt(12)
+ )
+ # Calendar arithmetic preserves the day where possible, including leap day.
+ assert result["meta"]["start_date"] == (
+ pd.Timestamp(end_date) - pd.DateOffset(months=31)
+ ).date().isoformat()
+
+
+def test_explicit_short_monthly_range_still_fails_history_gate(local_price_file) -> None:
+ result = json.loads(local_price_file.execute(
+ symbols=["AAA.US"], source="local", interval="1M",
+ start_date="2025-01-01", end_date="2026-01-01",
+ ))
+ assert result["status"] == "error"
+ assert "at least 30 valid bars" in result["error"]
+
+
[email protected]("interval", ["1D", "1W", "1m"])
+def test_nonmonthly_default_range_keeps_one_year(interval: str) -> None:
+ assert PortfolioRiskXrayTool._parse_dates(None, "2026-01-01", interval) == (
+ "2025-01-01", "2026-01-01"
+ )
diff --git a/agent/tests/test_turnover_direction_changes.py b/agent/tests/test_turnover_direction_changes.py
index ae11030b2..00408d5ce 100644
--- a/agent/tests/test_turnover_direction_changes.py
+++ b/agent/tests/test_turnover_direction_changes.py
@@ -61,3 +61,50 @@ def test_all_positions_can_reverse_without_an_invalid_solver_seed() -> None:
atol=1e-7,
)
assert optimizer.realized_turnover[1] == pytest.approx(1.0)
+
+
[email protected]("direction", [-1.0, 1.0])
+def test_liquidation_and_reentry_are_both_recorded(direction: float) -> None:
+ returns, positions, dates = _inputs(False)
+ positions *= direction
+ positions.iloc[6] = 0.0
+ optimizer = TurnoverAwareOptimizer(lookback=5, max_per_name=0.5)
+ result = optimizer.optimize(returns, positions, dates)
+
+ np.testing.assert_allclose(
+ optimizer.realized_turnover, calc_turnover_series(result).iloc[5:], atol=1e-7
+ )
+ np.testing.assert_allclose(optimizer.realized_turnover, [0.5, 0.5, 0.5])
+
+
+def test_reentry_penalty_starts_from_cash_not_the_liquidated_book() -> None:
+ dates = pd.bdate_range("2025-01-01", periods=8)
+ returns = pd.DataFrame({"A": -0.02, "B": 0.02}, index=dates)
+ positions = pd.DataFrame(0.0, index=dates, columns=["A", "B"])
+ positions.iloc[5, 0] = 1.0
+ positions.iloc[7] = 1.0
+ optimizer = TurnoverAwareOptimizer(lookback=5, turnover_penalty=1.0)
+ result = optimizer.optimize(returns, positions, dates)
+
+ assert result.iloc[5]["A"] == pytest.approx(1.0)
+ assert result.iloc[6].abs().sum() == 0.0
+ assert result.iloc[7]["B"] > 0.99
+ np.testing.assert_allclose(optimizer.realized_turnover, [0.5, 0.5, 0.5])
+
+
+def test_retained_allocation_after_missing_history_updates_prior_holdings() -> None:
+ returns, positions, dates = _inputs(False)
+ # Row 6 lacks B's usable covariance, so its raw short allocation survives.
+ # Row 7 only holds A and has a valid window again.
+ returns.loc[dates[:6], "B"] = np.nan
+ positions.iloc[5] = [1.0, 0.0]
+ positions.iloc[6] = [0.0, -1.0]
+ positions.iloc[7] = [1.0, 0.0]
+ optimizer = TurnoverAwareOptimizer(lookback=5, turnover_penalty=1.0)
+ result = optimizer.optimize(returns, positions, dates)
+
+ np.testing.assert_allclose(result.iloc[5:], positions.iloc[5:])
+ np.testing.assert_allclose(
+ optimizer.realized_turnover, calc_turnover_series(result).iloc[5:], atol=1e-7
+ )
+ np.testing.assert_allclose(optimizer.realized_turnover, [0.5, 1.0, 1.0])