Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(pattern-tool): use abs average in head and shoulders symmetry check

Lanre Shittu2208907890f0
diff --git a/agent/src/tools/pattern_tool.py b/agent/src/tools/pattern_tool.py
index 94cf1b0f1..628d5e1e0 100644
--- a/agent/src/tools/pattern_tool.py
+++ b/agent/src/tools/pattern_tool.py
@@ -183,7 +183,7 @@ def head_and_shoulders(close: pd.Series, window: int = 10) -> pd.Series:
if hv <= lv or hv <= rv:
continue
avg = (lv + rv) / 2
- if avg == 0 or abs(lv - rv) / avg > 0.05:
+ if avg == 0 or abs(lv - rv) / abs(avg) > 0.05:
continue
result.iloc[peaks[i + 1]] = 1
diff --git a/agent/tests/test_pattern_tool_head_shoulders_abs_avg.py b/agent/tests/test_pattern_tool_head_shoulders_abs_avg.py
new file mode 100644
index 000000000..32ba83f1e
--- /dev/null
+++ b/agent/tests/test_pattern_tool_head_shoulders_abs_avg.py
@@ -0,0 +1,22 @@
+"""Regression test for head_and_shoulders pattern detection on negative price series.
+
+Locks out a bug where head_and_shoulders used `abs(lv - rv) / avg` instead of
+`abs(lv - rv) / abs(avg)` in the shoulder-symmetry check, causing false
+detections for negative price series because division by a negative average
+yielded a negative relative difference (< 0.05).
+"""
+
+import pandas as pd
+from src.tools.pattern_tool import head_and_shoulders
+
+
+def test_head_and_shoulders_negative_prices_requires_abs_avg():
+ """Prove that head_and_shoulders does not falsely flag asymmetric negative shoulders."""
+ # Left shoulder = -100, head = -10, right shoulder = -50. Shoulders are
+ # far from symmetric, so this must not be flagged as a valid pattern.
+ prices = pd.Series([-200.0, -100.0, -200.0, -10.0, -200.0, -50.0, -200.0])
+ res = head_and_shoulders(prices, window=1)
+
+ assert (
+ res.iloc[3] == 0
+ ), f"Expected 0 (no pattern for asymmetric negative shoulders), got {res.iloc[3]}"