What is the RSI in Stocks and How Can I add it to my Stock Trading Bot

What is the RSI in Stocks and How Can I add it to my Stock Trading Bot
Title image for TradeOxy Blog Post: What is the RSI In Stocks and How Can I Add it to my Stock Trading Bot

The Relative Strength Index (RSI) in stocks is one of the worlds most popular technical indicators. Technical trading systems use the RSI to identify times when a stock is overbought or oversold, which in turn helps traders identify price targets for their portfolio.

In this episode, I'm going to share with you some of the research that underpins the RSI, then show you how to add this technical indicator to your algo trading bot.

What You'll Learn Through My Blog

I'm going to show you everything you need to build your own trading bot from scratch, including:

  • Your own completely customizable development environment, including the worlds most popular technical indicators, and cutting-edge AI from ChatGPT
  • The ability to retrieve historical stock data on over 10,000 US based stocks
  • The power to calculate stock technical indicators on any stock you retrieve
  • The insight to manage your risk

All of this is available in the free episodes of this series.

The premium episodes expand this amazing knowledge base to include:

  • The technical indicators you can include
  • Advanced risk management
  • Advanced strategy building

What You'll Have by the End of this Episode

By then end of this episode, you'll have an understanding of the Relative Strength Index technical indicator, and you'll know how to generate trading signals in your algo trading bot.

GitHub Code

All code for this episode can be found on the something-cool GitHub repository. It is open-sourced under the MIT licence, and you can access it here:

Prior Knowledge

To complete this episode, you need to have the following:

  1. A dev environment which has Python and TA Lib installed
  2. Access to historic market data

Previously I've written episodes for both of these requirements, you can access them here:

  1. Build Your Own Trading Bot Dev Environment that works from Anywhere and includes TA Lib, AI
  2. Build Your Own Trading Stock Trading Bot with Alpaca Markets: Historical Data Retrieval
While completing this episode, please remember that all trading is at your own risk. My goal is to explain and demonstrate, not provide any kind of advice on what will or won't work. Make sure you do your own research before risking any actual money.

Helpful Help from TradeOxy

TradeOxy's mission is to democratize algorithmic trading, and that mission extends to my blog.

If at any point you get stuck in this series, then reach out to us on our Discord chat. I and my team will be more than happy to help out (just make sure it's about our content).

What Is the Relative Strength Index (RSI)?

Before showing you the code to add the RSI to your algo trading bot, it's worth taking a little bit of time to understand how it works, and more importantly, what it shows you.

The RSI indicator measures the relative momentum in price movements. It does this by analyzing a set number of previous price items then calculating the current price against the average of the previous prices.

This calculation produces a strength signal which is relative to the previous prices - hence the name.

The RSI was developed by J Welles Wilder Jr and introduced in his seminal book, New Concepts in Technical Trading Systems (1978)

How do I go about Calculating RSI?

The formula is expressed as below:

RSI Formula. Part of the TradeOxy Blog Post: What is the RSI In Stocks and How Can I Add it to my Stock Trading Bot

What Does the RSI Actually Show?

According to proponents of the RSI, the RSI calculation above shows the strength of current prices compared to previous prices. For instance, if the current price is relatively larger than the previous historic average (based on the size of the RSI you are calculating), then a technical analysis approach would say that the price is becoming moving toward an oversold condition. The opposite also applies.

Image showing the levels for Overbought and Oversold using the classic RSI levels. Part of the TradeOxy Blog Post: What is the RSI In Stocks and How Can I Add it to my Stock Trading Bot

The manner in which the RSI is calculated also makes it effective at identifying price momentum.

How Can I Use the RSI?

The RSI is one of the easiest technical indicators you can use. The nature of the calculation means that it is an oscillating indicator that will always give you a value between 0 and 100. It doesn't matter if your stock is worth $100 or $1000 - the RSI will still give you a value between 0-100.

Using the RSI to identify Overbought and Oversold Conditions

Traders use RSI values to identify overbought and oversold conditions. For instance, many traders use an RSI value of 70 to identify overbought conditions and a value of 30 to identify oversold conditions.

Using the RSI to Identify Positive and Negative Reversals

The RSI can also be used to identify positive and negative market reversals.

Image showing an indicative RSI Positive Market Reversal. Part of the TradeOxy Blog Post: What is the RSI In Stocks and How Can I Add it to my Stock Trading Bot.

A positive market reversal occurs when the RSI indicator forms a higher low, while the price of the stock forms a lower low. When this occurs, the theory suggests that the stock may be about to experience a reversal upwards in price movement, known as having upward momentum. This is considered confirmed when the RSI forms a higher low and crosses above the value of 30 (or whatever you've set your overbought and oversold levels to). This can also be referred to as bullish divergence.

Image showing a negative RSI Market Reversal. Part of the TradeOxy Blog Post: What is the RSI In Stocks and How Can I Add it to my Stock Trading Bot.

A negative market reversal occurs when the RSI indicator forms a lower high, while the price of the asset forms a higher high. The theory suggests that this means the stock may be about to experience a reversal downwards in price movement, known as having downward momentum. This is considered confirmed when the RSI form a lower high and crosses below the value of 70 (or whatever you've set your overbought and oversold levels to). This can also be referred to as bearish divergence.

What are Some of the Downsides of the RSI?

There are several weaknesses to the RSI you should be aware of.

Firstly, the RSI does not take into account the fair or intrinsic value of a stock. In fact, as a technical analysis indicator, it is completely agnostic to the fair or intrinsic value of a stock. If you are a follower of Warren Buffet or pure value investing in general, then this indicator is not for you.

Secondly, the RSI, by nature, is a lagging indicator. It is ill suited for sharp, sudden shocks to the market such as news releases or new information. This means it can often be inaccurate when a trend reversal occurs.

Thirdly, in its raw form, the RSI can produce multiple consecutive trading signals, depending on how you have configured it. For instance, a stock may produce RSI values of 29, 28, 24, 22, 24, 27, 31. If your oversold level is set to 30, this would potentially produce six trading signals in a row (and probably destroy your account balance).

These downsides mean that you should never really use the RSI in isolation. Most quant traders use the RSI in combination with other indicators such as the Moving Average Convergence Divergence (MACD) to identify a stock's momentum and potential price breakouts. I cover how to do this in a premium episode of my blog.

How does the RSI indicator translate into RSI Strategy?

Investors analyze trends in the market, and the RSI can be a really effective way to get an indication of a stock's momentum.

The Simplest RSI Strategy

The simplest RSI strategy is to simply set buy and sell signals based on the raw value of the RSI. If you are using the RSI in this way, then you could create a strategy that says:

  • If the RSI value is greater than 70 then I am in overbought territory and should sell
  • If the RSI value is less than 30 then I am in oversold territory so I should buy
Indicative image of a simple RSI Strategy. Part of the TradeOxy Blog Post: What is the RSI In Stocks and How Can I Add it to my Stock Trading Bot.

While this strategy is incredibly simplistic, it does provide you with insight into the potential trend of the market with respect to recent price changes.

In the next episode, I'll show you how to build such a strategy.

More Complex RSI Strategies

Like most technical indicators, RSI interpretation can be powerful when combined with other readings. Here's a few of the more complex RSI strategies that combine other concepts in technical trading:

  1. Identifying when bullish divergence occurs through confirmation with the MACD
  2. Identifying when bearish divergence occurs through confirmation with the MACD
  3. Identifying trend reversals by including the Ichimoku Cloud

Sign up to my blog to see these strategies in action.

What are some other resources I could use to research this further?

If you're interested in researching the RSI further, then check out some of these resources:

  1. Investopedia: Relative Strength Index (RSI) Indicator Explained with Formula
  2. Fidelity: Relative Strength Index
  3. Charles Schwab: How to Use the Relative Strength Index (RSI) (Video)

How to Can I add the RSI to my Algo Trading Bot

Let's see how to add the RSI to your Algo Trading bot.

Dev Environment Setup

If you've previously added an indicator to your trading bot, then skip this section. If not, carry on below.

First, head over to your dev environment and navigate to your requirements.txt file.

  1. Add TA-Lib to the bottom of the file.
  2. Run the command pip install -r requirements.txt

Next, add a file to your dev environment called indicators.py. Your file structure should look like this:

Algo Trading Bot with an Indicators File added

At the top of indicators.py import TA Lib using this line of code: import talib

Check out this episode to learn more about TA Lib

Now, let's add some indicator routing to this file so we can manage our indicators. Add the following code:

Add the RSI Calculation to Your Trading Bot

Now, lets add the RSI calculation to your indicators.py file.

Do this with the following function added to the bottom of your file:

I'll quickly go through this powerful little function in order.

  1. Checks that the RSI period is greater than 0 (because that would be ridiculous)
  2. Checks that the length of the data provided to the RSI is greater than the RSI period
  3. Calculates RSI using the closing prices of the stock
  4. Identifies if the RSI is overbought or oversold
  5. Returns the outcome

Finally, lets update our function calc_indicator to include the RSI. Here's what the completed function looks like:

If you already have other functions from other episodes of my blog, you just need to add it in the if / else statement

Update app.py to see the RSI in Action

Let's see the RSI in action.

To do this, head to your app.py file, which we created in the dev environment setup.

In this file, add a new import statement to the file, below the other import statements. It should say:

import indicators

Now, head to your auto_run_trading_bot and add update it so that it looks like this:

Here's what mine looked like when I did this:

RSI Calculation on data including the ability to identify overbought and oversold conditions

Nice work.

Test Out the RSI on Different Stocks and Timeframes

To finish up this episode, I'll show some of the power of the trading bot we're building.

Identifying Multiple Oversold Assets. Let's say you want to identify multiple oversold assets in one go. You can do this by updating the symbols variable, located near the top of your app.py, to this:

symbols = ["AAPL", "GOOGL", "META"]

Testing out Different Timeframes. Many traders have specific timeframes they prefer to work with. You can do this by updating the timeframe variable to whatever timeframe you like. For instance:

timeframe = "1hour"

I'm sure you can already start imaging how powerful this trading bot is becoming!

Wrapping Up

I hope you enjoyed this introduction to the RSI in stocks and enjoyed seeing how to use it in your trading bot!

I'm always interested to hear what my readers and followers want to know more about, so if you've got an idea, why not drop us a suggestion in our suggestion box (aka contact form).

Join the TradeOxy Revolution

At TradeOxy, we're on a mission to democratize algorithmic trading. Why not join our journey and check out our list of amazing indicators and helpful education?

Full Code For app.py

Full code for app.py at end of episode:

Full Code for indicators.py

Full code for indicators.py at the end of episode: