0% found this document useful (0 votes)
15 views11 pages

3 Algorithms To Automate Chart Patterns in Trading

The document discusses three algorithms for automating chart pattern detection in trading: the Rolling Window Algorithm, the Directional Change (ZigZag) Algorithm, and the Smoothing Method. Each algorithm offers unique benefits, such as reducing human error and filtering out noise, to help traders identify significant market patterns more effectively. However, caution is advised as trading involves risks, and the algorithms are intended for informational purposes only.

Uploaded by

As Win
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views11 pages

3 Algorithms To Automate Chart Patterns in Trading

The document discusses three algorithms for automating chart pattern detection in trading: the Rolling Window Algorithm, the Directional Change (ZigZag) Algorithm, and the Smoothing Method. Each algorithm offers unique benefits, such as reducing human error and filtering out noise, to help traders identify significant market patterns more effectively. However, caution is advised as trading involves risks, and the algorithms are intended for informational purposes only.

Uploaded by

As Win
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

3 Algorithms to Automate

Chart Patterns in Trading

It’s 3 a.m., and while you’re fast asleep, a perfect head-


and-shoulders pattern forms on the EUR/USD chart.
By the time you wake up, the opportunity is gone, and
you’re left kicking yourself for missing it.
If only there were a way to keep an eye on the markets
24/7 without sacrificing sleep, sanity, or your social life.
Well, there is — algorithms. These tireless digital sentinels
can spot chart patterns faster than a hawk spotting a field
mouse, and they don’t even need coffee breaks.
In this article, I will explain you through three powerful
algorithms that can automate chart pattern detection in
trading:
the Rolling Window Algorithm
the Directional Change (ZigZag) Algorithm
the Smoothing Method.
Risk Disclaimer: Trading involves significant risk
of loss and is not suitable for everyone. The
algorithms and strategies discussed in this article
are for informational purposes only and do not
guarantee profits. Past performance is not
indicative of future results. Always conduct your
own research and consult a qualified financial
advisor before making trading decisions.

Why Automate Chart Patterns in the First Place?


Before we get into the nitty-gritty, let’s talk about why
automation is worth your time. Chart patterns are like the
footprints of market psychology — visual clues left behind
by buyers and sellers duking it out. Spotting a head and
shoulders or a triangle can signal a big move, but there’s a
catch: you’ve got to be watching the charts to catch them.
And unless you’ve got a time machine or a clone, that’s
impossible. Here’s why doing it manually is a losing battle:
Time Sucks: Markets don’t sleep, but you do. Missing a
pattern because you were at your kid’s soccer game stinks.
Human Error: One trader might see a double top, while
another calls it noise. Subjective calls lead to inconsistent
results.
Backtesting Blues: Want to test a pattern strategy on
five years of data? Good luck doing that by hand without
losing your mind.
Automation solves all of this. Algorithms don’t get tired,
don’t argue over what’s a pattern, and can crunch years of
data faster than you can say “Fibonacci retracement.”
Now, let’s meet the three algorithms that’ll do the heavy
lifting for you.

1. Rolling Window Algorithm: The No-Nonsense


Workhorse
If chart pattern detection were a construction site, the
Rolling Window Algorithm would be the trusty hammer —
simple, reliable, and gets the job done. This algorithm is all
about finding local highs and lows, the building blocks of
patterns like head and shoulders or double bottoms. I
remember the first time I coded this one up; it felt like I’d
unlocked a cheat code for trading.

How It Works
Imagine you’re looking at a price chart, and you want to
know if a particular candle is a peak (higher than its
neighbors) or a trough (lower than its neighbors). The
Rolling Window Algorithm does this by checking a
“window” of candles — say, two candles before and two
after the one you’re interested in. If your candle’s price is
the highest in that window, it’s a peak. If it’s the lowest,
it’s a trough. The only thing you need to decide is how big
that window should be.

Let’s Code It
Here’s a Python snippet to bring this to life. I’ve kept it
simple so you can tweak it to your heart’s content:

def find_peaks_troughs(prices, window_size):


"""
Find peaks and troughs in a price series using a sliding window.

Args:
prices (list): List of price values
window_size (int): Number of candles to look before/after each
point

Returns:
tuple: (peaks, troughs) where each is a list of (index, price)
tuples
"""
# Input validation
if not prices or window_size < 0 or window_size >= len(prices):
return [], []

peaks = []
troughs = []

for i in range(window_size, len(prices) - window_size):


window = prices[i - window_size:i + window_size + 1]
current_candle = prices[i]

if current_candle == max(window):
peaks.append((i, current_candle))
elif current_candle == min(window):
troughs.append((i, current_candle))

return peaks, troughs

# Test it out
price_data = [100, 102, 101, 105, 103, 107, 106, 104, 108, 107,
109]
window = 2
peaks, troughs = find_peaks_troughs(price_data,
window)print("Peaks (index, price):", peaks) # Expected: [(3,
105), (6, 107), (8, 108), (10, 109)]
print("Troughs (index, price):", troughs) # Expected: [(2,
101), (4, 103), (7, 104)]

What’s Happening Here?

 The Setup: price_data is your list of closing prices, and


window is how many candles you want to check on
either side.
 The Logic: For each candle, we grab a window of
prices and see if the current candle is the highest or
lowest in that group.

 The Payoff: You get a list of peaks and troughs, ready


to be used for pattern detection.

Where It Shines (And Where It Stumbles)


This algorithm is fantastic for spotting the bones of
patterns — those highs and lows that define a head and
shoulders or a cup and handle. But here’s the rub: it’s
sensitive to noise. A tiny wiggle in the price can trick it
into flagging a false peak. That’s where our next algorithm
comes in, like a bouncer at a noisy club, keeping the
riffraff out.

2. Directional Change (ZigZag) Algorithm: The Noise


Filter
The Directional Change Algorithm, often called the ZigZag,
is like the cool older sibling of the Rolling Window. Instead
of obsessing over every little price wiggle, it focuses on the
big moves — the ones that matter. I’ve lost count of how
many times this algorithm has saved me from chasing false
signals in choppy markets.

How It Works
Here’s the gist: the ZigZag tracks price movements and
only flags a peak or trough when the price reverses by a
certain percentage — say, 5%. Think of it like climbing a
mountain. You keep going up, noting the highest point
you’ve reached. If you slip back down by 5% of that height,
boom, you’ve confirmed a peak. Then you start looking for
the lowest point on the way down, waiting for a 5% bounce
to confirm a trough. The only knob you need to twist is that
retracement percentage.

Let’s Code It
Here’s a Python version of the ZigZag, stripped down to
the essentials:

def zigzag_pattern(prices, retrace_percent):


"""
Identify peaks and troughs in a price series using a zigzag pattern.

Args:
prices (list): List of price values.
retrace_percent (float): Minimum percentage change to identify a
peak/trough.

Returns:
tuple: (peaks, troughs), where each is a list of (index, price)
tuples.
"""
if len(prices) < 2:
return [], [] # Not enough data for a pattern

peaks = []
troughs = []
last_point = prices[0]
climbing = True

for i in range(1, len(prices)):


current_price = prices[i]

if climbing:
if current_price > last_point:
last_point = current_price
elif current_price < last_point * (1 - retrace_percent / 100):
peaks.append((i - 1, last_point))
last_point = current_price
climbing = False
else:
if current_price < last_point:
last_point = current_price
elif current_price > last_point * (1 + retrace_percent / 100):
troughs.append((i - 1, last_point))
last_point = current_price
climbing = True

# Handle the final point


if climbing and last_point > prices[-2] * (1 + retrace_percent / 100):
peaks.append((len(prices) - 1, last_point))
elif not climbing and last_point < prices[-2] * (1 - retrace_percent /
100):
troughs.append((len(prices) - 1, last_point))

return peaks, troughs

# Test
price_data = [100, 102, 101, 105, 103, 107, 106, 104, 108, 107,
109]
retrace = 2
peaks, troughs = zigzag_pattern(price_data,
retrace)print("ZigZag Peaks:", peaks)
print("ZigZag Troughs:", troughs)

Output:

ZigZag Peaks: [(3, 105), (8, 108), (10, 109)]


ZigZag Troughs: [(7, 104)]

What’s Going On?

 The Setup: We start with price_data and retrace, the


percentage drop or rise needed to confirm a turn.

 The Logic: If we’re climbing, we track the highest


price. If prices drop by retrace percent, we log a peak
and switch to looking for a trough. Same deal in
reverse.

 The Payoff: You get a cleaner set of peaks and troughs,


free of pesky noise.

Where It Shines (And Where It Stumbles)


The ZigZag is a lifesaver in choppy markets, filtering out
the small stuff so you can focus on big trends and
reversals. It’s perfect for patterns like triangles or
channels. But if you set the retracement percentage too
high, you might miss smaller patterns. It’s all about finding
the Goldilocks zone — not too hot, not too cold.

3. Smoothing Method: The Noise Assassin


Now, let’s talk about the Smoothing Method, the algorithm
that’s like a pair of noise-canceling headphones for your
price data. This one uses a fancy trick called kernel
regression to smooth out the wiggles, making it easier to
spot the real peaks and troughs. I’ll admit, the first time I
tried this, I was skeptical — smoothing sounded like it
might blur the good stuff. But boy, was I wrong.

How It Works
Here’s the deal: before you even think about finding peaks
and troughs, you run your price data through a smoothing
filter (think of it like ironing out the wrinkles in a shirt).
Then, you apply something like the Rolling Window
Algorithm to the smoothed data. By getting rid of the noise
upfront, you cut down on false signals, especially in wild
markets.

Let’s Code It
Here’s a Python snippet using a Gaussian kernel for
smoothing, paired with our old friend, the Rolling Window:

import numpy as np
from scipy.ndimage import gaussian_filter1d

def find_peaks_troughs(data, window_size):


peaks = []
troughs = []
data = np.array(data)

for i in range(window_size, len(data) - window_size):


if (data[i] > max(data[i-window_size:i]) and
data[i] > max(data[i+1:i+window_size+1])):
peaks.append(i)
if (data[i] < min(data[i-window_size:i]) and
data[i] < min(data[i+1:i+window_size+1])):
troughs.append(i)

return peaks, troughsdef smooth_and_find(prices,


smooth_factor, window_size):
if not prices or len(prices) < window_size * 2 + 1:
raise ValueError("Price data too short for given window
size")
if smooth_factor <= 0:
raise ValueError("Smooth factor must be positive")
if window_size < 1:
raise ValueError("Window size must be at least 1")

prices = np.array(prices)
smoothed_data = gaussian_filter1d(prices,
sigma=smooth_factor)
peaks, troughs = find_peaks_troughs(smoothed_data,
window_size)

return smoothed_data, peaks, troughs# Test drive


try:
price_data = [100, 102, 101, 105, 103, 107, 106, 104, 108,
107, 109]
smooth_factor = 1.0
window = 2

smoothed, peaks, troughs = smooth_and_find(price_data,


smooth_factor, window)

print("Original Data:", price_data)


print("Smoothed Data:", smoothed)
print("Smoothed Peaks (indices):", peaks)
print("Smoothed Troughs (indices):", troughs)

except ValueError as e:
print(f"Error: {e}")

Output:

Original Data: [100, 102, 101, 105, 103, 107, 106, 104, 108, 107, 109]
Smoothed Data: [100.60930803 101.49570657 101.68458311 103.85876028
104.13331893
105.68262424 106.08722095 105.68262424 106.68458311 107.13331893
108.13331893]
Smoothed Peaks (indices): [5]
Smoothed Troughs (indices): [2, 7]

What’s Happening Here?

 The Setup: price_data is your raw prices,


smooth_factor controls how much smoothing happens,
and window is for the peak/trough detection.

 The Smoothing: We use gaussian_filter1d to iron out


the wrinkles in the price data.

 The Detection: We reuse our Rolling Window function


on the smoothed data to find peaks and troughs.
 The Payoff: You get a cleaner set of peaks and troughs,
with fewer false alarms.

Where It Shines (And Where It Stumbles)


This method is a dream for spotting big, meaty patterns
like head and shoulders or cup and handle, especially in
noisy markets. But if you smooth too much, you might blur
out smaller patterns. It’s like trying to read fine print
through foggy glasses — balance is key.

You might also like