0% found this document useful (0 votes)
99 views2 pages

RV Python Script To Extract Stock Volatility

The document is a Python script that screens Nifty stocks based on their volatility relative to a benchmark index. It fetches historical close prices, calculates the volatility of each stock and the benchmark, and identifies stocks with a relative volatility (RV) greater than a specified threshold. The results are displayed in a sorted DataFrame format, highlighting stocks that meet the criteria.

Uploaded by

harxhk008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views2 pages

RV Python Script To Extract Stock Volatility

The document is a Python script that screens Nifty stocks based on their volatility relative to a benchmark index. It fetches historical close prices, calculates the volatility of each stock and the benchmark, and identifies stocks with a relative volatility (RV) greater than a specified threshold. The results are displayed in a sorted DataFrame format, highlighting stocks that meet the criteria.

Uploaded by

harxhk008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import yfinance as yf

import pandas as pd
import datetime

# Stock symbols to screen


NIFTY_STOCKS = [
"RELIANCE.NS", "TCS.NS", "INFY.NS", "HDFCBANK.NS", "ICICIBANK.NS",
"HINDUNILVR.NS", "ITC.NS", "LT.NS", "SBIN.NS", "KOTAKBANK.NS"
]

BENCHMARK = "^NSEI"
LOOKBACK_DAYS = 20
RV_THRESHOLD = 1.0

def fetch_close_prices(symbol):
df = yf.download(symbol, period="30d", interval="1d", progress=False)
if df.empty or 'Close' not in df.columns:
raise ValueError(f"No close price data for {symbol}")
return df['Close'].dropna()

def calculate_volatility(series):
returns = series.pct_change().dropna()
if len(returns) < LOOKBACK_DAYS:
raise ValueError("Not enough return data to calculate volatility")
return float(returns[-LOOKBACK_DAYS:].std())

def calculate_rv(stock_vol, benchmark_vol):


if stock_vol is None or benchmark_vol is None or benchmark_vol == 0:
return None
return float(stock_vol) / float(benchmark_vol)

def run_screener():
print(f"\n🔄 Running Screener @ {datetime.datetime.now().strftime('%Y-%m-%d %H:
%M:%S')}")

try:
benchmark_prices = fetch_close_prices(BENCHMARK)
benchmark_vol = calculate_volatility(benchmark_prices)
except Exception as e:
print(f"❌ Benchmark error: {e}")
return

results = []

for symbol in NIFTY_STOCKS:


try:
stock_prices = fetch_close_prices(symbol)
stock_vol = calculate_volatility(stock_prices)
rv = calculate_rv(stock_vol, benchmark_vol)

# Ensure RV is a scalar float


if isinstance(rv, float) and rv > RV_THRESHOLD:
results.append({
"Symbol": symbol,
"Volatility": round(stock_vol, 5),
"RV": round(rv, 3)
})

except Exception as e:
print(f"⚠️ Skipping {symbol}: {e}")

if results:
df = pd.DataFrame(results).sort_values(by="RV", ascending=False)
print("\n📊 Top Stocks with RV > 1:\n")
print(df.to_string(index=False))
else:
print("⚠️ No stocks with RV above threshold.")

# Run once
run_screener()

You might also like