"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(tools): add technical indicator computation tool (RSI, MACD, Bollinger, SMA, EMA) (#921)
卫斯李da37633fc2f2
diff --git a/agent/src/tools/technical_indicator_tool.py b/agent/src/tools/technical_indicator_tool.pynew file mode 100644index 000000000..3c0c2a62d--- /dev/null+++ b/agent/src/tools/technical_indicator_tool.py@@ -0,0 +1,218 @@+"""Read-only technical indicator tool.++Computes RSI, MACD, Bollinger Bands, SMA, and EMA for a given symbol using the+existing market-data pipeline. All computation is pure Python (numpy/pandas);+no new dependencies.+"""++from __future__ import annotations++import json+import logging+from datetime import datetime, timedelta+from typing import Any++import pandas as pd++from src.agent.tools import BaseTool+from src.market_data import fetch_market_data++logger = logging.getLogger(__name__)++# ── Indicator defaults ────────────────────────────────────────────────────────+_RSI_PERIOD = 14+_MACD_FAST = 12+_MACD_SLOW = 26+_MACD_SIGNAL = 9+_BB_PERIOD = 20+_BB_STD = 2.0+_SMA_PERIODS = (20, 50, 200)+_EMA_PERIOD = 20+_DEFAULT_LOOKBACK = 200+_MAX_LOOKBACK = 500+++def _compute_sma(close: pd.Series, period: int) -> float | None:+ """Simple moving average over the last *period* bars."""+ if len(close) < period:+ return None+ return float(close.iloc[-period:].mean())+++def _compute_ema(close: pd.Series, period: int) -> float | None:+ """Exponential moving average over the full series."""+ if len(close) < period:+ return None+ return float(close.ewm(span=period, adjust=False).mean().iloc[-1])+++def _compute_rsi(close: pd.Series, period: int = _RSI_PERIOD) -> float | None:+ """Relative Strength Index (Wilder smoothing) over *period* bars."""+ if len(close) < period + 1:+ return None+ delta = close.diff()+ gain = delta.clip(lower=0)+ loss = (-delta).clip(lower=0)+ avg_gain = gain.rolling(window=period).mean().iloc[-1]+ avg_loss = loss.rolling(window=period).mean().iloc[-1]+ if avg_loss == 0:+ return 100.0+ rs = avg_gain / avg_loss+ return float(100.0 - (100.0 / (1.0 + rs)))+++def _compute_macd(+ close: pd.Series,+ fast: int = _MACD_FAST,+ slow: int = _MACD_SLOW,+ signal: int = _MACD_SIGNAL,+) -> dict[str, float | None] | None:+ """MACD line, signal line, and histogram."""+ if len(close) < slow + signal:+ return None+ ema_fast = close.ewm(span=fast, adjust=False).mean()+ ema_slow = close.ewm(span=slow, adjust=False).mean()+ macd_line = ema_fast - ema_slow+ signal_line = macd_line.ewm(span=signal, adjust=False).mean()+ histogram = macd_line - signal_line+ return {+ "macd_line": round(float(macd_line.iloc[-1]), 4),+ "signal_line": round(float(signal_line.iloc[-1]), 4),+ "histogram": round(float(histogram.iloc[-1]), 4),+ }+++def _compute_bollinger(+ close: pd.Series,+ period: int = _BB_PERIOD,+ num_std: float = _BB_STD,+) -> dict[str, float | None] | None:+ """Bollinger Bands: upper, middle (SMA), lower."""+ if len(close) < period:+ return None+ sma = close.rolling(window=period).mean()+ std = close.rolling(window=period).std()+ return {+ "upper": round(float(sma.iloc[-1] + num_std * std.iloc[-1]), 2),+ "middle": round(float(sma.iloc[-1]), 2),+ "lower": round(float(sma.iloc[-1] - num_std * std.iloc[-1]), 2),+ }+++class TechnicalIndicatorTool(BaseTool):+ """Compute common technical indicators for a symbol.++ Fetches OHLCV data through the existing loader pipeline, then computes+ RSI, MACD, Bollinger Bands, SMA, and EMA. All math is pure Python; no+ new dependencies, no network calls beyond what the loaders already do.+ """++ name = "technical_indicators"+ description = (+ "Compute common technical indicators (RSI, MACD, Bollinger Bands, "+ "SMA, EMA) for a trading symbol. Uses the project's data loaders "+ "to fetch price history, then computes indicators locally."+ )+ parameters = {+ "type": "object",+ "properties": {+ "symbol": {+ "type": "string",+ "description": (+ "Trading symbol, e.g. AAPL for US stocks, "+ "600519.SH for A-shares, BTC-USDT for crypto."+ ),+ },+ "interval": {+ "type": "string",+ "description": "Bar interval: 1d (default), 1wk, or 1mo.",+ "default": "1d",+ },+ "lookback": {+ "type": "integer",+ "description": (+ "Number of bars to fetch. Default 200, max 500. "+ "More bars = more accurate long-term indicators (SMA 200)."+ ),+ "default": _DEFAULT_LOOKBACK,+ },+ },+ "required": ["symbol"],+ }+ repeatable = True+ is_readonly = True++ def execute(self, **kwargs: Any) -> str:+ symbol = str(kwargs.get("symbol", "")).strip()+ interval = str(kwargs.get("interval", "1d")).strip()+ lookback_raw = kwargs.get("lookback", _DEFAULT_LOOKBACK)++ if not symbol:+ return json.dumps({"ok": False, "error": "symbol is required"})++ try:+ lookback = int(lookback_raw)+ except (TypeError, ValueError):+ lookback = _DEFAULT_LOOKBACK+ lookback = max(10, min(lookback, _MAX_LOOKBACK))++ # Fetch enough bars to cover the longest indicator window + buffer.+ end_date = datetime.now().strftime("%Y-%m-%d")+ start_date = (datetime.now() - timedelta(days=lookback * 2)).strftime("%Y-%m-%d")++ try:+ data = fetch_market_data(+ codes=[symbol],+ start_date=start_date,+ end_date=end_date,+ interval=interval,+ max_rows=lookback,+ )+ except Exception as exc:+ logger.debug("fetch_market_data failed for %s: %s", symbol, exc)+ return json.dumps({"ok": False, "error": f"Failed to fetch data: {exc}"})++ df = data.get(symbol)+ if df is None or df.empty:+ return json.dumps({"ok": False, "error": f"No data returned for {symbol}"})++ close = df.get("close") if isinstance(df, pd.DataFrame) else None+ if close is None:+ # Some loaders return a dict-like structure; try common key names.+ if hasattr(df, "to_dict"):+ d = df.to_dict() if callable(df.to_dict) else dict(df)+ for key in ("close", "Close", "CLOSE", "adj_close"):+ if key in d:+ close = pd.Series(d[key])+ break+ if close is None:+ return json.dumps({"ok": False, "error": "No close price column in data"})++ if not isinstance(close, pd.Series):+ close = pd.Series(close)++ # ── Compute indicators ────────────────────────────────────────────+ indicators: dict[str, Any] = {+ "rsi_14": _compute_rsi(close),+ "macd": _compute_macd(close),+ "bollinger": _compute_bollinger(close),+ }+ for period in _SMA_PERIODS:+ indicators[f"sma_{period}"] = _compute_sma(close, period)+ indicators[f"ema_{_EMA_PERIOD}"] = _compute_ema(close, _EMA_PERIOD)++ latest_close = float(close.iloc[-1]) if len(close) > 0 else None+ latest_date = str(close.index[-1])[:10] if hasattr(close, "index") and len(close) > 0 else None++ return json.dumps(+ {+ "ok": True,+ "symbol": symbol,+ "interval": interval,+ "latest_close": latest_close,+ "latest_date": latest_date,+ "indicators": indicators,+ },+ ensure_ascii=False,+ default=str,+ )diff --git a/agent/tests/test_technical_indicator_tool.py b/agent/tests/test_technical_indicator_tool.pynew file mode 100644index 000000000..39ae6029b--- /dev/null+++ b/agent/tests/test_technical_indicator_tool.py@@ -0,0 +1,222 @@+"""Tests for the technical indicator tool."""++import json++import pandas as pd+import pytest++from src.tools.technical_indicator_tool import (+ TechnicalIndicatorTool,+ _compute_bollinger,+ _compute_ema,+ _compute_macd,+ _compute_rsi,+ _compute_sma,+)+++class TestSMA:+ def test_sma_normal(self):+ close = pd.Series([10.0, 20.0, 30.0, 40.0, 50.0], dtype=float)+ assert _compute_sma(close, 3) == pytest.approx(40.0) # (30+40+50)/3++ def test_sma_insufficient_bars(self):+ close = pd.Series([10.0, 20.0], dtype=float)+ assert _compute_sma(close, 5) is None++ def test_sma_exact_bars(self):+ close = pd.Series([10.0, 20.0, 30.0], dtype=float)+ assert _compute_sma(close, 3) == pytest.approx(20.0)+++class TestEMA:+ def test_ema_normal(self):+ close = pd.Series(range(1, 31), dtype=float)+ result = _compute_ema(close, 10)+ assert result is not None+ assert 25 < result < 30 # EMA should be near recent values++ def test_ema_insufficient_bars(self):+ close = pd.Series([10.0], dtype=float)+ assert _compute_ema(close, 10) is None+++class TestRSI:+ def test_rsi_uptrend(self):+ """All gains, no losses → RSI should approach 100."""+ close = pd.Series([float(100 + i) for i in range(30)], dtype=float)+ rsi = _compute_rsi(close)+ assert rsi is not None+ assert 95 <= rsi <= 100++ def test_rsi_flat(self):+ """Zero change → avg_loss = 0 → RSI = 100 (no downward pressure)."""+ close = pd.Series([100.0] * 30, dtype=float)+ rsi = _compute_rsi(close)+ assert rsi == 100.0++ def test_rsi_downtrend(self):+ """All losses, no gains → RSI should approach 0."""+ close = pd.Series([float(100 - i) for i in range(30)], dtype=float)+ rsi = _compute_rsi(close)+ assert rsi is not None+ assert 0 <= rsi <= 5++ def test_rsi_insufficient_bars(self):+ close = pd.Series([100.0, 101.0], dtype=float)+ assert _compute_rsi(close, 14) is None+++class TestMACD:+ def test_macd_normal(self):+ close = pd.Series(range(1, 101), dtype=float)+ result = _compute_macd(close)+ assert result is not None+ assert "macd_line" in result+ assert "signal_line" in result+ assert "histogram" in result+ assert isinstance(result["macd_line"], float)++ def test_macd_insufficient_bars(self):+ close = pd.Series(range(1, 20), dtype=float)+ assert _compute_macd(close) is None+++class TestBollinger:+ def test_bollinger_normal(self):+ close = pd.Series(range(1, 51), dtype=float)+ result = _compute_bollinger(close, period=20)+ assert result is not None+ assert result["upper"] > result["middle"] > result["lower"]++ def test_bollinger_flat(self):+ """Flat prices → bands collapse to the same value."""+ close = pd.Series([100.0] * 30, dtype=float)+ result = _compute_bollinger(close)+ assert result is not None+ assert result["upper"] == result["middle"] == result["lower"]++ def test_bollinger_insufficient_bars(self):+ close = pd.Series(range(1, 10), dtype=float)+ assert _compute_bollinger(close) is None+++class TestTechnicalIndicatorTool:+ def test_missing_symbol(self):+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute())+ assert result["ok"] is False+ assert "symbol" in result["error"]++ def test_empty_symbol(self):+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute(symbol=" "))+ assert result["ok"] is False++ def test_invalid_lookback_clamped(self):+ tool = TechnicalIndicatorTool()+ # Should not crash with non-numeric lookback+ result = json.loads(tool.execute(symbol="INVALID_SYMBOL_XYZ", lookback="abc"))+ assert "ok" in result+++class TestTechnicalIndicatorToolIntegration:+ """End-to-end tests with mocked fetch_market_data."""++ @pytest.fixture+ def sample_close(self):+ """250-bar uptrend series, enough for all indicators including SMA 200."""+ return pd.Series(+ [float(100 + i) for i in range(250)],+ index=pd.date_range("2024-01-01", periods=250, freq="B"),+ name="close",+ )++ @pytest.fixture+ def sample_df(self, sample_close):+ return pd.DataFrame({"close": sample_close, "open": sample_close * 0.99})++ def test_execute_success(self, monkeypatch, sample_df):+ """Full pipeline: fetch → compute → JSON output."""+ def _mock_fetch(**kwargs):+ return {"AAPL": sample_df}+ monkeypatch.setattr(+ "src.tools.technical_indicator_tool.fetch_market_data",+ _mock_fetch,+ )+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute(symbol="AAPL"))+ assert result["ok"] is True+ assert result["symbol"] == "AAPL"+ assert result["indicators"]["rsi_14"] is not None+ assert result["indicators"]["macd"] is not None+ assert result["indicators"]["bollinger"] is not None+ assert result["indicators"]["sma_20"] is not None+ assert result["indicators"]["sma_50"] is not None+ assert result["indicators"]["sma_200"] is not None+ assert result["indicators"]["ema_20"] is not None+ assert result["latest_close"] == 349.0+ assert result["latest_date"] is not None++ def test_execute_dataframe_with_adj_close(self, monkeypatch, sample_close):+ """Loader returns 'adj_close' instead of 'close'."""+ df = pd.DataFrame({"adj_close": sample_close})+ monkeypatch.setattr(+ "src.tools.technical_indicator_tool.fetch_market_data",+ lambda **kw: {"AAPL": df},+ )+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute(symbol="AAPL"))+ assert result["ok"] is True+ assert result["indicators"]["rsi_14"] is not None++ def test_execute_fetch_failure(self, monkeypatch):+ """Loader raises → error envelope."""+ monkeypatch.setattr(+ "src.tools.technical_indicator_tool.fetch_market_data",+ lambda **kw: (_ for _ in ()).throw(RuntimeError("network down")),+ )+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute(symbol="AAPL"))+ assert result["ok"] is False+ assert "network down" in result["error"]++ def test_execute_empty_data(self, monkeypatch):+ """Loader returns empty → error."""+ monkeypatch.setattr(+ "src.tools.technical_indicator_tool.fetch_market_data",+ lambda **kw: {"AAPL": pd.DataFrame()},+ )+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute(symbol="AAPL"))+ assert result["ok"] is False+ assert "No data" in result["error"]++ def test_execute_no_close_column(self, monkeypatch):+ """DataFrame without close column → error."""+ monkeypatch.setattr(+ "src.tools.technical_indicator_tool.fetch_market_data",+ lambda **kw: {"AAPL": pd.DataFrame({"high": [1.0], "low": [0.5]})},+ )+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute(symbol="AAPL"))+ assert result["ok"] is False+ assert "close" in result["error"].lower()++ def test_execute_short_data_returns_nulls(self, monkeypatch):+ """Too few bars → indicators return null, but not error."""+ short_close = pd.Series([float(100 + i) for i in range(10)],+ index=pd.date_range("2026-06-01", periods=10, freq="B"))+ monkeypatch.setattr(+ "src.tools.technical_indicator_tool.fetch_market_data",+ lambda **kw: {"AAPL": pd.DataFrame({"close": short_close})},+ )+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute(symbol="AAPL", lookback=10))+ assert result["ok"] is True+ # With 10 bars: RSI needs 15, MACD needs 35, BB needs 20 → all null+ assert result["indicators"]["rsi_14"] is None+ assert result["indicators"]["macd"] is None+ assert result["indicators"]["bollinger"] is None+ # But SMA 20 should be null, SMA 50/200 null — only EMA 20 needs 20 bars, null too+ assert result["indicators"]["sma_20"] is None