### Install NSEPython Library Source: https://context7.com/aeron7/nsepython/llms.txt Install the NSEPython library using pip. Choose the Local edition for Windows or the Server edition for cloud environments. ```bash # Local edition (Windows laptops) pip install nsepython ``` ```bash # Server edition (AWS, Google Colab, DigitalOcean) pip install nsepythonserver ``` -------------------------------- ### Install NSEPython Local Edition Source: https://github.com/aeron7/nsepython/blob/master/README.md Use pip to install the local edition of NSEPython, compatible with Windows 11 and 10. ```bash pip install nsepython ``` -------------------------------- ### Install NSEPython Server Edition Source: https://github.com/aeron7/nsepython/blob/master/README.md Use pip to install the server edition of NSEPython, suitable for AWS, Google Colab, and DigitalOcean environments. ```bash pip install nsepythonserver ``` -------------------------------- ### Get Full Bulk Deals Archive with get_bulkdeals() Source: https://context7.com/aeron7/nsepython/llms.txt Downloads the complete archive of bulk deals as a CSV file, accessible as a pandas DataFrame. Provides details on large trades. ```python from nsepython import get_bulkdeals df = get_bulkdeals() print(df.columns.tolist()) # ['Date', 'Symbol', 'Security Name', 'Client Name', 'Buy/Sell', 'Quantity Traded', 'Trade Price / Wght Avg Price'] print(df.head()) ``` -------------------------------- ### Get Live Large Deals Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves intraday bulk deals, block deals, or short selling data as a pandas DataFrame. Displays deal details. ```python from nsepython import nse_largedeals # Bulk deals bulk = nse_largedeals(mode="bulk_deals") print(bulk.head()) # Block deals block = nse_largedeals(mode="block_deals") print(block.head()) ``` -------------------------------- ### Get All NSE Equity Symbols with nse_eq_symbols() Source: https://context7.com/aeron7/nsepython/llms.txt Returns a list of all symbols currently listed in the NSE equity segment. Useful for validating symbols or getting a complete list. ```python from nsepython import nse_eq_symbols symbols = nse_eq_symbols() print(f"Total NSE equity symbols: {len(symbols)}") # e.g. 2400+ print(symbols[:10]) # ['20MICRONS', '21STCENMGM', '360ONE', '3IINFOLTD', '3MINDIA', ...] ``` -------------------------------- ### Get Full Block Deals Archive with get_blockdeals() Source: https://context7.com/aeron7/nsepython/llms.txt Downloads the complete archive of block deals as a CSV file, accessible as a pandas DataFrame. Useful for tracking significant block trades. ```python from nsepython import get_blockdeals df = get_blockdeals() print(df.head()) ``` -------------------------------- ### Get Live Market Status Source: https://context7.com/aeron7/nsepython/llms.txt Returns the current market status (open/closed) for all segments of the NSE. ```python from nsepython import nse_marketStatus status = nse_marketStatus() print(status) ``` -------------------------------- ### Get Pre-Open Gainers and Losers Source: https://context7.com/aeron7/nsepython/llms.txt Returns two DataFrames for pre-open gainers (pChange > filter) and losers (pChange < -filter). Displays symbol and percentage change for top entries. ```python from nsepython import nse_preopen_movers gainers, losers = nse_preopen_movers(key="FO", filter=1.5) print("Top pre-open gainers:") print(gainers[["symbol", "pChange"]].head()) print("Top pre-open losers:") print(losers[["symbol", "pChange"]].head()) ``` -------------------------------- ### Get F&O Lot Sizes with nse_get_fno_lot_sizes() Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves lot sizes for NSE F&O instruments. Can return all lot sizes as a dictionary, a specific symbol's lot size, or a full DataFrame. ```python from nsepython import nse_get_fno_lot_sizes # All lot sizes as dict all_lots = nse_get_fno_lot_sizes() print(all_lots["NIFTY"]) # e.g. 50 print(all_lots["RELIANCE"]) # e.g. 250 # Specific symbol lot = nse_get_fno_lot_sizes("BANKNIFTY") print(lot) # e.g. 15 # Full DataFrame df = nse_get_fno_lot_sizes(mode="pandas") print(df.head()) ``` -------------------------------- ### Get List of NSE Index Names Source: https://context7.com/aeron7/nsepython/llms.txt Fetches a list of all available index names from the live indices feed. ```python from nsepython import nse_get_index_list indices = nse_get_index_list() print(indices[:5]) # ['NIFTY 50', 'NIFTY NEXT 50', 'NIFTY 100', 'NIFTY 200', 'NIFTY 500'] ``` -------------------------------- ### Get Historical Index PE, PB, and Dividend Yield Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves historical Price-to-Earnings (PE), Price-to-Book (PB), and Dividend Yield ratios for a NIFTY index over a specified period. ```python from nsepython import index_pe_pb_div df = index_pe_pb_div("NIFTY 50", "01-Jan-2023", "31-Dec-2023") print(df.columns.tolist()) # ['HistoricalDate', 'pe', 'pb', 'divYield'] print(df.sort_values("HistoricalDate").tail()) ``` -------------------------------- ### Get Price Band Hitters Source: https://context7.com/aeron7/nsepython/llms.txt Fetches stocks that have hit their upper circuit, lower circuit, or both. Displays symbol, last price, and percentage change for top entries. ```python from nsepython import nse_price_band_hitters # All stocks hitting either circuit df = nse_price_band_hitters(bandtype="both", view="AllSec") print(df[["symbol", "lastPrice", "pChange"]].head()) # Only upper circuit df_upper = nse_price_band_hitters(bandtype="upper") ``` -------------------------------- ### Get Top 5 FNO Gainers Source: https://context7.com/aeron7/nsepython/llms.txt Returns the top 5 gainers from the FNO universe, ranked by percentage change. The output is provided as a pandas DataFrame. ```python from nsepython import nse_get_top_gainers df = nse_get_top_gainers() print(df[["symbol", "lastPrice", "pChange"]]) # symbol lastPrice pChange # 0 IDEA 15.30 4.80 # 1 SAIL 125.50 3.10 ``` -------------------------------- ### Archive Security Price-Volume Data with security_wise_archive() Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves historical price, volume, and deliverable quantity data for a specific security symbol within a date range. Requires start date, end date, and symbol. ```python from nsepython import security_wise_archive df = security_wise_archive("01-01-2024", "31-03-2024", "HDFCBANK", series="EQ") print(df[["CH_TIMESTAMP", "CH_CLOSING_PRICE", "CH_TOT_TRADED_QTY", "COP_DELIV_QTY"]].head()) ``` -------------------------------- ### Get Corporate Financial Results with nse_results() Source: https://context7.com/aeron7/nsepython/llms.txt Fetches corporate financial results as a pandas DataFrame. Specify 'Quarterly' or 'Annual' for the period. Useful for analyzing company performance. ```python from nsepython import nse_results df = nse_results(index="equities", period="Quarterly") print(df[["symbol", "companyName", "meetingDate", "purpose"]].head()) # Annual results df_annual = nse_results(index="equities", period="Annual") ``` -------------------------------- ### Get India VIX (Volatility Index) Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves the current value of India VIX (Volatility Index) from the live all-indices feed. ```python from nsepython import indiavix vix = indiavix() print(f"India VIX: {vix}") # e.g. 13.45 ``` -------------------------------- ### Get Full Index Information Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves a complete live data dictionary for any specified index by name. Includes details like last traded price, percentage change, high, and low. ```python from nsepython import index_info info = index_info("NIFTY BANK") print(info["last"]) # e.g. 49800.0 print(info["percentChange"]) # e.g. -0.25 print(info["high"]) print(info["low"]) ``` -------------------------------- ### Get Full Equity Quote with nse_eq Source: https://context7.com/aeron7/nsepython/llms.txt Fetches the complete equity quote JSON for a given stock symbol. Automatically detects if the symbol is an index or equity. ```python from nsepython import nse_eq data = nse_eq("RELIANCE") print(data["priceInfo"]["lastPrice"]) # e.g. 2945.5 print(data["priceInfo"]["change"]) # e.g. 12.3 print(data["priceInfo"]["pChange"]) # e.g. 0.42 print(data["metadata"]["companyName"]) # "Reliance Industries Limited" ``` -------------------------------- ### Get Pre-Open Session Data Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves pre-open session data for specified keys like NIFTY, BANKNIFTY, or FO segment. Supports pandas DataFrame or raw JSON output. Displays symbol, prices, and percentage change. ```python from nsepython import nse_preopen # Pre-open for NIFTY constituents df = nse_preopen("NIFTY") print(df[["symbol", "lastPrice", "pChange", "finalPrice"]].head()) # Raw JSON raw = nse_preopen("FO", type="raw") ``` -------------------------------- ### Get Top 5 FNO Losers Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves the top 5 losers from the FNO universe as a pandas DataFrame. Displays symbol, last price, and percentage change. ```python from nsepython import nse_get_top_losers df = nse_get_top_losers() print(df[["symbol", "lastPrice", "pChange"]]) ``` -------------------------------- ### Get Market Holidays Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves trading or clearing holiday data from NSE for the current year. Iterates through the first three F&O holidays to print the date and description. ```python from nsepython import nse_holidays holidays = nse_holidays(type="trading") fo_holidays = holidays["FO"] for h in fo_holidays[:3]: print(h["tradingDate"], "-", h["description"]) # 26-Jan-2024 - Republic Day # 19-Apr-2024 - Good Friday ``` -------------------------------- ### Get Historical Large Deals Source: https://context7.com/aeron7/nsepython/llms.txt Fetches historical bulk, block, or short-selling deals for a specified date range. Displays symbol, client name, buy/sell status, quantity, and trade price. ```python from nsepython import nse_largedeals_historical df = nse_largedeals_historical("01-01-2024", "31-01-2024", mode="bulk_deals") print(df[["symbol", "clientName", "buyOrSell", "quantityTraded", "tradePrice"]].head()) ``` -------------------------------- ### Get Historical Index Total Returns Source: https://context7.com/aeron7/nsepython/llms.txt Fetches Total Return Index (TRI) values, which include price and reinvested dividends, for a NIFTY index over a given date range. ```python from nsepython import index_total_returns df = index_total_returns("NIFTY 50", "01-Jan-2024", "30-Apr-2024") print(df[["HistoricalDate", "totalReturnsIndex"]].head()) ``` -------------------------------- ### Get Full Metadata with nse_quote_meta Source: https://context7.com/aeron7/nsepython/llms.txt Returns the complete metadata dictionary for an equity, future, or specific option contract. Useful for retrieving details like company name, industry, open interest, and implied volatility. ```python from nsepython import nse_quote_meta # Equity metadata meta = nse_quote_meta("WIPRO") print(meta.get("companyName"), meta.get("industry")) # Option contract metadata opt_meta = nse_quote_meta("NIFTY", "latest", "CE", 22500) print(opt_meta.get("openInterest")) # e.g. 845000 print(opt_meta.get("impliedVolatility")) # e.g. 12.5 print(opt_meta.get("lastPrice")) # e.g. 150.25 ``` -------------------------------- ### Get F&O Participant Open Interest Source: https://context7.com/aeron7/nsepython/llms.txt Downloads the NSE F&O participant-wise open interest data as a CSV for a given date. Displays the head of the DataFrame with participant OI details. ```python from nsepython import get_fao_participant_oi df = get_fao_participant_oi("03-05-2024") print(df.head()) # Columns: Client Type, Future Index Long, Future Index Short, # Option Index Call Long, Option Index Put Long, ... ``` -------------------------------- ### Get Live NSE Index Data Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves live data for all NIFTY indices from the niftyindices.com feed. Returns a DataFrame containing index names, last traded price, and percentage change. ```python from nsepython import nse_index df = nse_index() print(df[["indexName", "last", "percentChange"]].head()) # indexName last percentChange # 0 NIFTY 50 22300.50 0.81 # 1 NIFTY NEXT 50 63120.00 0.45 ``` -------------------------------- ### Get FII and DII Trading Activity Source: https://context7.com/aeron7/nsepython/llms.txt Returns today's Foreign Institutional Investor (FII) and Domestic Institutional Investor (DII) net buy/sell data as a DataFrame, including category, buy value, sell value, and net value. ```python from nsepython import nse_fiidii df = nse_fiidii() print(df) # category buyValue sellValue netValue # 0 FII 12345.5 11200.0 1145.5 # 1 DII 8900.0 9200.5 -300.5 ``` -------------------------------- ### Download Daily Bhavcopy with get_bhavcopy() Source: https://context7.com/aeron7/nsepython/llms.txt Downloads end-of-day price and volume data for all securities for a specified date. Returns a pandas DataFrame. ```python from nsepython import get_bhavcopy df = get_bhavcopy("02-05-2024") print(df.columns.tolist()) # ['SYMBOL', 'SERIES', 'DATE1', 'PREV_CLOSE', 'OPEN_PRICE', 'HIGH_PRICE', # 'LOW_PRICE', 'LAST_PRICE', 'CLOSE_PRICE', 'AVG_PRICE', 'TTL_TRD_QNTY', ...] print(df[df["SYMBOL"] == "RELIANCE"]) ``` -------------------------------- ### get_bulkdeals() Source: https://context7.com/aeron7/nsepython/llms.txt Downloads the complete archive of bulk deals from the NSE as a CSV file. Returns a pandas DataFrame. ```APIDOC ## get_bulkdeals() ### Description Downloads the complete bulk deals archive CSV. ### Returns - pandas.DataFrame: A DataFrame containing the full bulk deals archive. ### Example ```python from nsepython import get_bulkdeals df = get_bulkdeals() print(df.columns.tolist()) # ['Date', 'Symbol', 'Security Name', 'Client Name', 'Buy/Sell', 'Quantity Traded', 'Trade Price / Wght Avg Price'] print(df.head()) ``` ``` -------------------------------- ### Get Advances and Declines Data Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves advances and declines data for all Securities in the F&O segment. Can be returned as a pandas DataFrame or a raw dictionary. ```python from nsepython import nse_get_advances_declines df = nse_get_advances_declines() print(df[["symbol", "lastPrice", "change", "pChange"]].head()) ``` -------------------------------- ### nse_largedeals(mode='bulk_deals') Source: https://context7.com/aeron7/nsepython/llms.txt Fetches live intraday data for bulk deals, block deals, or short selling. Returns data as a pandas DataFrame. ```APIDOC ## nse_largedeals(mode="bulk_deals") ### Description Returns intraday bulk deals, block deals, or short selling data as a DataFrame. ### Method `nse_largedeals(mode="bulk_deals")` ### Parameters * **mode** (string) - Optional - Type of deals to fetch ('bulk_deals', 'block_deals', 'short_selling'). Defaults to 'bulk_deals'. ### Response Returns a pandas DataFrame containing deal information. ### Request Example ```python from nsepython import nse_largedeals # Bulk deals bulk = nse_largedeals(mode="bulk_deals") print(bulk.head()) # Block deals block = nse_largedeals(mode="block_deals") print(block.head()) ``` ``` -------------------------------- ### Calculate Stock Beta vs Index with get_beta() Source: https://context7.com/aeron7/nsepython/llms.txt Calculates the beta of a stock relative to a specified index using historical daily returns over a given number of days. Defaults to NIFTY 50 and 365 days. ```python from nsepython import get_beta ``` -------------------------------- ### Calculate Beta of RELIANCE vs NIFTY 50 Source: https://context7.com/aeron7/nsepython/llms.txt Calculates the beta of RELIANCE against NIFTY 50 for a 1-year period. Ensure the 'get_beta' function is available in your environment. ```python beta = get_beta("RELIANCE", days=365, symbol2="NIFTY 50") print(f"RELIANCE Beta: {beta}") # e.g. 1.032 ``` -------------------------------- ### Get Unified Quote with nse_quote Source: https://context7.com/aeron7/nsepython/llms.txt Returns equity data or index derivative data based on the symbol. Accepts an optional `section` parameter for granular data. ```python from nsepython import nse_quote # Equity stock quote eq_data = nse_quote("TCS") # Index derivative data idx_data = nse_quote("NIFTY") # Specific section (trade info with delivery data) trade_data = nse_quote("INFY", section="trade_info") print(trade_data["marketDeptOrderBook"]["tradeInfo"]["totalBuyQuantity"]) ``` -------------------------------- ### nse_preopen(key='NIFTY', type='pandas') Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves pre-open session data for specified market segments like NIFTY, BANKNIFTY, or FO. Supports pandas DataFrame or raw JSON output. ```APIDOC ## nse_preopen(key="NIFTY", type="pandas") ### Description Returns pre-open session data for NIFTY, BANKNIFTY, FO segment, or any other key. ### Method `nse_preopen(key="NIFTY", type="pandas")` ### Parameters * **key** (string) - Optional - The market key to fetch data for (e.g., 'NIFTY', 'BANKNIFTY', 'FO'). Defaults to 'NIFTY'. * **type** (string) - Optional - The output format ('pandas' for DataFrame, 'raw' for JSON). Defaults to 'pandas'. ### Response Returns a pandas DataFrame or raw JSON containing pre-open session data with columns like 'symbol', 'lastPrice', 'pChange', 'finalPrice'. ### Request Example ```python from nsepython import nse_preopen # Pre-open for NIFTY constituents df = nse_preopen("NIFTY") print(df[["symbol", "lastPrice", "pChange", "finalPrice"]].head()) # Raw JSON raw = nse_preopen("FO", type="raw") ``` ``` -------------------------------- ### Download Historical Derivatives Data Source: https://context7.com/aeron7/nsepython/llms.txt Downloads historical derivatives (futures or options) data in 40-day chunks. Requires symbol, date range, instrument type, and expiry date. ```python from nsepython import derivative_history # Historical futures data for NIFTY df = derivative_history( symbol="NIFTY", start_date="01-01-2024", end_date="31-03-2024", instrumentType="futures", expiry_date="28-Mar-2024" ) print(df[["FH_TIMESTAMP", "FH_CLOSE_PRICE", "FH_OPEN_INT"]].head()) ``` -------------------------------- ### Fetch Raw NSE API Response with nsefetch Source: https://context7.com/aeron7/nsepython/llms.txt Use the `nsefetch` function for low-level NSE API requests. It establishes a session, refreshes cookies, and returns parsed JSON. Handles `ValueError` by returning an empty dict. ```python from nsepython import nsefetch # Fetch raw NSE API response for any endpoint data = nsefetch("https://www.nseindia.com/api/allIndices") print(data["data"][0]) # {'key': 'BROAD MARKET INDICES', 'index': 'NIFTY 50', 'indexSymbol': 'NIFTY 50', # 'open': 22100.0, 'high': 22350.0, 'low': 22050.0, 'previousClose': 22120.0, # 'last': 22300.0, 'change': 180.0, 'percentChange': 0.81, ...} ``` -------------------------------- ### get_blockdeals() Source: https://context7.com/aeron7/nsepython/llms.txt Downloads the complete archive of block deals from the NSE as a CSV file. Returns a pandas DataFrame. ```APIDOC ## get_blockdeals() ### Description Downloads the complete block deals archive CSV. ### Returns - pandas.DataFrame: A DataFrame containing the full block deals archive. ### Example ```python from nsepython import get_blockdeals df = get_blockdeals() print(df.head()) ``` ``` -------------------------------- ### Get Last Traded Price with nse_quote_ltp Source: https://context7.com/aeron7/nsepython/llms.txt Returns the Last Traded Price (LTP) for equity, futures, or options. Resolves 'latest' and 'next' expiry keywords automatically. ```python from nsepython import nse_quote_ltp # Equity LTP print(nse_quote_ltp("RELIANCE")) # e.g. 2945.5 # Nearest futures LTP print(nse_quote_ltp("RELIANCE", "latest", "Fut")) # e.g. 2950.0 # Next expiry futures print(nse_quote_ltp("RELIANCE", "next", "Fut")) # e.g. 2955.0 # BANKNIFTY Put option LTP print(nse_quote_ltp("BANKNIFTY", "latest", "PE", 48000)) # e.g. 320.5 # Specific expiry date print(nse_quote_ltp("BANKNIFTY", "19-Jun-2025", "PE", 48000)) ``` -------------------------------- ### Fetch Raw Option Chain Data Source: https://context7.com/aeron7/nsepython/llms.txt Fetches the complete option chain for a given symbol and transforms it into a standardized format. Useful for further analysis of options data. ```python from nsepython import nse_optionchain_scrapper payload = nse_optionchain_scrapper("NIFTY") print(payload["underlyingValue"]) # e.g. 22300.5 print(len(payload["data"])) # number of strike-expiry combinations # First entry entry = payload["data"][0] print(entry["strikePrice"]) print(entry["CE"]["lastPrice"]) # Call LTP print(entry["PE"]["openInterest"]) # Put OI ``` -------------------------------- ### index_pe_pb_div Source: https://context7.com/aeron7/nsepython/llms.txt Returns historical Price-to-Earnings, Price-to-Book, and Dividend Yield ratios for any NIFTY index. ```APIDOC ## index_pe_pb_div(symbol, start_date, end_date) ### Description Returns historical Price-to-Earnings, Price-to-Book, and Dividend Yield ratios for any NIFTY index. ### Parameters #### Path Parameters - **symbol** (string) - Required - The index symbol (e.g., "NIFTY 50"). - **start_date** (string) - Required - The start date for the historical data (format: DD-Mon-YYYY). - **end_date** (string) - Required - The end date for the historical data (format: DD-Mon-YYYY). ### Request Example ```python from nsepython import index_pe_pb_div df = index_pe_pb_div("NIFTY 50", "01-Jan-2023", "31-Dec-2023") print(df.columns.tolist()) print(df.sort_values("HistoricalDate").tail()) ``` ### Response #### Success Response (200) - **DataFrame** - A pandas DataFrame containing historical PE, PB, and Dividend Yield ratios. ``` -------------------------------- ### Calculate Black-Scholes Option Greeks with black_scholes_dexter() Source: https://context7.com/aeron7/nsepython/llms.txt Computes Black-Scholes option premiums and greeks (theta, delta, gamma, vega, rho). Defaults to India VIX for volatility if not provided. Requires spot price, strike price, and days to expiry. ```python from nsepython import black_scholes_dexter # NIFTY CE option: Spot=22300, Strike=22500, DTE=7 days # σ auto-fetched from India VIX call_theta, put_theta, call_premium, put_premium, \ call_delta, put_delta, gamma, vega, call_rho, put_rho = \ black_scholes_dexter(S0=22300, X=22500, t=7) print(f"Call Premium : {call_premium:.2f}") # e.g. 145.30 print(f"Put Premium : {put_premium:.2f}") # e.g. 340.20 print(f"Call Delta : {call_delta:.4f}") # e.g. 0.4123 print(f"Put Delta : {put_delta:.4f}") # e.g. -0.5877 print(f"Gamma : {gamma:.6f}") print(f"Vega : {vega:.4f}") # With explicit volatility and risk-free rate results = black_scholes_dexter(S0=22300, X=22500, t=7, σ=14.5, r=6.5) ``` -------------------------------- ### Get List of FNO-Eligible Symbols Source: https://context7.com/aeron7/nsepython/llms.txt Returns a list of all symbols currently included in the Futures & Options (FNO) segment, including index names. Also provides the total count of such symbols. ```python from nsepython import fnolist symbols = fnolist() print(symbols[:10]) # ['NIFTY', 'FINNIFTY', 'BANKNIFTY', 'RELIANCE', 'TCS', 'INFY', ...] print(len(symbols)) # e.g. 185 ``` -------------------------------- ### Get Quote for a Specific Index Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves the live quote dictionary for a specified index name. Provides details like last traded price, percentage change, high, and low. ```python from nsepython import nse_get_index_quote q = nse_get_index_quote("NIFTY 50") print(q["last"]) # e.g. 22300.5 print(q["percentChange"]) # e.g. 0.81 print(q["high"]) # e.g. 22400.0 print(q["low"]) # e.g. 22100.0 ``` -------------------------------- ### nse_fiidii(mode='pandas') Source: https://context7.com/aeron7/nsepython/llms.txt Fetches today's Foreign Institutional Investor (FII) and Domestic Institutional Investor (DII) net buy/sell data. Returns data as a pandas DataFrame. ```APIDOC ## nse_fiidii(mode="pandas") ### Description Returns today's Foreign Institutional Investor (FII) and Domestic Institutional Investor (DII) net buy/sell data. ### Method `nse_fiidii(mode="pandas")` ### Parameters * **mode** (string) - Optional - Output format ('pandas' for DataFrame). Defaults to 'pandas'. ### Response Returns a pandas DataFrame with columns 'category', 'buyValue', 'sellValue', 'netValue'. ### Request Example ```python from nsepython import nse_fiidii df = nse_fiidii() print(df) # category buyValue sellValue netValue # 0 FII 12345.5 11200.0 1145.5 # 1 DII 8900.0 9200.5 -300.5 ``` ``` -------------------------------- ### Get Historical Expiry Dates Source: https://context7.com/aeron7/nsepython/llms.txt Fetches a list of expiry dates for a specified symbol within a date range. Includes the first expiry after the end date, useful for rolling strategies. ```python from nsepython import expiry_history dates = expiry_history("NIFTY", start_date="01-01-2024", end_date="31-03-2024", type="options") print(dates) # ['25-Jan-2024', '29-Feb-2024', '28-Mar-2024', '25-Apr-2024'] ``` -------------------------------- ### get_beta(symbol, days=365, symbol2="NIFTY 50") Source: https://context7.com/aeron7/nsepython/llms.txt Calculates the beta of a specified stock relative to an index (defaulting to NIFTY 50) using historical daily returns over a given number of days. Returns a float. ```APIDOC ## get_beta(symbol, days=365, symbol2="NIFTY 50") ### Description Calculates the beta of a stock relative to an index using historical daily returns over the specified number of days. ### Parameters - **symbol** (str) - Required - The stock symbol for which to calculate beta. - **days** (int) - Optional - The number of past days to consider for the calculation (default: 365). - **symbol2** (str) - Optional - The index symbol to compare against (default: "NIFTY 50"). ### Returns - float: The calculated beta value of the stock relative to the index. ### Example ```python from nsepython import get_beta # Calculate beta for HDFCBANK against NIFTY 50 over 1 year beta_hdfc = get_beta("HDFCBANK") print(f"Beta of HDFCBANK: {beta_hdfc:.4f}") # Calculate beta for RELIANCE against SENSEX over 6 months beta_reliance_sensex = get_beta("RELIANCE", days=180, symbol2="SENSEX") print(f"Beta of RELIANCE vs SENSEX: {beta_reliance_sensex:.4f}") ``` ``` -------------------------------- ### Get Full Derivatives Quote with nse_fno Source: https://context7.com/aeron7/nsepython/llms.txt Fetches the complete derivatives quote for an FNO-eligible symbol, including all futures and options data. This function returns the full payload from the NSE API. ```python from nsepython import nse_fno data = nse_fno("HDFC") # Returns full payload with futures and options data print(data.keys()) ``` -------------------------------- ### index_info Source: https://context7.com/aeron7/nsepython/llms.txt Returns the full live data dictionary for any index by name. ```APIDOC ## index_info(index) ### Description Returns the complete live data dictionary for any index by name. ### Parameters #### Path Parameters - **index** (string) - Required - The name of the index (e.g., "NIFTY BANK"). ### Request Example ```python from nsepython import index_info info = index_info("NIFTY BANK") print(info["last"]) print(info["percentChange"]) print(info["high"]) print(info["low"]) ``` ### Response #### Success Response (200) - **dict** - A dictionary containing the full live data for the specified index. ``` -------------------------------- ### Get Most Active Stocks Source: https://context7.com/aeron7/nsepython/llms.txt Fetches most actively traded securities, ETFs, or SME stocks. Can be sorted by traded value or volume. Displays symbol, last price, and total turnover for top entries. ```python from nsepython import nse_most_active # Most active by value (default) df = nse_most_active(type="securities", sort="value") print(df[["symbol", "lastPrice", "totalTurnover"]].head()) # Most active ETFs by volume df_etf = nse_most_active(type="etf", sort="volume") ``` -------------------------------- ### nse_get_fno_lot_sizes(symbol="all", mode="list") Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves lot sizes for NSE F&O instruments. Can return all lot sizes as a dictionary, a specific symbol's lot size, or a DataFrame of all lot sizes. ```APIDOC ## nse_get_fno_lot_sizes(symbol="all", mode="list") ### Description Returns the lot sizes for FNO instruments, either as a dict or as a pandas DataFrame. ### Parameters - **symbol** (str) - Optional - The FNO symbol to query (default: "all"). - **mode** (str) - Optional - The output format, "list" for dictionary, "pandas" for DataFrame (default: "list"). ### Returns - dict or pandas.DataFrame: Lot sizes information. ### Example ```python from nsepython import nse_get_fno_lot_sizes # All lot sizes as dict all_lots = nse_get_fno_lot_sizes() print(all_lots["NIFTY"]) # e.g. 50 print(all_lots["RELIANCE"]) # e.g. 250 # Specific symbol lot = nse_get_fno_lot_sizes("BANKNIFTY") print(lot) # e.g. 15 # Full DataFrame df = nse_get_fno_lot_sizes(mode="pandas") print(df.head()) ``` ``` -------------------------------- ### nsefetch(payload) Source: https://context7.com/aeron7/nsepython/llms.txt Low-level NSE API request with session handling. This function establishes a browser-like session against NSEIndia, refreshes cookies, and returns the parsed JSON response. It handles ValueError gracefully by returning an empty dict. ```APIDOC ## nsefetch(payload) — Low-level NSE API request with session handling ### Description The internal HTTP engine that establishes a browser-like session against NSEIndia, refreshes cookies by visiting the homepage and the option-chain page, and returns the parsed JSON response. All higher-level functions delegate to this. Handles `ValueError` gracefully by returning an empty dict. ### Parameters #### Path Parameters - **payload** (string) - Required - The URL endpoint to fetch data from. ### Request Example ```python from nsepython import nsefetch # Fetch raw NSE API response for any endpoint data = nsefetch("https://www.nseindia.com/api/allIndices") print(data["data"][0]) ``` ### Response #### Success Response (200) - **data** (dict) - Parsed JSON response from the NSE API. #### Response Example ```json { "data": [ { "key": "BROAD MARKET INDICES", "index": "NIFTY 50", "indexSymbol": "NIFTY 50", "open": 22100.0, "high": 22350.0, "low": 22050.0, "previousClose": 22120.0, "last": 22300.0, "change": 180.0, "percentChange": 0.81 } ] } ``` ``` -------------------------------- ### get_bhavcopy(date) Source: https://context7.com/aeron7/nsepython/llms.txt Downloads the daily bhavcopy (end-of-day price and volume data for all securities) for a specified date. Returns a pandas DataFrame. ```APIDOC ## get_bhavcopy(date) ### Description Downloads the full-day bhavcopy (EOD price/volume data for all securities) for the given date as a DataFrame. ### Parameters - **date** (str) - Required - The date for which to download the bhavcopy, in DD-MM-YYYY format. ### Returns - pandas.DataFrame: A DataFrame containing the bhavcopy data for the specified date. ### Example ```python from nsepython import get_bhavcopy df = get_bhavcopy("02-05-2024") print(df.columns.tolist()) # ['SYMBOL', 'SERIES', 'DATE1', 'PREV_CLOSE', 'OPEN_PRICE', 'HIGH_PRICE', # 'LOW_PRICE', 'LAST_PRICE', 'CLOSE_PRICE', 'AVG_PRICE', 'TTL_TRD_QNTY', ...] print(df[df["SYMBOL"] == "RELIANCE"]) ``` ``` -------------------------------- ### derivative_history Source: https://context7.com/aeron7/nsepython/llms.txt Downloads historical derivatives (futures or options) data in 40-day chunks. ```APIDOC ## derivative_history(symbol, start_date, end_date, instrumentType, expiry_date, strikePrice="", optionType="") ### Description Downloads historical derivatives (futures or options) data in 40-day chunks. ### Parameters #### Path Parameters - **symbol** (string) - Required - The symbol for the derivative (e.g., "NIFTY"). - **start_date** (string) - Required - The start date in DD-MM-YYYY format. - **end_date** (string) - Required - The end date in DD-MM-YYYY format. - **instrumentType** (string) - Required - Accepts "futures" or "options". - **expiry_date** (string) - Required - The expiry date in DD-Mon-YYYY format (e.g., "28-Mar-2024"). - **strikePrice** (string) - Optional - The strike price for options. Defaults to an empty string. - **optionType** (string) - Optional - The option type ("CE" or "PE") for options. Defaults to an empty string. ### Request Example ```python from nsepython import derivative_history # Historical futures data df = derivative_history( symbol="NIFTY", start_date="01-01-2024", end_date="31-03-2024", instrumentType="futures", expiry_date="28-Mar-2024" ) print(df[["FH_TIMESTAMP", "FH_CLOSE_PRICE", "FH_OPEN_INT"]].head()) ``` ### Response #### Success Response (DataFrame) Returns a pandas DataFrame with historical derivatives data. Columns include: - FH_TIMESTAMP - FH_CLOSE_PRICE - FH_OPEN_INT ... ``` -------------------------------- ### Get Expiry Date and DTE from Payload Source: https://context7.com/aeron7/nsepython/llms.txt Extracts the expiry date and Days-To-Expiry (DTE) for the i-th expiry from an option chain payload, filtering out past dates. Requires an option chain payload. ```python from nsepython import nse_optionchain_scrapper, nse_expirydetails payload = nse_optionchain_scrapper("FINNIFTY") expiry_date, dte = nse_expirydetails(payload, i=0) print(f"Nearest expiry: {expiry_date}, DTE: {dte}") # Nearest expiry: 2025-05-27, DTE: 5 next_expiry_date, next_dte = nse_expirydetails(payload, i=1) print(f"Next expiry: {next_expiry_date}, DTE: {next_dte}") ``` -------------------------------- ### Build Structured OI Chain DataFrame Source: https://context7.com/aeron7/nsepython/llms.txt Builds a formatted Open Interest chain DataFrame for a given symbol and expiry. Returns the DataFrame, underlying spot value, and timestamp. Supports 'full' (with bid/ask) and 'compact' modes. ```python from nsepython import oi_chain_builder # Full mode (includes bid/ask) df, spot, ts = oi_chain_builder("BANKNIFTY", expiry="latest", oi_mode="full") print(f"Spot: {spot}, Timestamp: {ts}") print(df[["Strike Price", "CALLS_OI", "CALLS_LTP", "PUTS_OI", "PUTS_LTP"]].head(10)) # Compact mode df2, spot2, ts2 = oi_chain_builder("NIFTY", oi_mode="compact") print(df2.columns.tolist()) # ['CALLS_OI', 'CALLS_Chng in OI', 'CALLS_Volume', 'CALLS_IV', # 'CALLS_LTP', 'CALLS_Net Chng', 'Strike Price', 'PUTS_OI', ...] ``` -------------------------------- ### Calculate Put-Call Ratio (PCR) Source: https://context7.com/aeron7/nsepython/llms.txt Calculates the Put-Call Ratio (total PE OI / total CE OI) for a given expiry index from an option chain payload. Use `inp=0` for the nearest expiry and `inp=1` for the next. ```python from nsepython import nse_optionchain_scrapper, pcr payload = nse_optionchain_scrapper("NIFTY") pcr_latest = pcr(payload, inp=0) # Nearest expiry pcr_next = pcr(payload, inp=1) # Next expiry print(f"PCR (nearest expiry): {pcr_latest:.2f}") # e.g. 1.23 print(f"PCR (next expiry): {pcr_next:.2f}") # e.g. 0.98 ``` -------------------------------- ### fnolist Source: https://context7.com/aeron7/nsepython/llms.txt Returns a list of all symbols currently in the Futures & Options segment, including index names. ```APIDOC ## fnolist() ### Description Returns a list of all symbols currently in the Futures & Options segment, including index names. ### Method GET ### Endpoint /api/fno-list ### Parameters None ### Request Example ```python from nsepython import fnolist symbols = fnolist() print(symbols[:10]) print(len(symbols)) ``` ### Response #### Success Response (200) - **list** - A list of FNO-eligible symbols. ``` -------------------------------- ### nse_marketStatus() Source: https://context7.com/aeron7/nsepython/llms.txt Retrieves the current live market status (open or closed) for all NSE market segments. Returns data as a dictionary. ```APIDOC ## nse_marketStatus() ### Description Returns the current market status (open/closed) for all segments. ### Method `nse_marketStatus()` ### Parameters None ### Response Returns a dictionary containing the market status for different segments. ### Request Example ```python from nsepython import nse_marketStatus status = nse_marketStatus() print(status) ``` ``` -------------------------------- ### Download Historical Equity Data Source: https://context7.com/aeron7/nsepython/llms.txt Downloads historical OHLCV data for an equity in batches. Merges data into a single DataFrame in reverse-chronological order. ```python from nsepython import equity_history df = equity_history("SBIN", "EQ", "01-01-2024", "30-04-2024") print(df.columns.tolist()) # ['CH_SYMBOL', 'CH_SERIES', 'CH_MARKET_TYPE', 'CH_TRADE_HIGH_PRICE', # 'CH_TRADE_LOW_PRICE', 'CH_OPENING_PRICE', 'CH_CLOSING_PRICE', # 'CH_LAST_TRADED_PRICE', 'CH_PREVIOUS_CLS_PRICE', 'CH_TOT_TRADED_QTY', # 'CH_TOT_TRADED_VAL', 'CH_52WEEK_HIGH_PRICE', 'CH_52WEEK_LOW_PRICE', # 'CH_TOTAL_TRADES', 'CH_ISIN', 'CH_TIMESTAMP', ...] print(df[["CH_TIMESTAMP", "CH_CLOSING_PRICE"]].head()) ``` -------------------------------- ### equity_history Source: https://context7.com/aeron7/nsepython/llms.txt Downloads historical price-volume data for an equity in 40-day batches and merges them into a single DataFrame in reverse-chronological order. ```APIDOC ## equity_history(symbol, series, start_date, end_date) ### Description Downloads historical price-volume data for an equity in 40-day batches (NSE API limit) and merges them into a single DataFrame in reverse-chronological order. ### Parameters #### Path Parameters - **symbol** (string) - Required - The equity symbol (e.g., "SBIN"). - **series** (string) - Required - The series type (e.g., "EQ"). - **start_date** (string) - Required - The start date in DD-MM-YYYY format. - **end_date** (string) - Required - The end date in DD-MM-YYYY format. ### Request Example ```python from nsepython import equity_history df = equity_history("SBIN", "EQ", "01-01-2024", "30-04-2024") print(df.columns.tolist()) print(df[["CH_TIMESTAMP", "CH_CLOSING_PRICE"]].head()) ``` ### Response #### Success Response (DataFrame) Returns a pandas DataFrame with historical OHLCV data. Columns include: - CH_SYMBOL - CH_SERIES - CH_MARKET_TYPE - CH_TRADE_HIGH_PRICE - CH_TRADE_LOW_PRICE - CH_OPENING_PRICE - CH_CLOSING_PRICE - CH_LAST_TRADED_PRICE - CH_PREVIOUS_CLS_PRICE - CH_TOT_TRADED_QTY - CH_TOT_TRADED_VAL - CH_52WEEK_HIGH_PRICE - CH_52WEEK_LOW_PRICE - CH_TOTAL_TRADES - CH_ISIN - CH_TIMESTAMP ... ``` -------------------------------- ### nse_optionchain_scrapper Source: https://context7.com/aeron7/nsepython/llms.txt Fetches the complete option chain for a given symbol (equity or index) and transforms the new NSE API structure into a standardized format. ```APIDOC ## nse_optionchain_scrapper(symbol) ### Description Fetches the complete option chain for a given symbol (equity or index) and transforms the new NSE API structure into a standardized `{strikePrice, expiryDate, CE, PE}` format compatible with all downstream functions. ### Parameters #### Path Parameters - **symbol** (string) - Required - The equity or index symbol (e.g., "NIFTY"). ### Request Example ```python from nsepython import nse_optionchain_scrapper payload = nse_optionchain_scrapper("NIFTY") print(payload["underlyingValue"]) print(len(payload["data"])) entry = payload["data"][0] print(entry["strikePrice"]) print(entry["CE"]["lastPrice"]) print(entry["PE"]["openInterest"]) ``` ### Response #### Success Response (JSON Object) Returns a JSON object containing: - **underlyingValue** (float): The current underlying spot price. - **data** (list): A list of option chain data, where each element contains: - **strikePrice** (float) - **expiryDate** (string) - **CE** (object): Call European details. - **PE** (object): Put European details. ``` -------------------------------- ### get_fao_participant_oi(date) Source: https://context7.com/aeron7/nsepython/llms.txt Downloads the NSE F&O participant-wise open interest data for a specified date. Returns data as a pandas DataFrame. ```APIDOC ## get_fao_participant_oi(date) ### Description Downloads the NSE F&O participant-wise open interest CSV for a given date. ### Method `get_fao_participant_oi(date)` ### Parameters * **date** (string) - Required - The date for which to fetch data (format: 'DD-MM-YYYY'). ### Response Returns a pandas DataFrame containing F&O participant-wise open interest data. ### Request Example ```python from nsepython import get_fao_participant_oi df = get_fao_participant_oi("03-05-2024") print(df.head()) # Columns: Client Type, Future Index Long, Future Index Short, # Option Index Call Long, Option Index Put Long, ... ``` ```