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
Transportfor details.The class is usable as a context manager. Using it in a
withblock 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 underdownload_folderto cache the nearest option expiry per symbol foroption_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
NSEFileUnavailableErroron404; 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, aFileCookieStoreis created atdownload_folder / cookie_filename. UseMemoryCookieStorefor multi-process or multi-threaded deployments. DefaultNone.throttle (Optional[pyrate_limiter.Limiter]) – Custom rate limiter. If
None, a default limiter of3 requests per secondshared across API and file downloads is used. DefaultNone.retry_config (Optional[RetryConfig]) – Retry policy configuration. If
None, a defaultRetryConfigis used. DefaultNone.timeout (int) – Network timeout in seconds, applied per request. Default
15.cookie_filename (Optional[str]) – Filename for the default file cookie store when
cookie_storeis not provided. IfNone, defaults to"cookies.txt". DefaultNone.
- Raises:
NotADirectoryError – If
download_folderexists 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
httpxsession. Call this at the end of a script when the client is no longer needed. Not required when using thewithstatement, as__exit__calls this automatically.Calling
exitmore 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.
- 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
datakey 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
datalist is empty, no matches were found for the query.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 asdebt. Defaults to"equity".
- Returns:
A dictionary containing a
datakey 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.
CMkey in the dictionary stands for Capital Markets (Equity Market).- Parameters:
type (str) – One of
tradingorclearing. Defaulttrading.- Returns:
Market holidays for all market segments.
- Return type:
dict[str, list[dict]]
- NSE.block_deals() Dict¶
Return block deals.
- Returns:
Block deals. The
datakey 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:
Bulk deals: https://github.com/BennyThadikaran/NseIndiaApi/blob/main/src/samples/bulk_deals-bulk_deals.json
Block deals: https://github.com/BennyThadikaran/NseIndiaApi/blob/main/src/samples/bulk_deals-block_deals.json
Short selling: https://github.com/BennyThadikaran/NseIndiaApi/blob/main/src/samples/bulk_deals-short_selling.json
- 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
fromdateis later thantodate.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
seriesandmarketTypevalues returned here can be passed directly toquote().- Parameters:
symbol (str) – Equity symbol code.
- Returns:
Stock meta info.
- Return type:
dict
Fetch shareholding pattern data for the given stock
symbol.Returns quarterly shareholding details with the latest quarter first.
- 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 namedate– Shareholding as-on datepr_and_prgrp– Shares held by Promoter and Promoter Grouppublic_val– Shares held by PublicemployeeTrusts– 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
seriesandmarket_typevalues can be obtained fromequity_meta_info().- Parameters:
symbol (str) – Equity symbol code.
series (str) – Any of the NSE equity series, e.g.
EQ,BE,BZ,SM,ST. DefaultEQ.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()forsymbol.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, andvolume.- Return type:
- 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:
- 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, orSZ. DefaultEQ. Referencemarket_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.
- Returns:
A dictionary. The
datakey 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
datalist indatato entries withpChange > 0, sorted descending bypChange.- Parameters:
data (dict) – Output of one of
list_sme()orlist_equity_stocks_by_index().count (int or None) – Optional. Limit the number of results returned.
- 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
datalist indatato entries withpChange < 0, sorted ascending bypChange(largest loss first).- Parameters:
data (dict) – Output of one of
list_sme()orlist_equity_stocks_by_index().count (int or None) – Optional. Limit the number of results returned.
- 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.
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
indexparameter tofetch_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
symbolandseriesbetweenfrom_dateandto_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:
- 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 beforeto_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. Defaulteq.
- Raises:
TypeError – If
from_dateorto_dateis not an instance ofdatetime.date.ValueError – If
from_dateoccurs afterto_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:
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.
- Parameters:
from_date (datetime.date or None) – Start date from which to fetch data. If
None, defaults to 30 days beforeto_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_dateorto_dateis not an instance ofdatetime.date.ValueError – If
from_dateis greater thanto_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:
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.
- Parameters:
symbol (str) – Symbol name.
instrument (str) – Instrument name. one of
futidx,futstk,optidx,optstk,futivx. Defaultfutidx.from_date (datetime.date or None) – Start date from which to fetch data. If
None, defaults to 30 days beforeto_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
yearparameter sent to NSE is derived from this date.option_type (str or None) – Optional filter for option type. Required when
instrumentisoptidxoroptstk. Must beceorpe.strike_price (float or None) – Optional strike price filter.
- Raises:
TypeError – If
from_date,to_date, orexpiryis not an instance ofdatetime.date.ValueError – If
from_dateis greater thanto_date.ValueError – If
instrumentisoptidxoroptstkandoption_typeis 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_dateandto_date(both inclusive) via NSE’s/historicalOR/indicesHistoryendpoint, returned in a flattened, row-based format.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.
- 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 beforeto_date.to_date (datetime.date or None) – End date of the data range. If
None, defaults to today’s date.
- Raises:
TypeError – If
from_dateorto_dateis not an instance ofdatetime.date.ValueError – If
from_dateoccurs afterto_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.
- Returns:
A dictionary with keys
IndexListandUnderlyingList. 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.
- Parameters:
index (str) – Index name. Default
nifty 50.- Returns:
A dictionary. The
datakey 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.
- Returns:
A dictionary. The
datakey 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.
- Returns:
A dictionary. The
datakey 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.
- Returns:
A dictionary. The
datakey 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.
- Returns:
A dictionary. The
datakey 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.
- Returns:
List of current IPOs.
- Return type:
list[dict]
- NSE.list_upcoming_ipo() List[Dict]¶
List upcoming IPOs.
- 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_dateis not provided, it defaults to the current date. Iffrom_dateis not provided, it defaults to 90 days beforeto_date.- 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_dateis earlier thanfrom_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_dateis not provided, it defaults to the current date. Iffrom_dateis not provided, it defaults to 7 days beforeto_date.- 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_dateis earlier thanfrom_date.
Below is the list of
dept_codevalues and their description:CMTR– Capital Market (Equities) TradeCOM– Commodity DerivativesCC– Corporate CommunicationsCRM– CRM & MarketingCD– Currency DerivativesDS– Debt SegmentSME– EmergeSMEITP– Emerge-ITPFAAC– Finance & AccountsFAO– Futures & OptionsINSP– Inspection & ComplianceLEGL– Legal, ISC & ArbitrationCMLS– ListingMA– Market AccessMSD– Member Service DepartmentMEMB– MembershipMF– Mutual FundNWPR– New ProductsNCFM– NSE Academy LimitedCMPT– NSE Clearing - Capital MarketIPO– Primary Market SegmentRDM– Retail Debt MarketSLBS– Securities Lending & Borrowing SchemeSURV– Surveillance & InvestigationTEL– Systems & TelecomUCIBD– UCI Business DevelopmentWDTR– 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. Defaultcm.- 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
dateand 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_folderfrom initialization is used.
- Raises:
ValueError – If
folderis not a directory.NSEFileUnavailableError – If NSE responds with
404. This typically means the report is not yet published fordate(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
dateand 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_folderfrom initialization is used.
- Raises:
ValueError – If
folderis not a directory.NSEFileUnavailableError – If NSE responds with
404. This typically means the report is not yet published fordate.
- 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
dateand 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_folderfrom initialization is used.
- Raises:
ValueError – If
folderis not a directory.NSEFileUnavailableError – If NSE responds with
404. This typically means the report is not yet published fordate.
- 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
dateand return the saved zip file path.The returned file is a zip archive containing a collection of reports, including a
Readme.txtthat 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_folderfrom initialization is used.
- Raises:
ValueError – If
folderis not a directory.NSEFileUnavailableError – If NSE responds with
404. This typically means the report is not yet published fordate.
- 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
dateand 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_folderfrom initialization is used.
- Raises:
ValueError – If
folderis not a directory.NSEFileUnavailableError – If NSE responds with
404. This typically means the report is not yet published fordate.
- 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
dateand 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_folderfrom initialization is used.
- Raises:
ValueError – If
folderis not a directory.NSEFileUnavailableError – If NSE responds with
404. This typically means the report is not yet published fordate.
- 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
dateand return the saved and extracted file path.The downloaded
.gzarchive 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_folderfrom initialization is used.
- Raises:
ValueError – If
folderis not a directory.NSEFileUnavailableError – If NSE responds with
404. This typically means the report is not yet published fordate.
- 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
.zipor.gzarchive, 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.zipfolder (pathlib.Path or str or None) – Folder path to save file. If not specified, uses
download_folderfrom 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.gzarchives.
- Raises:
ValueError – If
folderis not a directory, or ifextract_filesis provided as an empty list.zipfile.BadZipFile – If the downloaded zip is not a valid archive.
KeyError – If a name in
extract_filesis 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
.zipor.gzarchive, otherwise the path to the saved file. For zip archives withextract_filesspecified, 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
symbolis specified, only actions for that symbol are returned. Iffrom_dateandto_dateare both specified, only actions within the date range are returned.- Parameters:
segment (str) – One of
equities,sme,debtormf. Defaultequities.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_dateis greater thanto_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
symbolis specified, only announcements for that symbol are returned. IffnoisTrue, only announcements for FnO securities are returned. Iffrom_dateandto_dateare both specified, only announcements within the date range are returned.- Parameters:
index (str) – One of
equities,sme,debt,mforinvitsreits. Defaultequities.symbol (str or None) – Optional stock symbol to filter announcements.
fno (bool) – If
True, restrict results to FnO stocks. DefaultFalse.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_dateis greater thanto_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
symbolis specified, only board meetings for that symbol are returned. IffnoisTrue, only board meetings for FnO securities are returned. Iffrom_dateandto_dateare both specified, only meetings within the date range are returned.- Parameters:
index (str) – One of
equitiesorsme. Defaultequities.symbol (str or None) – Optional stock symbol to filter board meetings.
fno (bool) – If
True, restrict results to FnO stocks. DefaultFalse.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_dateis greater thanto_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
datakey holding a list of per-year report entries. Each entry includes afileNamepointing to the annual report PDF, which can be downloaded withdownload_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
- Parameters:
symbol (str) – Stock symbol for which annual reports are to be fetched.
segment (str) – One of
equitiesorsme. Defaultequities.
- Returns:
A dictionary with a
datakey 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 — useresults_comparison()for the numeric P&L summary per symbol.If
from_dateandto_dateare omitted, the API returns filings for the current year to date.- Parameters:
segment (str) – One of
equities,sme,debtormf. Defaultequities.period (str) – One of
quarterly,annualorhalf-yearly. Defaultquarterly.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_dateis greater thanto_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
resCmpDatalist — typically the last ~5 quarters — with revenue, net profit and EPS fields. Monetary amounts are in Rupees Lakhs (divide by 100 for Crores).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. Defaultnifty.- Returns:
Sorted list of current, next, and far month expiries, as strings in
DD-Mon-YYYYformat.- 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_dateis not provided, the nearest valid expiry is resolved automatically using the following order:Read a locally cached expiry date from
<self.dir>/.opt-expiry-cache/<symbol>.txt(if available).Validate the cached expiry against the current date.
If missing, unreadable, or expired, fetch expiry dates from NSE’s
option-chain-contract-infoendpoint and select the first (nearest) expiry.Atomically update the local cache with the resolved expiry date.
The final option chain data is fetched from NSE’s
option-chain-v3endpoint.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 usingMemoryCookieStoreand passing explicitexpiry_datevalues 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
expiryDatesfield.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_dateand 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"]whoseexpiryDatesfield matchesexpiry_date(formatted as"%d-%b-%Y") are included. For each retained strike:If a
PEentry is present, itsopenInterest,lastPrice,change,pChangeandimpliedVolatilityare recorded; otherwise the PE side is populated with zeros.If a
CEentry is present, itsopenInterest,lastPrice,change,pChangeandimpliedVolatilityare recorded; otherwise the CE side is populated with zeros.The per-strike PCR is
round(pe_oi / ce_oi, 2)whence_oiis non-zero, otherwiseNone.
The
max_coiandmax_poistrikes reported in the result default to0when no CE or PE data is found. Likewise,coi_totalandpoi_totalremain0in that case, andpcr(overall) isNonewhencoi_totalis0.Max pain is delegated to
max_pain()and receives the raw response plusexpiry_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 includeexpiry,timestamp,underlying,atm,max_pain,max_coi,max_poi,coi_total,poi_total,pcrandchain(a mapping of strike price strings to{"pe": {...}, "ce": {...}, "pcr": ...}).- Return type:
- 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.
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 to5.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-Afterheader. Defaults to8.backoff_factor (float) – Multiplier for the exponential backoff. The wait time is computed as
backoff_factor * 2 ** attempts_made. If set to0.0, exponential backoff is disabled and a uniform wait of1second is used instead. Defaults to1.respect_retry_after_header (bool) – If
True, the value of theRetry-AfterHTTP response header (if present on aRetryableStatusError) is parsed and used as the wait time, capped atmax_backoff_wait. Defaults toTrue.backoff_jitter (float) – Random jitter factor applied to the backoff to avoid thundering herd problems. Must be between
0.0and1.0inclusive. A value of0.0disables jitter. The actual wait is multiplied byrandom.uniform(1 - backoff_jitter, 1). Defaults to1.
- Raises:
ValueError – If
totalis negative.ValueError – If
max_backoff_waitis less than or equal to0.ValueError – If
backoff_factoris negative.ValueError – If
backoff_jitteris not between0.0and1.0inclusive.
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().