(3/5) Relative Strength Index (RSI): A Powerful Trading Indicator Implemented in Python

RSI Indicator

Hello and welcome all to the third article in the series of Understanding Technical Indicators and Analysis using Python. In this article, we discuss the Relative Strength Index indicator. If you’re new to TA, start with this tutorial on the basics of TA.

In 2021, it was recorded that most of the trading action in the whole world happened in India. This fact might be encouraging, but most traders do not use any trading strategies and just act on advice or intuition to book profit, leading to losses.

The Relative Strength Index (RSI) is a powerful momentum-based trading indicator. It helps identify overbought and oversold conditions in the market. When RSI is above 70, the asset is considered overbought, and when below 30, it is oversold. RSI can be implemented in Python using the Pandas library for efficient calculations.

This article will discuss a simple yet very powerful trading strategy known as the Relative strength index( RSI ). This indicator is used and recommended by seasoned traders. We will also understand how to implement it in Python with the help of Pandas.

Recommended: Weighted Moving Average – Implementation in Python

Recommended: FastAPI in Action: API Monitoring Strategies for Python Developers

The RSI Indicator: Concept and Interpretation

RSI, or Relative Strength Indicator, is a technical analysis indicator that uses momentum. Let’s examine the formula for the RSI indicator.

This trading indicator measures the magnitude of recent price changes to evaluate overbought or oversold market conditions. It helps traders identify the speed and change of price movements.

RSI Indicator
RSI Indicator

Here x is the period or number of days, and in general, an RSI period of 14 is used. If the RSI indicator value is above 70, it indicates that the asset is overbought and that now is a good time to sell it. Similarly, if the RSI score is below 30, the asset is oversold, and it is a good time to buy it. Let us now look at the Python implementation of the RSI indicator using pandas.

Implementing RSI in Python with Pandas

Let us now look at the RSI code. We will randomly generate data on price points and plot it.

import pandas as pd
import matplotlib.pyplot as plt
import random

def calculate_rsi(prices, period=14):
  """
  Calculates the Relative Strength Index (RSI) for a given list of prices.

  Args:
      prices: A list of closing prices.
      period: The number of periods for the moving average (default: 14).

  Returns:
      A pandas Series containing the RSI values for each price.
  """

  delta = prices.diff()
  delta = delta.dropna()  # Remove NaN from the first difference
  up, down = delta.clip(lower=0), delta.clip(upper=0, lower=None)  # Separate gains and losses

  ema_up = up.ewm(alpha=1/period, min_periods=period).mean()  # Exponential Moving Average for gains
  ema_down = down.abs().ewm(alpha=1/period, min_periods=period).mean()  # EMA for absolute losses

  rs = ema_up / ema_down  # Average gain / Average loss
  rsi = 100 - 100 / (1 + rs)  # Calculate RSI

  return rsi

def generate_random_prices(num_days=1000):
  """
  Generates a list of random stock prices for a specified number of days.

  Args:
      num_days: The number of days to generate prices for (default: 1000).

  Returns:
      A list of random closing prices.
  """

  # Simulate price fluctuations with a random walk
  prices = [100]  # Starting price
  for _ in range(num_days - 1):
    change = random.uniform(-1, 1) * 0.5  # Random change between -0.5 and 0.5
    prices.append(prices[-1] + change)

  return prices

# Generate random stock prices
prices = generate_random_prices()

# Calculate RSI using pandas for efficiency
df = pd.DataFrame({'Close': prices})
df['RSI'] = calculate_rsi(df['Close'])

# Plot the closing prices and RSI
plt.figure(figsize=(12, 6))
plt.plot(df.index, df['Close'], label='Closing Price')
plt.plot(df.index, df['RSI'], label='RSI')
plt.xlabel('Day')
plt.ylabel('Price/RSI')
plt.title('Random Stock Price with RSI (14-period)')
plt.legend()
plt.grid(True)
plt.show()

Let us now look at the output of the above code.

RSI Code Output
Analyzing RSI Output and Trading Signals

From the output, we can see instances where prices went down after the RSI crossed 70 and up after the RSI crossed 30. When the RSI is above 70, it indicates that the asset may be overbought, and traders might consider selling. Conversely, when the RSI is below 30, it suggests that the asset may be oversold, and traders might consider buying.

This is a generalized RSI code. As you can see, the RSI chart is typically plotted below the price chart. Traders look for divergences between the RSI and the price action to identify potential trend reversals or confirmations.

We can also use an Excel or CSV file for the RSI indicator, which can be downloaded from Yahoo Finance. Let’s look at the code for the same.

import pandas as pd

def calculate_rsi(filepath, period=14):
  """
  Calculates the Relative Strength Index (RSI) for prices loaded from an Excel or CSV file.

  Args:
      filepath: The path to the Excel or CSV file containing closing prices.
      period: The number of periods for the moving average (default: 14).

  Returns:
      A pandas DataFrame with 'Close' and 'RSI' columns.
  """

  # Read data from Excel or CSV
  data = pd.read_csv(filepath) if filepath.endswith('.csv') else pd.read_excel(filepath)

  # Ensure 'Close' price column exists
  if 'Close' not in data.columns:
    raise ValueError("Data doesn't contain a 'Close' price column.")

  prices = data['Close']

  # Calculate RSI
  delta = prices.diff()
  delta = delta.dropna()  # Remove NaN from the first difference
  up, down = delta.clip(lower=0), delta.clip(upper=0, lower=None)  # Separate gains and losses

  ema_up = up.ewm(alpha=1/period, min_periods=period).mean()  # EMA for gains
  ema_down = down.abs().ewm(alpha=1/period, min_periods=period).mean()  # EMA for absolute losses

  rs = ema_up / ema_down  # Average gain / Average loss
  rsi = 100 - 100 / (1 + rs)  # Calculate RSI

  # Add RSI to DataFrame
  data['RSI'] = rsi

  return data

# Example usage (replace 'your_data.xlsx' or 'your_data.csv' with your actual file path)
data = calculate_rsi('your_data.xlsx')  # For Excel file
# data = calculate_rsi('your_data.csv')  # For CSV file

# Access calculated RSI values
print(data[['Close', 'RSI']].tail())  # Print the last few rows with closing prices and RSI

Conclusion: Applying RSI for Successful Trading

The Relative Strength Index (RSI) is a valuable momentum oscillator that assists traders in making informed choices in the fast-paced financial markets. By calculating the velocity and size of price changes, RSI offers insights into potentially overbought and oversold market conditions, helping traders find optimal entry and exit points.

Implementing RSI in Python with the Pandas library allows traders to examine historical price data and produce useful trading signals efficiently. Python’s flexibility enables traders to personalize and streamline their RSI calculations effortlessly, whether using real-time data or historical records from Excel or CSV files.

Hope you enjoyed reading it!!!

Recommended: Create Minesweeper using Python From the Basic to Advanced

Recommended: Best Python Homework Help Websites (Reviewed by Experts)

Disclaimer: This article does not provide any investment or financial advice and is meant purely for educational purposes.