Get RSI of nifty 50 stocks using python script

I want to write a python script to get RSI value for one day for nifty 50 stocks. I have written a script but it gives wrong value.

Can you share your code?

Not able to attach any file here.

import json
import pandas as pd
import requests
from dateutil.utils import today
from datetime import datetime, timedelta
import calendar
import os
import time

from isin import nifty_50_isins

interval = “30minute”
to_date = datetime.today() - timedelta(days=1)
to_date = to_date.strftime(“%Y-%m-%d”)
from_date = datetime.today() - timedelta(days=3)
from_date = from_date.strftime(“%Y-%m-%d”)

def calculate_rsi(data, window=14):
delta = data.diff(1)

# Separate the gains and losses
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)

# Calculate the average gain and average loss
avg_gain = gain.rolling(window=window, min_periods=1).mean()
avg_loss = loss.rolling(window=window, min_periods=1).mean()

# Calculate the relative strength (RS)
rs = avg_gain / avg_loss

# Calculate the RSI
rsi = 100 - (100 / (1 + rs))

return rsi

headers = {
‘Accept’: ‘application/json’,
‘Authorization’: ‘’
}

for stock_name, isin in nifty_50_isins.items():
# Construct the URL
url = f"https://api.upstox.com/v2/historical-candle/NSE_EQ|{isin}/{interval}/{to_date}/{from_date}"
# Send the GET request
response = requests.get(url, headers=headers)
# Check if the response is successful
if response.status_code == 200:
# Parse the response JSON
data = response.json()

    # Extract the candles data
    candles = data.get("data", {}).get("candles", [])

    # Check if candles data is available
    if candles:
        # Extract closing prices (index 4 of each candle represents the close price)
        close_prices = [candle[4] for candle in candles]

        # Create a pandas Series with the closing prices
        close_series = pd.Series(close_prices)

        # Calculate RSI using the closing prices
        rsi = calculate_rsi(close_series)
        for rsi_value in rsi:
            if rsi_value > 60 and rsi_value != 100:
                rsi_value = "{:.2f}".format(rsi_value)
                # Print the stock name and RSI values
                print(f"{stock_name} ({isin}):", rsi_value)
    else:
        print(f"No data found in the response for {stock_name} ({isin}).")
else:
    print(f"Failed to retrieve data for {stock_name} ({isin}). Status code: {response.status_code}")

# Optionally, print the raw candle data
# for candle in candles:
#     print(candle)

Bro you can use pandas_ta library to get RSI. Create a Simple RSI Filter Crossing Above 80 - Python you can check this link for implementation.

what is your expected output?

I want to extract shares which has 60+ RSI in previous day.

it gives ModuleNotFoundError: No module named ‘pandas_ta’ error, tried adding this lib but it doesn’t work. Tried adding ta lib as well but than it gives AttributeError: module ‘ta’ has no attribute ‘rsi’ error.

I want to extract shares which has 60+ RSI in previous day