Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix: address maintainer review + CI env var gate failures

shadowinlife68b8434b1a3b
diff --git a/README.md b/README.md
index ddca36d1c..0a7dadd37 100644
--- a/README.md
+++ b/README.md
@@ -337,9 +337,9 @@ Beyond OHLCV, **18 read-only data tools** reach into fundamentals & flow β€” fun
Detailed inventories are folded below to keep the main README scannable. Open them when you want to inspect the available building blocks.
<details>
-<summary><b>Finance Skill Library</b> <sub>86 skills across 9 categories</sub></summary>
+<summary><b>Finance Skill Library</b> <sub>87 skills across 9 categories</sub></summary>
-- πŸ“Š 86 specialized finance skills organized into 9 categories
+- πŸ“Š 87 specialized finance skills organized into 9 categories
- 🌐 Complete coverage from traditional markets to crypto & DeFi
- πŸ”¬ Comprehensive capabilities spanning data sourcing to quantitative research
@@ -654,7 +654,7 @@ vibe-trading provider doctor # print redacted provider/proxy/package diagnostic
| Command | Description |
|---------|-------------|
| `/help` | Show all commands |
-| `/skills` | List all 86 finance skills |
+| `/skills` | List all 87 finance skills |
| `/swarm` | List 30 swarm team presets |
| `/swarm run <preset> [vars_json]` | Run a swarm team with live streaming |
| `/swarm list` | Swarm run history |
@@ -991,7 +991,7 @@ Browse on ClawHub: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills/vi
<details>
<summary><b>OpenSpace β€” self-evolving skills</b></summary>
-All 86 finance skills are published on [open-space.cloud](https://open-space.cloud) and evolve autonomously through OpenSpace's self-evolution engine.
+All 87 finance skills are published on [open-space.cloud](https://open-space.cloud) and evolve autonomously through OpenSpace's self-evolution engine.
To use with OpenSpace, add both MCP servers to your agent config:
@@ -1013,7 +1013,7 @@ To use with OpenSpace, add both MCP servers to your agent config:
}
```
-OpenSpace will auto-discover all 86 skills, enabling auto-fix, auto-improve, and community sharing. Search for Vibe-Trading skills via `search_skills("finance backtest")` in any OpenSpace-connected agent.
+OpenSpace will auto-discover all 87 skills, enabling auto-fix, auto-improve, and community sharing. Search for Vibe-Trading skills via `search_skills("finance backtest")` in any OpenSpace-connected agent.
</details>
@@ -1200,7 +1200,7 @@ Vibe-Trading/
β”‚ β”‚ β”œβ”€β”€ agent/ # ReAct agent core
β”‚ β”‚ β”‚ β”œβ”€β”€ loop.py # 5-layer compression + read/write tool batching
β”‚ β”‚ β”‚ β”œβ”€β”€ context.py # system prompt + auto-recall from persistent memory
-β”‚ β”‚ β”‚ β”œβ”€β”€ skills.py # skill loader (86 bundled + user-created via CRUD)
+β”‚ β”‚ β”‚ β”œβ”€β”€ skills.py # skill loader (87 bundled + user-created via CRUD)
β”‚ β”‚ β”‚ β”œβ”€β”€ tools.py # tool base class + registry
β”‚ β”‚ β”‚ β”œβ”€β”€ memory.py # lightweight workspace state per run
β”‚ β”‚ β”‚ β”œβ”€β”€ frontmatter.py # shared YAML frontmatter parser
@@ -1227,7 +1227,7 @@ Vibe-Trading/
β”‚ β”‚ β”œβ”€β”€ api/ # FastAPI route modules
β”‚ β”‚ β”‚ └── alpha_routes.py # /alpha/list, /alpha/{id}, /alpha/bench, SSE stream
β”‚ β”‚ β”‚
-β”‚ β”‚ β”œβ”€β”€ skills/ # 86 finance skills in 9 categories (SKILL.md each)
+β”‚ β”‚ β”œβ”€β”€ skills/ # 87 finance skills in 9 categories (SKILL.md each)
β”‚ β”‚ β”œβ”€β”€ swarm/ # Swarm DAG execution engine
β”‚ β”‚ β”‚ └── presets/ # 30 swarm preset YAML definitions
β”‚ β”‚ β”œβ”€β”€ session/ # Multi-turn chat + FTS5 session search
diff --git a/agent/SKILL.md b/agent/SKILL.md
index 6dbc89c6c..f0bc62597 100644
--- a/agent/SKILL.md
+++ b/agent/SKILL.md
@@ -1,7 +1,7 @@
---
name: vibe-trading
version: 0.1.11
-description: Professional finance research toolkit β€” backtesting (8 engines + benchmark comparison panel), factor analysis, Alpha Zoo (460 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 86 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract β†’ backtest β†’ render) across 20 market-data sources (tushare, yfinance, okx, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, india_broker, qveris, plus optional-key finnhub/alphavantage/tiingo/fmp).
+description: Professional finance research toolkit β€” backtesting (8 engines + benchmark comparison panel), factor analysis, Alpha Zoo (460 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 87 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract β†’ backtest β†’ render) across 20 market-data sources (tushare, yfinance, okx, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, india_broker, qveris, plus optional-key finnhub/alphavantage/tiingo/fmp).
dependencies:
python: ">=3.11"
pip:
@@ -23,7 +23,7 @@ mcp:
# Vibe-Trading
-Professional finance research toolkit with AI-powered backtesting (8 engines), multi-agent teams, 86 specialized skills, the **Alpha Zoo** (460 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic / fundamental with one-line CLI benchmarking), and the Shadow Account loop β€” extract your implicit trading rules from a journal, backtest them across Aθ‚‘/ζΈ―θ‚‘/ηΎŽθ‚‘/crypto, then see where they would have served you better.
+Professional finance research toolkit with AI-powered backtesting (8 engines), multi-agent teams, 87 specialized skills, the **Alpha Zoo** (460 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic / fundamental with one-line CLI benchmarking), and the Shadow Account loop β€” extract your implicit trading rules from a journal, backtest them across Aθ‚‘/ζΈ―θ‚‘/ηΎŽθ‚‘/crypto, then see where they would have served you better.
## Setup
@@ -53,7 +53,7 @@ Add to your agent's MCP config:
### API Key Requirements
-Core research MCP tools work with zero API keys for HK/US/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (460 pre-built alphas), and all 86 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.
+Core research MCP tools work with zero API keys for HK/US/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (460 pre-built alphas), and all 87 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.
| Feature | Key needed | When |
|---------|-----------|------|
@@ -133,7 +133,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.
| Tool | Description | API Key |
|------|-------------|---------|
-| `list_skills` | List all 86 finance skills | None |
+| `list_skills` | List all 87 finance skills | None |
| `load_skill` | Load full skill documentation | None |
| `start_research_goal` | Create an auditable research goal | None |
| `get_research_goal` | Read the current research goal | None |
@@ -196,7 +196,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.
pip install vibe-trading-ai
```
-That's it β€” no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 86 skills immediately.
+That's it β€” no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 87 skills immediately.
## Loading Tools from External MCP Servers
diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.py
index 7675d188f..07c5afde1 100644
--- a/agent/src/config/env_schema.py
+++ b/agent/src/config/env_schema.py
@@ -32,6 +32,7 @@ __all__ = [
"SwarmConfig",
"AgentTuningConfig",
"PathConfig",
+ "OcrConfig",
]
@@ -168,6 +169,22 @@ class DataConfig(_EnvBase):
qveris_api_key: str = Field(alias="QVERIS_API_KEY", default="")
qveris_base_url: str = Field(alias="QVERIS_BASE_URL", default="")
rsshub_base_url: str = Field(alias="RSSHUB_BASE_URL", default="")
+ dashscope_api_key: str = Field(alias="DASHSCOPE_API_KEY", default="")
+
+
+# ---------------------------------------------------------------------------
+# OCR
+# ---------------------------------------------------------------------------
+
+
+class OcrConfig(_EnvBase):
+ """OCR engine selection and model configuration.
+
+ Sources: ``src/tools/ocr/engine.py``, ``src/tools/ocr/qwen_vision_ocr.py``.
+ """
+
+ vibe_trading_ocr_engine: str = Field(alias="VIBE_TRADING_OCR_ENGINE", default="auto")
+ vibe_trading_ocr_qwen_model: str = Field(alias="VIBE_TRADING_OCR_QWEN_MODEL", default="")
# ---------------------------------------------------------------------------
@@ -301,6 +318,9 @@ class PathConfig(_EnvBase):
allow_session_mcp_servers: EnvBool = Field(alias="ALLOW_SESSION_MCP_SERVERS", default=False)
vibe_trading_theme: str = Field(alias="VIBE_TRADING_THEME", default="")
vibe_goal_session_id: str = Field(alias="VIBE_GOAL_SESSION_ID", default="")
+ vibe_trading_strategy_store_db_path: str = Field(
+ alias="VIBE_TRADING_STRATEGY_STORE_DB_PATH", default="",
+ )
# ---------------------------------------------------------------------------
@@ -325,6 +345,7 @@ class EnvConfig(_EnvBase):
swarm: SwarmConfig = Field(default_factory=SwarmConfig)
agent_tuning: AgentTuningConfig = Field(default_factory=AgentTuningConfig)
paths: PathConfig = Field(default_factory=PathConfig)
+ ocr: OcrConfig = Field(default_factory=OcrConfig)
@model_validator(mode="after")
def _resolve_api_key_alias(self) -> "EnvConfig":
diff --git a/agent/src/strategy_store/metrics.py b/agent/src/strategy_store/metrics.py
new file mode 100644
index 000000000..59be0416c
--- /dev/null
+++ b/agent/src/strategy_store/metrics.py
@@ -0,0 +1,78 @@
+"""Shared decay metrics computation for bench history.
+
+Both ``sdm_decay_scan`` and ``sdm_status`` tools call this to compute
+baseline/rolling IC and Sharpe metrics from a chronologically ordered
+bench-history list.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+def compute_decay_metrics(
+ bench_history: list[Any],
+) -> dict[str, float | None]:
+ """Compute baseline and rolling metrics from bench history.
+
+ For factor artifacts: uses ``ic_mean`` to compute baseline/rolling IC metrics.
+ For strategy artifacts: uses ``sharpe`` to compute rolling Sharpe.
+
+ ``bench_history`` is expected to be newest-first (as returned by the store);
+ it is reversed internally to chronological order before computation.
+
+ Returns:
+ Dict with keys: ``baseline_ic_mean``, ``rolling_ic_mean``, ``ic_ratio``,
+ ``rolling_ir``, ``ic_positive_ratio``, ``rolling_sharpe``, ``baseline_sharpe``.
+ Values are ``None`` when insufficient data (< 3 non-None entries).
+ """
+ result: dict[str, float | None] = {
+ "baseline_ic_mean": None,
+ "rolling_ic_mean": None,
+ "ic_ratio": None,
+ "rolling_ir": None,
+ "ic_positive_ratio": None,
+ "rolling_sharpe": None,
+ "baseline_sharpe": None,
+ }
+
+ chronological = list(reversed(bench_history))
+
+ ic_values = [r.ic_mean for r in chronological if r.ic_mean is not None]
+ sharpe_values = [r.sharpe for r in chronological if r.sharpe is not None]
+
+ has_ic = len(ic_values) >= 3
+ has_sharpe = len(sharpe_values) >= 3
+
+ if has_ic:
+ baseline_ics = ic_values[:5]
+ rolling_ics = ic_values[-5:]
+
+ baseline_mean = sum(baseline_ics) / len(baseline_ics)
+ rolling_mean = sum(rolling_ics) / len(rolling_ics)
+
+ result["baseline_ic_mean"] = round(baseline_mean, 6)
+ result["rolling_ic_mean"] = round(rolling_mean, 6)
+
+ if baseline_mean != 0:
+ result["ic_ratio"] = round(rolling_mean / baseline_mean, 4)
+
+ if len(rolling_ics) > 1:
+ mean_r = sum(rolling_ics) / len(rolling_ics)
+ var_r = sum((x - mean_r) ** 2 for x in rolling_ics) / (len(rolling_ics) - 1)
+ std_r = var_r**0.5
+ if std_r > 0:
+ result["rolling_ir"] = round(mean_r / std_r, 4)
+
+ positive_count = sum(1 for v in ic_values if v > 0)
+ result["ic_positive_ratio"] = round(positive_count / len(ic_values), 4)
+
+ if has_sharpe:
+ result["baseline_sharpe"] = round(
+ sum(sharpe_values[:5]) / len(sharpe_values[:5]), 6
+ )
+ result["rolling_sharpe"] = round(
+ sum(sharpe_values[-5:]) / len(sharpe_values[-5:]), 6
+ )
+
+ return result
diff --git a/agent/src/strategy_store/sqlite_store.py b/agent/src/strategy_store/sqlite_store.py
index b4a297d1d..20c4615b0 100644
--- a/agent/src/strategy_store/sqlite_store.py
+++ b/agent/src/strategy_store/sqlite_store.py
@@ -8,7 +8,6 @@ for schema migrations.
from __future__ import annotations
import json
-import os
import sqlite3
import threading
import uuid
@@ -33,7 +32,6 @@ from src.strategy_store.models import (
# ---------------------------------------------------------------------------
_DEFAULT_DB_PATH = Path.home() / ".vibe-trading" / "strategy_store.db"
-_DB_PATH_ENV = "VIBE_TRADING_STRATEGY_STORE_DB_PATH"
# ---------------------------------------------------------------------------
# Helpers
@@ -64,7 +62,9 @@ def _json_loads(value: str | None, default: object) -> object:
def _default_db_path() -> Path:
"""Return the configured strategy-store database path."""
- raw_path = os.getenv(_DB_PATH_ENV, "").strip()
+ from src.config.accessor import get_env_config
+
+ raw_path = get_env_config().paths.vibe_trading_strategy_store_db_path.strip()
if raw_path:
return Path(raw_path).expanduser()
return _DEFAULT_DB_PATH
@@ -128,7 +128,7 @@ class SqliteStrategyStore:
CREATE TABLE IF NOT EXISTS artifacts (
id TEXT PRIMARY KEY,
type TEXT NOT NULL CHECK(type IN ('factor', 'strategy')),
- name TEXT NOT NULL UNIQUE,
+ name TEXT NOT NULL,
source_paper TEXT,
source_url TEXT,
formula_latex TEXT,
@@ -150,7 +150,8 @@ class SqliteStrategyStore:
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
disabled_at TEXT,
- disabled_reason TEXT
+ disabled_reason TEXT,
+ UNIQUE(name, universe)
);
CREATE TABLE IF NOT EXISTS bench_history (
diff --git a/agent/src/tools/doc_reader_tool.py b/agent/src/tools/doc_reader_tool.py
index 0112ce2ed..59c9c07b0 100644
--- a/agent/src/tools/doc_reader_tool.py
+++ b/agent/src/tools/doc_reader_tool.py
@@ -133,6 +133,7 @@ def _read_pdf(path: Path, pages: str) -> str:
total_targets = len(targets)
chunks: list[str] = []
ocr_pages = 0
+ skipped_pages = 0
for idx, i in enumerate(targets, start=1):
if not 0 <= i < total_pages:
continue
@@ -147,14 +148,15 @@ def _read_pdf(path: Path, pages: str) -> str:
message=f"page {i + 1}/{total_pages}",
)
continue
- # Scanned/image page detected β€” OCR required
if not _ocr_available():
- engine = _get_ocr()
- hint = get_ocr_install_hint(engine)
- return _err(
- f"Page {i + 1}/{total_pages} is a scanned/image page with no "
- f"extractable text, but no OCR engine is available. {hint}"
+ skipped_pages += 1
+ emit_progress(
+ "reading_pdf",
+ current=idx,
+ total=total_targets,
+ message=f"page {i + 1}/{total_pages} (skipped: no OCR)",
)
+ continue
bitmap = page.render(scale=300 / 72)
img = bitmap.to_numpy()
ocr_text = _ocr_image_array(img)
@@ -170,11 +172,19 @@ def _read_pdf(path: Path, pages: str) -> str:
message=f"page {i + 1}/{total_pages} (OCR)" if ocr_text.strip() else f"page {i + 1}/{total_pages}",
)
full = "\n\n".join(chunks)
+ if not full and skipped_pages > 0:
+ engine = _get_ocr()
+ hint = get_ocr_install_hint(engine)
+ return _err(
+ f"All {total_pages} page(s) are scanned/image pages with no "
+ f"extractable text, and no OCR engine is available. {hint}"
+ )
return _envelope(
path, "pdf", full,
total_pages=total_pages,
pages_read=len(targets),
ocr_pages=ocr_pages,
+ skipped_pages=skipped_pages,
)
finally:
doc.close()
diff --git a/agent/src/tools/ocr/engine.py b/agent/src/tools/ocr/engine.py
index cd58bb93c..373c347d6 100644
--- a/agent/src/tools/ocr/engine.py
+++ b/agent/src/tools/ocr/engine.py
@@ -7,14 +7,12 @@ Allows users to swap between local OCR (RapidOCR) and cloud vision models
from __future__ import annotations
import logging
-import os
from typing import Protocol, runtime_checkable
import numpy as np
logger = logging.getLogger(__name__)
-_OCR_ENGINE_ENV = "VIBE_TRADING_OCR_ENGINE"
_VALID_ENGINES = ("auto", "rapid", "qwen-vl", "none")
@@ -37,6 +35,13 @@ class OcrEngine(Protocol):
...
+def _get_ocr_choice() -> str:
+ """Return the configured OCR engine choice (cached per process)."""
+ from src.config.accessor import get_env_config
+
+ return get_env_config().ocr.vibe_trading_ocr_engine.strip().lower()
+
+
def get_ocr_engine() -> OcrEngine | None:
"""Return the configured OCR engine, or None if unavailable.
@@ -46,7 +51,7 @@ def get_ocr_engine() -> OcrEngine | None:
- "qwen-vl": Qwen-VL vision model (cloud, DashScope API)
- "none": disable OCR entirely
"""
- choice = os.getenv(_OCR_ENGINE_ENV, "auto").strip().lower()
+ choice = _get_ocr_choice()
if choice not in _VALID_ENGINES:
logger.warning("Unknown OCR engine '%s', falling back to 'auto'", choice)
choice = "auto"
@@ -100,7 +105,7 @@ def get_ocr_install_hint(engine: OcrEngine | None) -> str:
if engine is not None:
return ""
- choice = os.getenv(_OCR_ENGINE_ENV, "auto").strip().lower()
+ choice = _get_ocr_choice()
if choice == "qwen-vl":
return (
diff --git a/agent/src/tools/ocr/qwen_vision_ocr.py b/agent/src/tools/ocr/qwen_vision_ocr.py
index a85f91175..0ffce4611 100644
--- a/agent/src/tools/ocr/qwen_vision_ocr.py
+++ b/agent/src/tools/ocr/qwen_vision_ocr.py
@@ -5,16 +5,13 @@ from __future__ import annotations
import base64
import io
import logging
-import os
import numpy as np
logger = logging.getLogger(__name__)
-_DASHSCOPE_API_KEY_ENV = "DASHSCOPE_API_KEY"
_DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
_DEFAULT_MODEL = "qwen-vl-plus"
-_MODEL_ENV = "VIBE_TRADING_OCR_QWEN_MODEL"
_OCR_SYSTEM_PROMPT = (
"You are a precise OCR engine. Extract ALL text from the provided image. "
@@ -37,7 +34,9 @@ class QwenVisionOcrEngine:
self._client = None
def is_available(self) -> bool:
- api_key = os.getenv(_DASHSCOPE_API_KEY_ENV)
+ from src.config.accessor import get_env_config
+
+ api_key = get_env_config().data.dashscope_api_key
if not api_key:
return False
try:
@@ -54,11 +53,13 @@ class QwenVisionOcrEngine:
def recognize(self, image: np.ndarray) -> str:
if not self.is_available():
raise RuntimeError(
- f"Qwen-VL OCR requires {_DASHSCOPE_API_KEY_ENV} environment variable"
+ "Qwen-VL OCR requires DASHSCOPE_API_KEY environment variable"
)
b64 = self._numpy_to_base64(image)
- model = os.getenv(_MODEL_ENV, _DEFAULT_MODEL)
+ from src.config.accessor import get_env_config
+
+ model = get_env_config().ocr.vibe_trading_ocr_qwen_model or _DEFAULT_MODEL
try:
response = self._client.chat.completions.create(
diff --git a/agent/src/tools/sdm_decay_scan_tool.py b/agent/src/tools/sdm_decay_scan_tool.py
index f8f824277..cf3409af6 100644
--- a/agent/src/tools/sdm_decay_scan_tool.py
+++ b/agent/src/tools/sdm_decay_scan_tool.py
@@ -3,15 +3,14 @@
from __future__ import annotations
import json
-from dataclasses import asdict
from typing import Any
from src.agent.tools import BaseTool
from src.strategy_store.decay import DecayEvaluator
+from src.strategy_store.metrics import compute_decay_metrics
from src.strategy_store.models import (
ArtifactStatus,
ArtifactType,
- DecaySignal,
DecaySnapshot,
)
from src.strategy_store._shared import get_store as _get_store
@@ -25,60 +24,6 @@ def _error(exc: Exception) -> str:
return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)
-def _compute_scan_metrics(
- bench_history: list[Any],
-) -> dict[str, float | None]:
- """Compute baseline and rolling IC metrics from bench history.
-
- Uses last 20 bench results: baseline from first 5, rolling from last 5.
- Returns dict with baseline_ic_mean, rolling_ic_mean, ic_ratio,
- rolling_ir, ic_positive_ratio.
- """
- result: dict[str, float | None] = {
- "baseline_ic_mean": None,
- "rolling_ic_mean": None,
- "ic_ratio": None,
- "rolling_ir": None,
- "ic_positive_ratio": None,
- }
-
- # bench_history is newest-first; reverse for chronological order
- chronological = list(reversed(bench_history))
-
- ic_values = [
- r.ic_mean for r in chronological if r.ic_mean is not None
- ]
-
- if len(ic_values) < 3:
- return result
-
- baseline_ics = ic_values[:5]
- rolling_ics = ic_values[-5:]
-
- baseline_mean = sum(baseline_ics) / len(baseline_ics)
- rolling_mean = sum(rolling_ics) / len(rolling_ics)
-
- result["baseline_ic_mean"] = round(baseline_mean, 6)
- result["rolling_ic_mean"] = round(rolling_mean, 6)
-
- if baseline_mean != 0:
- result["ic_ratio"] = round(rolling_mean / baseline_mean, 4)
-
- # IR from rolling window
- if len(rolling_ics) > 1:
- mean_r = sum(rolling_ics) / len(rolling_ics)
- var_r = sum((x - mean_r) ** 2 for x in rolling_ics) / (len(rolling_ics) - 1)
- std_r = var_r**0.5
- if std_r > 0:
- result["rolling_ir"] = round(mean_r / std_r, 4)
-
- # IC positive ratio across all available values
- positive_count = sum(1 for v in ic_values if v > 0)
- result["ic_positive_ratio"] = round(positive_count / len(ic_values), 4)
-
- return result
-
-
class SdmDecayScanTool(BaseTool):
"""Run decay monitoring scan on active factors/strategies."""
@@ -88,7 +33,7 @@ class SdmDecayScanTool(BaseTool):
"Evaluates rolling IC vs baseline for each active artifact and "
"reports decay signals."
)
- is_readonly = True
+ is_readonly = False
repeatable = True
parameters = {
"type": "object",
@@ -164,12 +109,13 @@ class SdmDecayScanTool(BaseTool):
})
continue
- metrics = _compute_scan_metrics(bench_history)
+ metrics = compute_decay_metrics(bench_history)
signal = evaluator.evaluate_decay(
ic_ratio=metrics["ic_ratio"],
ir=metrics["rolling_ir"],
ic_positive_ratio=metrics["ic_positive_ratio"],
+ sharpe=metrics["rolling_sharpe"],
)
# Count by signal
@@ -189,6 +135,14 @@ class SdmDecayScanTool(BaseTool):
artifact.status, prior_signals + [signal]
)
+ # Count consecutive non-healthy signals for snapshot
+ consecutive_warnings = 0
+ for s in reversed(prior_signals + [signal]):
+ if s.value != "healthy":
+ consecutive_warnings += 1
+ else:
+ break
+
# Apply transition if not dry_run
transition_info: dict[str, Any] | None = None
if recommended and not dry_run:
@@ -217,6 +171,7 @@ class SdmDecayScanTool(BaseTool):
baseline_ic_mean=metrics["baseline_ic_mean"],
ic_ratio=metrics["ic_ratio"],
decay_signal=signal,
+ consecutive_warnings=consecutive_warnings,
detail=json.dumps(metrics, ensure_ascii=False),
)
store.record_decay_snapshot(snapshot)
diff --git a/agent/src/tools/sdm_status_tool.py b/agent/src/tools/sdm_status_tool.py
index f7def2516..2ef1ed535 100644
--- a/agent/src/tools/sdm_status_tool.py
+++ b/agent/src/tools/sdm_status_tool.py
@@ -8,10 +8,10 @@ from typing import Any
from src.agent.tools import BaseTool
from src.strategy_store.decay import DecayEvaluator
+from src.strategy_store.metrics import compute_decay_metrics
from src.strategy_store.models import (
ArtifactStatus,
ArtifactType,
- DecaySignal,
)
from src.strategy_store._shared import get_store as _get_store
@@ -43,60 +43,6 @@ def _artifact_to_dict(artifact: Any) -> dict[str, Any]:
return d
-def _compute_ic_metrics(
- bench_history: list[Any],
-) -> dict[str, float | None]:
- """Compute baseline and rolling IC metrics from bench history.
-
- Returns dict with baseline_ic_mean, rolling_ic_mean, ic_ratio,
- rolling_ir, ic_positive_ratio.
- """
- result: dict[str, float | None] = {
- "baseline_ic_mean": None,
- "rolling_ic_mean": None,
- "ic_ratio": None,
- "rolling_ir": None,
- "ic_positive_ratio": None,
- }
-
- # bench_history is newest-first; reverse for chronological order
- chronological = list(reversed(bench_history))
-
- ic_values = [
- r.ic_mean for r in chronological if r.ic_mean is not None
- ]
-
- if len(ic_values) < 3:
- return result
-
- # Baseline from first 5 entries, rolling from last 5
- baseline_ics = ic_values[:5]
- rolling_ics = ic_values[-5:]
-
- baseline_mean = sum(baseline_ics) / len(baseline_ics)
- rolling_mean = sum(rolling_ics) / len(rolling_ics)
-
- result["baseline_ic_mean"] = round(baseline_mean, 6)
- result["rolling_ic_mean"] = round(rolling_mean, 6)
-
- if baseline_mean != 0:
- result["ic_ratio"] = round(rolling_mean / baseline_mean, 4)
-
- # IR from rolling window
- if len(rolling_ics) > 1:
- mean_r = sum(rolling_ics) / len(rolling_ics)
- var_r = sum((x - mean_r) ** 2 for x in rolling_ics) / (len(rolling_ics) - 1)
- std_r = var_r**0.5
- if std_r > 0:
- result["rolling_ir"] = round(mean_r / std_r, 4)
-
- # IC positive ratio
- positive_count = sum(1 for v in ic_values if v > 0)
- result["ic_positive_ratio"] = round(positive_count / len(ic_values), 4)
-
- return result
-
-
class SdmStatusTool(BaseTool):
"""Query or update factor/strategy status in the strategy store."""
@@ -105,7 +51,7 @@ class SdmStatusTool(BaseTool):
"Query or update factor/strategy status in the strategy store. "
"Actions: list, detail, disable, enable, decay_check."
)
- is_readonly = True
+ is_readonly = False
repeatable = True
parameters = {
"type": "object",
@@ -256,13 +202,14 @@ class SdmStatusTool(BaseTool):
"message": f"Need at least 3 bench results, have {len(bench_history)}",
})
- metrics = _compute_ic_metrics(bench_history)
+ metrics = compute_decay_metrics(bench_history)
evaluator = DecayEvaluator()
signal = evaluator.evaluate_decay(
ic_ratio=metrics["ic_ratio"],
ir=metrics["rolling_ir"],
ic_positive_ratio=metrics["ic_positive_ratio"],
+ sharpe=metrics["rolling_sharpe"],
)
# Get prior decay signals from history
diff --git a/agent/tests/test_strategy_store.py b/agent/tests/test_strategy_store.py
index a1a2a062b..cf6c6b1b3 100644
--- a/agent/tests/test_strategy_store.py
+++ b/agent/tests/test_strategy_store.py
@@ -501,6 +501,55 @@ class TestSdmTools:
assert result["transitions_applied"] == 0
assert result["summary"]["total_scanned"] == 1
+ def test_decay_scan_tool_active_to_monitoring_transition(self):
+ """Non-dry-run scan transitions active β†’ monitoring after 3+ warnings."""
+ from src.tools.sdm_register_tool import SdmRegisterTool
+ from src.tools.sdm_decay_scan_tool import SdmDecayScanTool
+
+ reg = json.loads(
+ SdmRegisterTool().execute(
+ artifact_type="factor", name="decay_factor", universe="CSI300"
+ )
+ )
+ aid = reg["artifact"]["id"]
+
+ import src.strategy_store._shared as shared
+
+ store = shared._store
+ assert store is not None
+ store.update_status(aid, ArtifactStatus.ACTIVE)
+
+ # 5 baseline (high IC=0.08) + 5 rolling (low IC=0.04) β†’ ratio ~0.5 = WARNING
+ for _ in range(5):
+ store.record_bench(BenchResult(artifact_id=aid, ic_mean=0.08))
+ for _ in range(5):
+ store.record_bench(BenchResult(artifact_id=aid, ic_mean=0.04))
+
+ # Pre-populate 2 prior WARNING snapshots so the 3rd scan triggers transition
+ store.record_decay_snapshot(
+ DecaySnapshot(artifact_id=aid, ic_ratio=0.5, decay_signal=DecaySignal.WARNING)
+ )
+ store.record_decay_snapshot(
+ DecaySnapshot(artifact_id=aid, ic_ratio=0.5, decay_signal=DecaySignal.WARNING)
+ )
+
+ # Third scan: now has 3 consecutive WARNING → active→monitoring
+ result = json.loads(SdmDecayScanTool().execute(dry_run=False))
+ assert result["status"] == "ok"
+ assert result["dry_run"] is False
+ assert result["summary"]["total_scanned"] == 1
+ assert result["transitions_applied"] >= 1
+
+ # Verify the artifact actually transitioned to monitoring
+ artifact = store.get_artifact(aid)
+ assert artifact is not None
+ assert artifact.status == ArtifactStatus.MONITORING
+
+ # Verify a decay snapshot was recorded with consecutive_warnings > 0
+ snapshots = store.get_decay_history(aid, limit=1)
+ assert len(snapshots) == 1
+ assert snapshots[0].consecutive_warnings >= 1
+
# ===========================================================================
# TestSqliteStore