Calculating the Relative Strength Index (RSI) in Python: A Comprehensive Guide

2 min

The Relative Strength Index, commonly known as RSI, is a vital tool used by traders to measure the speed and change of price movements of an asset. It's a momentum indicator that plays a pivotal role in identifying overbought or oversold conditions in the market.

In this comprehensive guide, we'll delve deep into how to calculate RSI using Python.

Key Takeaways

  • The RSI is a momentum oscillator that helps traders identify overbought or oversold market conditions.
  • Calculating the RSI involves steps like determining price changes, calculating gains and losses, and finding the relative strength.
  • Python is an excellent tool for calculating the RSI, especially with libraries like NumPy and yfinance.
  • This guide provides a Python function to calculate RSI, which can be used with any data series of closing prices.

What is the Relative Strength Index (RSI)?

The RSI is a technical analysis tool that measures the magnitude of recent price changes to evaluate overbought or oversold conditions in an asset. It generates a value between 0 and 100, with a high value indicating overbought conditions and a low value signaling oversold conditions.

Calculating RSI: Step-by-Step Guide

Here's the step-by-step process to calculate RSI in Python:

  1. Calculate the change in price: This is the difference between the current close price and the previous close price.
  2. Calculate the gain: This involves summing up all positive changes.
  3. Calculate the loss: Sum up all negative changes.
  4. Calculate the average gain and average loss: Divide the sum of gains and losses by the number of periods, usually 14.
  5. Calculate the relative strength: Divide the average gain by the average loss.
  6. Calculate the RSI: Use the formula 100 - (100 / (1 + relative strength)).

Python Code for Calculating RSI

Here is a Python sample code for calculating RSI:

import numpy as np
import yfinance as yf

prices = yf.download(["AAPL"])["Adj Close"]

def rsi(prices, n=14):
    """Compute the RSI given prices
    
    :param prices: pandas.Series
    :return: rsi
    """
    
    # Calculate the difference between the current and previous close price
    delta = prices.diff()
    
    # Calculate the sum of all positive changes
    gain = delta.where(delta > 0, 0)
    
    # Calculate the sum of all negative changes
    loss = -delta.where(delta < 0, 0)
    
    # Calculate the average gain over the last n periods
    avg_gain = gain.rolling(n).mean()
    
    # Calculate the average loss over the last n periods
    avg_loss = loss.rolling(n).mean()
    
    # Calculate the relative strength
    rs = avg_gain / avg_loss
    
    # Calculate the RSI
    rsi = 100 - (100 / (1 + rs))
    
    return rsi

print(rsi(prices))

You can replace 'prices' with the data series of close prices you wish to use. The 'n' argument specifies the number of periods to use in the calculation, with a default value of 14.

Conclusion

Calculating RSI with Python equips traders with a powerful tool to gauge overbought or oversold conditions in the market. As a part of a broader trading strategy, the RSI can provide valuable insights and contribute to more informed decision-making.