Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(portfolio): annualize weekly and monthly risk bars correctly

Rudy Celekli8afa3879a459
diff --git a/README.md b/README.md
index 17969bf5b..8ab651bde 100644
--- a/README.md
+++ b/README.md
@@ -416,6 +416,10 @@ The Web UI adds a read-only **Portfolio** page that aggregates holdings across t
Broker-reported source currencies are preserved during valuation: HKD account totals and positions, including Futu `HK.*` holdings, are converted with the snapshot USD/HKD rate before USD and CNY values are displayed. Older snapshots remain stored, but value history compares only snapshots produced by the current valuation methodology to avoid false gains or losses after a valuation fix.
+For `portfolio_risk_xray`, weekly (`1W`) and monthly (`1M`) inputs annualize
+volatility with 52 and 12 bars per year respectively; daily bars retain the
+252-bar convention. Monthly `1M` is distinct from minute `1m`.
+
### Portfolio connector compatibility
| Badge | Meaning |
diff --git a/agent/src/tools/portfolio_risk_tool.py b/agent/src/tools/portfolio_risk_tool.py
index fda8e509e..95113e2ff 100644
--- a/agent/src/tools/portfolio_risk_tool.py
+++ b/agent/src/tools/portfolio_risk_tool.py
@@ -16,7 +16,8 @@ from typing import Any, Callable, Mapping
import pandas as pd
-from backtest.risk_xray import compute_risk_xray
+from backtest.metrics import calc_bars_per_year
+from backtest.risk_xray import PERIODS_PER_YEAR, compute_risk_xray
from src.agent.tools import BaseTool
from src.market_data import fetch_market_data
@@ -119,7 +120,15 @@ class PortfolioRiskXrayTool(BaseTool):
closes = self._closes_frame(raw, symbols)
unresolved = raw.get("_unresolved") if isinstance(raw, Mapping) else None
- report = compute_risk_xray(closes, weights)
+ # Calendar bars have the same annual count across markets; preserve
+ # the existing daily convention for other intervals.
+ token = interval.strip()
+ periods_per_year = (
+ calc_bars_per_year(token)
+ if token == "1M" or token.lower() == "1w"
+ else PERIODS_PER_YEAR
+ )
+ report = compute_risk_xray(closes, weights, periods_per_year=periods_per_year)
envelope = {
"status": "ok",
"data": report,
diff --git a/agent/tests/test_portfolio_risk_calendar_bars.py b/agent/tests/test_portfolio_risk_calendar_bars.py
new file mode 100644
index 000000000..3c1fd320c
--- /dev/null
+++ b/agent/tests/test_portfolio_risk_calendar_bars.py
@@ -0,0 +1,53 @@
+"""Public portfolio risk tool annualizes weekly/monthly bars by their frequency."""
+
+from __future__ import annotations
+
+import json
+import math
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from src.tools.portfolio_risk_tool import PortfolioRiskXrayTool
+
+
+ "interval,frequency,annual_bars",
+ [
+ ("1W", "W-FRI", 52),
+ ("1w", "W-FRI", 52),
+ ("1M", "MS", 12),
+ ("1D", "B", 252),
+ ("1m", "min", 252),
+ ],
+)
+def test_public_tool_annualizes_calendar_bars(
+ interval: str, frequency: str, annual_bars: int
+) -> None:
+ closes = 100 * np.cumprod(1 + np.tile([0.02, -0.01, 0.005, -0.015], 15))
+ dates = pd.date_range("2020-01-01", periods=len(closes), freq=frequency)
+ records = [
+ {"date": date.isoformat(), "close": float(close)}
+ for date, close in zip(dates, closes)
+ ]
+ calls = []
+
+ def fetch(**kwargs):
+ calls.append(kwargs)
+ return {"AAA": records}
+
+ result = json.loads(
+ PortfolioRiskXrayTool(data_fetcher=fetch).execute(
+ symbols=["AAA"],
+ interval=interval,
+ start_date="2020-01-01",
+ end_date="2026-01-01",
+ )
+ )
+ assert result["status"] == "ok"
+ assert calls[0]["interval"] == interval
+ vol = result["data"]["volatility"]
+ 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))