openpatterns 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,416 @@
1
+ """Chart pattern detection over confirmed swing points, with full lifecycle.
2
+
3
+ Every detector follows the same discipline:
4
+
5
+ 1. A candidate exists only once its last defining pivot is **confirmed**
6
+ (``Pivot.confirmed_at``) — that bar is the detection's ``formed_at``, and
7
+ the detection starts life as ``FORMING``.
8
+ 2. From ``formed_at`` onward, each later bar either **confirms** the pattern
9
+ (close beyond its trigger level → ``confirmed_at``), **invalidates** it
10
+ (price violates the geometry → ``invalidated_at``), or leaves it forming.
11
+ 3. Nothing is ever back-dated: ``confirmed_at >= formed_at >= `` the last
12
+ pivot's own confirmation bar.
13
+
14
+ Tolerances are explicit module constants; see README for the frozen spec.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Iterable
20
+
21
+ import numpy as np
22
+
23
+ from .core import Detection, Direction, OHLCV, Status
24
+ from .swings import Pivot, rolling_pivots
25
+
26
+ __all__ = ["detect_chart_patterns", "CHART_PATTERNS"]
27
+
28
+ # ---------------------------------------------------------------- tolerances
29
+ EQ_TOL = 0.02 # double top/bottom: peaks/troughs equal within 2%
30
+ SHOULDER_TOL = 0.04 # H&S: shoulders equal within 4%
31
+ HEAD_MIN = 0.01 # H&S: head exceeds both shoulders by >= 1%
32
+ FLAT_SLOPE = 0.0008 # triangles: |slope| per bar / mean price below this = flat
33
+ TRI_MIN_PIVOTS = 3 # triangles: pivots per side to fit a line
34
+ MAX_WAIT = 60 # bars after formed_at before a forming pattern expires
35
+
36
+ POLE_MIN_MOVE = 0.08 # flags/pennants: pole leg must move >= 8% of its start price
37
+ POLE_MAX_BARS = 15 # flags/pennants: pole leg completes within this many bars
38
+ FLAG_MIN_PIVOTS = 2 # flags/pennants: consolidation pivots per side to fit a line
39
+ FLAG_MAX_BARS = 25 # flags/pennants: consolidation pivots lie within this many
40
+ # bars after the pole's end pivot
41
+ FLAG_MAX_SLOPE = 0.01 # flags/pennants: max |slope| per bar / mean price of either
42
+ # consolidation line ("mild" drift, not a new trend)
43
+ FLAG_PARALLEL_TOL = 0.003 # flags: channel lines parallel within this relative-slope gap
44
+ FLAG_MAX_WAIT = 20 # flags/pennants: tighter expiry than MAX_WAIT (short patterns)
45
+ WEDGE_MIN_PIVOTS = 3 # wedges: pivots per side to fit a line (as triangles)
46
+ WEDGE_MIN_CONVERGENCE = 0.0005 # wedges: lower-line slope must exceed upper-line
47
+ # slope by this (relative) so the lines converge
48
+
49
+ CHART_PATTERNS = [
50
+ "double_top", "double_bottom",
51
+ "head_and_shoulders", "inverse_head_and_shoulders",
52
+ "ascending_triangle", "descending_triangle", "symmetrical_triangle",
53
+ "bull_flag", "bear_flag",
54
+ "bull_pennant", "bear_pennant",
55
+ "rising_wedge", "falling_wedge",
56
+ ]
57
+
58
+
59
+ def _resolve(
60
+ data: OHLCV, start: int, trigger: float, invalid: float, bullish: bool,
61
+ trigger_line=None, invalid_line=None, max_wait: int = MAX_WAIT,
62
+ cross_kills: bool = False,
63
+ ) -> tuple[Status, int | None, int | None]:
64
+ """Walk bars from ``start``: breakout past trigger confirms, crossing the
65
+ invalidation level kills. ``trigger_line`` / ``invalid_line`` (callables
66
+ bar -> price) override the flat levels when given. ``cross_kills`` kills
67
+ the pattern the bar its two lines meet (apex passed; converging patterns
68
+ only). Expires after ``max_wait`` bars."""
69
+ n = len(data)
70
+ end = min(n, start + max_wait + 1)
71
+ for i in range(start, end):
72
+ t = trigger_line(i) if trigger_line is not None else trigger
73
+ v = invalid_line(i) if invalid_line is not None else invalid
74
+ if cross_kills:
75
+ up, lo = (t, v) if bullish else (v, t)
76
+ if lo >= up: # apex passed without breakout
77
+ return Status.INVALIDATED, None, i
78
+ if bullish:
79
+ if data.close[i] > t:
80
+ return Status.CONFIRMED, i, None
81
+ if data.close[i] < v:
82
+ return Status.INVALIDATED, None, i
83
+ else:
84
+ if data.close[i] < t:
85
+ return Status.CONFIRMED, i, None
86
+ if data.close[i] > v:
87
+ return Status.INVALIDATED, None, i
88
+ if end < n: # expired unresolved
89
+ return Status.INVALIDATED, None, end - 1
90
+ return Status.FORMING, None, None
91
+
92
+
93
+ def _double(data: OHLCV, pivots: list[Pivot], kind: str) -> list[Detection]:
94
+ """double_top (kind='high') / double_bottom (kind='low')."""
95
+ out: list[Detection] = []
96
+ seq = pivots
97
+ for k in range(len(seq) - 2):
98
+ a, m, b = seq[k], seq[k + 1], seq[k + 2]
99
+ if a.kind != kind or b.kind != kind or m.kind == kind:
100
+ continue
101
+ ref = max(abs(a.price), 1e-12)
102
+ if abs(a.price - b.price) > EQ_TOL * ref:
103
+ continue
104
+ bullish = kind == "low"
105
+ neckline = m.price
106
+ formed_at = b.confirmed_at
107
+ if formed_at >= len(data):
108
+ continue
109
+ extreme = min(a.price, b.price) if bullish else max(a.price, b.price)
110
+ invalid = extreme * (1 - EQ_TOL) if bullish else extreme * (1 + EQ_TOL)
111
+ status, conf, inv = _resolve(data, formed_at, neckline, invalid, bullish)
112
+ height = abs(((a.price + b.price) / 2) - neckline)
113
+ target = neckline + height if bullish else neckline - height
114
+ out.append(Detection(
115
+ pattern="double_bottom" if bullish else "double_top",
116
+ direction=Direction.BULLISH if bullish else Direction.BEARISH,
117
+ status=status, formed_at=formed_at,
118
+ confirmed_at=conf, invalidated_at=inv,
119
+ pivots=[(a.index, a.price), (m.index, m.price), (b.index, b.price)],
120
+ levels={"neckline": neckline, "target": target},
121
+ ))
122
+ return out
123
+
124
+
125
+ def _hns(data: OHLCV, pivots: list[Pivot], inverse: bool) -> list[Detection]:
126
+ """head_and_shoulders (tops, bearish) / inverse (bottoms, bullish)."""
127
+ out: list[Detection] = []
128
+ kind = "low" if inverse else "high"
129
+ sgn = -1.0 if inverse else 1.0
130
+ ext = [p for p in pivots if p.kind == kind]
131
+ opp = [p for p in pivots if p.kind != kind]
132
+ for k in range(len(ext) - 2):
133
+ ls, hd, rs = ext[k], ext[k + 1], ext[k + 2]
134
+ # head must exceed both shoulders (in pattern direction)
135
+ if not (sgn * hd.price > sgn * ls.price * (1 + sgn * HEAD_MIN)
136
+ and sgn * hd.price > sgn * rs.price * (1 + sgn * HEAD_MIN)):
137
+ continue
138
+ if abs(ls.price - rs.price) > SHOULDER_TOL * abs(ls.price):
139
+ continue
140
+ # neckline pivots: the opposite-kind pivots between ls-hd and hd-rs
141
+ n1 = [p for p in opp if ls.index < p.index < hd.index]
142
+ n2 = [p for p in opp if hd.index < p.index < rs.index]
143
+ if not n1 or not n2:
144
+ continue
145
+ p1, p2 = n1[-1], n2[-1]
146
+ if p2.index == p1.index:
147
+ continue
148
+ slope = (p2.price - p1.price) / (p2.index - p1.index)
149
+ def neck(i: int, p1=p1, slope=slope) -> float:
150
+ return p1.price + slope * (i - p1.index)
151
+ formed_at = max(rs.confirmed_at, p2.confirmed_at)
152
+ if formed_at >= len(data):
153
+ continue
154
+ bullish = inverse
155
+ invalid = hd.price * (1 - HEAD_MIN) if inverse else hd.price * (1 + HEAD_MIN)
156
+ status, conf, inv = _resolve(
157
+ data, formed_at, 0.0, invalid, bullish, trigger_line=neck,
158
+ )
159
+ height = abs(hd.price - neck(hd.index))
160
+ base = neck(rs.index)
161
+ target = base + height if bullish else base - height
162
+ out.append(Detection(
163
+ pattern="inverse_head_and_shoulders" if inverse else "head_and_shoulders",
164
+ direction=Direction.BULLISH if bullish else Direction.BEARISH,
165
+ status=status, formed_at=formed_at,
166
+ confirmed_at=conf, invalidated_at=inv,
167
+ pivots=[(ls.index, ls.price), (p1.index, p1.price), (hd.index, hd.price),
168
+ (p2.index, p2.price), (rs.index, rs.price)],
169
+ levels={"neckline_start": p1.price, "neckline_slope": slope, "target": target},
170
+ ))
171
+ return out
172
+
173
+
174
+ def _fit(points: list[Pivot]) -> tuple[float, float]:
175
+ xs = np.array([p.index for p in points], dtype=float)
176
+ ys = np.array([p.price for p in points], dtype=float)
177
+ slope, intercept = np.polyfit(xs, ys, 1)
178
+ return float(slope), float(intercept)
179
+
180
+
181
+ def _triangles(data: OHLCV, pivots: list[Pivot]) -> list[Detection]:
182
+ out: list[Detection] = []
183
+ highs = [p for p in pivots if p.kind == "high"]
184
+ lows = [p for p in pivots if p.kind == "low"]
185
+ if len(highs) < TRI_MIN_PIVOTS or len(lows) < TRI_MIN_PIVOTS:
186
+ return out
187
+ hs = highs[-TRI_MIN_PIVOTS:]
188
+ ls = lows[-TRI_MIN_PIVOTS:]
189
+ mean_px = float(np.mean(data.close))
190
+ h_slope, h_int = _fit(hs)
191
+ l_slope, l_int = _fit(ls)
192
+ rel_h, rel_l = h_slope / mean_px, l_slope / mean_px
193
+ flat_h, flat_l = abs(rel_h) <= FLAT_SLOPE, abs(rel_l) <= FLAT_SLOPE
194
+ name = None
195
+ if flat_h and rel_l > FLAT_SLOPE:
196
+ name, bullish = "ascending_triangle", True
197
+ elif flat_l and rel_h < -FLAT_SLOPE:
198
+ name, bullish = "descending_triangle", False
199
+ elif rel_h < -FLAT_SLOPE and rel_l > FLAT_SLOPE:
200
+ # symmetrical: breakout side decides; treat as neutral until confirmed
201
+ name, bullish = "symmetrical_triangle", None
202
+ if name is None:
203
+ return out
204
+ formed_at = max(hs[-1].confirmed_at, ls[-1].confirmed_at)
205
+ if formed_at >= len(data):
206
+ return out
207
+ def upper(i: int) -> float:
208
+ return h_int + h_slope * i
209
+ def lower(i: int) -> float:
210
+ return l_int + l_slope * i
211
+ n = len(data)
212
+ end = min(n, formed_at + MAX_WAIT + 1)
213
+ status: Status = Status.FORMING
214
+ conf = inv = None
215
+ direction = Direction.NEUTRAL
216
+ for i in range(formed_at, end):
217
+ up, lo = upper(i), lower(i)
218
+ if lo >= up: # apex passed without breakout
219
+ status, inv = Status.INVALIDATED, i
220
+ break
221
+ if data.close[i] > up and bullish in (True, None):
222
+ status, conf, direction = Status.CONFIRMED, i, Direction.BULLISH
223
+ break
224
+ if data.close[i] < lo and bullish in (False, None):
225
+ status, conf, direction = Status.CONFIRMED, i, Direction.BEARISH
226
+ break
227
+ if bullish is True and data.close[i] < lo:
228
+ status, inv = Status.INVALIDATED, i
229
+ break
230
+ if bullish is False and data.close[i] > up:
231
+ status, inv = Status.INVALIDATED, i
232
+ break
233
+ else:
234
+ if end < n:
235
+ status, inv = Status.INVALIDATED, end - 1
236
+ if status != Status.CONFIRMED:
237
+ direction = (Direction.BULLISH if bullish is True
238
+ else Direction.BEARISH if bullish is False else Direction.NEUTRAL)
239
+ out.append(Detection(
240
+ pattern=name, direction=direction, status=status,
241
+ formed_at=formed_at, confirmed_at=conf, invalidated_at=inv,
242
+ pivots=[(p.index, p.price) for p in sorted(hs + ls, key=lambda p: p.index)],
243
+ levels={"upper_slope": h_slope, "upper_intercept": h_int,
244
+ "lower_slope": l_slope, "lower_intercept": l_int},
245
+ ))
246
+ return out
247
+
248
+
249
+ def _flags_pennants(data: OHLCV, pivots: list[Pivot]) -> list[Detection]:
250
+ """bull_flag / bear_flag / bull_pennant / bear_pennant.
251
+
252
+ A pole is an impulse leg between two **adjacent** opposite-kind pivots
253
+ moving >= ``POLE_MIN_MOVE`` within <= ``POLE_MAX_BARS`` bars. The
254
+ consolidation is fitted through the pivot highs/lows that follow the
255
+ pole's end pivot (>= ``FLAG_MIN_PIVOTS`` per side, all within
256
+ ``FLAG_MAX_BARS`` bars of it):
257
+
258
+ - flag: two roughly parallel lines (relative-slope gap within
259
+ ``FLAG_PARALLEL_TOL``) drifting mildly against the pole direction;
260
+ - pennant: converging lines, upper falling and lower rising (a small
261
+ symmetrical triangle after a pole).
262
+
263
+ Confirms on a close breaking the consolidation in the pole direction;
264
+ invalidates on a close through the opposite line, on the pennant's apex
265
+ passing, or after ``FLAG_MAX_WAIT`` bars.
266
+ """
267
+ out: list[Detection] = []
268
+ n = len(data)
269
+ mean_px = float(np.mean(data.close))
270
+ for k in range(len(pivots) - 1):
271
+ a, b = pivots[k], pivots[k + 1] # adjacent pivots: candidate pole leg
272
+ if a.kind == b.kind:
273
+ continue
274
+ bullish = a.kind == "low" # low -> high pole; else high -> low
275
+ move = (b.price - a.price) / max(abs(a.price), 1e-12)
276
+ if (move if bullish else -move) < POLE_MIN_MOVE:
277
+ continue
278
+ if b.index - a.index > POLE_MAX_BARS:
279
+ continue
280
+ cons = [p for p in pivots if b.index < p.index <= b.index + FLAG_MAX_BARS]
281
+ hs = [p for p in cons if p.kind == "high"]
282
+ ls = [p for p in cons if p.kind == "low"]
283
+ if len(hs) < FLAG_MIN_PIVOTS or len(ls) < FLAG_MIN_PIVOTS:
284
+ continue
285
+ h_slope, h_int = _fit(hs)
286
+ l_slope, l_int = _fit(ls)
287
+ rel_h, rel_l = h_slope / mean_px, l_slope / mean_px
288
+ if max(abs(rel_h), abs(rel_l)) > FLAG_MAX_SLOPE:
289
+ continue
290
+ name = None
291
+ parallel = abs(rel_h - rel_l) <= FLAG_PARALLEL_TOL
292
+ if bullish and rel_h <= 0 and rel_l <= 0 and parallel:
293
+ name = "bull_flag"
294
+ elif not bullish and rel_h >= 0 and rel_l >= 0 and parallel:
295
+ name = "bear_flag"
296
+ elif rel_h < -FLAT_SLOPE and rel_l > FLAT_SLOPE:
297
+ name = "bull_pennant" if bullish else "bear_pennant"
298
+ if name is None:
299
+ continue
300
+ formed_at = max(a.confirmed_at, b.confirmed_at,
301
+ *[p.confirmed_at for p in cons])
302
+ if formed_at >= n:
303
+ continue
304
+ def upper(i: int, s=h_slope, c=h_int) -> float:
305
+ return c + s * i
306
+ def lower(i: int, s=l_slope, c=l_int) -> float:
307
+ return c + s * i
308
+ pennant = name.endswith("pennant")
309
+ status, conf, inv = _resolve(
310
+ data, formed_at, 0.0, 0.0, bullish,
311
+ trigger_line=upper if bullish else lower,
312
+ invalid_line=lower if bullish else upper,
313
+ max_wait=FLAG_MAX_WAIT, cross_kills=pennant,
314
+ )
315
+ height = abs(b.price - a.price) # measured move: the pole's height
316
+ brk = upper(formed_at) if bullish else lower(formed_at)
317
+ target = brk + height if bullish else brk - height
318
+ pts = sorted([a, b] + cons, key=lambda p: p.index)
319
+ out.append(Detection(
320
+ pattern=name,
321
+ direction=Direction.BULLISH if bullish else Direction.BEARISH,
322
+ status=status, formed_at=formed_at,
323
+ confirmed_at=conf, invalidated_at=inv,
324
+ pivots=[(p.index, p.price) for p in pts],
325
+ levels={"pole_start": a.price, "pole_end": b.price,
326
+ "upper_slope": h_slope, "upper_intercept": h_int,
327
+ "lower_slope": l_slope, "lower_intercept": l_int,
328
+ "target": target},
329
+ ))
330
+ return out
331
+
332
+
333
+ def _wedges(data: OHLCV, pivots: list[Pivot]) -> list[Detection]:
334
+ """rising_wedge (both lines rising, bearish) / falling_wedge (both
335
+ falling, bullish).
336
+
337
+ As with triangles, lines are fitted through the last ``WEDGE_MIN_PIVOTS``
338
+ pivot highs and lows. Both relative slopes must exceed ``FLAT_SLOPE`` in
339
+ the same direction, and the lower line's slope must exceed the upper
340
+ line's by ``WEDGE_MIN_CONVERGENCE`` (relative) so the lines converge.
341
+ A rising wedge confirms on a close below the lower line; a falling wedge
342
+ on a close above the upper line. A close through the opposite line, the
343
+ apex passing, or ``MAX_WAIT`` bars elapsing invalidates.
344
+ """
345
+ out: list[Detection] = []
346
+ highs = [p for p in pivots if p.kind == "high"]
347
+ lows = [p for p in pivots if p.kind == "low"]
348
+ if len(highs) < WEDGE_MIN_PIVOTS or len(lows) < WEDGE_MIN_PIVOTS:
349
+ return out
350
+ hs = highs[-WEDGE_MIN_PIVOTS:]
351
+ ls = lows[-WEDGE_MIN_PIVOTS:]
352
+ mean_px = float(np.mean(data.close))
353
+ h_slope, h_int = _fit(hs)
354
+ l_slope, l_int = _fit(ls)
355
+ rel_h, rel_l = h_slope / mean_px, l_slope / mean_px
356
+ if rel_l - rel_h < WEDGE_MIN_CONVERGENCE:
357
+ return out
358
+ if rel_h > FLAT_SLOPE and rel_l > FLAT_SLOPE:
359
+ name, bullish = "rising_wedge", False
360
+ elif rel_h < -FLAT_SLOPE and rel_l < -FLAT_SLOPE:
361
+ name, bullish = "falling_wedge", True
362
+ else:
363
+ return out
364
+ formed_at = max(hs[-1].confirmed_at, ls[-1].confirmed_at)
365
+ if formed_at >= len(data):
366
+ return out
367
+ def upper(i: int) -> float:
368
+ return h_int + h_slope * i
369
+ def lower(i: int) -> float:
370
+ return l_int + l_slope * i
371
+ status, conf, inv = _resolve(
372
+ data, formed_at, 0.0, 0.0, bullish,
373
+ trigger_line=upper if bullish else lower,
374
+ invalid_line=lower if bullish else upper,
375
+ cross_kills=True,
376
+ )
377
+ out.append(Detection(
378
+ pattern=name,
379
+ direction=Direction.BULLISH if bullish else Direction.BEARISH,
380
+ status=status, formed_at=formed_at,
381
+ confirmed_at=conf, invalidated_at=inv,
382
+ pivots=[(p.index, p.price) for p in sorted(hs + ls, key=lambda p: p.index)],
383
+ levels={"upper_slope": h_slope, "upper_intercept": h_int,
384
+ "lower_slope": l_slope, "lower_intercept": l_int},
385
+ ))
386
+ return out
387
+
388
+
389
+ def detect_chart_patterns(
390
+ data: OHLCV,
391
+ patterns: Iterable[str] | None = None,
392
+ order: int = 5,
393
+ pivots: list[Pivot] | None = None,
394
+ ) -> list[Detection]:
395
+ names = set(patterns) if patterns is not None else set(CHART_PATTERNS)
396
+ unknown = names - set(CHART_PATTERNS)
397
+ if unknown:
398
+ raise KeyError(f"unknown chart patterns: {sorted(unknown)}")
399
+ pv = pivots if pivots is not None else rolling_pivots(data, order=order)
400
+ out: list[Detection] = []
401
+ if {"double_top"} & names:
402
+ out += [d for d in _double(data, pv, "high")]
403
+ if {"double_bottom"} & names:
404
+ out += [d for d in _double(data, pv, "low")]
405
+ if "head_and_shoulders" in names:
406
+ out += _hns(data, pv, inverse=False)
407
+ if "inverse_head_and_shoulders" in names:
408
+ out += _hns(data, pv, inverse=True)
409
+ if names & {"ascending_triangle", "descending_triangle", "symmetrical_triangle"}:
410
+ out += [d for d in _triangles(data, pv) if d.pattern in names]
411
+ if names & {"bull_flag", "bear_flag", "bull_pennant", "bear_pennant"}:
412
+ out += [d for d in _flags_pennants(data, pv) if d.pattern in names]
413
+ if names & {"rising_wedge", "falling_wedge"}:
414
+ out += [d for d in _wedges(data, pv) if d.pattern in names]
415
+ out.sort(key=lambda d: d.formed_at)
416
+ return out
openpatterns/core.py ADDED
@@ -0,0 +1,144 @@
1
+ """Core types: OHLCV container and the Detection lifecycle.
2
+
3
+ The central contract of this library is repaint-safety. Every detection
4
+ carries explicit lifecycle indices:
5
+
6
+ - ``formed_at``: the bar index at which the pattern's geometry was complete
7
+ (last defining bar or pivot in place). At this bar the pattern may still
8
+ repaint: a pivot is not knowable until later bars rule out a higher high /
9
+ lower low.
10
+ - ``confirmed_at``: the first bar index at which the detection was fully
11
+ locked using **no future data** — all defining pivots confirmed and, for
12
+ breakout patterns, the trigger level crossed. Alerts and backtests must key
13
+ off this index.
14
+ - ``invalidated_at``: the bar at which a forming pattern stopped being valid.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass, field
20
+ from enum import Enum
21
+ from typing import Any, Sequence
22
+
23
+ import numpy as np
24
+
25
+ __all__ = ["Status", "Direction", "Detection", "OHLCV"]
26
+
27
+
28
+ class Status(str, Enum):
29
+ FORMING = "forming"
30
+ CONFIRMED = "confirmed"
31
+ INVALIDATED = "invalidated"
32
+
33
+
34
+ class Direction(int, Enum):
35
+ BULLISH = 1
36
+ BEARISH = -1
37
+ NEUTRAL = 0
38
+
39
+
40
+ @dataclass
41
+ class Detection:
42
+ """One pattern instance found on a series."""
43
+
44
+ pattern: str
45
+ direction: Direction
46
+ status: Status
47
+ formed_at: int
48
+ confirmed_at: int | None = None
49
+ invalidated_at: int | None = None
50
+ # (bar_index, price) of each defining pivot, oldest first
51
+ pivots: list[tuple[int, float]] = field(default_factory=list)
52
+ # named price levels: e.g. "neckline", "breakout", "target"
53
+ levels: dict[str, float] = field(default_factory=dict)
54
+ meta: dict[str, Any] = field(default_factory=dict)
55
+
56
+ def to_dict(self) -> dict[str, Any]:
57
+ return {
58
+ "pattern": self.pattern,
59
+ "direction": int(self.direction),
60
+ "status": self.status.value,
61
+ "formed_at": self.formed_at,
62
+ "confirmed_at": self.confirmed_at,
63
+ "invalidated_at": self.invalidated_at,
64
+ "pivots": [[int(i), float(p)] for i, p in self.pivots],
65
+ "levels": {k: float(v) for k, v in self.levels.items()},
66
+ "meta": self.meta,
67
+ }
68
+
69
+
70
+ class OHLCV:
71
+ """Column-oriented OHLCV container over numpy arrays.
72
+
73
+ Accepts any sequences; validates lengths and OHLC sanity. ``volume``
74
+ and ``timestamp`` are optional.
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ open: Sequence[float],
80
+ high: Sequence[float],
81
+ low: Sequence[float],
82
+ close: Sequence[float],
83
+ volume: Sequence[float] | None = None,
84
+ timestamp: Sequence[Any] | None = None,
85
+ ) -> None:
86
+ self.open = np.asarray(open, dtype=np.float64)
87
+ self.high = np.asarray(high, dtype=np.float64)
88
+ self.low = np.asarray(low, dtype=np.float64)
89
+ self.close = np.asarray(close, dtype=np.float64)
90
+ n = len(self.open)
91
+ if not (len(self.high) == len(self.low) == len(self.close) == n):
92
+ raise ValueError("open/high/low/close must have equal length")
93
+ if n == 0:
94
+ raise ValueError("empty series")
95
+ if volume is not None:
96
+ self.volume = np.asarray(volume, dtype=np.float64)
97
+ if len(self.volume) != n:
98
+ raise ValueError("volume length mismatch")
99
+ else:
100
+ self.volume = None
101
+ self.timestamp = list(timestamp) if timestamp is not None else None
102
+ if self.timestamp is not None and len(self.timestamp) != n:
103
+ raise ValueError("timestamp length mismatch")
104
+ bad = (self.high < self.low) | (self.high < np.maximum(self.open, self.close)) | (
105
+ self.low > np.minimum(self.open, self.close)
106
+ )
107
+ if bool(bad.any()):
108
+ raise ValueError(f"invalid OHLC rows at indices {np.flatnonzero(bad)[:10].tolist()}")
109
+
110
+ def __len__(self) -> int:
111
+ return len(self.open)
112
+
113
+ @classmethod
114
+ def from_dataframe(cls, df: Any) -> "OHLCV":
115
+ cols = {c.lower(): c for c in df.columns}
116
+ def col(name: str):
117
+ return df[cols[name]].to_numpy() if name in cols else None
118
+ ts = None
119
+ if "timestamp" in cols:
120
+ ts = list(df[cols["timestamp"]])
121
+ elif df.index is not None:
122
+ ts = list(df.index)
123
+ return cls(
124
+ open=col("open"), high=col("high"), low=col("low"), close=col("close"),
125
+ volume=col("volume"), timestamp=ts,
126
+ )
127
+
128
+ @classmethod
129
+ def from_records(cls, records: Sequence[dict[str, Any]]) -> "OHLCV":
130
+ def pick(r: dict[str, Any], *names: str):
131
+ for n in names:
132
+ if n in r:
133
+ return r[n]
134
+ raise KeyError(names[0])
135
+ return cls(
136
+ open=[pick(r, "open", "o") for r in records],
137
+ high=[pick(r, "high", "h") for r in records],
138
+ low=[pick(r, "low", "l") for r in records],
139
+ close=[pick(r, "close", "c") for r in records],
140
+ volume=[r.get("volume", r.get("v")) for r in records]
141
+ if all(("volume" in r or "v" in r) for r in records) else None,
142
+ timestamp=[r.get("timestamp", r.get("t")) for r in records]
143
+ if all(("timestamp" in r or "t" in r) for r in records) else None,
144
+ )
openpatterns/eval.py ADDED
@@ -0,0 +1,84 @@
1
+ """Historical hit-rate evaluation for confirmed detections.
2
+
3
+ Methodology (fixed, so published numbers are reproducible):
4
+
5
+ - Only detections with ``status == CONFIRMED`` and a directional bias are
6
+ evaluated; entry is the close of the confirmation bar (``confirmed_at``),
7
+ i.e. the first bar the signal was actually knowable — no lookahead.
8
+ - For each horizon ``H``, the signed forward return is
9
+ ``(close[confirmed_at + H] / entry - 1) * direction``.
10
+ - ``hit_rate`` is the fraction of signed returns > 0.
11
+
12
+ These are descriptive statistics on raw closes: no costs, no slippage, no
13
+ position sizing, overlapping signals are all counted. They quantify the
14
+ detector, not a trading strategy.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import numpy as np
20
+
21
+ from .core import OHLCV, Detection, Status
22
+ from .scan import scan
23
+
24
+ __all__ = ["collect_returns", "merge_returns", "summarize"]
25
+
26
+ Returns = dict[str, dict[int, list[float]]]
27
+
28
+
29
+ def collect_returns(
30
+ data: OHLCV,
31
+ detections: list[Detection] | None = None,
32
+ horizons: tuple[int, ...] = (5, 10, 20),
33
+ order: int = 5,
34
+ ) -> Returns:
35
+ """Signed forward returns per pattern per horizon for one series."""
36
+ dets = detections if detections is not None else scan(data, order=order)
37
+ out: Returns = {}
38
+ n = len(data)
39
+ for d in dets:
40
+ if d.status is not Status.CONFIRMED or d.confirmed_at is None:
41
+ continue
42
+ direction = int(d.direction)
43
+ if direction == 0:
44
+ continue
45
+ i = d.confirmed_at
46
+ entry = float(data.close[i])
47
+ if entry <= 0:
48
+ continue
49
+ for h in horizons:
50
+ j = i + h
51
+ if j >= n:
52
+ continue
53
+ ret = (float(data.close[j]) / entry - 1.0) * direction
54
+ out.setdefault(d.pattern, {}).setdefault(h, []).append(ret)
55
+ return out
56
+
57
+
58
+ def merge_returns(*parts: Returns) -> Returns:
59
+ """Pool returns from several series (e.g. symbols) into one table."""
60
+ out: Returns = {}
61
+ for part in parts:
62
+ for pat, hs in part.items():
63
+ for h, vals in hs.items():
64
+ out.setdefault(pat, {}).setdefault(h, []).extend(vals)
65
+ return out
66
+
67
+
68
+ def summarize(returns: Returns) -> list[dict]:
69
+ """Flatten pooled returns into rows: pattern, horizon, n, hit_rate, mean, median."""
70
+ rows: list[dict] = []
71
+ for pat in sorted(returns):
72
+ for h in sorted(returns[pat]):
73
+ vals = np.asarray(returns[pat][h], dtype=float)
74
+ if len(vals) == 0:
75
+ continue
76
+ rows.append({
77
+ "pattern": pat,
78
+ "horizon": h,
79
+ "n": int(len(vals)),
80
+ "hit_rate": float(np.mean(vals > 0)),
81
+ "mean_return": float(vals.mean()),
82
+ "median_return": float(np.median(vals)),
83
+ })
84
+ return rows