import yfinance as yf
import pandas as pd
import numpy as np
def get_nifty50_symbols():
# You can fetch Nifty 50 symbols from NSE or any other source
# For this example, I'll use a static list of symbols
return ["ADANIPORTS.NS", "ASIANPAINT.NS", "AXISBANK.NS", "BAJAJ-AUTO.NS", "BAJAJFINSV.NS",
"BAJFINANCE.NS", "BHARTIARTL.NS", "BPCL.NS", "BRITANNIA.NS", "CIPLA.NS", "COALINDIA.NS",
"DIVISLAB.NS", "DRREDDY.NS", "EICHERMOT.NS", "GRASIM.NS", "HCLTECH.NS", "LICI.NS",
"HDFCBANK.NS", "HDFCLIFE.NS", "HEROMOTOCO.NS", "HINDALCO.NS", "HINDUNILVR.NS",
"ICICIBANK.NS", "INDUSINDBK.NS", "INFY.NS", "IOC.NS", "ITC.NS", "JSWSTEEL.NS",
"KOTAKBANK.NS", "LT.NS", "M&M.NS", "MARUTI.NS", "NESTLEIND.NS", "NTPC.NS", "ONGC.NS",
"POWERGRID.NS", "RELIANCE.NS", "SBILIFE.NS", "SBIN.NS", "SHREECEM.NS", "SUNPHARMA.NS",
"TATACONSUM.NS", "TATAMOTORS.NS", "TATASTEEL.NS", "TCS.NS", "TECHM.NS", "TITAN.NS",
"ULTRACEMCO.NS", "UPL.NS", "WIPRO.NS"]
# Function to download and process stock data for NIFTY 50
def get_nifty50_data(start_date, lookback_period=123):
# Get NIFTY 50 stock symbols
# nifty50_symbols = pd.read_html('https://en.wikipedia.org/wiki/NIFTY_50')[2]['Symbol']
# nifty50_symbols = nifty50_symbols + '.NS'
nifty50_symbols = get_nifty50_symbols()
# Download historical data for NIFTY 50 stocks
print("Downloading data for NIFTY 50 stocks...")
stocks_data = yf.download(nifty50_symbols, start=start_date)['Adj Close']
# Download historical data for NIFTY 50 index
print("Downloading data for NIFTY 50 index...")
index_data = yf.download('^NSEI', start=start_date)['Adj Close']
# Calculate returns for the lookback period
stock_return = stocks_data.iloc[-1] / stocks_data.iloc[-lookback_period]
index_return = index_data.iloc[-1] / index_data.iloc[-lookback_period]
# Calculate RS values as the ratio of returns minus 1
rs_values = stock_return / index_return - 1
# Rank the stocks based on RS
rs_ranking = rs_values.sort_values(ascending=False)
return rs_ranking
# Function to save the ranking to a CSV file
def save_ranking_to_csv(ranking, file_name):
ranking.to_csv(file_name, header=["Relative Strength"], index_label="Stock")
print(f"Saved ranking to {file_name}")
# Start date for downloading historical data
start_date = '2022-01-01'
# Calculate RS ranking for NIFTY 50 stocks
nifty50_ranking = get_nifty50_data(start_date)
print("\nTop NIFTY 50 Stocks by Relative Strength (RS):")
print(nifty50_ranking)
# Save the ranking to a CSV file
# save_ranking_to_csv(nifty50_ranking, "nifty50_rs_ranking.csv")
filepath = r"/content/drive/MyDrive/Quantzaar-tradingS, InvestmentS, Trade&investMyTheory/Backtesting/nifty50_rs_ranking.csv"
nifty50_ranking.to_csv(filepath, header=["Relative Strength"], index_label="Stock")
OUTPUT sample:
[*********************100%%**********************] 50 of 50 completed
[*********************100%%**********************] 1 of 1 completed
Top NIFTY 50 Stocks by Relative Strength (RS):
Ticker
M&M.NS 4.678069
POWERGRID.NS 2.744263
SBIN.NS 2.464280
DIVISLAB.NS 2.425309
ONGC.NS 2.414882
BPCL.NS 2.373599
COALINDIA.NS 2.207892
NTPC.NS 2.192894
MARUTI.NS 2.191889
ADANIPORTS.NS 2.128205
EICHERMOT.NS 2.104814
TATAMOTORS.NS 2.076403
GRASIM.NS 1.859392
BHARTIARTL.NS 1.846706
BAJAJ-AUTO.NS 1.828874
LICI.NS 1.700953
IOC.NS 1.651606
SBILIFE.NS 1.637801