import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import requests
from datetime import datetime
import json
import time
class NiftyOptionsAnalyzer:
def __init__(self):
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept-Language': 'en-US,en;q=0.9',
'Referer': 'https://www.nseindia.com/'
}
self.session = requests.Session()
self.options_data = None
self.nifty_spot = None
def get_cookies(self):
"""Obtain cookies for NSE website access"""
try:
response = self.session.get('https://www.nseindia.com/', headers=self.headers, timeout=5)
return response.status_code == 200
except Exception as e:
print(f"Error obtaining cookies: {e}")
return False
def fetch_options_chain(self, symbol="NIFTY"):
"""Fetch options chain data for the given symbol"""
if not self.get_cookies():
return False
try:
url = f"https://www.nseindia.com/api/option-chain-indices?symbol={symbol}"
response = self.session.get(url, headers=self.headers, timeout=5)
if response.status_code == 200:
data = response.json()
self.nifty_spot = data['records']['underlyingValue']
# Process the options data
records = data['records']['data']
calls = []
puts = []
for record in records:
if 'CE' in record and 'PE' in record:
calls.append(record['CE'])
puts.append(record['PE'])
calls_df = pd.DataFrame(calls)
puts_df = pd.DataFrame(puts)
# Merge call and put data
calls_df = calls_df.rename(columns={col: f'call_{col}' for col in calls_df.columns if col != 'strikePrice'})
puts_df = puts_df.rename(columns={col: f'put_{col}' for col in puts_df.columns if col != 'strikePrice'})
self.options_data = pd.merge(calls_df, puts_df, on='strikePrice')
return True
else:
print(f"Failed to fetch data: Status code {response.status_code}")
return False
except Exception as e:
print(f"Error fetching options chain: {e}")
return False
def calculate_pcr(self):
"""Calculate the Put-Call Ratio based on Open Interest"""
if self.options_data is None:
return None
total_put_oi = self.options_data['put_openInterest'].sum()
total_call_oi = self.options_data['call_openInterest'].sum()
pcr = total_put_oi / total_call_oi if total_call_oi > 0 else 0
return pcr
def calculate_max_pain(self):
"""Calculate the Max Pain strike price"""
if self.options_data is None:
return None
strikes = self.options_data['strikePrice'].unique()
pain_values = []
for strike in strikes:
pain = 0
for _, row in self.options_data.iterrows():
# Call options pain
if row['strikePrice'] < strike:
pain += row['call_openInterest'] * (strike - row['strikePrice'])
# Put options pain
if row['strikePrice'] > strike:
pain += row['put_openInterest'] * (row['strikePrice'] - strike)
pain_values.append(pain)
# Find the strike with minimum pain
max_pain_strike = strikes[np.argmin(pain_values)]
return max_pain_strike
def analyze_oi_trend(self):
"""Analyze OI trends to determine market direction"""
if self.options_data is None:
return None
# Filter for strikes around current spot price (±5%)
lower_bound = self.nifty_spot * 0.95
upper_bound = self.nifty_spot * 1.05
relevant_data = self.options_data[
(self.options_data['strikePrice'] >= lower_bound) &
(self.options_data['strikePrice'] <= upper_bound)
]
call_oi_change = relevant_data['call_changeinOpenInterest'].sum()
put_oi_change = relevant_data['put_changeinOpenInterest'].sum()
if call_oi_change > 0 and put_oi_change < 0:
return "Bullish"
elif call_oi_change < 0 and put_oi_change > 0:
return "Bearish"
elif call_oi_change > 0 and put_oi_change > 0:
return "Moderately Bullish" if call_oi_change > put_oi_change else "Moderately Bearish"
else:
return "Weak Bullish" if abs(call_oi_change) < abs(put_oi_change) else "Weak Bearish"
def calculate_iv_skew(self):
"""Calculate implied volatility skew to determine market sentiment"""
if self.options_data is None:
return None
# Find ATM strike (closest to spot)
atm_index = (self.options_data['strikePrice'] - self.nifty_spot).abs().idxmin()
# Get IVs for OTM options
otm_calls = self.options_data.iloc[atm_index:].head(5)
otm_puts = self.options_data.iloc[max(0, atm_index-5):atm_index]
avg_call_iv = otm_calls['call_impliedVolatility'].mean()
avg_put_iv = otm_puts['put_impliedVolatility'].mean()
iv_skew = avg_put_iv - avg_call_iv
if iv_skew > 5:
return "Strongly Bearish"
elif iv_skew > 2:
return "Bearish"
elif iv_skew < -5:
return "Strongly Bullish"
elif iv_skew < -2:
return "Bullish"
else:
return "Neutral"
def suggest_strikes(self):
"""Suggest strike prices based on analysis"""
if self.options_data is None:
return None
trend = self.analyze_oi_trend()
pcr = self.calculate_pcr()
max_pain = self.calculate_max_pain()
iv_sentiment = self.calculate_iv_skew()
# Round spot to nearest 50 for Nifty
atm_strike = round(self.nifty_spot / 50) * 50
result = {
"Spot Price": self.nifty_spot,
"Market Trend": trend,
"Put-Call Ratio": f"{pcr:.2f}",
"PCR Interpretation": "Bearish" if pcr > 1.5 else "Bullish" if pcr < 0.7 else "Neutral",
"Max Pain Strike": max_pain,
"IV Skew Sentiment": iv_sentiment
}
# Suggest option strikes based on the analysis
if "Bullish" in trend or pcr < 0.7:
result["Suggested Call Buying Strikes"] = [atm_strike, atm_strike + 50, atm_strike + 100]
result["Suggested Put Selling Strikes"] = [atm_strike - 100, atm_strike - 150]
elif "Bearish" in trend or pcr > 1.5:
result["Suggested Put Buying Strikes"] = [atm_strike, atm_strike - 50, atm_strike - 100]
result["Suggested Call Selling Strikes"] = [atm_strike + 100, atm_strike + 150]
else:
result["Suggested Iron Condor Strikes"] = {
"Sell Call": atm_strike + 100,
"Buy Call": atm_strike + 200,
"Sell Put": atm_strike - 100,
"Buy Put": atm_strike - 200
}
return result
def visualize_options_chain(self):
"""Create visualizations for the options chain analysis"""
if self.options_data is None:
return
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
# 1. OI Distribution
strikes = self.options_data['strikePrice']
call_oi = self.options_data['call_openInterest']
put_oi = self.options_data['put_openInterest']
ax1.bar(strikes, call_oi, width=10, alpha=0.6, color='green', label='Call OI')
ax1.bar(strikes, -put_oi, width=10, alpha=0.6, color='red', label='Put OI')
ax1.axvline(x=self.nifty_spot, color='black', linestyle='--', label='Spot Price')
ax1.set_title('Nifty Options Open Interest Distribution')
ax1.set_ylabel('Open Interest')
ax1.legend()
# 2. IV Skew
call_iv = self.options_data['call_impliedVolatility']
put_iv = self.options_data['put_impliedVolatility']
ax2.plot(strikes, call_iv, 'g-', label='Call IV')
ax2.plot(strikes, put_iv, 'r-', label='Put IV')
ax2.axvline(x=self.nifty_spot, color='black', linestyle='--', label='Spot Price')
ax2.set_title('Nifty Options IV Skew')
ax2.set_xlabel('Strike Price')
ax2.set_ylabel('Implied Volatility (%)')
ax2.legend()
plt.tight_layout()
plt.show()
def analyze_nifty_options():
analyzer = NiftyOptionsAnalyzer()
print("Fetching Nifty Options Chain...")
if analyzer.fetch_options_chain():
print(f"Current Nifty Spot: {analyzer.nifty_spot}")
# Get analysis results
suggestion = analyzer.suggest_strikes()
for key, value in suggestion.items():
print(f"{key}: {value}")
# Generate visualizations
analyzer.visualize_options_chain()
else:
print("Failed to fetch options data. Please check your connection or try again later.")
if __name__ == "__main__":
analyze_nifty_options()
Would you like me to explain or break down the code?