Basic Functions
Let’s explore various functions of NSEPython –
Logger Function
We use Python Logging Function (opens new window). So You can use it to debug your code. Lets add one line to our previous code and enable the logger function and see the output –
Input
from nsepython import *
logging.basicConfig(level=logging.DEBUG)
def nse_custom_function_secfno(symbol,attribute="lastPrice"):
positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
endp = len(positions['data'])
for x in range(0, endp):
if(positions['data'][x]['symbol']==symbol.upper()):
return positions['data'][x][attribute]
print(nse_custom_function_secfno("Reliance"))
print(nse_custom_function_secfno("Reliance","pChange"))
Output
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): www.nseindia.com:443
DEBUG:urllib3.connectionpool:https://www.nseindia.com:443 "GET /api/equity-stockIndices?index=SECURITIES%20IN%20F%26O HTTP/1.1" 401 272
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): nseindia.com:80
DEBUG:urllib3.connectionpool:http://nseindia.com:80 "GET / HTTP/1.1" 301 0
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): www.nseindia.com:80
DEBUG:urllib3.connectionpool:http://www.nseindia.com:80 "GET / HTTP/1.1" 301 0
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): www.nseindia.com:443
DEBUG:urllib3.connectionpool:https://www.nseindia.com:443 "GET / HTTP/1.1" 200 40642
DEBUG:urllib3.connectionpool:https://www.nseindia.com:443 "GET /api/equity-stockIndices?index=SECURITIES%20IN%20F%26O HTTP/1.1" 200 24124
2094.45
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): www.nseindia.com:443
DEBUG:urllib3.connectionpool:https://www.nseindia.com:443 "GET /api/equity-stockIndices?index=SECURITIES%20IN%20F%26O HTTP/1.1" 200 24124
5.99
Getting the FNO List
Input
print(fnolist())
Output
['BANKNIFTY', 'NIFTY', 'FINNIFTY', 'ADANIENT', 'ADANIPOWER', 'AMARAJABAT', 'ACC', 'PVR', 'RAMCOCEM', 'AMBUJACEM', 'APOLLOHOSP', 'ASIANPAINT', 'AUROPHARMA', 'AXISBANK', 'BAJAJ-AUTO', 'BAJAJFINSV', 'BAJFINANCE', 'ADANIPORTS', 'BALKRISIND', 'BHARTIARTL', 'BANDHANBNK', 'BATAINDIA', 'BEL', 'BERGEPAINT', 'BHARATFORG', 'BHEL', 'BOSCHLTD', 'BRITANNIA', 'CANBK', 'CIPLA', 'COALINDIA', 'COLPAL', 'CUMMINSIND', 'DABUR', 'BANKBARODA', 'DIVISLAB', 'DRREDDY', 'EICHERMOT', 'EXIDEIND', 'FEDERALBNK', 'GAIL', 'GLENMARK', 'GRASIM', 'HAVELLS', 'HCLTECH', 'HDFCLIFE', 'HEROMOTOCO', 'HINDALCO', 'HINDPETRO', 'HINDUNILVR', 'ICICIBANK', 'ICICIPRULI', 'INDIGO', 'INDUSINDBK', 'INFY', 'ITC', 'JUBLFOOD', 'JUSTDIAL', 'KOTAKBANK', 'LICHSGFIN', 'LUPIN', 'MANAPPURAM', 'MARICO', 'MARUTI', 'BIOCON', 'CADILAHC', 'MCDOWELL-N', 'MFSL', 'MGL', 'MINDTREE', 'MOTHERSUMI', 'MRF', 'MUTHOOTFIN', 'NATIONALUM', 'NCC', 'NIITTECH', 'NMDC', 'NTPC', 'PEL', 'PETRONET', 'PFC', 'PIDILITIND', 'RBLBANK', 'RECLTD', 'SAIL', 'SBIN', 'SIEMENS', 'SRF', 'SRTRANSFIN', 'SUNTV', 'TATAPOWER', 'TECHM', 'TITAN', 'TORNTPHARM', 'TORNTPOWER', 'TVSMOTOR', 'UJJIVAN', 'ULTRACEMCO', 'UPL', 'VOLTAS', 'ASHOKLEY', 'CONCOR', 'INFRATEL', 'BPCL', 'CHOLAFIN', 'DLF', 'EQUITAS', 'ESCORTS', 'IDEA', 'JSWSTEEL', 'LT', 'GODREJCP', 'GODREJPROP', 'SBILIFE', 'HDFC', 'HDFCBANK', 'IDFCFIRSTB', 'JINDALSTEL', 'M&M', 'M&MFIN', 'UBL', 'NAUKRI', 'NESTLEIND', 'ONGC', 'PAGEIND', 'POWERGRID', 'RELIANCE', 'SHREECEM', 'SUNPHARMA', 'TATAMOTORS', 'TATASTEEL', 'CENTURYTEX', 'VEDL', 'APOLLOTYRE', 'PNB', 'TATACHEM', 'IGL', 'IOC', 'TATACONSUM', 'TCS', 'WIPRO', 'ZEEL', 'L&TFH', 'IBULHSGFIN', 'GMRINFRA']
It will give you the entire list of FNO.
Running Status
This is basically a dumb function but quite handy. You can understand it from the source code –
def running_status():
start_now=datetime.datetime.now().replace(hour=9, minute=15, second=0, microsecond=0)
end_now=datetime.datetime.now().replace(hour=15, minute=30, second=0, microsecond=0)
return start_now
Input
print(running_status())
Output
False
It will give True
if the market is running and False
if the market is not running.
OI Chain Builder Function
Usage
oi_data,ltp,crontime=oi_chain_builder(symbol,expiry,oi_mode,mode)
Inputs
- symbol = FNO Symbol
- expiry(Optional) = “latest” (By default) or, You can choose next expiry by typing the expiry dates like “30-Jul-2020”
- oi_mode(Optional) = “full” (By default) or “compact” (It will fetch all options info).
oi_data, ltp, crontime = oi_chain_builder("RELIANCE","latest","full")
print(oi_data)
print(ltp)
print(crontime)
Output
- oi_data = It will be a Pandas Dataframe.
- ltp = LTP of the symbol
- crontime = Data’s Updation Time as per NSE Server when fetched
CALLS_Chart CALLS_OI ... PUTS_OI PUTS_Chart
0 0.0 4.0 ... 4.0 0.0
1 0.0 0.0 ... 0.0 0.0
2 0.0 0.0 ... 98.0 0.0
3 0.0 0.0 ... 0.0 0.0
4 0.0 0.0 ... 0.0 0.0
.. ... ... ... ... ...
62 0.0 395.0 ... 0.0 0.0
63 0.0 0.0 ... 0.0 0.0
64 0.0 0.0 ... 0.0 0.0
65 0.0 0.0 ... 0.0 0.0
66 0.0 172.0 ... 8.0 0.0
[67 rows x 23 columns]
2094.45
28-May-2021 15:30:00
Getting live Quotes API
There are two types of APIs that fetch live quotes for stock in NSE.
- nseindia.com/api/quote-equity?symbol=BAJAJFINSV(opens new window)
- nseindia.com/api/quote-derivative?symbol=BANKNIFTY(opens new window)
Equity API and Derivatives API will show a huge JSON data which will may the loadtime of this site sensitive.
You can check the section of Parsing the Data with Pandas in the nsefetch() function for reference.
print(nse_eq("JUSTDIAL"))
print(nse_fno("BANKNIFTY"))
- You can also alternatively use
quote_equity()
function instead ofnse_eq()
. - You can also alternatively use
quote_derivative()
function instead ofnse_fno()
.
Note –
nse_eq()
andquote_equity()
will paste the output from the Equity API.quote_derivative()
andnse_fno()
will paste the output from Derivatives API.
Stocks API
To get LTP of any stock, You need to do this –
print(nse_eq("JUSTDIAL")['priceInfo']['lastPrice'])
For Open, High, Low, Clsoe, You need to do this –
print(nse_eq("JUSTDIAL")['priceInfo']['open'])`
print(nse_eq("JUSTDIAL")['priceInfo']['intraDayHighLow']['min'])
print(nse_eq("JUSTDIAL")['priceInfo']['intraDayHighLow']['max'])
print(nse_eq("JUSTDIAL")['priceInfo']['close'])
You can also find things like sector’s PE or sector’s name of which the stock belong –
print(nse_eq("JUSTDIAL")['metadata']['pdSectorPe'])
print(nse_eq("JUSTDIAL")['metadata']['pdSectorInd'])
Derivatives API
To get LTP of any derivative’s underlying, You need to do this –
print(nse_fno("BANKNIFTY")['underlyingValue'])
Quote API
If We see the source code –
def nse_quote(symbol):
symbol = nsesymbolpurify(symbol)
if any(x in symbol for x in fnolist()):
payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
else:
payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
return payload
It actually checks if it is index or non-index and acts as a universal function towards the quote system defined using nse_eq()
and nse_fno()
. It will automatically give the correct scrip info.
Quote API Delivery Details
In the previous iteration of nse_quote() function was not showing the delivery details.
Do note – same can be achievable using Bhavcopy function as shown here NSEPy Functions – Unofficed . But following the request of community, this function is added. Refer – [Feature Request] Nsetools_get_quote is not fetching Delivery data and Delivery %
The Source code is modified to –
def nse_quote(symbol,section=""):
#https://forum.unofficed.com/t/nsetools-get-quote-is-not-fetching-delivery-data-and-delivery-can-you-include-this-as-part-of-feature-request/1115/4
symbol = nsesymbolpurify(symbol)
if(section==""):
if any(x in symbol for x in fnolist()):
payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
else:
payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
return payload
if(section!=""):
payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol+'§ion='+section)
return payload
print(nse_quote("INFY","trade_info"))
{'noBlockDeals': True, 'bulkBlockDeals': [{'name': 'Session I'}, {'name': 'Session II'}], 'marketDeptOrderBook': {'totalBuyQuantity': 0, 'totalSellQuantity': 1060, 'bid': [{'price': 0, 'quantity': 0}, {'price': 0, 'quantity': 0}, {'price': 0, 'quantity': 0}, {'price': 0, 'quantity': 0}, {'price': 0, 'quantity': 0}], 'ask': [{'price': 1227.55, 'quantity': 1060}, {'price': 0, 'quantity': 0}, {'price': 0, 'quantity': 0}, {'price': 0, 'quantity': 0}, {'price': 0, 'quantity': 0}], 'tradeInfo': {'totalTradedVolume': 5680192, 'totalTradedValue': 69680.62, 'totalMarketCap': 50902831.74, 'ffmc': 43796057.9853049, 'impactCost': 0.01}, 'valueAtRisk': {'securityVar': 10.67, 'indexVar': 0, 'varMargin': 10.67, 'extremeLossMargin': 3.5, 'adhocMargin': 0, 'applicableMargin': 14.17}}, 'securityWiseDP': {'quantityTraded': 5680192, 'deliveryQuantity': 3669872, 'deliveryToTradedQuantity': 64.61, 'seriesRemarks': None, 'secWiseDelPosDate': '26-APR-2023 EOD'}}
Quote LTP API
print(nse_quote_ltp("BANKNIFTY"))
It will print the price of the BankNIFTY Index.
print(nse_quote_ltp("BANKNIFTY","latest","Fut"))
print(nse_quote_ltp("RELIANCE","latest","Fut"))
It will print the price of Reliance Futures of the current expiry.
print(nse_quote_ltp("RELIANCE"))
It will print the price of Reliance.
print(nse_quote_ltp("BANKNIFTY","13-Aug-2020","PE",21000))
print(nse_quote_ltp("RELIANCE","latest","PE",2300))
You can also use it in this way to find the option prices of a particular strike price of particular expiry.
TIP
- These APIs show a very detailed level of data.
- You need to explore yourself using the JSON formats.
- If there is any significant stuff, I may create a separate function for it later on.
Update
In the June 7, 2021 Update, The usage of next
variable is also extended –
print(nse_quote_ltp("RELIANCE"))
print(nse_quote_ltp("RELIANCE","latest","Fut"))
print(nse_quote_ltp("RELIANCE","next","Fut"))
print(nse_quote_ltp("BANKNIFTY","latest","PE",32000))
print(nse_quote_ltp("BANKNIFTY","next","PE",32000))
print(nse_quote_ltp("BANKNIFTY","10-Jun-2021","PE",32000))
print(nse_quote_ltp("BANKNIFTY","17-Jun-2021","PE",32000))
print(nse_quote_ltp("RELIANCE","latest","PE",2300))
print(nse_quote_ltp("RELIANCE","next","PE",2300))
Quote Meta API
This nse_quote_meta
will give you all the information along with the LTP.
print(nse_quote_meta("BANKNIFTY","latest","Fut"))
Output
{
"instrumentType":"Index Futures",
"expiryDate":"29-Jul-2021",
"optionType":"-",
"strikePrice":0,
"identifier":"FUTIDXBANKNIFTY29-07-2021XX0.00",
"openPrice":35698.95,
"highPrice":35990,
"lowPrice":35350,
"closePrice":35516.15,
"prevClose":35488.65,
"lastPrice":35543.55,
"change":54.900000000001455,
"pChange":0.15469734689823775,
"numberOfContractsTraded":132482,
"totalTurnover":1176203.35
}
Expiry List Function
Input
print(expiry_list('ACC'))
Output
It will be a Pandas Dataframe.
Date
0 24-Jun-2021
1 29-Jul-2021
Update
Extended the expiry_list()
variable –
print(expiry_list("RELIANCE","list"))
Output
It will output as List
Format.
['24-Jun-2021', '29-Jul-2021', '26-Aug-2021']