nsetools in Python
Python provides a library that enables developers to retrieve real-time information from the National Stock Exchange (India). This library is referred to as nsetools. It can be utilized in various projects that necessitate obtaining live quotations for a specified stock or index, or for generating extensive datasets for subsequent data analysis.
Additionally, we have the capability to develop Command-Line Interface (CLI) Applications that can provide us with real-time market information at remarkable speeds, surpassing the performance of any web browser. The precision of the data is contingent upon the accuracy supplied by the official website of the National Stock Exchange of India Limited.
Features of the Python nsetools library
Some of the key features of the Python nsetools library are stated as follows:
- The nsetools library works out of the box, without any setup requirements.
- This library helps programmers to fetch livestock code and index codes at blazing fast speed.
- It also offers a set of all stocks and indices traded on the National Stock Exchange.
Moreover, it also provides a set of:
- Top losers
- Top gainers
- Most active
Additionally, it provides various useful Application Programming Interfaces (APIs) to verify a stock code and an index code.
- The library can optionally return information in JSON format.
- It boasts complete unit test coverage at one hundred percent.
Installing Python nsetools library
The process of installing the nsetools library is straightforward and does not require any external dependencies. All dependencies needed for the library are included within the standard distribution packages of Python. You can install the nsetools library using the pip installer with the syntax demonstrated below:
Command:
pip install nsetools
Updating the library
For those who have previously installed the nsetools library on their machines, the command below can be used to update the library.
pip install nsetools -upgrade
Python 3 support
Support for Python 3 has been integrated into the library starting from version 1.0.0 and subsequent releases. As a result, this library is now compatible with both Python 2 and Python 3.
Creating an NSE object
An NSE object can be generated by utilizing the Nse function provided by the nsetools library. This process is demonstrated in the example below:
Example:
# importing the Nse() function from the nsetools library
from nsetools import Nse
# creating an NSE object
nse-obj = Nse()
# printing the value of the object
print("NSE Object:", nse-obj)
Output:
NSE Object: Driver Class for National Stock Exchange (NSE)
Explanation:
In the preceding code segment, we have brought in the necessary function from the library. Subsequently, a variable has been established that utilizes the Nse function to instantiate an NSE object. Finally, we have displayed the value of this variable for the users.
Getting Information using the nsetools library
Let us examine an example that illustrates how to utilize nsetools for the purpose of collecting information.
from nsepython import nse-eq
# Get quote for State Bank of India (SBIN)
data = nse-eq("SBIN")
# Print the whole structure (to explore available fields)
print(data)
# Extract useful information
print("Company Name:", data.get("info", {}).get("companyName", "Not Available"))
print("Symbol:", data.get("info", {}).get("symbol", "Not Available"))
print("Last Price:", data.get("priceInfo", {}).get("lastPrice", "Not Available"))
print("Average Price:", data.get("priceInfo", {}).get("averagePrice", "Not Available"))
Output:
{'info': {'symbol': 'SBIN', 'companyName': 'State Bank of India', 'industry': 'Public Sector Bank', 'activeSeries': ['EQ', 'T0'], 'debtSeries': [], 'isFNOSec': True, 'isCASec': False, 'isSLBSec': True, 'isDebtSec': True, 'isSuspended': False, 'tempSuspendedSeries': ['N1', 'N4', 'N3', 'IL', 'N5', 'N6', 'N2'], 'isETFSec': False, 'isDelisted': False, 'isin': 'INE062A01020', 'slb-isin': 'INE062A01020', 'listingDate': '1995-03-01', 'isMunicipalBond': False, 'isHybridSymbol': False, 'isTop10': False, 'identifier': 'SBINEQN'}, 'metadata': {'series': 'EQ', 'symbol': 'SBIN', 'isin': 'INE062A01020', 'status': 'Listed', 'listingDate': '01-Mar-1995', 'industry': 'Public Sector Bank', 'lastUpdateTime': '10-Sep-2025 11:58:56', 'pdSectorPe': 9.22, 'pdSymbolPe': 9.22, 'pdSectorInd': 'NIFTY 50', 'pdSectorIndAll': ['NIFTY 50', 'NIFTY BANK', 'NIFTY FINANCIAL SERVICES', 'NIFTY FINANCIAL SERVICES 25/50', 'NIFTY500 MULTICAP 50:25:25', 'NIFTY TOTAL MARKET', 'NIFTY HOUSING', 'NIFTY200 VALUE 30', 'NIFTY SERVICES SECTOR', 'NIFTY TOP 15 EQUAL WEIGHT', 'NIFTY RURAL', 'NIFTY500 LARGEMIDSMALL EQUAL-CAP WEIGHTED', 'NIFTY DIVIDEND OPPORTUNITIES 50', 'NIFTY TOP 20 EQUAL WEIGHT', 'NIFTY PSU BANK', 'NIFTY500 EQUAL WEIGHT', 'NIFTY 200', 'NIFTY 100', 'NIFTY100 LIQUID 15', 'NIFTY100 ESG', 'NIFTY 500', 'NIFTY INDIA FPI 150', 'NIFTY HIGH BETA 50', 'NIFTY500 LOW VOLATILITY 50', 'NIFTY100 ENHANCED ESG', 'NIFTY500 VALUE 50', 'NIFTY LARGEMIDCAP 250', 'NIFTY100 EQUAL WEIGHT', 'NIFTY50 EQUAL WEIGHT', 'NIFTY50 VALUE 20']}, 'securityInfo': {'boardStatus': 'Main', 'tradingStatus': 'Active', 'tradingSegment': 'Normal Market', 'sessionNo': '-', 'slb': 'Yes', 'classOfShare': 'Equity', 'derivatives': 'Yes', 'surveillance': {'surv': None, 'desc': None}, 'faceValue': 1, 'issuedSize': 9230617586}, 'sddDetails': {'SDDAuditor': '-', 'SDDStatus': '-'}, 'currentMarketType': 'NM', 'priceInfo': {'lastPrice': 821.25, 'change': 12.399999999999977, 'pChange': 1.5330407368486094, 'previousClose': 808.85, 'open': 812, 'close': 0, 'vwap': 818.39, 'stockIndClosePrice': 0, 'lowerCP': '728.00', 'upperCP': '889.70', 'pPriceBand': 'No Band', 'basePrice': 808.85, 'intraDayHighLow': {'min': 810.4, 'max': 824.6, 'value': 821.25}, 'weekHighLow': {'min': 680, 'minDate': '03-Mar-2025', 'max': 875.45, 'maxDate': '06-Dec-2024', 'value': 821.25}, 'iNavValue': None, 'checkINAV': False, 'tickSize': 0.05, 'ieq': ''}, 'industryInfo': {'macro': 'Financial Services', 'sector': 'Financial Services', 'industry': 'Banks', 'basicIndustry': 'Public Sector Bank'}, 'preOpenMarket': {'preopen': [{'price': 810.05, 'buyQty': 350, 'sellQty': 0}, {'price': 810.1, 'buyQty': 1005, 'sellQty': 0}, {'price': 810.55, 'buyQty': 50, 'sellQty': 0}, {'price': 811, 'buyQty': 1000, 'sellQty': 0}, {'price': 811.05, 'buyQty': 50, 'sellQty': 0}, {'price': 812, 'buyQty': 0, 'sellQty': 3258, 'iep': True}, {'price': 812.05, 'buyQty': 0, 'sellQty': 6}, {'price': 812.1, 'buyQty': 0, 'sellQty': 6}, {'price': 812.15, 'buyQty': 0, 'sellQty': 6}, {'price': 812.2, 'buyQty': 0, 'sellQty': 6}], 'ato': {'buy': 0, 'sell': 0}, 'IEP': 812, 'totalTradedVolume': 28875, 'finalPrice': 812, 'finalQuantity': 28875, 'lastUpdateTime': '10-Sep-2025 09:07:48', 'totalBuyQuantity': 78075, 'totalSellQuantity': 195898, 'atoBuyQty': 0, 'atoSellQty': 0, 'Change': 3.15, 'perChange': 0.39, 'prevClose': 808.85}}
Company Name: State Bank of India
Symbol: SBIN
Last Price: 821.25
Average Price: Not Available
Explanation:
In the preceding code snippet, we have included the necessary module and instantiated an NSE object by utilizing the Nse function. Following this, we established an additional variable that employs the get_quote function on the NSE object to retrieve the stock quotation for the designated company. Finally, we have displayed the relevant information for the users.
Python nsetools FAQs
1. What is nsetools in Python?
NSETOOLS is a Python library designed for developers to gather real-time information from the National Stock Exchange of India.
2. How can we install nsetools?
To install the nsetools library in Python, we can utilize the pip command.
pip install nsetools
3. How can we import and initialize nsetools?
To import and set up nsetools in Python, you can follow these steps:
from nsetools import Nse
nse = Nse()
4. How can we get the list of all NSE stock codes?
We can get the list of all NSE stock codes by:
all-codes = nse.get-stock-codes()
print(all-codes)
5. How do we handle errors if a stock code is invalid?
To effectively manage errors arising from an invalid stock code, we can undertake the following actions:
try:
quote = nse.get-quote("INVALID")
print(quote)
except Exception as e:
print("Error:", e)
6. Does nsetools provide historical stock data?
No, the nsetools library does not offer historical stock data. To obtain historical data, we can utilize libraries such as nsepython or download NSE Bhavcopy in CSV format.
7. How can we search for a stock by name?
To locate a stock by its name, we can employ the following code:
search-result = nse.get-stock-codes()
print([code for code, name in search-result.items() if "Reliance" in name])