Usage

Installation

To use nse, first install it using pip:

$ pip install nse

Example

from nse import NSE
from pathlib import Path

# Working directory
DIR = Path(__file__).parent

nse = NSE(download_folder=DIR)

status = nse.status()

nse.exit() # close requests session
Using ‘with’ statement
with NSE(download_folder=DIR) as nse:
    status = nse.status()

API

class nse.NSE(download_folder: str | Path)

An Unofficial Python API for the NSE India stock exchange.

Methods will raise
  • TimeoutError if request takes too long.

  • ConnectionError if request failed for any reason.

Parameters:

download_folder (pathlib.Path or str) – A folder/dir to save downloaded files and cookie files

Raises:

ValueError – if download_folder is not a folder/dir

General Methods

NSE.exit()

Close the requests session.

Use at the end of script or when class is no longer required.

Not required when using the ``with`` statement.

NSE.status() List[Dict]

Returns market status

Sample response

Returns:

Market status of all NSE market segments

Return type:

list[dict]

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

NSE holiday list

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

Sample response

Parameters:

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

Returns:

Market holidays for all market segments.

Return type:

dict[str, list[dict]]

NSE.blockDeals() Dict

Block deals

Sample response

Returns:

Block deals. data key is a list of all block deal (Empty list if no block deals).

Return type:

dict

Stocks Quotes and Market info

NSE.equityMetaInfo(symbol) Dict

Meta info for equity symbols.

Provides useful info like stock name, code, industry, ISIN code, current status like suspended, delisted etc.

Also has info if stock is an FnO, ETF or Debt security

Sample response

Parameters:

symbol (str) – Equity symbol code

Returns:

Stock meta info

Return type:

dict

NSE.quote(symbol, type: Literal['equity', 'fno'] = 'equity', section: Literal['trade_info'] | None = None) Dict

Price quotes and other data for equity or derivative symbols

Sample response

For Market cap, delivery data and order book, use pass section=’trade_info’ as keyword argument. See sample response below:

Sample response

Parameters:
  • symbol (str) – Equity symbol code

  • type (str) – One of equity or fno. Default equity

  • section – Optional. If specified must be trade_info

Raises:

ValueError – if section does not equal trade_info

Returns:

Price quote and other stock meta info

Return type:

dict

NSE.equityQuote(symbol) Dict[str, str | float]

A convenience method that extracts date and OCHLV data from NSE.quote for given stock symbol

Sample response

Parameters:

symbol (str) – Equity symbol code

Returns:

Date and OCHLV data

Return type:

dict[str, str or float]

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

Top gainers by percent change above zero.

Sample response

Parameters:
  • data (dict) –

    • Output of one of NSE.listIndexStocks, NSE.listSME, NSE.listFnoStocks

  • count (int) – Optional. Limit number of result returned

Returns:

List of top gainers

Return type:

list[dict]

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

Top losers by percent change below zero.

Sample response

Parameters:
  • data (dict) –

    • Output of one of NSE.listIndexStocks, NSE.listSME, NSE.listFnoStocks

  • count (int) – Optional. Limit number of result returned

Returns:

List of top losers

Return type:

list[dict]

NSE.advanceDecline() List[Dict[str, str]]

Advance decline for all Market indices

Sample response

Returns:

Advance decline values for all market indices

Return type:

list[ dict[str, str] ]

List Stocks

NSE.listFnoStocks()

List all Futures and Options (FNO) stocks

Sample response

Returns:

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

NSE.listIndices()

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.

NSE.listIndexStocks(index)

List all stocks by index

Sample response

Parameters:

index (str) – Market Index Name

Returns:

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

NSE.listEtf()

List all etf stocks

Sample response

Returns:

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

NSE.listSme()

List all sme stocks

Sample response

Returns:

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

NSE.listSgb()

List all sovereign gold bonds

Sample response

Returns:

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

List IPOs

NSE.listCurrentIPO() List[Dict]

List current IPOs

Sample response

Returns:

List of Dict containing current IPOs

Return type:

List[Dict]

NSE.listUpcomingIPO() List[Dict]

List upcoming IPOs

Sample response

Returns:

List of Dict containing upcoming IPOs

Return type:

List[Dict]

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

List past IPOs

Sample response

Parameters:
  • from_date (datetime.datetime) – Optional defaults to 90 days from to_date

  • to_date (datetime.datetime) – Optional defaults to current date

Raises:

ValueError – if to_date is less than from_date

Returns:

List of Dict containing past IPOs

Return type:

List[Dict]

NSE Circulars

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

Return exchange circulars and communications by Department

Sample response

Parameters:
  • dept_code – Optional Department code. See table below for options

  • from_date (datetime.datetime) – Optional defaults to 7 days from to_date

  • to_date (datetime.datetime) – Optional defaults to current date

Raises:

ValueError – if to_date is less 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

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.equityBhavcopy(date: datetime, folder: str | Path | None = None) Path

Download the daily Equity bhavcopy report for specified date and return the saved filepath.

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

  • folder (pathlib.Path or str) – Optional folder/dir path to save file. If not specified, use download_folder specified during class initializataion.

Raises:
  • ValueError – if folder is not a folder/dir.

  • FileNotFoundError – if download failed or file corrupted

  • RuntimeError – if report unavailable or not yet updated.

Returns:

Path to saved file

Return type:

pathlib.Path

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

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

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

  • folder (pathlib.Path or str) – Optional folder/dir path to save file. If not specified, use download_folder specified during class initializataion.

Raises:
  • ValueError – if folder is not a folder/dir

  • FileNotFoundError – if download failed or file corrupted

  • RuntimeError – if report unavailable or not yet updated.

Returns:

Path to saved file

Return type:

pathlib.Path

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

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

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

  • folder (pathlib.Path or str) – Optional folder/dir path to save file. If not specified, use download_folder specified during class initializataion.

Raises:
  • ValueError – if folder is not a folder/dir

  • FileNotFoundError – if download failed or file corrupted

  • RuntimeError – if report unavailable or not yet updated.

Returns:

Path to saved file

Return type:

pathlib.Path

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

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

The file returned is a zip file containing a collection of various reports.

It includes a Readme.txt, explaining the contents of each file and the file naming format.

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

  • folder (pathlib.Path or str) – Optional folder path to save file. If not specified, use download_folder specified during class initializataion.

Raises:
  • ValueError – if folder is not a dir/folder

  • FileNotFoundError – if download failed or file corrupted

  • RuntimeError – if report unavailable or not yet updated.

Returns:

Path to 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.fnoBhavcopy(date: datetime, folder: str | Path | None = None) Path

Download the daily Udiff format FnO bhavcopy report for specified date and return the saved file path.

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

  • folder (pathlib.Path or str) – Optional folder path to save file. If not specified, use download_folder specified during class initializataion.

Raises:
  • ValueError – if folder is not a dir/folder

  • FileNotFoundError – if download failed or file corrupted

  • RuntimeError – if report unavailable or not yet updated.

Returns:

Path to saved file

Return type:

pathlib.Path

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

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

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

  • folder (pathlib.Path or str) – Optional folder path to save file. If not specified, use download_folder specified during class initializataion.

Raises:
  • ValueError – if folder is not a dir/folder

  • FileNotFoundError – if download failed or file corrupted

  • RuntimeError – if report unavailable or not yet updated.

Returns:

Path to saved file

Return type:

pathlib.Path

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.

Sample response

If symbol is specified, only actions for the symbol is returned.

If from_data and to_date are specified, actions within the date range are returned

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

  • symbol (str or None) – Optional Stock symbol

  • from_date (datetime.datetime) – Optional from date

  • to_date (datetime.datetime) – Optional to date

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 for current date.

If symbol is specified, only announcements for the symbol is returned.

If from_date and to_date are specified, announcements within the date range are returned

Sample response

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

  • symbol (str or None) – Optional Stock symbol

  • fno (bool) – Only FnO stocks

  • from_date (datetime.datetime) – Optional from date

  • to_date (datetime.datetime) – Optional to date

Raises:

ValueError – if from_date is greater than to_date

Returns:

A list of corporate actions

Return type:

list[dict]

NSE.boardMeetings(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 the symbol is returned.

If from_date and to_date are specified, board 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

  • fno (bool) – Only FnO stocks

  • from_date (datetime.datetime) – Optional from date

  • to_date (datetime.datetime) – Optional to date

Raises:

ValueError – if from_date is greater than to_date

Returns:

A list of corporate board meetings

Return type:

list[dict]

Futures and Options (FnO)

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

Get current, next and far month expiry as a sorted list with order guaranteed.

Its easy to calculate the last thursday of the month. But you need to consider holidays.

This serves as a lightweight lookup option.

Parameters:

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

Returns:

Sorted list of current, next and far month expiry

Return type:

list[str]

NSE.fnoLots() Dict[str, int]

Get the lot size of FnO stocks.

Sample response

Returns:

A dictionary with symbol code as keys and lot sizes for values

Return type:

dict[str, int]

NSE.optionChain(symbol: Literal['banknifty', 'nifty', 'finnifty', 'niftyit'] | str) Dict

Unprocessed option chain from NSE for Index futures or FNO stocks

Sample response

Parameters:

symbol (str) – FnO stock or index futures code. For Index futures, must be one of banknifty, nifty, finnifty, niftyit

Returns:

Option chain for all expiries

Return type:

dict

NSE.compileOptionChain(symbol: str | Literal['banknifty', 'nifty', 'finnifty', 'niftyit'], expiryDate: datetime) Dict[str, str | float | int]

Filter raw option chain by expiryDate 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, Implied Volatility for both Call and Put

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

Sample response

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

  • expiryDate (datetime.datetime) – Option chain Expiry date

Returns:

Option chain filtered by expiryDate

Return type:

dict[str, str | float | int]

static NSE.maxpain(optionChain: Dict, expiryDate: datetime) float

Get the max pain strike price

Parameters:
  • optionChain (dict) – Output of NSE.optionChain

  • expiryDate (datetime.datetime) – Options expiry date

Returns:

max pain strike price

Return type:

float