How to implement RSI Divergence in Python
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
RSI divergence is a pattern where price and momentum stop agreeing. A bullish setup appears when price makes a lower low while RSI makes a higher low, and a bearish setup appears when price makes a higher high while RSI makes a lower high.
Compute RSI first
Before you can detect divergence, you need a reliable RSI series. The example below uses pandas and Wilder-style smoothing with ewm, which is a practical approach for backtesting and chart analysis.
This function expects a Series of closing prices. The first period rows will be NaN, which is normal because RSI needs historical data before it can produce a stable value.
Find swing highs and swing lows
Divergence is based on pivots, not on every single candle. A simple way to detect pivots is to compare each value with a small window around it.
This method is intentionally simple. It works well for illustrating the idea, and it is good enough for many research scripts. In production trading systems, you may want stricter pivot rules or a confirmation delay so the signal does not repaint as the most recent candles move.
Detect bullish and bearish divergence
Now compare the last two relevant pivots in price with the RSI values at those same pivot indexes.
Here is a full runnable example with sample data:
The output is a list of index pairs. Each pair marks the first and second pivot that formed the divergence. In a charting application, you would use those indexes to draw lines between price pivots and RSI pivots.
Make the signal usable
A divergence signal by itself is usually not enough for a trade. Most traders add one more filter, such as trend direction, volume confirmation, or a support and resistance check. Even a simple rule like "only take bullish divergence above a long-term moving average" can eliminate many weak setups.
If you want to backtest this properly, store signals in a DataFrame with timestamps, entry rules, exit rules, and stop placement. That makes the script measurable instead of just visually interesting.
Common Pitfalls
The most common error is comparing arbitrary local points instead of confirmed pivots. That creates many false positives because every small wiggle starts to look like divergence.
Another mistake is using RSI values before the indicator is warmed up. Early NaN rows or unstable initial values can distort the first few comparisons.
Window size matters too. A very small window finds too many pivots, while a very large window misses useful signals. Test a few values against the timeframe you trade instead of assuming one setting fits every market.
Finally, do not treat divergence as a guaranteed reversal. Strong trends can keep moving against a divergence for a long time, so risk management still matters.
Summary
- Compute RSI on a clean closing-price series before looking for patterns.
- Detect divergence from pivot highs and pivot lows, not from every bar.
- Bullish divergence means lower price lows with higher RSI lows.
- Bearish divergence means higher price highs with lower RSI highs.
- Add confirmation and backtesting before using divergence in a live strategy.
Related reading
- How to implement segment trees with lazy propagation?
- How to implement strlen as fast as possible
- How to implement the Bayesian average algorithm for a binary rating system
- How to improve the performance of Leetcode 4sum-ii challenge
- How to implement the ReLU function in Numpy
- How to implement the Softmax function in Python?
- How to increment all values in an array interval by a given amount
- How to intersect two sorted integer arrays without duplicates?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.