Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(pattern-tool): use abs(avg) when evaluating double top peak difference (#926)

Santh2a50c5563a6c
diff --git a/agent/src/tools/pattern_tool.py b/agent/src/tools/pattern_tool.py
index 4dff94da8..94cf1b0f1 100644
--- a/agent/src/tools/pattern_tool.py
+++ b/agent/src/tools/pattern_tool.py
@@ -209,7 +209,7 @@ def double_top_bottom(close: pd.Series, window: int = 10) -> pd.Series:
if np.isnan(v1) or np.isnan(v2):
continue
avg = (v1 + v2) / 2
- if avg != 0 and abs(v1 - v2) / avg < 0.03:
+ if avg != 0 and abs(v1 - v2) / abs(avg) < 0.03:
result.iloc[pv["peaks"][i + 1]] = 1
for i in range(len(pv["valleys"]) - 1):
diff --git a/agent/tests/test_pattern_tool_double_top_abs_avg.py b/agent/tests/test_pattern_tool_double_top_abs_avg.py
new file mode 100644
index 000000000..053af3c31
--- /dev/null
+++ b/agent/tests/test_pattern_tool_double_top_abs_avg.py
@@ -0,0 +1,22 @@
+"""Regression test for double_top_bottom pattern detection on negative price series.
+
+Locks out a bug where double_top_bottom used `abs(v1 - v2) / avg` instead of
+`abs(v1 - v2) / abs(avg)` in the peaks loop, causing false double top detections
+for negative price series because division by a negative average yielded a
+negative relative difference (< 0.03).
+"""
+
+import numpy as np
+import pandas as pd
+from src.tools.pattern_tool import double_top_bottom
+
+
+def test_double_top_negative_prices_requires_abs_avg():
+ """Prove that double_top_bottom does not falsely flag divergent negative peaks as a double top."""
+ # Peak 1 = -100.0, Peak 2 = -1.0. Relative difference is large (~1.96), not a double top.
+ prices = pd.Series([-100.0, -100.0, -100.0, -100.0, -100.0, -100.0, -100.0, -50.0, -1.0, -50.0, -100.0])
+ res = double_top_bottom(prices, window=2)
+
+ # Peak 2 is at index 8. On un-fixed code, res.iloc[8] == 1 (false double top).
+ # On fixed code, res.iloc[8] == 0 (no false double top).
+ assert res.iloc[8] == 0, f"Expected 0 (no double top for divergent negative peaks), got {res.iloc[8]}"