RV Python Script To Extract Stock Volatility
RV Python Script To Extract Stock Volatility
import pandas as pd
import datetime
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 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 = []
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()