Skip to content
The Chat Archive
qwen-max-2025-01-25· Alibaba (Qwen) LMArena Human Preference 140K

Build me python code for nifty options chain to decide market trend and strikes

  1. User

    Build me python code for nifty options chain to decide market trend and strikes

  2. Assistant

    To build a Python script for analyzing the Nifty options chain to decide market trends and identify key strike prices, we can use publicly available data from sources like the National Stock Exchange (NSE) of India. The script will:

    1. Fetch the latest options chain data for Nifty.
    2. Analyze the open interest (OI) and volume data to determine market sentiment.
    3. Identify key support and resistance levels based on maximum OI.

    Below is the Python code that accomplishes this:

    Prerequisites:

    • Install required libraries: requests, pandas, numpy, and matplotlib.
      pip install requests pandas numpy matplotlib
      

    Python Code:

    import requests
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    # Function to fetch Nifty options chain data
    def fetch_nifty_options_chain():
        # URL for NSE's option chain API (replace with actual endpoint if needed)
        url = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
        
        # Headers to mimic browser request
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
        }
        
        try:
            # Create a session to maintain cookies
            session = requests.Session()
            response = session.get(url, headers=headers, timeout=10)
            
            if response.status_code == 200:
                data = response.json()
                return data
            else:
                print(f"Failed to fetch data. Status code: {response.status_code}")
                return None
        except Exception as e:
            print(f"Error fetching data: {e}")
            return None
    
    # Function to analyze the options chain
    def analyze_options_chain(data):
        if not data:
            print("No data to analyze.")
            return
        
        # Extract relevant data
        records = data['records']['data']
        current_price = data['records']['underlyingValue']
        
        # Prepare lists to store strikes and OI
        call_oi = []
        put_oi = []
        strikes = []
        
        for record in records:
            strike_price = record['strikePrice']
            strikes.append(strike_price)
            
            # Add Call OI
            call_oi.append(record['CE']['openInterest'] if 'CE' in record else 0)
            
            # Add Put OI
            put_oi.append(record['PE']['openInterest'] if 'PE' in record else 0)
        
        # Create a DataFrame
        df = pd.DataFrame({
            'Strike Price': strikes,
            'Call OI': call_oi,
            'Put OI': put_oi
        })
        
        # Calculate Put-Call Ratio
        total_call_oi = df['Call OI'].sum()
        total_put_oi = df['Put OI'].sum()
        pcr = total_put_oi / total_call_oi if total_call_oi != 0 else 0
        
        # Market trend based on PCR
        if pcr > 1:
            market_trend = "Bullish (Higher Put OI)"
        elif pcr < 1:
            market_trend = "Bearish (Higher Call OI)"
        else:
            market_trend = "Neutral"
        
        # Identify key support and resistance levels
        max_call_oi_strike = df.loc[df['Call OI'].idxmax()]['Strike Price']
        max_put_oi_strike = df.loc[df['Put OI'].idxmax()]['Strike Price']
        
        # Print analysis results
        print(f"Current Nifty Price: {current_price}")
        print(f"Total Call OI: {total_call_oi}, Total Put OI: {total_put_oi}")
        print(f"Put-Call Ratio (PCR): {pcr:.2f}")
        print(f"Market Trend: {market_trend}")
        print(f"Key Resistance Level (Max Call OI): {max_call_oi_strike}")
        print(f"Key Support Level (Max Put OI): {max_put_oi_strike}")
        
        # Plot Open Interest
        plt.figure(figsize=(12, 6))
        plt.bar(df['Strike Price'], df['Call OI'], label='Call OI', color='blue', alpha=0.6)
        plt.bar(df['Strike Price'], df['Put OI'], label='Put OI', color='red', alpha=0.6)
        plt.axvline(x=current_price, color='green', linestyle='--', label='Current Price')
        plt.axvline(x=max_call_oi_strike, color='orange', linestyle='--', label='Resistance (Max Call OI)')
        plt.axvline(x=max_put_oi_strike, color='purple', linestyle='--', label='Support (Max Put OI)')
        plt.title('Nifty Options Chain Analysis')
        plt.xlabel('Strike Price')
        plt.ylabel('Open Interest')
        plt.legend()
        plt.grid(True)
        plt.show()
    
    # Main function
    if __name__ == "__main__":
        # Fetch and analyze Nifty options chain
        options_data = fetch_nifty_options_chain()
        analyze_options_chain(options_data)
    

    Explanation of the Code:

    1. Fetch Data: The script uses the NSE API to fetch the latest Nifty options chain data.
    2. Analyze Data:
      • It calculates the total Call and Put Open Interest (OI).
      • Computes the Put-Call Ratio (PCR) to determine the market trend.
      • Identifies key support (maximum Put OI) and resistance (maximum Call OI) levels.
    3. Visualization:
      • A bar chart is plotted to show Call and Put OI across strike prices.
      • Vertical lines indicate the current price, key resistance, and support levels.

    Output:

    The script will display:

    1. Current Nifty price.
    2. Total Call and Put OI.
    3. Put-Call Ratio (PCR) and market trend.
    4. Key resistance and support levels.
    5. A visual chart for better interpretation.

    Notes:

    • Ensure you comply with NSE's terms of service when using their API.
    • If the API endpoint changes or requires authentication, update the URL and headers accordingly.
    • You can extend this script to include more advanced analysis, such as implied volatility or historical trends.

    Let me know if you need further assistance!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.