API

NSE class

class nse.NSE(download_folder: str | Path, use_http2: bool = False, cookie_store: CookieStore | None = None, throttle: Limiter | None = None, retry_config: RetryConfig | None = None, timeout: int = 15, cookie_filename: str | None = None)

An Unofficial Python API for the NSE India stock exchange.

This class is a thin, high-level wrapper over NSE’s public JSON and archive endpoints. Each method maps to a specific NSE page or report and returns the raw parsed JSON (or a downloaded file path) with minimal post-processing, so callers can rely on NSE’s own field names.

All network I/O is delegated to an internal transport layer, which applies request throttling (default: 3 requests/second), automatic retries with exponential backoff, and cookie management. See Transport for details.

The class is usable as a context manager. Using it in a with block is recommended, as it guarantees that session cookies are flushed to the cookie store and the underlying HTTP session is closed:

from nse import NSE

with NSE(download_folder=".") as nse:
    print(nse.status())

If you prefer manual lifecycle management, call exit() when done.

Note

A hidden .opt-expiry-cache/ directory is created under download_folder to cache the nearest option expiry per symbol for option_chain(). It is safe to delete; entries are refetched on demand.

Shared exceptions

Because every method issues its requests through the internal transport, the following exceptions may be raised by any method. They are not repeated in each method’s docstring:

Raises:
  • httpx.TimeoutException – The request exceeded the configured timeout and all retries were exhausted.

  • httpx.ConnectError – A connection to NSE could not be established and all retries were exhausted.

  • httpx.ReadError – The response body could not be read and all retries were exhausted.

  • httpx.RemoteProtocolError – The server violated the HTTP protocol. The session is transparently restarted and the request retried; this exception propagates only if all retries are exhausted.

  • RetryableStatusError – NSE returned a retryable status code (429, 502, 503, 504) and all retries were exhausted.

  • httpx.HTTPStatusError – NSE returned any other non-2xx status code.

Methods that download dated reports may additionally raise NSEFileUnavailableError on 404; this is noted on those methods individually.

__init__(download_folder: str | Path, use_http2: bool = False, cookie_store: CookieStore | None = None, throttle: Limiter | None = None, retry_config: RetryConfig | None = None, timeout: int = 15, cookie_filename: str | None = None)

Initialise the NSE client.

Creates the download directory if it does not exist, sets up the cookie store, rate limiter, and retry configuration, and starts an HTTP session. If the configured cookie store is empty, a network request is made to NSE immediately to fetch initial cookies (this is subject to the retry policy and rate limiter).

Parameters:
  • download_folder (pathlib.Path or str) – Directory for downloaded files and the default cookie file. Created (including parents) if it does not exist.

  • use_http2 (bool) – Enable HTTP/2 for the underlying client. Default False.

  • cookie_store (Optional[CookieStore]) – Custom cookie storage backend. If None, a FileCookieStore is created at download_folder / cookie_filename. Use MemoryCookieStore for multi-process or multi-threaded deployments. Default None.

  • throttle (Optional[pyrate_limiter.Limiter]) – Custom rate limiter. If None, a default limiter of 3 requests per second shared across API and file downloads is used. Default None.

  • retry_config (Optional[RetryConfig]) – Retry policy configuration. If None, a default RetryConfig is used. Default None.

  • timeout (int) – Network timeout in seconds, applied per request. Default 15.

  • cookie_filename (Optional[str]) – Filename for the default file cookie store when cookie_store is not provided. If None, defaults to "cookies.txt". Default None.

Raises:

NotADirectoryError – If download_folder exists but is not a directory.

General Methods

NSE.exit()

Close the underlying HTTP session and persist cookies.

Saves the current session cookies to the configured cookie store, then closes the httpx session. Call this at the end of a script when the client is no longer needed. Not required when using the with statement, as __exit__ calls this automatically.

Calling exit more than once is safe, though subsequent calls operate on an already-closed session.

Returns:

None

Return type:

None

NSE.status() → List[Dict]

Return the current market status for all NSE segments.

Reflects NSE’s live market-state feed and includes segments such as capital market, currency, commodity, and debt. The response changes throughout the trading day as segments open, close, or enter pre-open.

Sample response

Returns:

Market status of all NSE market segments. Each item is a dictionary describing one segment.

Return type:

list[dict]

NSE.lookup(query: str, segment: Literal['all', 'equity', 'derivatives', 'etf', 'others'] = 'equity') → dict

Look up stocks, derivatives, ETFs, or other instruments by company name or symbol.

Returns a dictionary with the data key containing a list of matching results. Each item in the list includes details such as the company name, stock symbol, segment, series, last traded price, change, percentage change, and URLs for the quote page.

If the data list is empty, no matches were found for the query.

Sample response

with NSE("") as nse:
    result = nse.lookup(query="hdfcbank")

    print(result['data'][0]['companyName'])  # HDFC Bank Limited
    print(result['data'][0]['symbol'])       # HDFCBANK
    print(result['data'][0]['segment'])      # in equity
    print(result['data'][0]['series'])       # EQ
Parameters:
  • query (str) – Company name or stock symbol to search for.

  • segment (Literal["all", "equity", "derivatives", "etf", "others"]) – Market segment to search within. One of "all", "equity", "derivatives", "etf", or "others". The "others" segment includes instruments such as debt. Defaults to "equity".

Returns:

A dictionary containing a data key with a list of matching results.

Return type:

dict

NSE.holidays(type: Literal['trading', 'clearing'] = 'trading') → Dict[str, List[Dict]]

Return the NSE holiday list.

CM key in the dictionary stands for Capital Markets (Equity Market).

Sample response

Parameters:

type (str) – One of trading or clearing. Default trading.

Returns:

Market holidays for all market segments.

Return type:

dict[str, list[dict]]

NSE.block_deals() → Dict

Return block deals.

Sample response

Returns:

Block deals. The data key is a list of all block deals (empty list if there are none).

Return type:

dict

NSE.bulk_deals(option_type: Literal['block_deals', 'bulk_deals', 'short_selling'], from_date: datetime, to_date: datetime) → List[Dict]

Retrieve bulk, block, or short-selling deal data for a date range.

Downloads historical deal data based on the selected report type. The requested date range must be valid and must not exceed one year.

Sample responses:

Parameters:
  • option_type (str) – Type of deal report to fetch. Must be one of "bulk_deals", "block_deals", or "short_selling".

  • from_date (datetime.datetime) – Start date of the report (inclusive).

  • to_date (datetime.datetime) – End date of the report (inclusive).

Raises:
  • ValueError – If fromdate is later than todate.

  • ValueError – If the date range exceeds one year.

  • RuntimeError – If no data is available for the specified date range and report type.

Returns:

A list of dictionaries containing deal records for the requested report type.

Return type:

list[dict]

Stocks Quotes and Market info

NSE.equity_meta_info(symbol) → Dict

Return meta info for an equity symbol.

Returns a dictionary containing the symbol, company name, ISIN, market type, available and suspended trading series, and flags indicating whether the security is listed, suspended, delisted, or belongs to categories such as FnO, ETF, SLB, debt, municipal bond, or hybrid symbol.

The series and marketType values returned here can be passed directly to quote().

Sample response

Parameters:

symbol (str) – Equity symbol code.

Returns:

Stock meta info.

Return type:

dict

NSE.shareholding(symbol: str, index: Literal['equities', 'sme'] = 'equities') → List[dict]

Fetch shareholding pattern data for the given stock symbol.

Returns quarterly shareholding details with the latest quarter first.

Sample response

Reference URL:

https://www.nseindia.com/companies-listing/corporate-filings-shareholding-pattern?symbol=HDFCBANK&tabIndex=equity (company listing page)

Parameters:
  • symbol (str) – Stock symbol code.

  • index (str) – Market segment, either "equities" or "sme".

Returns:

List of quarterly shareholding records. Each dictionary contains key fields including:

  • symbol – Stock symbol name

  • date – Shareholding as-on date

  • pr_and_prgrp – Shares held by Promoter and Promoter Group

  • public_val – Shares held by Public

  • employeeTrusts – Shares held by Employee Trusts

The first item in the list corresponds to the most recent quarter.

Return type:

list[dict[str, Any]]

NSE.quote(symbol: str, series: str = 'eq', market_type: str = 'n') → Dict

Return price quotes and other data for an equity symbol.

Returns a dictionary containing the current quote, market depth (order book), OHLC and price statistics, trading metrics, security information, and the last update timestamp.

The series and market_type values can be obtained from equity_meta_info().

Sample response

Parameters:
  • symbol (str) – Equity symbol code.

  • series (str) – Any of the NSE equity series, e.g. EQ, BE, BZ, SM, ST. Default EQ.

  • market_type (str) – Internal NSE market classification. Default N.

Returns:

Price quote and other stock information.

Return type:

dict

NSE.equity_quote(symbol) → OHLCV

Extract date and OHLCV data from quote() for symbol.

A convenience wrapper over quote() that returns the fields typically needed for a daily OHLCV bar.

Parameters:

symbol (str) – Equity symbol code.

Returns:

OHLCV data containing date, open, high, low, close, and volume.

Return type:

OHLCV

NSE.get_detailed_scrip_data(symbol: str, series: Literal['eq', 'be', 'bz', 'sm', 'st', 'sz'] = 'eq', market_type: str = 'n') → Dict

Retrieve detailed symbol data for an equity or SME symbol.

Fetches comprehensive data including order book, metadata, trade information, price information, and security information for the given symbol and series via NSE’s Next API.

Reference URL:

https://www.nseindia.com/get-quotes/equity?symbol=ETERNAL

Sample response:

https://github.com/BennyThadikaran/NseIndiaApi/blob/main/src/samples/get_detailed_scrip_data.json

Parameters:
  • symbol (str) – Exchange-traded symbol for which data is requested (e.g. ETERNAL, HDFCBANK).

  • series (str) – Equity or SME series. Must be one of EQ, BE, BZ, SM, ST, or SZ. Default EQ. Reference

  • market_type (str) – Market type for which data is requested. Default N.

Returns:

A dictionary containing detailed symbol data.

Return type:

dict

NSE.live_volume_gainers() → dict

Get live volume gainers.

Sample response

Returns:

A dictionary. The data key contains a list of stocks with volume surge metrics, price performance, and turnover data.

Return type:

dict

NSE.gainers(data: Dict, count: int | None = None) → List[Dict]

Return top gainers by percent change above zero.

Filters the data list in data to entries with pChange > 0, sorted descending by pChange.

Sample response

Parameters:
Returns:

List of top gainers.

Return type:

list[dict]

NSE.losers(data: Dict, count: int | None = None) → List[Dict]

Return top losers by percent change below zero.

Filters the data list in data to entries with pChange < 0, sorted ascending by pChange (largest loss first).

Sample response

Parameters:
Returns:

List of top losers.

Return type:

list[dict]

NSE.advance_decline(index: str = 'nifty 50') → Dict

Fetch advance-decline data for an NSE index.

Added in version 3.0.0.

Reintroduced using the new NSE API endpoint. Deprecated in v1.0.9 because the original NSE endpoint was no longer active.

Sample response

Example:

advanceDecline()
advanceDecline("NIFTY BANK")
Parameters:

index (str) – NSE index name. Default NIFTY 50.

Returns:

Advance-decline statistics.

Return type:

dict

NSE.fetch_index_names() → Dict[str, List[Tuple[str, str]]]

Return the list of index names.

Returns a dictionary with a list of tuples. Each tuple contains the short index name and the full name of the index. The full name can be passed as the index parameter to fetch_historical_index_data().

Returns:

A dictionary mapping a key to a list of (short_name, full_name) tuples.

Return type:

dict[str, list[tuple[str, str]]]

NSE.fetch_equity_historical_data(symbol: str, from_date: date | None = None, to_date: date | None = None, series: Literal['ae', 'af', 'be', 'bl', 'eq', 'il', 'rl', 'w3', 'gb', 'gs'] = 'eq') → List[Dict]

Retrieve historical daily price and volume data for an equity symbol.

Fetches historical trade data for symbol and series between from_date and to_date (both inclusive). If no dates are provided, data for the last 30 days ending today is returned.

Data is fetched via NSE’s Next API historical trade data endpoint.

Reference URL:

https://www.nseindia.com/get-quote/equity/HDFCBANK/HDFC-Bank-Limited (Historical data section)

The response is a list of rows, where each row is a dictionary with column names as keys and their corresponding values. The trade date is available under the key mTIMESTAMP.

Requests covering more than 100 days are split into chunks and concatenated.

Sample response:

https://github.com/BennyThadikaran/NseIndiaApi/blob/main/src/samples/fetch_equity_historical_data.json

Parameters:
  • symbol (str) – Exchange-traded symbol for which historical data is requested (e.g. HDFCBANK, SGBAPR28I, GOLDBEES).

  • from_date (datetime.date or None) – Start date of the data range. If None, defaults to 30 days before to_date.

  • to_date (datetime.date or None) – End date of the data range. If None, defaults to today’s date.

  • series (str) – Equity series for which historical data is requested. Must be one of ae, af, be, bl, eq, il, rl, w3, gb, gs. Default eq.

Raises:
  • TypeError – If from_date or to_date is not an instance of datetime.date.

  • ValueError – If from_date occurs after to_date.

Returns:

A list of dictionaries, each representing one day of historical trade data. The list is ordered chronologically from oldest to newest.

Return type:

list[dict]

NSE.fetch_historical_vix_data(from_date: date | None = None, to_date: date | None = None) → List[Dict]

Download historical India VIX data within a date range.

Reference URL:

https://www.nseindia.com/reports-indices-historical-vix

Each row is a dictionary with column names as keys and their corresponding values. The date is stored under the key EOD_TIMESTAMP.

Requests spanning more than one year are split into chunks and concatenated.

Sample response

Parameters:
  • from_date (datetime.date or None) – Start date from which to fetch data. If None, defaults to 30 days before to_date.

  • to_date (datetime.date or None) – End date up to which to fetch data. If None, defaults to today’s date.

Raises:
  • TypeError – If from_date or to_date is not an instance of datetime.date.

  • ValueError – If from_date is greater than to_date.

Returns:

A list of rows, each row a dictionary with column names mapped to values. Returned in the order provided by NSE (newest-first).

Return type:

list[dict]

NSE.fetch_historical_fno_data(symbol: str, instrument: Literal['futidx', 'futstk', 'optidx', 'optstk', 'futivx'] = 'futidx', from_date: date | None = None, to_date: date | None = None, expiry: date | None = None, option_type: Literal['ce', 'pe'] | None = None, strike_price: float | None = None) → List[dict]

Download historical futures and options data within a date range.

Reference URL:

https://www.nseindia.com/report-detail/fo_eq_security

Each row is a dictionary with column names as keys and their corresponding values.

Requests spanning more than one year are split into chunks and concatenated.

Sample response

Parameters:
  • symbol (str) – Symbol name.

  • instrument (str) – Instrument name. one of futidx, futstk, optidx, optstk, futivx. Default futidx.

  • from_date (datetime.date or None) – Start date from which to fetch data. If None, defaults to 30 days before to_date.

  • to_date (datetime.date or None) – End date up to which to fetch data. If None, defaults to today’s date.

  • expiry (datetime.date or None) – Optional expiry date of the instrument to filter results. When provided, the year parameter sent to NSE is derived from this date.

  • option_type (str or None) – Optional filter for option type. Required when instrument is optidx or optstk. Must be ce or pe.

  • strike_price (float or None) – Optional strike price filter.

Raises:
  • TypeError – If from_date, to_date, or expiry is not an instance of datetime.date.

  • ValueError – If from_date is greater than to_date.

  • ValueError – If instrument is optidx or optstk and option_type is not specified.

Returns:

A list of rows, each row a dictionary with column names mapped to values. The list is ordered chronologically from oldest to newest.

Return type:

list[dict]

NSE.fetch_historical_index_data(index: str, from_date: date | None = None, to_date: date | None = None) → List[Dict]

Retrieve historical index data for an NSE index within a date range.

Downloads historical index data between from_date and to_date (both inclusive) via NSE’s /historicalOR/indicesHistory endpoint, returned in a flattened, row-based format.

Reference URL:

https://www.nseindia.com/reports-indices-historical-index-data

The returned data is a list of dictionaries, where each dictionary represents a single trading day. Price and turnover values are merged into the same row where available.

Requests spanning more than one year are split into chunks and concatenated.

Sample response

Parameters:
  • index (str) – Name of the index for which historical data is requested.

  • from_date (datetime.date or None) – Start date of the data range. If None, defaults to 30 days before to_date.

  • to_date (datetime.date or None) – End date of the data range. If None, defaults to today’s date.

Raises:
  • TypeError – If from_date or to_date is not an instance of datetime.date.

  • ValueError – If from_date occurs after to_date.

Returns:

A list of dictionaries, each representing one day of historical index data. The list is ordered chronologically from oldest to newest.

Return type:

list[dict]

NSE.fetch_fno_underlying() → Dict[str, List[Dict[str, str]]]

Fetch the indices and stocks for which FnO contracts are available to trade.

Reference URL:

https://www.nseindia.com/market-data/securities-available-for-trading

Returns:

A dictionary with keys IndexList and UnderlyingList. The values are lists of indices and stocks, each with their names and tickers, in alphabetical order for stocks.

Return type:

dict[str, list[dict[str, str]]]

List Stocks

NSE.list_equity_stocks_by_index(index='nifty 50') → dict

List equity stocks by their index name. Defaults to nifty 50.

See list of acceptable values for index argument.

Sample response

Reference Page:

https://www.nseindia.com/market-data/live-equity-market?symbol=NIFTY%2050

Parameters:

index (str) – Index name. Default nifty 50.

Returns:

A dictionary. The data key is a list of all stocks represented by a dictionary with the symbol name and other metadata.

Return type:

dict

NSE.list_indices() → dict

List all indices.

Sample response

Returns:

A dictionary. The data key is a list of all Indices represented by a dictionary with the symbol code and other metadata.

Return type:

dict

NSE.list_etf() → dict

List all ETF stocks.

Sample response

Returns:

A dictionary. The data key is a list of all ETFs represented by a dictionary with the symbol code and other metadata.

Return type:

dict

NSE.list_sme() → dict

List all SME stocks.

Sample response

Returns:

A dictionary. The data key is a list of all SMEs represented by a dictionary with the symbol code and other metadata.

Return type:

dict

NSE.list_sgb() → dict

List all Sovereign Gold Bonds.

Sample response

Returns:

A dictionary. The data key is a list of all SGBs represented by a dictionary with the symbol code and other metadata.

Return type:

dict

List IPOs

NSE.list_current_ipo() → List[Dict]

List current IPOs.

Sample response

Returns:

List of current IPOs.

Return type:

list[dict]

NSE.list_upcoming_ipo() → List[Dict]

List upcoming IPOs.

Sample response

Returns:

List of upcoming IPOs.

Return type:

list[dict]

NSE.list_past_ipo(from_date: datetime | None = None, to_date: datetime | None = None) → List[Dict]

List past IPOs within a date range.

If to_date is not provided, it defaults to the current date. If from_date is not provided, it defaults to 90 days before to_date.

Sample response

Parameters:
  • from_date (datetime.datetime or None) – Optional start date. Defaults to 90 days before to_date.

  • to_date (datetime.datetime or None) – Optional end date. Defaults to the current date.

Raises:

ValueError – If to_date is earlier than from_date.

Returns:

List of past IPOs.

Return type:

list[dict]

NSE Circulars

NSE.circulars(subject: str | None = None, dept_code: str | None = None, from_date: datetime | None = None, to_date: datetime | None = None) → dict

Return exchange circulars and communications by department.

If to_date is not provided, it defaults to the current date. If from_date is not provided, it defaults to 7 days before to_date.

Sample response

Parameters:
  • subject (str or None) – Optional keyword string used to filter circulars based on their subject.

  • dept_code (str or None) – Optional department code. See the list below for accepted values.

  • from_date (datetime.datetime or None) – Optional start date. Defaults to 7 days before to_date.

  • to_date (datetime.datetime or None) – Optional end date. Defaults to the current date.

Raises:

ValueError – If to_date is earlier than from_date.

Below is the list of dept_code values and their description:

  • CMTR – Capital Market (Equities) Trade

  • COM – Commodity Derivatives

  • CC – Corporate Communications

  • CRM – CRM & Marketing

  • CD – Currency Derivatives

  • DS – Debt Segment

  • SME – Emerge

  • SMEITP – Emerge-ITP

  • FAAC – Finance & Accounts

  • FAO – Futures & Options

  • INSP – Inspection & Compliance

  • LEGL – Legal, ISC & Arbitration

  • CMLS – Listing

  • MA – Market Access

  • MSD – Member Service Department

  • MEMB – Membership

  • MF – Mutual Fund

  • NWPR – New Products

  • NCFM – NSE Academy Limited

  • CMPT – NSE Clearing - Capital Market

  • IPO – Primary Market Segment

  • RDM – Retail Debt Market

  • SLBS – Securities Lending & Borrowing Scheme

  • SURV – Surveillance & Investigation

  • TEL – Systems & Telecom

  • UCIBD – UCI Business Development

  • WDTR – Wholesale Debt Market

Returns:

A dictionary of circulars for the requested filters.

Return type:

dict

Download NSE reports

Reports are saved to filesystem and a pathlib.Path object is returned.

By default, all methods save the file to the download_folder specified during initialization. Optionally all methods accept a folder argument if wish to save to another folder.

Zip files are automatically extracted and saved to file.

NSE.fetch_daily_reports_file_metadata(segment: Literal['cm', 'index', 'slbs', 'sme', 'fo', 'com', 'cd', 'nbf', 'wdm', 'cbm', 'tri-party'] = 'cm') → Dict

Return file metadata for daily reports in a given segment.

The returned dictionary contains info about the current day’s and previous day’s reports, useful for checking whether a report is ready and updated before attempting a download.

Parameters:

segment (str) – The market segment to retrieve metadata for. One of cm, index, slbs, sme, fo, com, cd, nbf, wdm, cbm, tri-party. Default cm.

Returns:

A dictionary containing metadata about the daily report files for the specified segment.

Return type:

dict

NSE.equity_bhavcopy(date: datetime, folder: str | Path | None = None) → Path

Download the daily Equity bhavcopy report for date and return the saved file path.

The file format depends on the date:

  • Before 8th July 2024, the legacy bhavcopy format is downloaded, e.g. cm02JAN2023bhav.csv.

  • On or after 8th July 2024, the UDIFF bhavcopy format is used, e.g. BhavCopy_NSE_CM_0_0_0_20250102_F_0000.csv.

The downloaded archive (.zip) is automatically extracted and the archive deleted; the returned path points to the extracted CSV.

Parameters:
  • date (datetime.datetime) – Date of the bhavcopy to download.

  • folder (pathlib.Path or str or None) – Optional folder to save the file in. If not specified, the download_folder from initialization is used.

Raises:
  • ValueError – If folder is not a directory.

  • NSEFileUnavailableError – If NSE responds with 404. This typically means the report is not yet published for date (e.g. a weekend, holiday, or future date), or the archive has not yet been uploaded.

Returns:

Path to the extracted CSV file.

Return type:

pathlib.Path

NSE.delivery_bhavcopy(date: datetime, folder: str | Path | None = None) → Path

Download the daily Equity delivery report for date and return the saved file path.

The delivered file is a plain CSV (no archive extraction is needed).

Parameters:
  • date (datetime.datetime) – Date of the delivery bhavcopy to download.

  • folder (pathlib.Path or str or None) – Optional folder to save the file in. If not specified, the download_folder from initialization is used.

Raises:
  • ValueError – If folder is not a directory.

  • NSEFileUnavailableError – If NSE responds with 404. This typically means the report is not yet published for date.

Returns:

Path to the saved CSV file.

Return type:

pathlib.Path

NSE.indices_bhavcopy(date: datetime, folder: str | Path | None = None) → Path

Download the daily Equity Indices report for date and return the saved file path.

The delivered file is a plain CSV (no archive extraction is needed).

Parameters:
  • date (datetime.datetime) – Date of the Indices bhavcopy to download.

  • folder (pathlib.Path or str or None) – Optional folder to save the file in. If not specified, the download_folder from initialization is used.

Raises:
  • ValueError – If folder is not a directory.

  • NSEFileUnavailableError – If NSE responds with 404. This typically means the report is not yet published for date.

Returns:

Path to the saved CSV file.

Return type:

pathlib.Path

NSE.pr_bhavcopy(date: datetime, folder: str | Path | None = None) → Path

Download the daily PR Bhavcopy zip report for date and return the saved zip file path.

The returned file is a zip archive containing a collection of reports, including a Readme.txt that explains the contents of each file and the file naming format. Unlike other bhavcopy methods, this archive is not extracted.

Parameters:
  • date (datetime.datetime) – Report date to download.

  • folder (pathlib.Path or str or None) – Optional folder to save the file in. If not specified, the download_folder from initialization is used.

Raises:
  • ValueError – If folder is not a directory.

  • NSEFileUnavailableError – If NSE responds with 404. This typically means the report is not yet published for date.

Returns:

Path to the saved zip file.

Return type:

pathlib.Path

from datetime import datetime
from zipfile import ZipFile

import pandas as pd
from nse import NSE

dt = datetime(2024, 9, 15)

with NSE("") as nse:
  # Download the PR bhavcopy zip file
  zipped_file = nse.pr_bhavcopy(dt)

# Extract all files into current folder
with ZipFile(zipped_file) as zip:
  zip.namelist() # get the list of files
  zip.extractall()

# OR Load a file named HL150924.csv from the zipfile into a Pandas DataFrame
with ZipFile(zipped_file) as file:
  with zip.open(f"HL{dt:%d%m%Y}.csv") as f:
      df = pd.read_csv(f, index_col="Symbol")
NSE.fno_bhavcopy(date: datetime, folder: str | Path | None = None) → Path

Download the daily UDIFF-format FnO bhavcopy report for date and return the saved file path.

The downloaded archive (.zip) is automatically extracted and the archive deleted; the returned path points to the extracted CSV.

Parameters:
  • date (datetime.datetime) – Date of the FnO bhavcopy to download.

  • folder (pathlib.Path or str or None) – Optional folder to save the file in. If not specified, the download_folder from initialization is used.

Raises:
  • ValueError – If folder is not a directory.

  • NSEFileUnavailableError – If NSE responds with 404. This typically means the report is not yet published for date.

Returns:

Path to the extracted CSV file.

Return type:

pathlib.Path

NSE.priceband_report(date: datetime, folder: str | Path | None = None) → Path

Download the daily priceband report for date and return the saved file path.

The delivered file is a plain CSV (no archive extraction is needed).

Parameters:
  • date (datetime.datetime) – Report date to download.

  • folder (pathlib.Path or str or None) – Optional folder to save the file in. If not specified, the download_folder from initialization is used.

Raises:
  • ValueError – If folder is not a directory.

  • NSEFileUnavailableError – If NSE responds with 404. This typically means the report is not yet published for date.

Returns:

Path to the saved CSV file.

Return type:

pathlib.Path

NSE.cm_mii_security_report(date: datetime, folder: str | Path | None = None) → Path

Download the daily CM MII security file report for date and return the saved and extracted file path.

The downloaded .gz archive is automatically decompressed and the archive deleted; the returned path points to the resulting CSV.

Parameters:
  • date (datetime.datetime) – Report date to download.

  • folder (pathlib.Path or str or None) – Optional folder to save the file in. If not specified, the download_folder from initialization is used.

Raises:
  • ValueError – If folder is not a directory.

  • NSEFileUnavailableError – If NSE responds with 404. This typically means the report is not yet published for date.

Returns:

Path to the extracted CSV file.

Return type:

pathlib.Path

NSE.download_document(url: str, folder: str | Path | None = None, extract_files: List[str] | None = None) → Path

Download the document from the specified URL and return the saved file path. If the downloaded file is a .zip or .gz archive, extracts its contents to the specified folder and returns the extracted file path.

Parameters:
  • url (str) – URL of the document to download e.g. https://archives.nseindia.com/annual_reports/AR_ULTRACEMCO_2010_2011_08082011052526.zip

  • folder (pathlib.Path or str or None) – Folder path to save file. If not specified, uses download_folder from class initialization.

  • extract_files (List[str] or None) – A list of filenames to be extracted from a zip archive. If None, the first file in the zip will be extracted. Must be non-empty if provided. Ignored for .gz archives.

Raises:
  • ValueError – If folder is not a directory, or if extract_files is provided as an empty list.

  • zipfile.BadZipFile – If the downloaded zip is not a valid archive.

  • KeyError – If a name in extract_files is not present in the zip.

  • OSError – If file I/O fails during download or extraction.

Returns:

Path to the extracted file if the download was a .zip or .gz archive, otherwise the path to the saved file. For zip archives with extract_files specified, the last filepath in the list is returned.

Return type:

pathlib.Path

This method is useful for downloading attachments from announcements, actions etc. See code example below

from nse import NSE

with NSE(download_folder="") as nse:
    announcements = nse.announcements()

    for dct in announcements:
        # Only download the first pdf attachment
        if "attchmntFile" in dct and ".pdf" in dct["attchmntFile"]:
            filepath = nse.download_document(dct["attchmntFile"])
            print(filepath)  # saved file path
            break

The below code to downloads PR290725.zip from NSE daily reports and extract only mcap and etf files.

dt = date(2025, 7, 29)
BHAV_PR_URL = f"https://nsearchives.nseindia.com/archives/equities/bhavcopy/pr/PR{dt:%d%m%y}.zip"

# Specify the file names to extract in a list
file_list = [
  f"mcap{dt:%d%m%Y}.csv",
  f"etf{dt:%d%m%y}.csv",
]

with NSE("") as nse:
    nse.download_document(BHAV_PR_URL, extract_files=file_list)

Corporate Announcements and Actions

NSE.actions(segment: Literal['equities', 'sme', 'debt', 'mf'] = 'equities', symbol: str | None = None, from_date: datetime | None = None, to_date: datetime | None = None) → List[Dict]

Get all forthcoming corporate actions.

If symbol is specified, only actions for that symbol are returned. If from_date and to_date are both specified, only actions within the date range are returned.

Sample response

Parameters:
  • segment (str) – One of equities, sme, debt or mf. Default equities.

  • symbol (str or None) – Optional stock symbol to filter actions.

  • from_date (datetime.datetime or None) – Optional start date of the range.

  • to_date (datetime.datetime or None) – Optional end date of the range.

Raises:

ValueError – If from_date is greater than to_date.

Returns:

A list of corporate actions.

Return type:

list[dict]

NSE.announcements(index: Literal['equities', 'sme', 'debt', 'mf', 'invitsreits'] = 'equities', symbol: str | None = None, fno=False, from_date: datetime | None = None, to_date: datetime | None = None) → List[Dict]

Get all corporate announcements.

If symbol is specified, only announcements for that symbol are returned. If fno is True, only announcements for FnO securities are returned. If from_date and to_date are both specified, only announcements within the date range are returned.

Sample response

Parameters:
  • index (str) – One of equities, sme, debt, mf or invitsreits. Default equities.

  • symbol (str or None) – Optional stock symbol to filter announcements.

  • fno (bool) – If True, restrict results to FnO stocks. Default False.

  • from_date (datetime.datetime or None) – Optional start date of the range.

  • to_date (datetime.datetime or None) – Optional end date of the range.

Raises:

ValueError – If from_date is greater than to_date.

Returns:

A list of corporate announcements.

Return type:

list[dict]

NSE.board_meetings(index: Literal['equities', 'sme'] = 'equities', symbol: str | None = None, fno: bool = False, from_date: datetime | None = None, to_date: datetime | None = None) → List[Dict]

Get all forthcoming board meetings.

If symbol is specified, only board meetings for that symbol are returned. If fno is True, only board meetings for FnO securities are returned. If from_date and to_date are both specified, only meetings within the date range are returned.

Sample response

Parameters:
  • index (str) – One of equities or sme. Default equities.

  • symbol (str or None) – Optional stock symbol to filter board meetings.

  • fno (bool) – If True, restrict results to FnO stocks. Default False.

  • from_date (datetime.datetime or None) – Optional start date of the range.

  • to_date (datetime.datetime or None) – Optional end date of the range.

Raises:

ValueError – If from_date is greater than to_date.

Returns:

A list of corporate board meetings.

Return type:

list[dict]

NSE.annual_reports(symbol: str, segment: Literal['equities', 'sme'] = 'equities') → Dict[str, List[Dict[str, str]]]

Return annual reports for symbol.

The returned dictionary contains a data key holding a list of per-year report entries. Each entry includes a fileName pointing to the annual report PDF, which can be downloaded with download_document().

with NSE("") as nse:
    annual_reports = nse.annual_reports(symbol="HDFCBANK")

    file = nse.download_document(annual_reports["data"][0]["fileName"])

    print(file)  # filepath of downloaded annual report

Sample response

Parameters:
  • symbol (str) – Stock symbol for which annual reports are to be fetched.

  • segment (str) – One of equities or sme. Default equities.

Returns:

A dictionary with a data key holding a list of dictionaries, each containing a link to a yearly annual report.

Return type:

dict[str, list[dict[str, str]]]

NSE.financial_results(segment: Literal['equities', 'sme', 'debt', 'mf'] = 'equities', period: Literal['quarterly', 'annual', 'half-yearly'] = 'quarterly', symbol: str | None = None, from_date: datetime | None = None, to_date: datetime | None = None) → List[Dict]

Get corporate financial-results filings (metadata) for a date range.

Returns one row per filing with broadcast/filing dates, the quarter covered (fromDate / toDate), relatingTo (e.g. “Third Quarter”), consolidated/audited flags, and an optional XBRL link. Revenue and EPS figures are not included here — use results_comparison() for the numeric P&L summary per symbol.

If from_date and to_date are omitted, the API returns filings for the current year to date.

Sample response

Reference URL:

https://www.nseindia.com/companies-listing/corporate-filings-financial-results

Parameters:
  • segment (str) – One of equities, sme, debt or mf. Default equities.

  • period (str) – One of quarterly, annual or half-yearly. Default quarterly.

  • symbol (str or None) – Optional stock symbol to filter filings.

  • from_date (datetime.datetime or None) – Optional start of the broadcast-date window (inclusive).

  • to_date (datetime.datetime or None) – Optional end of the broadcast-date window (inclusive).

Raises:

ValueError – If from_date is greater than to_date.

Returns:

A list of financial-results filing records.

Return type:

list[dict]

NSE.results_comparison(symbol: str) → Dict

Get quarterly financial results comparison (P&L summary) for a symbol.

NSE’s endpoint path is spelled results-comparision (official typo).

The response contains a resCmpData list — typically the last ~5 quarters — with revenue, net profit and EPS fields. Monetary amounts are in Rupees Lakhs (divide by 100 for Crores).

Sample response

Reference URL:

https://www.nseindia.com/companies-listing/corporate-filings-financial-results

with NSE("") as nse:
    data = nse.results_comparison("RELIANCE")
    for row in data["resCmpData"]:
        print(row["re_to_dt"], row.get("re_total_inc"), row.get("re_net_profit"))
Parameters:

symbol (str) – Stock symbol (e.g. RELIANCE, HDFCBANK).

Returns:

Dictionary with resCmpData — list of quarter rows.

Return type:

dict

Futures and Options (FnO)

NSE.get_futures_expiry(index: Literal['nifty', 'banknifty', 'finnifty'] = 'nifty') → List[str]

Return the current, next, and far month expiry dates for an index.

Expiries are returned as a sorted list with order guaranteed, so the first item is the nearest expiry. This is a lightweight lookup that avoids the need to compute the last Thursday of the month and account for exchange holidays.

Parameters:

index (str) – One of nifty, banknifty, finnifty. Default nifty.

Returns:

Sorted list of current, next, and far month expiries, as strings in DD-Mon-YYYY format.

Return type:

list[str]

NSE.fno_lots() → Dict[str, int]

Return the lot size of FnO stocks.

Downloads NSE’s fo_mktlots.csv and parses it into a symbol → lot size mapping. The CSV contains two header rows, which are skipped. Rows where the lot size column is empty or cannot be parsed as an integer are skipped.

Note

A symbol with an empty lot size is omitted from the returned dictionary. This indicates that the symbol has been removed, or is scheduled to be removed, from the FnO segment.

Note

The lot size is extracted from the next-month expiry column rather than the current-month expiry column.

Returns:

A dictionary mapping symbol codes to lot sizes.

Return type:

dict[str, int]

NSE.option_chain(symbol: Literal['banknifty', 'nifty', 'finnifty', 'niftyit'] | str, expiry_date: datetime | None = None) → Dict

Fetch the raw (unprocessed) option chain data for an index or F&O stock.

If expiry_date is not provided, the nearest valid expiry is resolved automatically using the following order:

  1. Read a locally cached expiry date from <self.dir>/.opt-expiry-cache/<symbol>.txt (if available).

  2. Validate the cached expiry against the current date.

  3. If missing, unreadable, or expired, fetch expiry dates from NSE’s option-chain-contract-info endpoint and select the first (nearest) expiry.

  4. Atomically update the local cache with the resolved expiry date.

The final option chain data is fetched from NSE’s option-chain-v3 endpoint.

Note

The cache is written atomically via a temp file and os.replace, so concurrent readers never observe a partially written file. Per-symbol cache files also mean two processes resolving different symbols cannot clobber each other’s entries. However, there is no locking: two processes resolving the same symbol concurrently may both hit NSE and race on the final rename (last writer wins, same value, so harmless). In multi-process deployments, consider using MemoryCookieStore and passing explicit expiry_date values to skip the cache entirely.

Reference sample response: https://github.com/BennyThadikaran/NseIndiaApi/blob/main/src/samples/option_chain.json

Parameters:
  • symbol (str) – FnO stock symbol or index futures identifier. For index futures, must be one of banknifty, nifty, finnifty, niftyit.

  • expiry_date (datetime.datetime or None) – Expiry date of the instrument. If None, the nearest valid expiry is automatically resolved and cached.

Raises:
  • ValueError – If the NSE response does not contain the expiryDates field.

  • ValueError – If NSE returns an empty list of expiry dates.

Returns:

Raw JSON response from NSE containing the option chain for the requested symbol and expiry.

Return type:

dict

NSE.compile_option_chain(symbol: str | Literal['banknifty', 'nifty', 'finnifty', 'niftyit'], expiry_date: datetime) → CompiledOptionChain

Filter raw option chain by expiry_date and calculate various statistics required for analysis. This makes it easy to build an option chain for analysis using a simple loop.

Statistics include:

  • Max pain

  • Strike price with max Call and Put Open Interest

  • Total Call and Put Open Interest

  • Total PCR ratio

  • PCR for every strike price

  • Every strike price has Last price, Open Interest, Change, Percent Change, Implied Volatility for both Call and Put

Other included values: At the Money (ATM) strike price, Underlying strike price, Expiry date.

The ATM strike is derived by computing the strike interval from the first two entries in data["filtered"]["data"] and rounding the underlying value to the nearest multiple of that interval.

Only entries in data["records"]["data"] whose expiryDates field matches expiry_date (formatted as "%d-%b-%Y") are included. For each retained strike:

  • If a PE entry is present, its openInterest, lastPrice, change, pChange and impliedVolatility are recorded; otherwise the PE side is populated with zeros.

  • If a CE entry is present, its openInterest, lastPrice, change, pChange and impliedVolatility are recorded; otherwise the CE side is populated with zeros.

  • The per-strike PCR is round(pe_oi / ce_oi, 2) when ce_oi is non-zero, otherwise None.

The max_coi and max_poi strikes reported in the result default to 0 when no CE or PE data is found. Likewise, coi_total and poi_total remain 0 in that case, and pcr (overall) is None when coi_total is 0.

Max pain is delegated to max_pain() and receives the raw response plus expiry_date.

Parameters:
  • symbol (str) – FnO stock or Index futures symbol code. If Index futures must be one of banknifty, nifty, finnifty, niftyit.

  • expiry_date (datetime.datetime) – Option chain expiry date.

Returns:

Option chain filtered by expiry_date. Keys include expiry, timestamp, underlying, atm, max_pain, max_coi, max_poi, coi_total, poi_total, pcr and chain (a mapping of strike price strings to {"pe": {...}, "ce": {...}, "pcr": ...}).

Return type:

CompiledOptionChain

static NSE.max_pain(option_chain: Dict, expiry_date: datetime) → float

Return the max pain strike price.

Uses prefix sums to pre-compute values and avoid nested loops, giving O(n) performance for the max pain calculation.

See Prefix sum for details.

Note

This method relies on NSE returning strikes in sorted ascending order within the option chain response, and does not sort them itself. If the ordering is ever broken, the computed max pain will be incorrect.

Parameters:
  • option_chain (dict) – Output of option_chain().

  • expiry_date (datetime.datetime) – Options expiry date.

Returns:

Max pain strike price.

Return type:

float

Retry Configuration

class nse.RetryConfig(total: int = 5, max_backoff_wait: float = 8, backoff_factor: float = 1, respect_retry_after_header: bool = True, backoff_jitter: float = 1)

Configuration for the retry behaviour applied by retry().

Parameters:
  • total (int) – Maximum number of retry attempts before giving up. If set to 0, no retries are attempted and the original exception is raised immediately. Defaults to 5.

  • max_backoff_wait (float) – Maximum number of seconds to wait between retries. This caps both the computed exponential backoff and any value derived from the Retry-After header. Defaults to 8.

  • backoff_factor (float) – Multiplier for the exponential backoff. The wait time is computed as backoff_factor * 2 ** attempts_made. If set to 0.0, exponential backoff is disabled and a uniform wait of 1 second is used instead. Defaults to 1.

  • respect_retry_after_header (bool) – If True, the value of the Retry-After HTTP response header (if present on a RetryableStatusError) is parsed and used as the wait time, capped at max_backoff_wait. Defaults to True.

  • backoff_jitter (float) – Random jitter factor applied to the backoff to avoid thundering herd problems. Must be between 0.0 and 1.0 inclusive. A value of 0.0 disables jitter. The actual wait is multiplied by random.uniform(1 - backoff_jitter, 1). Defaults to 1.

Raises:
  • ValueError – If total is negative.

  • ValueError – If max_backoff_wait is less than or equal to 0.

  • ValueError – If backoff_factor is negative.

  • ValueError – If backoff_jitter is not between 0.0 and 1.0 inclusive.

Note

Validation occurs in __post_init__(), so invalid configurations raise immediately upon instantiation.

Type Reference

The library exposes some TypedDict classes that describe the shape of structured return values. They are primarily useful for type checkers and editor autocomplete; at runtime they behave like ordinary dict objects.

OHLCV

Result of NSE.equity_quote().

class nse.NSE.OHLCV

Result of NSE.equity_quote().

close: float
date: str
high: float
low: float
open: float
volume: int

CompiledOptionChain

class nse.NSE.CompiledOptionChain

Result of NSE.compile_option_chain().

atm: float
chain: Dict[str, StrikeRow]
coi_total: int
expiry: str
max_coi: int
max_pain: float
max_poi: int
pcr: float | None
poi_total: int
timestamp: str
underlying: float

StrikeRow

class nse.NSE.StrikeRow

One strike price row in the compiled option chain.

ce: OptionLeg
pcr: float | None
pe: OptionLeg

OptionLeg

class nse.NSE.OptionLeg

A single leg (PE or CE) of an option chain strike row.

chg: float
iv: float
last: float
oi: int
pct_chg: float