-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_patterns.py
More file actions
300 lines (284 loc) · 10.6 KB
/
Copy pathtest_patterns.py
File metadata and controls
300 lines (284 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import pytest
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from historic_market import (
detect_head_and_shoulders,
detect_double_bottom,
detect_cup_and_handle,
detect_symmetrical_triangle
)
# -----------------------------------------------------------------------------
# Helper to create synthetic price data with known patterns
# -----------------------------------------------------------------------------
def create_synthetic_head_shoulders(
left_shoulder_price=100,
head_price=120,
right_shoulder_price=98,
neckline_price=90,
noise=0.5,
n_points=100
):
"""
Generate a synthetic Head & Shoulders pattern.
Returns a DataFrame with 'Close' and 'Date' columns.
"""
x = np.linspace(0, 1, n_points)
# Create a baseline with three peaks: left shoulder, head, right shoulder
# left shoulder at ~0.2, head at ~0.5, right shoulder at ~0.8
# We'll use gaussian-like shapes
y = neckline_price + 0 * x
# Left shoulder
y += 10 * np.exp(-((x - 0.25) ** 2) / (2 * 0.02 ** 2))
# Head
y += 30 * np.exp(-((x - 0.5) ** 2) / (2 * 0.02 ** 2))
# Right shoulder
y += 8 * np.exp(-((x - 0.75) ** 2) / (2 * 0.02 ** 2))
# Add two troughs for neckline (optional, but we can just use the baseline)
# Add noise
y += np.random.normal(0, noise, n_points)
# Ensure the head is highest, shoulders lower
df = pd.DataFrame({
'Close': y,
'Date': pd.date_range(start='2020-01-01', periods=n_points, freq='D')
})
return df
def create_synthetic_double_bottom(
bottom1_price=100,
bottom2_price=102,
neckline_price=120,
noise=0.5,
n_points=100
):
"""
Generate a synthetic Double Bottom pattern.
"""
x = np.linspace(0, 1, n_points)
# Two troughs: first at ~0.3, second at ~0.7, peak in between
y = neckline_price + 0 * x
# First bottom
y -= 20 * np.exp(-((x - 0.3) ** 2) / (2 * 0.03 ** 2))
# Intermediate peak
y += 10 * np.exp(-((x - 0.5) ** 2) / (2 * 0.02 ** 2))
# Second bottom
y -= 18 * np.exp(-((x - 0.7) ** 2) / (2 * 0.03 ** 2))
# Add noise
y += np.random.normal(0, noise, n_points)
df = pd.DataFrame({
'Close': y,
'Date': pd.date_range(start='2020-01-01', periods=n_points, freq='D')
})
return df
def create_synthetic_cup_handle(
left_rim=120,
cup_bottom=90,
right_rim=118,
handle_bottom=105,
noise=0.5,
n_points=100
):
"""
Generate a synthetic Cup and Handle pattern.
"""
x = np.linspace(0, 1, n_points)
# Cup: quadratic curve from left rim to bottom to right rim
# Handle: small dip after right rim
y = np.zeros(n_points)
# Cup phase (0 to 0.7)
cup_mask = x <= 0.7
x_cup = x[cup_mask]
# Quadratic interpolation: left rim at x=0, bottom at x=0.35, right rim at x=0.7
# Use three points to fit a quadratic
x_pts = np.array([0, 0.35, 0.7])
y_pts = np.array([left_rim, cup_bottom, right_rim])
coeffs = np.polyfit(x_pts, y_pts, 2)
y[cup_mask] = np.polyval(coeffs, x_cup)
# Handle phase (0.7 to 1.0)
handle_mask = x > 0.7
x_handle = x[handle_mask]
# Handle: slight dip then recovery to right_rim
handle_peak = right_rim
handle_bottom_val = handle_bottom
# Linear interpolation from right_rim at x=0.7 to handle_bottom at x=0.85 to right_rim at x=1.0
x_handle_norm = (x_handle - 0.7) / 0.3 # 0 to 1
y_handle = handle_peak + (handle_bottom_val - handle_peak) * np.sin(x_handle_norm * np.pi)
y[handle_mask] = y_handle
# Add noise
y += np.random.normal(0, noise, n_points)
df = pd.DataFrame({
'Close': y,
'Date': pd.date_range(start='2020-01-01', periods=n_points, freq='D')
})
return df
def create_synthetic_triangle(
start_price=100,
end_price=110,
amplitude=20,
noise=0.5,
n_points=100,
breakout_bullish=True
):
"""
Generate a synthetic Symmetrical Triangle pattern with a breakout.
"""
x = np.linspace(0, 1, n_points)
# Upper trendline: decreasing from start+amplitude to end_price+small
upper = start_price + amplitude * (1 - x) + 2
lower = start_price - amplitude * (1 - x) - 2
# Price oscillates between upper and lower with decreasing amplitude
y = (upper + lower) / 2 + (upper - lower) / 2 * np.sin(x * 10 * np.pi)
# Breakout near the end
breakout_idx = int(0.85 * n_points)
if breakout_bullish:
y[breakout_idx:] = upper[breakout_idx:] + 5 # Break above upper
else:
y[breakout_idx:] = lower[breakout_idx:] - 5 # Break below lower
y += np.random.normal(0, noise, n_points)
df = pd.DataFrame({
'Close': y,
'Date': pd.date_range(start='2020-01-01', periods=n_points, freq='D')
})
return df
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
def test_head_and_shoulders_detection():
"""Test that a synthetic Head & Shoulders is detected."""
df = create_synthetic_head_shoulders(
left_shoulder_price=100,
head_price=120,
right_shoulder_price=98,
neckline_price=90,
noise=0.2
)
patterns = detect_head_and_shoulders(df, depth=2, min_pattern_separation=5, debug=False)
assert len(patterns) >= 1, "Should detect at least one H&S pattern"
p = patterns[0]
# Check that the pattern has the expected structure
assert 'left_shoulder_idx' in p
assert 'head_idx' in p
assert 'right_shoulder_idx' in p
assert 'breakout_idx' in p
# Head should be higher than shoulders
assert p['head_price'] > p['left_shoulder_price']
assert p['head_price'] > p['right_shoulder_price']
# Confidence should be reasonable
assert 0.0 <= p['confidence'] <= 1.0
def test_double_bottom_detection():
"""Test that a synthetic Double Bottom is detected."""
df = create_synthetic_double_bottom(
bottom1_price=100,
bottom2_price=102,
neckline_price=120,
noise=0.2
)
patterns = detect_double_bottom(df, order=3, tolerance=0.05, min_pattern_length=10, debug=False)
assert len(patterns) >= 1, "Should detect at least one Double Bottom"
p = patterns[0]
assert 'trough1_idx' in p
assert 'trough2_idx' in p
assert 'neckline_idx' in p
assert 'breakout_idx' in p
# Troughs should be close in price
price1, price2 = p['trough_prices']
assert abs(price1 - price2) / min(price1, price2) < 0.05
assert p['confidence'] > 0.5
def test_cup_and_handle_detection():
"""Test that a synthetic Cup and Handle is detected."""
df = create_synthetic_cup_handle(
left_rim=120,
cup_bottom=90,
right_rim=118,
handle_bottom=105,
noise=0.2
)
patterns = detect_cup_and_handle(df, order=5, cup_min_bars=10, handle_max_retrace=0.5, debug=False)
assert len(patterns) >= 1, "Should detect at least one Cup and Handle"
p = patterns[0]
assert 'left_peak' in p
assert 'cup_bottom' in p
assert 'right_peak' in p
assert 'handle_bottom' in p
assert 'breakout' in p
# The breakout should be above the right rim
right_rim_price = df['Close'].iloc[p['right_peak']]
breakout_price = df['Close'].iloc[p['breakout']]
assert breakout_price > right_rim_price * 1.01
def test_symmetrical_triangle_detection_bullish():
"""Test that a bullish symmetrical triangle is detected."""
df = create_synthetic_triangle(
start_price=100,
end_price=110,
amplitude=20,
noise=0.2,
breakout_bullish=True
)
patterns = detect_symmetrical_triangle(df, order=3, min_pattern_length=10, debug=False)
assert len(patterns) >= 1, "Should detect at least one Symmetrical Triangle"
p = patterns[0]
assert 'breakout_idx' in p
assert p['breakout_type'] == 'Bullish'
assert p['confidence'] > 0.5
def test_symmetrical_triangle_detection_bearish():
"""Test that a bearish symmetrical triangle is detected."""
df = create_synthetic_triangle(
start_price=100,
end_price=110,
amplitude=20,
noise=0.2,
breakout_bullish=False
)
patterns = detect_symmetrical_triangle(df, order=3, min_pattern_length=10, debug=False)
assert len(patterns) >= 1, "Should detect at least one Symmetrical Triangle"
p = patterns[0]
assert 'breakout_idx' in p
assert p['breakout_type'] == 'Bearish'
def test_no_pattern_detected_with_random_data():
"""Ensure that random data does not produce false positives."""
np.random.seed(42)
random_prices = 100 + np.cumsum(np.random.randn(200)) # random walk
df = pd.DataFrame({
'Close': random_prices,
'Date': pd.date_range(start='2020-01-01', periods=200, freq='D')
})
# Expect no patterns
hs = detect_head_and_shoulders(df, depth=3, debug=False)
db = detect_double_bottom(df, order=5, debug=False)
ch = detect_cup_and_handle(df, order=5, debug=False)
st = detect_symmetrical_triangle(df, order=3, debug=False)
# For random data, we may still get some patterns due to noise, but we expect few
# We'll just assert that the counts are not unreasonably high.
# This test is more about ensuring the functions run without errors.
assert isinstance(hs, list)
assert isinstance(db, list)
assert isinstance(ch, list)
assert isinstance(st, list)
def test_edge_cases_empty_data():
"""Test that empty DataFrames return empty lists without errors."""
df = pd.DataFrame(columns=['Close', 'Date'])
assert detect_head_and_shoulders(df) == []
assert detect_double_bottom(df) == []
assert detect_cup_and_handle(df) == []
assert detect_symmetrical_triangle(df) == []
def test_edge_cases_short_data():
"""Test that DataFrames with insufficient data return empty lists."""
df = pd.DataFrame({
'Close': np.random.randn(10),
'Date': pd.date_range(start='2020-01-01', periods=10, freq='D')
})
# All detection functions require a minimum length.
assert detect_head_and_shoulders(df) == []
assert detect_double_bottom(df) == []
assert detect_cup_and_handle(df) == []
assert detect_symmetrical_triangle(df) == []
def test_parameter_variations():
"""Test that detectors respond to parameter changes (basic)."""
df = create_synthetic_head_shoulders(noise=0.1)
# Using a smaller depth should detect more patterns
patterns1 = detect_head_and_shoulders(df, depth=2)
patterns2 = detect_head_and_shoulders(df, depth=5)
# We just check that both run and return lists
assert isinstance(patterns1, list)
assert isinstance(patterns2, list)
if __name__ == "__main__":
pytest.main([__file__])