Introduction
The RSI indicator is a momentum oscillator that measures the speed and change of price movements. It’s particularly useful for identifying potential overbought and oversold conditions in the market. With the right know-how, you can use it to develop a robust RSI trading strategy, identify buy and sell signals, and even screen stocks using an RSI indicator screener.
In this guide we’ll explore RSI’s origins, its mathematical construction, and how to use it while trading. We’ll also provide a step-by-step guide on how to implement the RSI in Python, allowing you to integrate it into your own trading algorithms. By the end of this guide, you’ll have a solid understanding of RSI strategy and how to use it to finesse your trading decisions. So, let’s get started!
Origins of the RSI Indicator
The Relative Strength Index, or RSI, was developed by J. Welles Wilder Jr., a mechanical engineer who turned his analytical mind towards the world of finance. Wilder introduced the RSI in his 1978 book, “New Concepts in Technical Trading Systems”, which also introduced several other ground-breaking technical indicators.
Wilder designed the RSI to measure the speed and change of price movements in an attempt to overcome the inherent challenges of timing trade entry and exit points. The RSI is a momentum oscillator, meaning it measures the speed (velocity) and magnitude (distance) of directional price movements. It oscillates between zero and 100, providing insights into potential overbought and oversold conditions in the market.
The RSI quickly gained popularity and has since become a staple in the toolkit of many traders. Its versatility and simplicity have made it a favorite among both novice and experienced traders, and it’s widely used in various markets, including stocks, forex, commodities, and bonds.
Mathematical Construction
Calculating RSI is achieved using a relatively simple formula:
RSI = 100 – [100 / (1 + RS)]
Where RS (Relative Strength) is the average gain of up periods during the specified time frame divided by the absolute value of the average loss of down periods:
RS = Average Gain / Average Loss
The standard time frame used by Wilder was 14 periods, which could be anything from 14 minutes to 14 hours, days, weeks, or months, depending on the trader’s preference.
Let’s break down the formula:
- Average Gain and Average Loss: For the first calculation, the average gain and average loss are calculated over the specified number of periods (14 in Wilder’s case). For subsequent calculations, the average gain and average loss are calculated as the previous average gain or loss multiplied by the number of periods minus one, plus the current gain or loss.
- Relative Strength (RS): This is the ratio of the average gain to the average loss. It reflects the magnitude of recent gains to recent losses in an attempt to determine whether an asset is being ‘overbought’ or ‘oversold’.
- Relative Strength Index (RSI): The RSI is then derived by applying the first part of the formula, which normalizes the RS ratio into an oscillator that moves between 0 and 100.
Despite its name, the RSI does not compare the strength of two securities. Instead, it measures the strength of a single security’s price history. It’s important to note that the RSI is a bounded oscillator, meaning it fluctuates within a fixed range of 0 to 100, unlike the Rate of Change (ROC) indicator, which is unbounded.
The RSI is a smoothing oscillator, meaning it incorporates a smoothing process to reduce volatility and noise in the data. This smoothing process, which involves averaging the gains and losses over the specified period, makes the RSI more responsive to changes in price momentum.
In the strictest definition, RSI uses a Wilder’s moving average, which is slightly different from a simple moving average. A Wilder’s moving average applies more weight to recent data, which can make a difference in certain markets. We look at this difference in the Python section later on in more detail.
The RSI provides a way to quantify the changes in price momentum, which can be a powerful tool when developing an RSI trading strategy.
Understanding the RSI Indicator
The RSI oscillates between 0 and 100, with certain levels typically interpreted as indicating overbought or oversold conditions. However, these levels are not set in stone and can vary depending on the asset and market conditions. For example CQG, one of the most respected software groups sets their overbought level at 75 by default.
When the RSI rises above a certain level (often 70), the asset is considered overbought. This suggests that the asset may be trading at a price above its intrinsic value, and a price correction or downturn may be imminent. Conversely, when the RSI falls below a certain level (often 30), the asset is considered oversold. This suggests that the asset may be trading at a price below its intrinsic value, and a price increase or uptrend may be on the horizon.
The RSI is most effective when used in conjunction with other technical analysis tools and indicators. For instance, traders often use the RSI in combination with candlestick pattern analysis, moving averages, and other momentum indicators to confirm signals and avoid false positives. We already addressed pairing it with Williams %R in post about that indicator.
Buy and Sell Signals
The RSI can provide valuable insights into the momentum of an asset. But how can we translate these insights into actionable buy and sell signals?
Identifying Overbought and Oversold Conditions
An asset is potentially overbought when RSI exceeds 70 and oversold when it falls below 30. However, these thresholds can vary with market conditions and are not absolute. An asset can remain in overbought or oversold territory for extended periods, especially during strong trends. Therefore, these signals should be corroborated with other technical analysis tools or indicators before making a trade.
Spotting RSI Divergence
Divergence occurs when the price of an asset and the RSI move in opposite directions. If the price is making higher highs but the RSI is making lower highs, it’s a bearish divergence, suggesting a potential selling opportunity. We point out an example of this further down on the chart we plot with Python. Conversely, if the price is making lower lows but the RSI is making higher lows, it’s a bullish divergence, indicating a possible buying opportunity.
Using the RSI in Trending Markets
The RSI can also be used to generate buy and sell signals in trending markets. In an uptrend, traders might look for opportunities to buy when the RSI falls below and then rises back above an oversold level. In a downtrend, traders might look for opportunities to sell when the RSI rises above and then falls back below an overbought level.
RSI Trading Strategies
Now that we understand how to interpret the RSI and identify potential buy and sell signals, let’s explore how to incorporate these insights into an effective trading strategy.
Basic RSI Strategy
A basic RSI trading strategy involves entering a buy order when the RSI falls below and then rises back above the 30 level, indicating that the asset may be oversold and a price increase could be on the horizon. Conversely, a sell order would be placed when the RSI rises above and then falls back below the 70 level, indicating that the asset may be overbought and a price decrease could be imminent.
While this strategy is relatively straightforward and can be effective under specific market circumstances, it’s essential to remember that even though RSI is considered a leading indicator, it doesn’t guarantee future price movements. Thus, while the RSI can offer valuable market insights, it’s best used in tandem with other technical analysis tools and indicators for more comprehensive analysis.
RSI Divergence Strategy
Another popular RSI trading strategy involves looking for divergences between the price and the RSI. As we discussed in the previous section, a divergence occurs when the price is moving in one direction, but the RSI is moving in the opposite direction. This could indicate that the current price trend is losing momentum and a reversal could be imminent.
For example, if the price is making higher highs but the RSI is making lower highs, this could signal a potential selling opportunity. Conversely, if the price is making lower lows but the RSI is making higher lows, this could signal a potential buying opportunity.
RSI Swing Rejection Strategy
The RSI Swing Rejection Strategy is another advanced trading strategy that involves the RSI. This strategy looks for specific patterns in the RSI in relation to the 50 level to identify potential trading opportunities.
In this strategy, a buy signal is generated when the RSI falls below 50, rises back above 50, falls back below 50, and then rises above 50 again. This pattern is known as a “positive reversal”. Conversely, a sell signal is generated when the RSI rises above 50, falls back below 50, rises back above 50, and then falls below 50 again. This pattern is known as a “negative reversal”.
Pros and Cons of the RSI Indicator
Pros
- Versatility: The RSI is a versatile indicator that can be used in a variety of trading strategies. Whether you’re looking to identify potential overbought or oversold conditions, spot divergences, or generate buy and sell signals in trending markets, the RSI can provide valuable insights. It’s also proved itself as a useful accompaniment when reading about the other indicators we have explored.
- Ease of Interpretation: The RSI is relatively straightforward to interpret, making it accessible to both novice and experienced traders. The RSI oscillates between 0 and 100, with levels above 70 typically considered overbought and levels below 30 considered oversold.
- Applicability Across Markets: The RSI can be used in various markets, including stocks, forex, commodities, and more. This makes it a valuable tool for traders who operate in different markets.
Cons
- False Signals: The RSI can sometimes generate false signals, particularly in volatile markets. For example, the RSI may indicate that an asset is overbought or oversold, but explosive trends can cause issues the price may continue to rise or fall for some time until a full scale blowout occurs marked by the RSI’s violent momentum. Therefore, it’s important to use the RSI in conjunction with other technical analysis tools and indicators and some common sense.
- Requires Confirmation: While RSI is often considered a leading indicator, suggesting potential future price movements, it doesn’t always guarantee accuracy and is based off lagging components. Hence, although it can offer valuable market insights, it’s best to use it in combination with other technical analysis tools and indicators for a more comprehensive view of the market.
- Parameter Selection: The effectiveness of the RSI can depend on the selection of parameters, particularly the time period used for calculation. While a 14-period RSI is commonly used, this may not be optimal for all trading strategies or market conditions.
Coding the RSI Indicator in Python
Step 1: Import Required Libraries
The very first step is to import the necessary Python libraries.
import yfinance as yf
import pandas as pd
import mplfinance as mpf
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
These are:
yfinance
: Used for downloading financial data from Yahoo Finance.pandas
: A library providing high-performance, easy-to-use data structures, and data analysis tools.mplfinance
: A library to create financial plots and charts.matplotlib.pyplot
: This is for creating static, animated, and interactive visualizations in Python.matplotlib.lines.Line2D
: This class is used to create a line in 2D.numpy
: This is a powerful library that provides support for arrays and mathematical functions.
Step 2: Define the RSI Calculation Function
def calculate_rsi(data, lookback):
delta = data['Close'].diff()
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
#average_gain = up.rolling(window=lookback).mean()
#average_loss = abs(down.rolling(window=lookback).mean())
average_gain = up.ewm(com=lookback-1, min_periods=lookback).mean()
average_loss = abs(down.ewm(com=lookback-1, min_periods=lookback).mean())
rs = average_gain / average_loss
rsi = 100 - (100 / (1 + rs))
return rsi
Here we’re defining a function that calculates the Relative Strength Index (RSI). It first calculates the difference between consecutive close prices. It then separates these changes into up and down movements. Next, it calculates the exponential moving averages of the up and down movements over a defined lookback period. These averages represent the average gain and average loss. The function then calculates the relative strength (RS) as the ratio of average gain to average loss and uses this to calculate the RSI.
This function uses an exponential moving average for smoothing the average gain and average loss. This method, also known as the Wilder’s moving average, applies more weight to recent data, making it more reactive to recent price changes.
If you want to see what difference it makes using a simple moving average remove the # marks from the two green lines (these hashtags comment out these sections of the code so they don’t run) and place hash marks in front of the next 2 lines instead to disable those instead. You can then compare the different RSI lines on the chart created in the final step, remember to save the changes to see the difference.
Step 3: Download the Data
data = yf.download('META', start='2022-07-01', end='2023-07-01')
This line downloads the price data for the ‘META’ (Meta Platforms Inc., formerly Facebook Inc.) from Yahoo Finance for the period from ‘2022-07-01’ to ‘2023-07-01’.
Step 4: Calculate the RSI
data['RSI'] = calculate_rsi(data, 14)
This line adds a new column ‘RSI’ to the data, calculated using the function defined earlier.
Step 5: Add the 50 Line
data['50 Line'] = 50
This line adds a new column ’50 Line’ to the data, which is a constant value of 50.
Step 6: Ensure the Index is a DatetimeIndex
data.index = pd.DatetimeIndex(data.index)
This line ensures that the index of the data is a DatetimeIndex
, which is required for plotting with mplfinance
.
Step 7: Define Additional Plots
apd = [
mpf.make_addplot(data['RSI'], panel=2, color='b', secondary_y=False, ylabel='RSI'),
mpf.make_addplot(data['50**Line'], panel=2, color='black', secondary_y=False, linestyle='dashed')
]
Here, two additional plots are being defined – the RSI and the 50 line – which will be added to the main plot. These are added to the second panel in the chart. The mpf.make_addplot()
function is used to create these additional plots.
Step 8: Define Panel Sizes
panel_sizes = (5, 1, 3)
The panel_sizes
tuple defines the size ratios of the three panels in the plot. The first panel (candles) is 5 times the size of the second panel (volume) and 1.66 times the size of the third panel (RSI).
Step 9: Create a Subplot for the RSI and Add the Additional Plot
fig, axes = mpf.plot(data, type='candle', style='yahoo', addplot=apd, volume=True, panel_ratios=panel_sizes, title='Meta Platforms Inc. and RSI', returnfig=True)
This line creates a candlestick plot with the ‘yahoo’ style and the panel sizes defined earlier. It includes volume and the additional plots (‘RSI’ and ’50 Line’). The mpf.plot()
function returns a Figure
object and a list of Axes
objects which can be further manipulated.
Step 10: Create a Legend for the Plot
legend_lines = [Line2D([0], [0], color=c, lw=1.5, linestyle=ls) for c, ls in zip(['b', 'black'], ['solid', 'dashed'])]
axes[2].legend(legend_lines, ['RSI', '50 Line'], loc='lower left')
This step creates a legend for the chart by creating a list of dummy lines (which will be replaced in the legend) and then using these dummy lines to create the legend. The legend is added to the lower left corner of the third panel (RSI panel).
Step 11: Display the Plot
mpf.show()
Finally, the mpf.show()
function is called to display the plot.
To run this script in VSCode, you simply need to open a new Python file (.py
), paste this script into the file, and then run the script. This can usually be done by right-clicking in the file and selecting ‘Run Python File in Terminal’. Alternatively, you can use the ‘Play’ button in the top-right corner of the VSCode window (depending on your VSCode version and settings). Make sure you have installed all the required libraries (using pip install command in terminal or command prompt).
You should then end up with a chart that looks like mine shown below. If you go to a website like yahoo finance and load their version of the same chart you’ll see the exact same pattern created by their RSI line as ours. If you instead use the simple moving average option offered above in Step 2, you’ll notice quite a difference. I hope this highlights the importance of understanding the underlying calculations of any technical indicator you use or code, as different interpretations could potentially affect your trading decisions.
Using the RSI Indicator for Screening Stocks
Screening stocks is a crucial part of any trader’s workflow. It allows you to filter through thousands of stocks to find those that meet your specific criteria without having to open a chart for each until you’re alerted to do so. The Python code we presented above for the RSI could now be used to build an RSI indicator screener, remember it’s plotting these columns of data behind the scenes which you can trigger alerts from.
Whether you’re screening for overbought and oversold conditions or RSI divergence to price or melding the output with other indicators or candlestick patterns for the perfect storm, it open up endless possibilities to move your trade execution win odds in your favour. Manage that consistently, even in just a small way and you could be very rich. Think how casinos win by tipping the odds in their favour ever so slightly day in day out.
Key Takeaways
- The Relative Strength Index (RSI) is popular for gauging the strength of a market trend, identifying potential overbought or oversold conditions, and spotting divergences.
- Divergences between the RSI and price movements can often signal potential market reversals.
- Three common RSI trading strategies include the basic RSI strategy, the RSI divergence strategy, and the RSI Swing Rejection Strategy.
- The RSI, while useful, can sometimes generate false signals and should be used in conjunction with other technical analysis tools.
- Python can be effectively used to code the RSI indicator, enabling its integration into your own trading algorithms.
- The RSI can then be utilized for screening stocks, helping to filter out those that meet specific trading criteria.
Further Reading
For further reading on the RSI and its applications in trading, consider the following resources:
- Books:
- “New Concepts in Technical Trading Systems” by J. Welles Wilder Jr. This is the book where Wilder first introduced the RSI, along with several other technical indicators. It provides a detailed explanation of the RSI and its applications in trading.
- “Technical Analysis of the Financial Markets” by John J. Murphy. This book is a comprehensive guide to technical analysis and includes a detailed section on the RSI.
- Academic Papers:
- “The Profitability of Technical Analysis: A Review” by Cheol-Ho Park and Scott H. Irwin (2007). This review paper discusses the profitability of various technical analysis indicators, including the RSI. Trader.yt reviews it in our article here.
Leave a Reply