Algorithmic Trading in Python: RSI

Rohan Kumar
Analytics Vidhya
Published in
4 min readMay 19, 2021

Here’s another one! in my Python for stock analysis. Hope ya’ll like this! For a more complete stock analysis go onto my article:

Introduction to Relative Strength Index (RSI)

The Relative Strength Index (RSI) is a popular technical indicator and momentum oscillator, developed by J. Welles Wilder in 1978. The RSI compares the size and rate of a securities recent gains and losses (usually in a 14 day period) and signals to a trader if a security is consider “overbought” or “oversold”.

The RSI values are measured within the 0–100 range, with a value of 70 and above signaling a security is overbought and values of 30 and below being oversold. Values above 70 may signal a good time to sell and exit your position. Values below 30 signal a good time to buy and enter a position.

How to Measure RSI?

To calculate the RSI, a trader must first calculate the average of the gains and losses during a certain period of time. Typically, this period is 14 days, but is ultimately decided by the trader.

Short-term focused traders may use a smaller value (e.g. 8), while longer-term traders may use higher values such as n = 24. For this example, we will be using the 14-day period that was suggested by J. Welles Wilder.

The average gains and losses are calculated using a smoothed moving average, or rolling mean. In this example, we will be using the exponential moving average (EMA) to calculate the rolling means within the 14 day window.

Once this is done, the following formula can be used to constrain the values within the 0–100 range:

We will implement this in PYTHON, and we’ll use MSFT historical data for this tutorial.

Let’s read the data, I have the CSV file downloaded from Yahoo Finance. These CSV file have over 20 + years of data, that should be enough for this tutorial.

Now let’s get started!

  1. IMPORTS and DATA READ

Let’s import the essential libraries.

import numpy as npimport pandas as pdimport matplotlib.pyplot as plt

Then I am going to read the CSV which I downloaded from Yahoo Finance. You can also get data by using the python library provided by Yahoo Finance i.e. yfinance.

stock = pd.read_csv("MSFT.csv")print(stock)
MSFT historical data

Now we will use TA-LIB library to calculate RSI.

stock[‘RSI’] = ta.RSI(stock[‘Close’],14)stock[‘RSI’].plot(figsize=(15,15))plt.show()
RSI PLOT FOR MSFT

Let’s plot the constraints of overbought = RSI 70 and oversold = RSI 30

Rather than guess and eyeball when the RSI indicator tells us to buy/sell, it might be helpful to create buy and sell triggers in the dataframe.

Looking good huh! you can do the same and get started in algorithmic trading using python in just some seconds!! GET STARTED and let me know if you have some querys.

How can we attempt to predict future stock behaviour?

Here I am providing you with a list of different models that can be used to predict stock prices.

Predicting Stock Prices Using Facebook’s Prophet Model

Time-Series Forecasting: Predicting Microsoft (MSFT) Stock Prices Using ARIMA Model

Time-Series Forecasting: Predicting Apple Stock Price Using An LSTM Model

I recommend you to read through these articles, the models described are able to predict the prices with very good precision.

Disclaimer There have been attempts to predict stock prices using time series analysis algorithms, though they still cannot be used to place bets in the real market. This is just a tutorial article that does not intent in any way to “direct” people into buying stocks.

Now its your turn to clap and follow me. Thank you for reading!

Give me a FOLLOW if you liked this, for more tech blogs!

“If at first you don’t succeed, then skydiving isn’t for you.” — Mel Helitzer

Sayonara!

--

--

Rohan Kumar
Analytics Vidhya

Poet | Story writer | Blogger "I took a walk in the woods and came out taller than the trees."~ Henry David Thorea