"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Fixed error
Will Liaoeefcf383ea17
diff --git a/agent/src/tools/technical_indicator_tool.py b/agent/src/tools/technical_indicator_tool.pyindex 3c0c2a62d..6fa59e3ca 100644--- a/agent/src/tools/technical_indicator_tool.py+++ b/agent/src/tools/technical_indicator_tool.py@@ -99,6 +99,34 @@ def _compute_bollinger(}+def _records_to_frame(data: Any) -> pd.DataFrame | None:+ """Coerce a ``fetch_market_data`` per-symbol payload into a DataFrame.++ ``fetch_market_data`` returns per-symbol either a list of row dicts+ (``orient="records"``) or — when the row count exceeds ``max_rows`` — a+ ``cap_rows`` truncation envelope ``{"data": [...], "truncated": True}``.+ Legacy loaders returned DataFrames directly. All three shapes are+ accepted here so the tool never assumes one contract.+ """+ if data is None:+ return None+ if isinstance(data, pd.DataFrame):+ return data+ if isinstance(data, dict) and isinstance(data.get("data"), list):+ # cap_rows truncation envelope: {"data": [row dicts], "truncated": True}.+ data = data["data"]+ if isinstance(data, list):+ return pd.DataFrame(data) if data else None+ if isinstance(data, dict):+ if data and all(+ not hasattr(value, "__len__") or isinstance(value, (str, bytes))+ for value in data.values()+ ):+ return pd.DataFrame([data]) # a single record dict+ return pd.DataFrame(data) # dict of column arrays+ return None++class TechnicalIndicatorTool(BaseTool):"""Compute common technical indicators for a symbol.@@ -172,19 +200,15 @@ class TechnicalIndicatorTool(BaseTool):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)+ df = _records_to_frame(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+ close = None+ for key in ("close", "Close", "CLOSE", "adj_close"):+ if key in df.columns:+ close = df[key]+ breakif close is None:return json.dumps({"ok": False, "error": "No close price column in data"})@@ -202,7 +226,18 @@ class TechnicalIndicatorTool(BaseTool):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+ date_col = next(+ (+ k+ for k in ("date", "Date", "datetime", "timestamp", "trade_date")+ if k in df.columns+ ),+ None,+ )+ if date_col is not None and len(df) > 0:+ latest_date = str(df[date_col].iloc[-1])[:10]+ else:+ latest_date = str(close.index[-1])[:10] if len(close) > 0 else Nonereturn json.dumps({diff --git a/agent/tests/test_technical_indicator_tool.py b/agent/tests/test_technical_indicator_tool.pyindex 39ae6029b..7bbc70771 100644--- a/agent/tests/test_technical_indicator_tool.py+++ b/agent/tests/test_technical_indicator_tool.py@@ -220,3 +220,73 @@ class TestTechnicalIndicatorToolIntegration:assert result["indicators"]["bollinger"] is None# But SMA 20 should be null, SMA 50/200 null — only EMA 20 needs 20 bars, null tooassert result["indicators"]["sma_20"] is None++ def test_execute_records_list(self, monkeypatch):+ """fetch_market_data returns a records list (new loader contract)."""+ records = [+ {+ "date": (+ pd.Timestamp("2024-01-01") + pd.Timedelta(days=i)+ ).strftime("%Y-%m-%d"),+ "close": float(100 + i),+ "open": float(99 + i),+ }+ for i in range(250)+ ]+ monkeypatch.setattr(+ "src.tools.technical_indicator_tool.fetch_market_data",+ lambda **kw: {"AAPL": records},+ )+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute(symbol="AAPL"))+ assert result["ok"] is True+ assert result["latest_close"] == 349.0+ assert result["latest_date"] == (+ pd.Timestamp("2024-01-01") + pd.Timedelta(days=249)+ ).strftime("%Y-%m-%d")+ assert result["indicators"]["rsi_14"] is not None+ assert result["indicators"]["sma_200"] is not None++ def test_execute_truncation_envelope(self, monkeypatch):+ """fetch_market_data returns the cap_rows truncation envelope dict."""+ records = [+ {+ "date": (+ pd.Timestamp("2024-01-01") + pd.Timedelta(days=i)+ ).strftime("%Y-%m-%d"),+ "close": float(100 + i),+ }+ for i in range(250)+ ]+ monkeypatch.setattr(+ "src.tools.technical_indicator_tool.fetch_market_data",+ lambda **kw: {+ "AAPL": {+ "rows": 400,+ "returned": len(records),+ "truncated": True,+ "policy": "every-2nd-row",+ "hint": "narrow the date range",+ "data": records,+ }+ },+ )+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute(symbol="AAPL"))+ assert result["ok"] is True+ assert result["latest_close"] == 349.0+ assert result["latest_date"] == (+ pd.Timestamp("2024-01-01") + pd.Timedelta(days=249)+ ).strftime("%Y-%m-%d")+ assert result["indicators"]["sma_200"] is not None++ def test_execute_empty_records_list(self, monkeypatch):+ """fetch_market_data returns an empty records list → error."""+ monkeypatch.setattr(+ "src.tools.technical_indicator_tool.fetch_market_data",+ lambda **kw: {"AAPL": []},+ )+ tool = TechnicalIndicatorTool()+ result = json.loads(tool.execute(symbol="AAPL"))+ assert result["ok"] is False+ assert "No data" in result["error"]