Skip to content

"Vibe-Trading: Your Personal Trading Agent"

polish: post-merge review fixups for #461/#464/#466

Haozhe Wu85599573cd00
diff --git a/agent/backtest/optimizers/turnover_aware.py b/agent/backtest/optimizers/turnover_aware.py
index 8f278ad65..da1377a1f 100644
--- a/agent/backtest/optimizers/turnover_aware.py
+++ b/agent/backtest/optimizers/turnover_aware.py
@@ -1,4 +1,4 @@
-"""Turnover-aware optimizer: max-Sharpe objective with an L1 turnover penalty.
+"""Turnover-aware optimizer: mean-variance utility with an L1 turnover penalty.
Solves, per rebalance date::
@@ -17,7 +17,10 @@ optimizer strongly prefer holding still. Callers should tune ``gamma`` relative
to their data frequency.
Realized per-rebalance turnover (``0.5 * ||w_t - w_{t-1}||_1``) is accumulated
-on the instance for cost-adjusted analysis.
+on the instance for cost-adjusted analysis. This is a class-API affordance:
+the engine's module-level ``optimize`` entry constructs a fresh instance and
+returns only the positions frame, so callers who want the turnover series must
+instantiate ``TurnoverAwareOptimizer`` directly.
"""
from __future__ import annotations
@@ -37,7 +40,6 @@ class TurnoverAwareOptimizer(BaseOptimizer):
risk_aversion: Weight on the variance term (lambda).
turnover_penalty: Weight on the L1 turnover term (gamma). 0 reduces to
the mean-variance baseline.
- risk_free: Risk-free rate subtracted from mean returns.
realized_turnover: Per-rebalance realized turnover collected during
``optimize`` (``0.5 * ||w_t - w_{t-1}||_1``).
"""
@@ -47,13 +49,11 @@ class TurnoverAwareOptimizer(BaseOptimizer):
lookback: int = 60,
risk_aversion: float = 1.0,
turnover_penalty: float = 0.0,
- risk_free: float = 0.0,
**kwargs: Any,
) -> None:
super().__init__(lookback=lookback, **kwargs)
self.risk_aversion = float(risk_aversion)
self.turnover_penalty = float(turnover_penalty)
- self.risk_free = float(risk_free)
self._prev: Dict[str, float] = {}
self.realized_turnover: List[float] = []
@@ -79,12 +79,11 @@ class TurnoverAwareOptimizer(BaseOptimizer):
return self._equal_weight(0)
w_prev = np.array([self._prev.get(code, 0.0) for code in active], dtype=float)
- rf = self.risk_free
lam = self.risk_aversion
gamma = self.turnover_penalty
def objective(w: np.ndarray) -> float:
- ret = w @ mu - rf
+ ret = w @ mu
var = w @ cov @ w
turn = np.abs(w - w_prev).sum()
return -ret + lam * var + gamma * turn
@@ -121,12 +120,10 @@ def optimize(
lookback: int = 60,
risk_aversion: float = 1.0,
turnover_penalty: float = 0.0,
- risk_free: float = 0.0,
) -> pd.DataFrame:
"""Module-level entry: turnover-penalized mean-variance positions."""
return TurnoverAwareOptimizer(
lookback=lookback,
risk_aversion=risk_aversion,
turnover_penalty=turnover_penalty,
- risk_free=risk_free,
).optimize(ret, pos, dates)
diff --git a/agent/src/skills/asset-allocation/SKILL.md b/agent/src/skills/asset-allocation/SKILL.md
index 12299e37c..b3e49a975 100644
--- a/agent/src/skills/asset-allocation/SKILL.md
+++ b/agent/src/skills/asset-allocation/SKILL.md
@@ -98,6 +98,7 @@ Configure them in `config.json` through `optimizer` and `optimizer_params`:
| `risk_parity` | Risk Parity | Equalize risk contribution while accounting for correlation | Long-term robust allocation |
| `mean_variance` | Mean-Variance | Maximize Sharpe ratio or minimize variance | When return forecasts are available |
| `max_diversification` | Maximum Diversification | Maximize the diversification ratio | When pursuing a low-correlation portfolio |
+| `turnover_aware` | Turnover-Aware | Mean-variance utility with an L1 penalty on weight changes vs the previous rebalance | When trading costs matter; tune `turnover_penalty` to your data frequency |
### 1. `equal_volatility`
@@ -182,11 +183,37 @@ Configure them in `config.json` through `optimizer` and `optimizer_params`:
**Advantages**: does not require return forecasts and seeks true diversification.
**Disadvantages**: effectiveness is limited in highly correlated environments.
+### 5. `turnover_aware`
+
+```json
+{
+ "optimizer": "turnover_aware",
+ "optimizer_params": {
+ "lookback": 60,
+ "risk_aversion": 1.0,
+ "turnover_penalty": 0.5
+ }
+}
+```
+
+**Principle**: minimize `-w'μ + λ·w'Σw + γ·||w - w_prev||₁` subject to long-only, fully-invested weights — mean-variance utility with an L1 penalty on weight changes versus the previous rebalance, so the optimizer only trades when the expected improvement outweighs the (implicit) cost.
+
+| Parameter | Default | Description |
+|------|--------|------|
+| lookback | 60 | Calculation window |
+| risk_aversion | 1.0 | Weight on the variance term (λ) |
+| turnover_penalty | 0.0 | Weight on the L1 turnover term (γ); 0 reduces to the mean-variance baseline |
+
+**Advantages**: dampens rebalancing churn, which usually dominates realized costs; the first rebalance is unpenalized so the cold start is undistorted.
+**Disadvantages**: `turnover_penalty` is scale-sensitive to the return frequency of the input window — for daily returns even γ ≈ 0.5 strongly prefers holding still, so tune it per data frequency.
+
### Optimizer Selection Decision Tree
```
Do you have return forecasts?
-├── Yes → mean_variance (remember to add constraints)
+├── Yes → Do trading costs / churn matter?
+│ ├── Yes → turnover_aware (tune turnover_penalty to data frequency)
+│ └── No → mean_variance (remember to add constraints)
└── No → Do you need to account for correlation?
├── Yes → risk_parity (recommended default)
└── No → Are volatility differences across assets large?
diff --git a/agent/src/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.md
index c5c675aeb..4ac070a8e 100644
--- a/agent/src/skills/strategy-generate/SKILL.md
+++ b/agent/src/skills/strategy-generate/SKILL.md
@@ -136,8 +136,8 @@ Self-check after writing `signal_engine.py`:
- Minute backtests can be very data-heavy. Recommended limits are no more than 30 days for `1m`, or 1 year for `1H`
- `extra_fields`: China A-shares can use values such as `["pe", "pb", "roe"]`; other markets should use `null`
- `fundamental_fields`: optional China A-share statement fields, such as `{"income": ["total_revenue", "n_income"], "fina_indicator": ["roe"]}`; use `null` unless the strategy needs financial statement pre-filtering
-- `optimizer`: optional, one of `"equal_volatility"` / `"risk_parity"` / `"mean_variance"` / `"max_diversification"` / `null` (equal-weight by default)
-- `optimizer_params`: optimizer parameters, such as `{"lookback": 60}`. `mean_variance` additionally supports `{"risk_free": 0.0}`
+- `optimizer`: optional, one of `"equal_volatility"` / `"risk_parity"` / `"mean_variance"` / `"max_diversification"` / `"turnover_aware"` / `null` (equal-weight by default)
+- `optimizer_params`: optimizer parameters, such as `{"lookback": 60}`. `mean_variance` additionally supports `{"risk_free": 0.0}`; `turnover_aware` supports `{"risk_aversion": 1.0, "turnover_penalty": 0.5}` (L1 penalty on weight changes; tune to data frequency)
- `engine`: backtest engine, default `"daily"`. For options strategies, set `"options"` (requires `OptionsSignalEngine`)
- `initial_cash`: default 1,000,000
- `commission`: default 0.1%
diff --git a/agent/src/tools/image_vision_tool.py b/agent/src/tools/image_vision_tool.py
index 01237c6d6..6b6b7940d 100644
--- a/agent/src/tools/image_vision_tool.py
+++ b/agent/src/tools/image_vision_tool.py
@@ -58,8 +58,11 @@ class AnalyzeImageTool(BaseTool):
"about it. Use this for charts, candlestick/K-line screenshots, "
"account or app screenshots and photos - anything where reading the "
"picture matters. (read_document only OCRs text and fails on charts.) "
+ "Requires a vision-capable session model (e.g. gpt-4o / claude / "
+ "gemini / qwen-vl); a text-only model may error or answer without "
+ "seeing the image. "
"Supported: jpg/png/gif/bmp/webp under the allowed file roots. "
- 'Example: {"path": "/root/.vibe-trading/weixin/abc.jpg", '
+ 'Example: {"path": "~/.vibe-trading/uploads/weixin/abc.jpg", '
'"question": "解读这张K线图的走势"}.'
)
parameters = {
diff --git a/agent/tests/test_distribution_skill_manifest.py b/agent/tests/test_distribution_skill_manifest.py
index 3e7cedeee..3cfd96675 100644
--- a/agent/tests/test_distribution_skill_manifest.py
+++ b/agent/tests/test_distribution_skill_manifest.py
@@ -68,7 +68,7 @@ def test_alpha_zoo_counts_match_factor_modules() -> None:
zoo_counts = {
path.name: sum(1 for module in path.glob("*.py") if module.name != "__init__.py")
for path in ZOOS_DIR.iterdir()
- if path.is_dir()
+ if path.is_dir() and path.name != "__pycache__"
}
_assert_all_counts(r"Alpha Zoo\D{0,4}(\d+)\s+pre-built", sum(zoo_counts.values()))
diff --git a/agent/tests/test_image_vision_tool.py b/agent/tests/test_image_vision_tool.py
index 9e2f9e164..189804383 100644
--- a/agent/tests/test_image_vision_tool.py
+++ b/agent/tests/test_image_vision_tool.py
@@ -67,7 +67,6 @@ def test_happy_path_sends_data_url_and_returns_answer(tool, png_in_allowed_root)
def test_empty_model_answer_is_an_error(tool, png_in_allowed_root):
- result = None
response = MagicMock()
response.content = ""
with patch("src.providers.chat.ChatLLM") as chat_cls: