Detect Candlestick Patterns in Python Without TA-Lib
Candlestick patterns are inequalities over four numbers per row, so pandas and NumPy can detect them. Here is how to define them yourself and where that falls short.

TA-Lib is the usual answer to candlestick pattern detection in Python, and it is also the usual source of the install problem. The Python wrapper sits on top of a C library, so on a machine without a matching build toolchain or prebuilt wheel, pip install fails during compilation. In a locked-down CI image or a slim container, that failure arrives before you have written any trading logic.
The patterns themselves do not need a C library. A candle is four numbers: open, high, low, close. Every classic pattern is a set of inequalities over those numbers and, for multi-candle patterns, over the previous row. With pandas and NumPy you can express them as vectorised boolean columns over an OHLC DataFrame, such as one downloaded with yfinance.
The trade-off is that you now own the definitions. TA-Lib encodes particular threshold choices. When you write your own, you must decide what 'small body' means, and you should write that down rather than hide it in a magic number.
Reduce each candle to a few measurements
Start by computing the geometry once, then build every pattern from those columns. yfinance returns a DataFrame with Open, High, Low and Close columns. Depending on how you call it, the columns may come back as a MultiIndex, so flatten them to plain names first.
import numpy as np
import pandas as pd
def add_features(df):
o, h, l, c = df['Open'], df['High'], df['Low'], df['Close']
out = df.copy()
out['body'] = (c - o).abs()
out['range'] = h - l
out['upper'] = h - np.maximum(o, c)
out['lower'] = np.minimum(o, c) - l
return outExpressing everything relative to the candle's range, rather than in absolute price, lets one threshold work across instruments with very different price levels. It also keeps the logic readable: the upper shadow is the high minus the top of the body, and the lower shadow is the bottom of the body minus the low.
Single-candle patterns as boolean columns
A doji is a candle whose body is tiny relative to its range. A hammer has a long lower shadow, a short upper shadow and a small body. Each becomes one line of vectorised comparison, with no loop over rows.
def single_candle(df, doji_frac=0.1, shadow_mult=2.0):
d = add_features(df)
valid = d['range'] > 0
d['doji'] = valid & (d['body'] <= doji_frac * d['range'])
d['hammer_shape'] = (
valid
& (d['lower'] >= shadow_mult * d['body'])
& (d['upper'] <= d['body'])
)
return dThe valid mask matters. Illiquid or halted sessions can produce rows where high equals low, and dividing by or comparing against a zero range gives misleading matches. Note that hammer_shape is only the shape. Whether it counts as a hammer depends on the preceding trend, which the next section adds.
Multi-candle patterns with shift
Two-candle patterns compare each row to the one before it using shift(1). A bullish engulfing pattern is a down candle followed by an up candle whose body covers the previous body.
def bullish_engulfing(df):
o, c = df['Open'], df['Close']
po, pc = o.shift(1), c.shift(1)
return (pc < po) & (c > o) & (o <= pc) & (c >= po)The first row has no predecessor, so the comparison evaluates to False there, which is the behaviour you want. For context, such as requiring a prior decline, compare the close to a rolling mean or to the close several rows back, and combine that with the shape condition using &. Three-candle patterns such as morning star extend the same idea with shift(2).
Where this approach does not fit
Hand-rolled detection gives you transparency, not authority. Your doji threshold will not match anyone else's, so results will differ from TA-Lib or other libraries, and you cannot compare them without aligning definitions first. If you need output identical to an existing system, installing the C library, or using a prebuilt distribution of it, is the more honest route.
Candlestick patterns are also weak signals on their own. Detecting a pattern is not the same as showing it predicts anything, so test each one on out-of-sample data and include transaction costs before it drives a strategy. Watch for lookahead bias too: a pattern is only known once the final candle closes, so act on the next bar, not the same one.
Finally, data quality changes results. Adjusted versus unadjusted prices, gaps and bad ticks all shift the geometry that the patterns depend on. Check your inputs before you trust a signal.
- #Algorithmic Trading
- #Python
- #candlestick-chart
- #pandas
- #tooling-recommendation
- #yfinance



Comments