"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(pattern): emit strict JSON when trend_slope mean is undefined
santhrealbd610d0b6784
diff --git a/agent/src/tools/pattern_tool.py b/agent/src/tools/pattern_tool.pyindex f55176cec..4dff94da8 100644--- a/agent/src/tools/pattern_tool.py+++ b/agent/src/tools/pattern_tool.py@@ -7,6 +7,7 @@ Can be called before coding (to inform strategy design) or after backtest (to anfrom __future__ import annotationsimport json+import mathfrom typing import Any, Dictimport numpy as np@@ -291,11 +292,23 @@ def broadening(close: pd.Series, window: int = 20) -> pd.Series:# Available pattern registry# ---------------------------------------------------------------------------+def _trend_slope_summary(df: pd.DataFrame, window: int) -> dict:+ """Mean rolling slope, or 0 when no finite window exists (e.g. halt gaps)."""+ if len(df) <= window:+ return {"mean_slope": 0.0}+ mean = trend_line_slope(df["close"], window=window).dropna().mean()+ # dropna().mean() is NaN when every window contains a NaN close; bare NaN+ # is not valid JSON (options_pricing already uses allow_nan=False).+ if mean is None or not math.isfinite(float(mean)):+ return {"mean_slope": 0.0}+ return {"mean_slope": float(mean)}++_PATTERN_FUNCS = {"peaks_valleys": lambda df, w: find_peaks_valleys(df["close"], window=w),"candlestick": lambda df, w: candlestick_patterns(df["open"], df["high"], df["low"], df["close"]).value_counts().to_dict(),"support_resistance": lambda df, w: support_resistance(df["close"], window=w),- "trend_slope": lambda df, w: {"mean_slope": float(trend_line_slope(df["close"], window=w).dropna().mean())} if len(df) > w else {"mean_slope": 0},+ "trend_slope": _trend_slope_summary,"head_and_shoulders": lambda df, w: {"count": int(head_and_shoulders(df["close"], window=w).sum())},"double_top_bottom": lambda df, w: {"double_top": int((double_top_bottom(df["close"], window=w) == 1).sum()), "double_bottom": int((double_top_bottom(df["close"], window=w) == -1).sum())},"triangle": lambda df, w: {"ascending": int((triangle(df["close"], window=w) == 1).sum()), "descending": int((triangle(df["close"], window=w) == -1).sum())},@@ -358,7 +371,18 @@ def run_pattern(run_dir: str, patterns: str = "all", window: int = 10) -> str:code_results[pattern_name] = func(df, window)results[code] = code_results- return json.dumps({"status": "ok", "results": results, "patterns": selected, "window": window}, ensure_ascii=False, default=str)+ try:+ return json.dumps(+ {"status": "ok", "results": results, "patterns": selected, "window": window},+ ensure_ascii=False,+ default=str,+ allow_nan=False,+ )+ except ValueError as exc:+ return json.dumps(+ {"status": "error", "error": f"non-serializable numeric result: {exc}"},+ ensure_ascii=False,+ )class PatternTool(BaseTool):diff --git a/agent/tests/test_pattern_tool.py b/agent/tests/test_pattern_tool.pyindex fb8b1ad47..a98cbc213 100644--- a/agent/tests/test_pattern_tool.py+++ b/agent/tests/test_pattern_tool.py@@ -307,3 +307,21 @@ def test_run_pattern_trend_slope_window_one_returns_json_error(allow_runs: Path)assert out["status"] == "error"assert "window" in out["error"]assert "trend_slope" in out["error"] or ">= 2" in out["error"]+++def test_run_pattern_trend_slope_halt_gaps_emits_strict_json(allow_runs: Path) -> None:+ """Alternating NaN closes leave no clean polyfit window; mean must not be NaN."""+ run_dir = allow_runs / "run_halt"+ arts = run_dir / "artifacts"+ arts.mkdir(parents=True)+ n = 15+ close = [100.0 if i % 2 == 0 else float("nan") for i in range(n)]+ pd.DataFrame(+ {"open": close, "high": close, "low": close, "close": close, "volume": 1},+ index=pd.date_range("2024-01-01", periods=n),+ ).to_csv(arts / "ohlcv_HALT.csv")+ raw = run_pattern(str(run_dir), patterns="trend_slope", window=5)+ assert "NaN" not in raw and "Infinity" not in raw+ out = json.loads(raw, parse_constant=lambda c: (_ for _ in ()).throw(ValueError(c)))+ assert out["status"] == "ok"+ assert out["results"]["HALT"]["trend_slope"]["mean_slope"] == 0.0