nsepython 2.94__py3-none-any.whl → 2.97__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nsepython/rahu.py CHANGED
@@ -1,954 +1,966 @@
1
- import os,sys
2
- # os.chdir(os.path.dirname(os.path.abspath(__file__)))
3
- # sys.path.insert(1, os.path.join(sys.path[0], '..'))
4
-
5
- import requests
6
- import pandas as pd
7
- import json
8
- import random
9
- import datetime,time
10
- import logging
11
- import re
12
- import urllib.parse
13
-
14
- mode ='local'
15
-
16
- if(mode=='vpn'):
17
- def nsefetch(payload):
18
- if (("%26" in payload) or ("%20" in payload)):
19
- encoded_url = payload
20
- else:
21
- encoded_url = urllib.parse.quote(payload, safe=':/?&=')
22
- payload_var = 'curl -b cookies.txt "' + encoded_url + '"' + curl_headers + ''
23
- try:
24
- output = os.popen(payload_var).read()
25
- output=json.loads(output)
26
- except ValueError: # includes simplejson.decoder.JSONDecodeError:
27
- payload2 = "https://www.nseindia.com"
28
- output2 = os.popen('curl -c cookies.txt "'+payload2+'"'+curl_headers+'').read()
29
-
30
- output = os.popen(payload_var).read()
31
- output=json.loads(output)
32
- return output
33
- if(mode=='local'):
34
- def nsefetch(payload):
35
- try:
36
- output = requests.get(payload,headers=headers).json()
37
- #print(output)
38
- except ValueError:
39
- s =requests.Session()
40
- output = s.get("http://nseindia.com",headers=headers)
41
- output = s.get(payload,headers=headers).json()
42
- return output
43
-
44
-
45
- # headers = {
46
- # 'Connection': 'keep-alive',
47
- # 'Cache-Control': 'max-age=0',
48
- # 'DNT': '1',
49
- # 'Upgrade-Insecure-Requests': '1',
50
- # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36',
51
- # 'Sec-Fetch-User': '?1',
52
- # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
53
- # 'Sec-Fetch-Site': 'none',
54
- # 'Sec-Fetch-Mode': 'navigate',
55
- # 'Accept-Encoding': 'gzip, deflate, br',
56
- # 'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
57
- # }
58
-
59
- #Rahul_Mittal's entry
60
- headers = {
61
- "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
62
- "accept-language": "en-US,en;q=0.9,en-IN;q=0.8,en-GB;q=0.7",
63
- "cache-control": "max-age=0",
64
- "priority": "u=0, i",
65
- "sec-ch-ua": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
66
- "sec-ch-ua-mobile": "?0",
67
- "sec-ch-ua-platform": '"Windows"',
68
- "sec-fetch-dest": "document",
69
- "sec-fetch-mode": "navigate",
70
- "sec-fetch-site": "none",
71
- "sec-fetch-user": "?1",
72
- "upgrade-insecure-requests": "1",
73
- "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0"
74
- }
75
-
76
-
77
-
78
- #Curl headers
79
- curl_headers = ''' -H "authority: beta.nseindia.com" -H "cache-control: max-age=0" -H "dnt: 1" -H "upgrade-insecure-requests: 1" -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36" -H "sec-fetch-user: ?1" -H "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" -H "sec-fetch-site: none" -H "sec-fetch-mode: navigate" -H "accept-encoding: gzip, deflate, br" -H "accept-language: en-US,en;q=0.9,hi;q=0.8" --compressed'''
80
-
81
- run_time=datetime.datetime.now()
82
-
83
- #Constants
84
- indices = ['NIFTY','FINNIFTY','BANKNIFTY']
85
-
86
- def running_status():
87
- start_now=datetime.datetime.now().replace(hour=9, minute=15, second=0, microsecond=0)
88
- end_now=datetime.datetime.now().replace(hour=15, minute=30, second=0, microsecond=0)
89
- return start_now<datetime.datetime.now()<end_now
90
-
91
- #Getting FNO Symboles
92
- def fnolist():
93
- # df = pd.read_csv("https://www1.nseindia.com/content/fo/fo_mktlots.csv")
94
- # return [x.strip(' ') for x in df.drop(df.index[3]).iloc[:,1].to_list()]
95
-
96
- positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
97
-
98
- nselist=['NIFTY','NIFTYIT','BANKNIFTY']
99
-
100
- i=0
101
- for x in range(i, len(positions['data'])):
102
- nselist=nselist+[positions['data'][x]['symbol']]
103
-
104
- return nselist
105
-
106
- def nsesymbolpurify(symbol):
107
- symbol = symbol.replace('&','%26') #URL Parse for Stocks Like M&M Finance
108
- return symbol
109
-
110
- def nse_optionchain_scrapper(symbol):
111
- symbol = nsesymbolpurify(symbol)
112
- if any(x in symbol for x in indices):
113
- payload = nsefetch('https://www.nseindia.com/api/option-chain-indices?symbol='+symbol)
114
- else:
115
- payload = nsefetch('https://www.nseindia.com/api/option-chain-equities?symbol='+symbol)
116
- return payload
117
-
118
-
119
- def oi_chain_builder(symbol,expiry="latest",oi_mode="full"):
120
-
121
- payload = nse_optionchain_scrapper(symbol)
122
-
123
- if(oi_mode=='compact'):
124
- col_names = ['CALLS_OI','CALLS_Chng in OI','CALLS_Volume','CALLS_IV','CALLS_LTP','CALLS_Net Chng','Strike Price','PUTS_OI','PUTS_Chng in OI','PUTS_Volume','PUTS_IV','PUTS_LTP','PUTS_Net Chng']
125
- if(oi_mode=='full'):
126
- col_names = ['CALLS_Chart','CALLS_OI','CALLS_Chng in OI','CALLS_Volume','CALLS_IV','CALLS_LTP','CALLS_Net Chng','CALLS_Bid Qty','CALLS_Bid Price','CALLS_Ask Price','CALLS_Ask Qty','Strike Price','PUTS_Bid Qty','PUTS_Bid Price','PUTS_Ask Price','PUTS_Ask Qty','PUTS_Net Chng','PUTS_LTP','PUTS_IV','PUTS_Volume','PUTS_Chng in OI','PUTS_OI','PUTS_Chart']
127
- oi_data = pd.DataFrame(columns = col_names)
128
-
129
- #oi_row = {'CALLS_OI':0, 'CALLS_Chng in OI':0, 'CALLS_Volume':0, 'CALLS_IV':0, 'CALLS_LTP':0, 'CALLS_Net Chng':0, 'Strike Price':0, 'PUTS_OI':0, 'PUTS_Chng in OI':0, 'PUTS_Volume':0, 'PUTS_IV':0, 'PUTS_LTP':0, 'PUTS_Net Chng':0}
130
- oi_row = {'CALLS_OI':0, 'CALLS_Chng in OI':0, 'CALLS_Volume':0, 'CALLS_IV':0, 'CALLS_LTP':0, 'CALLS_Net Chng':0, 'CALLS_Bid Qty':0,'CALLS_Bid Price':0,'CALLS_Ask Price':0,'CALLS_Ask Qty':0,'Strike Price':0, 'PUTS_OI':0, 'PUTS_Chng in OI':0, 'PUTS_Volume':0, 'PUTS_IV':0, 'PUTS_LTP':0, 'PUTS_Net Chng':0,'PUTS_Bid Qty':0,'PUTS_Bid Price':0,'PUTS_Ask Price':0,'PUTS_Ask Qty':0}
131
- if(expiry=="latest"):
132
- expiry = payload['records']['expiryDates'][0]
133
- m=0
134
- for m in range(len(payload['records']['data'])):
135
- if(payload['records']['data'][m]['expiryDate']==expiry):
136
- if(1>0):
137
- try:
138
- oi_row['CALLS_OI']=payload['records']['data'][m]['CE']['openInterest']
139
- oi_row['CALLS_Chng in OI']=payload['records']['data'][m]['CE']['changeinOpenInterest']
140
- oi_row['CALLS_Volume']=payload['records']['data'][m]['CE']['totalTradedVolume']
141
- oi_row['CALLS_IV']=payload['records']['data'][m]['CE']['impliedVolatility']
142
- oi_row['CALLS_LTP']=payload['records']['data'][m]['CE']['lastPrice']
143
- oi_row['CALLS_Net Chng']=payload['records']['data'][m]['CE']['change']
144
- if(oi_mode=='full'):
145
- oi_row['CALLS_Bid Qty']=payload['records']['data'][m]['CE']['bidQty']
146
- oi_row['CALLS_Bid Price']=payload['records']['data'][m]['CE']['bidprice']
147
- oi_row['CALLS_Ask Price']=payload['records']['data'][m]['CE']['askPrice']
148
- oi_row['CALLS_Ask Qty']=payload['records']['data'][m]['CE']['askQty']
149
- except KeyError:
150
- oi_row['CALLS_OI'], oi_row['CALLS_Chng in OI'], oi_row['CALLS_Volume'], oi_row['CALLS_IV'], oi_row['CALLS_LTP'],oi_row['CALLS_Net Chng']=0,0,0,0,0,0
151
- if(oi_mode=='full'):
152
- oi_row['CALLS_Bid Qty'],oi_row['CALLS_Bid Price'],oi_row['CALLS_Ask Price'],oi_row['CALLS_Ask Qty']=0,0,0,0
153
- pass
154
-
155
- oi_row['Strike Price']=payload['records']['data'][m]['strikePrice']
156
-
157
- try:
158
- oi_row['PUTS_OI']=payload['records']['data'][m]['PE']['openInterest']
159
- oi_row['PUTS_Chng in OI']=payload['records']['data'][m]['PE']['changeinOpenInterest']
160
- oi_row['PUTS_Volume']=payload['records']['data'][m]['PE']['totalTradedVolume']
161
- oi_row['PUTS_IV']=payload['records']['data'][m]['PE']['impliedVolatility']
162
- oi_row['PUTS_LTP']=payload['records']['data'][m]['PE']['lastPrice']
163
- oi_row['PUTS_Net Chng']=payload['records']['data'][m]['PE']['change']
164
- if(oi_mode=='full'):
165
- oi_row['PUTS_Bid Qty']=payload['records']['data'][m]['PE']['bidQty']
166
- oi_row['PUTS_Bid Price']=payload['records']['data'][m]['PE']['bidprice']
167
- oi_row['PUTS_Ask Price']=payload['records']['data'][m]['PE']['askPrice']
168
- oi_row['PUTS_Ask Qty']=payload['records']['data'][m]['PE']['askQty']
169
- except KeyError:
170
- oi_row['PUTS_OI'], oi_row['PUTS_Chng in OI'], oi_row['PUTS_Volume'], oi_row['PUTS_IV'], oi_row['PUTS_LTP'],oi_row['PUTS_Net Chng']=0,0,0,0,0,0
171
- if(oi_mode=='full'):
172
- oi_row['PUTS_Bid Qty'],oi_row['PUTS_Bid Price'],oi_row['PUTS_Ask Price'],oi_row['PUTS_Ask Qty']=0,0,0,0
173
- else:
174
- logging.info(m)
175
-
176
- if(oi_mode=='full'):
177
- oi_row['CALLS_Chart'],oi_row['PUTS_Chart']=0,0
178
- #oi_data = oi_data.append(oi_row, ignore_index=True)
179
- #oi_data = pd.concat([oi_data, oi_row], ignore_index=True)
180
- oi_data = pd.concat([oi_data, pd.DataFrame([oi_row])], ignore_index=True)
181
-
182
-
183
-
184
- oi_data['time_stamp']=payload['records']['timestamp']
185
- return oi_data,float(payload['records']['underlyingValue']),payload['records']['timestamp']
186
-
187
-
188
- def nse_quote(symbol,section=""):
189
- #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
190
- symbol = nsesymbolpurify(symbol)
191
-
192
- if(section==""):
193
- if any(x in symbol for x in fnolist()):
194
- payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
195
- else:
196
- payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
197
- return payload
198
-
199
- if(section!=""):
200
- payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol+'&section='+section)
201
- return payload
202
-
203
-
204
- def nse_expirydetails(payload,i=0): #Can make problem. Use nse_expirydetails_by_symbol()
205
-
206
- expiry_dates = payload['records']['expiryDates']
207
- expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
208
- expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
209
- currentExpiry=expiry_dates[i]
210
- currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date() # converting json datetime to alice datetime
211
- date_today = run_time.strftime('%Y-%m-%d') # required to remove hh:mm:ss
212
- date_today = datetime.datetime.strptime(date_today,'%Y-%m-%d').date()
213
- dte = (currentExpiry - date_today).days
214
- return currentExpiry,dte
215
-
216
- def pcr(payload,inp='0'):
217
- ce_oi = 0
218
- pe_oi = 0
219
- for i in payload['records']['data']:
220
- if i['expiryDate'] == payload['records']['expiryDates'][inp]:
221
- try:
222
- ce_oi += i['CE']['openInterest']
223
- pe_oi += i['PE']['openInterest']
224
- except KeyError:
225
- pass
226
- return pe_oi / ce_oi
227
-
228
- #forum.unofficed.com/t/unable-to-find-nse-quote-meta-api/702/4
229
- #Refer https://forum.unofficed.com/t/changed-the-nse-quote-ltp-function/1276
230
- def nse_quote_ltp(symbol,expiryDate="latest",optionType="-",strikePrice=0):
231
- payload = nse_quote(symbol)
232
-
233
- meta = "Options"
234
- if(optionType=="Fut"): meta = "Futures"
235
- if(optionType=="PE"):optionType="Put"
236
- if(optionType=="CE"):optionType="Call"
237
-
238
- if(expiryDate=="latest") or (expiryDate=="next"):
239
-
240
- if(meta=="Futures"):
241
- selected_key = next((key for key in payload["expiryDatesByInstrument"] if "futures" in key.lower()), None)
242
- if(meta=="Options"):
243
- selected_key = next((key for key in payload["expiryDatesByInstrument"] if "options" in key.lower()), None)
244
-
245
- expiry_dates=payload["expiryDatesByInstrument"][selected_key]
246
- expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
247
- expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
248
- if(expiryDate=="latest"): expiryDate=expiry_dates[0]
249
- if(expiryDate=="next"): expiryDate=expiry_dates[1]
250
-
251
-
252
- if(optionType!="-"):
253
- for i in payload['stocks']:
254
- if meta in i['metadata']['instrumentType']:
255
- #print(i['metadata'])
256
- if(optionType=="Fut"):
257
- if(i['metadata']['expiryDate']==expiryDate):
258
- lastPrice = i['metadata']['lastPrice']
259
-
260
- if((optionType=="Put")or(optionType=="Call")):
261
- if (i['metadata']["expiryDate"]==expiryDate):
262
- if (i['metadata']["optionType"]==optionType):
263
- if (i['metadata']["strikePrice"]==strikePrice):
264
- #print(i['metadata'])
265
- lastPrice = i['metadata']['lastPrice']
266
-
267
- if(optionType=="-"):
268
- lastPrice = payload['underlyingValue']
269
-
270
- return lastPrice
271
-
272
- # print(nse_quote_ltp("RELIANCE"))
273
- # print(nse_quote_ltp("RELIANCE","latest","Fut"))
274
- # print(nse_quote_ltp("RELIANCE","next","Fut"))
275
- # print(nse_quote_ltp("BANKNIFTY","latest","PE",32000))
276
- # print(nse_quote_ltp("BANKNIFTY","next","PE",32000))
277
- # print(nse_quote_ltp("BANKNIFTY","10-Jun-2021","PE",32000))
278
- # print(nse_quote_ltp("BANKNIFTY","17-Jun-2021","PE",32000))
279
- # print(nse_quote_ltp("RELIANCE","latest","PE",2300))
280
- # print(nse_quote_ltp("RELIANCE","next","PE",2300))
281
-
282
- def nse_quote_meta(symbol,expiryDate="latest",optionType="-",strikePrice=0):
283
- payload = nse_quote(symbol)
284
- #https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists
285
- #https://stackoverflow.com/questions/19199984/sort-a-list-in-python
286
-
287
- #BankNIFTY and NIFTY has weekly options. Using this Jugaad which has primary base of assumption that Reliance will not step out of FNO.
288
- #forum.unofficed.com/t/unable-to-find-nse-quote-meta-api/702/4
289
- if((symbol in indices) and (optionType=="Fut")):
290
- dates = expiry_list("RELIANCE","list")
291
- if(expiryDate=="latest"): expiryDate=dates[0]
292
- if(expiryDate=="next"): expiryDate=dates[1]
293
-
294
- if(expiryDate=="latest") or (expiryDate=="next"):
295
- dates=list(set((payload["expiryDates"])))
296
- dates.sort(key = lambda date: datetime.datetime.strptime(date, '%d-%b-%Y'))
297
- if(expiryDate=="latest"): expiryDate=dates[0]
298
- if(expiryDate=="next"): expiryDate=dates[1]
299
-
300
- meta = "Options"
301
- if(optionType=="Fut"): meta = "Futures"
302
- if(optionType=="PE"):optionType="Put"
303
- if(optionType=="CE"):optionType="Call"
304
-
305
- if(optionType!="-"):
306
- for i in payload['stocks']:
307
- if meta in i['metadata']['instrumentType']:
308
- #print(i['metadata'])
309
- if(optionType=="Fut"):
310
- if(i['metadata']['expiryDate']==expiryDate):
311
- metadata = i['metadata']
312
-
313
- if((optionType=="Put")or(optionType=="Call")):
314
- if (i['metadata']["expiryDate"]==expiryDate):
315
- if (i['metadata']["optionType"]==optionType):
316
- if (i['metadata']["strikePrice"]==strikePrice):
317
- #print(i['metadata'])
318
- metadata = i['metadata']
319
-
320
- if(optionType=="-"):
321
- metadata = i['metadata']
322
-
323
- return metadata
324
-
325
- def nse_optionchain_ltp(payload,strikePrice,optionType,inp=0,intent=""):
326
- expiry_dates = payload['records']['expiryDates']
327
- expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
328
- expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
329
- expiryDate=expiry_dates[inp]
330
- for x in range(len(payload['records']['data'])):
331
- if((payload['records']['data'][x]['strikePrice']==strikePrice) & (payload['records']['data'][x]['expiryDate']==expiryDate)):
332
- if(intent==""): return payload['records']['data'][x][optionType]['lastPrice']
333
- if(intent=="sell"): return payload['records']['data'][x][optionType]['bidprice']
334
- if(intent=="buy"): return payload['records']['data'][x][optionType]['askPrice']
335
-
336
- def nse_eq(symbol):
337
- symbol = nsesymbolpurify(symbol)
338
- try:
339
- payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
340
- try:
341
- if(payload['error']=={}):
342
- print("Please use nse_fno() function to reduce latency.")
343
- payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
344
- except:
345
- pass
346
- except KeyError:
347
- print("Getting Error While Fetching.")
348
- return payload
349
-
350
-
351
- def nse_fno(symbol):
352
- symbol = nsesymbolpurify(symbol)
353
- try:
354
- payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
355
- try:
356
- if(payload['error']=={}):
357
- print("Please use nse_eq() function to reduce latency.")
358
- payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
359
- except KeyError:
360
- pass
361
- except KeyError:
362
- print("Getting Error While Fetching.")
363
- return payload
364
-
365
- def quote_equity(symbol):
366
- return nse_eq(symbol)
367
-
368
- def quote_derivative(symbol):
369
- return nse_fno(symbol)
370
-
371
- def option_chain(symbol):
372
- return nse_optionchain_scrapper(symbol)
373
-
374
- def nse_holidays(type="trading"):
375
- if(type=="clearing"):
376
- payload = nsefetch('https://www.nseindia.com/api/holiday-master?type=clearing')
377
- if(type=="trading"):
378
- payload = nsefetch('https://www.nseindia.com/api/holiday-master?type=trading')
379
- return payload
380
-
381
- def holiday_master(type="trading"):
382
- return nse_holidays(type)
383
-
384
- def nse_results(index="equities",period="Quarterly"):
385
- if(index=="equities") or (index=="debt") or (index=="sme"):
386
- if(period=="Quarterly") or (period=="Annual")or (period=="Half-Yearly")or (period=="Others"):
387
- payload = nsefetch('https://www.nseindia.com/api/corporates-financial-results?index='+index+'&period='+period)
388
- return pd.json_normalize(payload)
389
- else:
390
- print("Give Correct Period Input")
391
- else:
392
- print("Give Correct Index Input")
393
-
394
- def nse_events():
395
- output = nsefetch('https://www.nseindia.com/api/event-calendar')
396
- return pd.json_normalize(output)
397
-
398
- def nse_past_results(symbol):
399
- symbol = nsesymbolpurify(symbol)
400
- return nsefetch('https://www.nseindia.com/api/results-comparision?symbol='+symbol)
401
-
402
- def expiry_list(symbol,type="list"):
403
- logging.info("Getting Expiry List of: "+ symbol)
404
-
405
- if(type!="list"):
406
- payload = nse_optionchain_scrapper(symbol)
407
- payload = pd.DataFrame({'Date':payload['records']['expiryDates']})
408
- return payload
409
-
410
- if(type=="list"):
411
- payload = nse_quote(symbol)
412
- dates=list(set((payload["expiryDates"])))
413
- dates.sort(key = lambda date: datetime.datetime.strptime(date, '%d-%b-%Y'))
414
- return dates
415
-
416
-
417
- def nse_custom_function_secfno(symbol,attribute="lastPrice"):
418
- positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
419
- endp = len(positions['data'])
420
- for x in range(0, endp):
421
- if(positions['data'][x]['symbol']==symbol.upper()):
422
- return positions['data'][x][attribute]
423
-
424
- def nse_blockdeal():
425
- payload = nsefetch('https://nseindia.com/api/block-deal')
426
- return payload
427
-
428
- def nse_marketStatus():
429
- payload = nsefetch('https://nseindia.com/api/marketStatus')
430
- return payload
431
-
432
- def nse_circular(mode="latest"):
433
- if(mode=="latest"):
434
- payload = nsefetch('https://nseindia.com/api/latest-circular')
435
- else:
436
- payload = nsefetch('https://www.nseindia.com/api/circulars')
437
- return payload
438
-
439
- def nse_fiidii(mode="pandas"):
440
- try:
441
- if(mode=="pandas"):
442
- return pd.DataFrame(nsefetch('https://www.nseindia.com/api/fiidiiTradeReact'))
443
- else:
444
- return nsefetch('https://www.nseindia.com/api/fiidiiTradeReact')
445
- except:
446
- logger.info("Pandas is not working for some reason.")
447
- return nsefetch('https://www.nseindia.com/api/fiidiiTradeReact')
448
-
449
- def nsetools_get_quote(symbol):
450
- payload = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
451
- for m in range(len(payload['data'])):
452
- if(payload['data'][m]['symbol']==symbol.upper()):
453
- return payload['data'][m]
454
-
455
-
456
- def nse_index():
457
- payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
458
- payload = pd.DataFrame(payload["data"])
459
- return payload
460
-
461
- def nse_get_index_list():
462
- payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
463
- payload = pd.DataFrame(payload["data"])
464
- return payload["indexName"].tolist()
465
-
466
- def nse_get_index_quote(index):
467
- payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
468
- for m in range(len(payload['data'])):
469
- if(payload['data'][m]["indexName"] == index.upper()):
470
- return payload['data'][m]
471
-
472
- def nse_get_advances_declines(mode="pandas"):
473
- try:
474
- if(mode=="pandas"):
475
- positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
476
- return pd.DataFrame(positions['data'])
477
- else:
478
- return nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
479
- except:
480
- logger.info("Pandas is not working for some reason.")
481
- return nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
482
-
483
- def nse_get_top_losers():
484
- positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
485
- df = pd.DataFrame(positions['data'])
486
- df = df.sort_values(by="pChange")
487
- return df.head(5)
488
-
489
- def nse_get_top_gainers():
490
- positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
491
- df = pd.DataFrame(positions['data'])
492
- df = df.sort_values(by="pChange" , ascending = False)
493
- return df.head(5)
494
-
495
- def nse_get_fno_lot_sizes(symbol="all",mode="list"):
496
- url="https://archives.nseindia.com/content/fo/fo_mktlots.csv"
497
-
498
- if(mode=="list"):
499
- s=requests.get(url).text
500
- res_dict = {}
501
- for line in s.split('\n'):
502
- if line != '' and re.search(',', line) and (line.casefold().find('symbol') == -1):
503
- (code, name) = [x.strip() for x in line.split(',')[1:3]]
504
- res_dict[code] = int(name)
505
- if(symbol=="all"):
506
- return res_dict
507
- if(symbol!=""):
508
- return res_dict[symbol.upper()]
509
-
510
- if(mode=="pandas"):
511
- payload = pd.read_csv(url)
512
- if(symbol=="all"):
513
- return payload
514
- else:
515
- payload = payload[(payload.iloc[:, 1] == symbol.upper())]
516
- return payload
517
-
518
- def whoistheboss():
519
- return "subhash"
520
-
521
- def indiavix():
522
- payload = nsefetch("https://www.nseindia.com/api/allIndices")
523
- for x in range(0, len(payload["data"])):
524
- if(payload["data"][x]["index"]=="INDIA VIX"):
525
- return payload["data"][x]["last"]
526
-
527
- def index_info(index):
528
- payload = nsefetch("https://www.nseindia.com/api/allIndices")
529
- for x in range(0, len(payload["data"])):
530
- if(payload["data"][x]["index"]==index):
531
- return payload["data"][x]
532
-
533
- import math
534
- from scipy.stats import norm
535
-
536
- def black_scholes_dexter(S0,X,t,σ="",r=10,q=0.0,td=365):
537
-
538
- if(σ==""):σ =indiavix()
539
-
540
- S0,X,σ,r,q,t = float(S0),float(X),float(σ/100),float(r/100),float(q/100),float(t/td)
541
- #https://unofficed.com/black-scholes-model-options-calculator-google-sheet/
542
-
543
- d1 = (math.log(S0/X)+(r-q+0.5*σ**2)*t)/(σ*math.sqrt(t))
544
- #stackoverflow.com/questions/34258537/python-typeerror-unsupported-operand-types-for-float-and-int
545
-
546
- #stackoverflow.com/questions/809362/how-to-calculate-cumulative-normal-distribution
547
- Nd1 = (math.exp((-d1**2)/2))/math.sqrt(2*math.pi)
548
- d2 = d1-σ*math.sqrt(t)
549
- Nd2 = norm.cdf(d2)
550
- call_theta =(-((S0*σ*math.exp(-q*t))/(2*math.sqrt(t))*(1/(math.sqrt(2*math.pi)))*math.exp(-(d1*d1)/2))-(r*X*math.exp(-r*t)*norm.cdf(d2))+(q*math.exp(-q*t)*S0*norm.cdf(d1)))/td
551
- put_theta =(-((S0*σ*math.exp(-q*t))/(2*math.sqrt(t))*(1/(math.sqrt(2*math.pi)))*math.exp(-(d1*d1)/2))+(r*X*math.exp(-r*t)*norm.cdf(-d2))-(q*math.exp(-q*t)*S0*norm.cdf(-d1)))/td
552
- call_premium =math.exp(-q*t)*S0*norm.cdf(d1)-X*math.exp(-r*t)*norm.cdf(d1-σ*math.sqrt(t))
553
- put_premium =X*math.exp(-r*t)*norm.cdf(-d2)-math.exp(-q*t)*S0*norm.cdf(-d1)
554
- call_delta =math.exp(-q*t)*norm.cdf(d1)
555
- put_delta =math.exp(-q*t)*(norm.cdf(d1)-1)
556
- gamma =(math.exp(-r*t)/(S0*σ*math.sqrt(t)))*(1/(math.sqrt(2*math.pi)))*math.exp(-(d1*d1)/2)
557
- vega = ((1/100)*S0*math.exp(-r*t)*math.sqrt(t))*(1/(math.sqrt(2*math.pi))*math.exp(-(d1*d1)/2))
558
- call_rho =(1/100)*X*t*math.exp(-r*t)*norm.cdf(d2)
559
- put_rho =(-1/100)*X*t*math.exp(-r*t)*norm.cdf(-d2)
560
-
561
- return call_theta,put_theta,call_premium,put_premium,call_delta,put_delta,gamma,vega,call_rho,put_rho
562
-
563
- def equity_history_virgin(symbol,series,start_date,end_date):
564
- #url="https://www.nseindia.com/api/historical/cm/equity?symbol="+symbol+"&series=[%22"+series+"%22]&from="+str(start_date)+"&to="+str(end_date)+""
565
- url = 'https://www.nseindia.com/api/historical/cm/equity?symbol=' + symbol + '&series=["' + series + '"]&from=' + start_date + '&to=' + end_date
566
-
567
- payload = nsefetch(url)
568
- return pd.DataFrame.from_records(payload["data"])
569
-
570
- # You shall see beautiful use the logger function.
571
- def equity_history(symbol,series,start_date,end_date):
572
- #We are getting the input in text. So it is being converted to Datetime object from String.
573
- start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
574
- end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
575
- logging.info("Starting Date: "+str(start_date))
576
- logging.info("Ending Date: "+str(end_date))
577
-
578
- #We are calculating the difference between the days
579
- diff = end_date-start_date
580
- logging.info("Total Number of Days: "+str(diff.days))
581
- logging.info("Total FOR Loops in the program: "+str(int(diff.days/40)))
582
- logging.info("Remainder Loop: " + str(diff.days-(int(diff.days/40)*40)))
583
-
584
-
585
- total=pd.DataFrame()
586
- for i in range (0,int(diff.days/40)):
587
-
588
- temp_date = (start_date+datetime.timedelta(days=(40))).strftime("%d-%m-%Y")
589
- start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
590
-
591
- logging.info("Loop = "+str(i))
592
- logging.info("====")
593
- logging.info("Starting Date: "+str(start_date))
594
- logging.info("Ending Date: "+str(temp_date))
595
- logging.info("====")
596
-
597
- #total=total.append(equity_history_virgin(symbol,series,start_date,temp_date))
598
- #total=total.concat(equity_history_virgin(symbol,series,start_date,temp_date))
599
- total = pd.concat([total, equity_history_virgin(symbol, series, start_date, temp_date)])
600
-
601
-
602
- logging.info("Length of the Table: "+ str(len(total)))
603
-
604
- #Preparation for the next loop
605
- start_date = datetime.datetime.strptime(temp_date, "%d-%m-%Y")
606
-
607
-
608
- start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
609
- end_date = datetime.datetime.strftime(end_date, "%d-%m-%Y")
610
-
611
- logging.info("End Loop")
612
- logging.info("====")
613
- logging.info("Starting Date: "+str(start_date))
614
- logging.info("Ending Date: "+str(end_date))
615
- logging.info("====")
616
-
617
- #total=total.append(equity_history_virgin(symbol,series,start_date,end_date))
618
- #total=total.concat(equity_history_virgin(symbol,series,start_date,end_date))
619
- total = pd.concat([total, equity_history_virgin(symbol, series, start_date, end_date)])
620
-
621
-
622
- logging.info("Finale")
623
- logging.info("Length of the Total Dataset: "+ str(len(total)))
624
- payload = total.iloc[::-1].reset_index(drop=True)
625
- return payload
626
-
627
- def derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice="",optionType=""):
628
-
629
- instrumentType = instrumentType.lower()
630
-
631
- if(instrumentType=="options"):
632
- instrumentType="OPTSTK"
633
- if("NIFTY" in symbol): instrumentType="OPTIDX"
634
-
635
- if(instrumentType=="futures"):
636
- instrumentType="FUTSTK"
637
- if("NIFTY" in symbol): instrumentType="FUTIDX"
638
-
639
-
640
- #if(((instrumentType=="OPTIDX")or (instrumentType=="OPTSTK")) and (expiry_date!="")):
641
- if(strikePrice!=""):
642
- strikePrice = "%.2f" % strikePrice
643
- strikePrice = str(strikePrice)
644
-
645
- nsefetch_url = "https://www.nseindia.com/api/historical/fo/derivatives?&from="+str(start_date)+"&to="+str(end_date)+"&optionType="+optionType+"&strikePrice="+strikePrice+"&expiryDate="+expiry_date+"&instrumentType="+instrumentType+"&symbol="+symbol+""
646
- payload = nsefetch(nsefetch_url)
647
- logging.info(nsefetch_url)
648
- logging.info(payload)
649
- return pd.DataFrame.from_records(payload["data"])
650
-
651
- def derivative_history(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice="",optionType=""):
652
- #We are getting the input in text. So it is being converted to Datetime object from String.
653
- start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
654
- end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
655
- logging.info("Starting Date: "+str(start_date))
656
- logging.info("Ending Date: "+str(end_date))
657
-
658
- #We are calculating the difference between the days
659
- diff = end_date-start_date
660
- logging.info("Total Number of Days: "+str(diff.days))
661
- logging.info("Total FOR Loops in the program: "+str(int(diff.days/40)))
662
- logging.info("Remainder Loop: " + str(diff.days-(int(diff.days/40)*40)))
663
-
664
-
665
- total=pd.DataFrame()
666
- for i in range (0,int(diff.days/40)):
667
-
668
- temp_date = (start_date+datetime.timedelta(days=(40))).strftime("%d-%m-%Y")
669
- start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
670
-
671
- logging.info("Loop = "+str(i))
672
- logging.info("====")
673
- logging.info("Starting Date: "+str(start_date))
674
- logging.info("Ending Date: "+str(temp_date))
675
- logging.info("====")
676
-
677
- #total=total.append(derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType))
678
- #total=total.concat([total, derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType)])
679
- total = pd.concat([total, derivative_history_virgin(symbol, start_date, temp_date, instrumentType, expiry_date, strikePrice, optionType)])
680
-
681
-
682
- logging.info("Length of the Table: "+ str(len(total)))
683
-
684
- #Preparation for the next loop
685
- start_date = datetime.datetime.strptime(temp_date, "%d-%m-%Y")
686
-
687
-
688
- start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
689
- end_date = datetime.datetime.strftime(end_date, "%d-%m-%Y")
690
-
691
- logging.info("End Loop")
692
- logging.info("====")
693
- logging.info("Starting Date: "+str(start_date))
694
- logging.info("Ending Date: "+str(end_date))
695
- logging.info("====")
696
-
697
- #total=total.append(derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType))
698
- #total = total.concat([total, derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType)])
699
- total = pd.concat([total, derivative_history_virgin(symbol, start_date, end_date, instrumentType, expiry_date, strikePrice, optionType)])
700
-
701
-
702
-
703
- logging.info("Finale")
704
- logging.info("Length of the Total Dataset: "+ str(len(total)))
705
- payload = total.iloc[::-1].reset_index(drop=True)
706
- return payload
707
-
708
-
709
- def expiry_history(symbol,start_date="",end_date="",type="options"):
710
- if(end_date==""):end_date=end_date
711
- nsefetch_url = "https://www.nseindia.com/api/historical/fo/derivatives/meta?&from="+start_date+"&to="+end_date+"&symbol="+symbol+""
712
- payload = nsefetch(nsefetch_url)
713
-
714
- #print(payload)
715
-
716
- for key, value in payload['expiryDatesByInstrument'].items():
717
- if type.lower() == "options" and "OPT" in key:
718
- payload_data = payload['expiryDatesByInstrument'][key]
719
- break
720
- elif type.lower() == "futures" and "FUT" in key:
721
- payload_data = payload['expiryDatesByInstrument'][key]
722
- break
723
-
724
- # Convert start_date and end_date to datetime objects
725
- start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
726
- end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
727
-
728
- # Initialize an empty list to store filtered dates
729
- filtered_date_payload = []
730
-
731
- # Initialize a flag to check if the first date after end_date has been added
732
- added_after_end_date = False
733
-
734
- # Iterate through date_payload and filter dates within the range
735
- for date_str in payload_data:
736
- date_obj = datetime.datetime.strptime(date_str, "%d-%b-%Y")
737
- if start_date <= date_obj <= end_date:
738
- filtered_date_payload.append(date_str)
739
- elif date_obj > end_date and not added_after_end_date:
740
- filtered_date_payload.append(date_str)
741
- added_after_end_date = True
742
-
743
- return filtered_date_payload
744
-
745
- # # Nifty Indicies Site
746
-
747
- niftyindices_headers = {
748
- 'Connection': 'keep-alive',
749
- 'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
750
- 'Accept': 'application/json, text/javascript, */*; q=0.01',
751
- 'DNT': '1',
752
- 'X-Requested-With': 'XMLHttpRequest',
753
- 'sec-ch-ua-mobile': '?0',
754
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
755
- 'Content-Type': 'application/json; charset=UTF-8',
756
- 'Origin': 'https://niftyindices.com',
757
- 'Sec-Fetch-Site': 'same-origin',
758
- 'Sec-Fetch-Mode': 'cors',
759
- 'Sec-Fetch-Dest': 'empty',
760
- 'Referer': 'https://niftyindices.com/reports/historical-data',
761
- 'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
762
- }
763
-
764
- def index_history(symbol,start_date,end_date):
765
- data = {'cinfo': "{'name':'" + symbol + "','startDate':'" + start_date + "','endDate':'" + end_date + "','indexName':'" + symbol + "'}"}
766
- payload = requests.post('https://niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString', headers=niftyindices_headers, json=data).json()
767
- payload = json.loads(payload["d"])
768
- payload=pd.DataFrame.from_records(payload)
769
- return payload
770
-
771
- def index_pe_pb_div(symbol,start_date,end_date):
772
- data = {'cinfo': "{'name':'" + symbol + "','startDate':'" + start_date + "','endDate':'" + end_date + "','indexName':'" + symbol + "'}"}
773
- payload = requests.post('https://niftyindices.com/Backpage.aspx/getpepbHistoricaldataDBtoString', headers=niftyindices_headers, json=data).json()
774
- payload = json.loads(payload["d"])
775
- payload=pd.DataFrame.from_records(payload)
776
- return payload
777
-
778
- def index_total_returns(symbol,start_date,end_date):
779
- data = {'cinfo': "{'name':'" + symbol + "','startDate':'" + start_date + "','endDate':'" + end_date + "','indexName':'" + symbol + "'}"}
780
- payload = requests.post('https://niftyindices.com/Backpage.aspx/getTotalReturnIndexString', headers=niftyindices_headers, json=data).json()
781
- payload = json.loads(payload["d"])
782
- payload=pd.DataFrame.from_records(payload)
783
- return payload
784
-
785
- def get_bhavcopy(date):
786
- date = date.replace("-","")
787
- payload=pd.read_csv("https://archives.nseindia.com/products/content/sec_bhavdata_full_"+date+".csv")
788
- return payload
789
-
790
- def get_bulkdeals():
791
- payload=pd.read_csv("https://archives.nseindia.com/content/equities/bulk.csv")
792
- return payload
793
-
794
- def get_blockdeals():
795
- payload=pd.read_csv("https://archives.nseindia.com/content/equities/block.csv")
796
- return payload
797
-
798
- #Request from subhash
799
- ## https://unofficed.com/how-to-find-the-beta-of-indian-stocks-using-python/
800
- def get_beta_df_maker(symbol,days):
801
- if("NIFTY" in symbol):
802
- end_date = datetime.datetime.now().strftime("%d-%b-%Y")
803
- end_date = str(end_date)
804
-
805
- start_date = (datetime.datetime.now()- datetime.timedelta(days=days)).strftime("%d-%b-%Y")
806
- start_date = str(start_date)
807
-
808
- df2=index_history(symbol,start_date,end_date)
809
- df2["daily_change"]=df2["CLOSE"].astype(float).pct_change()
810
- df2=df2[['HistoricalDate','daily_change']]
811
- df2 = df2.iloc[1: , :]
812
- return df2
813
- else:
814
- end_date = datetime.datetime.now().strftime("%d-%m-%Y")
815
- end_date = str(end_date)
816
-
817
- start_date = (datetime.datetime.now()- datetime.timedelta(days=days)).strftime("%d-%m-%Y")
818
- start_date = str(start_date)
819
-
820
- df = equity_history(symbol,"EQ",start_date,end_date)
821
-
822
- df["daily_change"]=df["CH_CLOSING_PRICE"].pct_change()
823
- df=df[['CH_TIMESTAMP','daily_change']]
824
- df = df.iloc[1: , :] #thispointer.com/drop-first-row-of-pandas-dataframe-3-ways/
825
- return df
826
-
827
- def getbeta(symbol,days=365,symbol2="NIFTY 50"):
828
- return get_beta(symbol,days,symbol2)
829
-
830
- def get_beta(symbol,days=365,symbol2="NIFTY 50"):
831
- #Default is 248 days. (Input of Subhash)
832
- df = get_beta_df_maker(symbol,days)
833
- df2 = get_beta_df_maker(symbol2,days)
834
-
835
- x=df["daily_change"].tolist()
836
- y=df2["daily_change"].tolist()
837
- #stackoverflow.com/questions/42670055/is-there-any-better-way-to-calculate-the-covariance-of-two-lists-than-this
838
- mean_x = sum(x) / len(x)
839
- mean_y = sum(y) / len(y)
840
- covariance = sum((a - mean_x) * (b - mean_y) for (a,b) in zip(x,y)) / len(x)
841
-
842
- mean = sum(y) / len(y)
843
- variance = sum((i - mean) ** 2 for i in y) / len(y)
844
-
845
- beta = covariance/variance
846
- return round(beta,3)
847
-
848
- def nse_preopen(key="NIFTY",type="pandas"):
849
- payload = nsefetch("https://www.nseindia.com/api/market-data-pre-open?key="+key+"")
850
- if(type=="pandas"):
851
- payload = pd.DataFrame(payload['data'])
852
- payload = pd.json_normalize(payload['metadata'])
853
- return payload
854
- else:
855
- return payload
856
-
857
- #By Avinash https://forum.unofficed.com/t/nsepython-documentation/376/102?u=dexter
858
- def nse_preopen_movers(key="FO",filter=1.5):
859
- preOpen_gainer=nse_preopen(key)
860
- return preOpen_gainer[preOpen_gainer['pChange'] >1.5],preOpen_gainer[preOpen_gainer['pChange'] <-1.5]
861
-
862
- # type = "securities"
863
- # type = "etf"
864
- # type = "sme"
865
- #
866
- # sort = "volume"
867
- # sort = "value"
868
-
869
- def nse_most_active(type="securities",sort="value"):
870
- payload = nsefetch("https://www.nseindia.com/api/live-analysis-most-active-"+type+"?index="+sort+"")
871
- payload = pd.DataFrame(payload["data"])
872
- return payload
873
-
874
-
875
- def nse_eq_symbols():
876
- #https://forum.unofficed.com/t/feature-request-stocklist-api/1073/11
877
- eq_list_pd = pd.read_csv('https://archives.nseindia.com/content/equities/EQUITY_L.csv')
878
- return eq_list_pd['SYMBOL'].tolist()
879
-
880
- def nse_price_band_hitters(bandtype="both",view="AllSec"):
881
- payload = nsefetch("https://www.nseindia.com/api/live-analysis-price-band-hitter")
882
-
883
- #bandtype can be upper, lower, both
884
- #view can be AllSec,SecGtr20,SecLwr20
885
- return pd.DataFrame(payload[bandtype][view]["data"])
886
-
887
- def nse_largedeals(mode="bulk_deals"):
888
- payload = nsefetch('https://www.nseindia.com/api/snapshot-capital-market-largedeal')
889
- if(mode=="bulk_deals"):
890
- return pd.DataFrame(payload["BULK_DEALS_DATA"])
891
- if(mode=="short_deals"):
892
- return pd.DataFrame(payload["SHORT_DEALS_DATA"])
893
- if(mode=="block_deals"):
894
- return pd.DataFrame(payload["BLOCK_DEALS_DATA"])
895
-
896
- def nse_largedeals_historical(from_date, to_date, mode="bulk_deals"):
897
- if mode == "bulk_deals":
898
- mode = "bulk-deals"
899
- elif mode == "short_deals":
900
- mode = "short-selling"
901
- elif mode == "block_deals":
902
- mode = "block-deals"
903
-
904
- url='https://www.nseindia.com/api/historical/' + mode + '?from=' + from_date + '&to=' + to_date
905
- logging.info("Fetching " + str(url))
906
- payload = nsefetch(url)
907
- return pd.DataFrame(payload["data"])
908
-
909
- #https://forum.unofficed.com/t/feature-request-nse-fno-participant-wise-oi/1179/7
910
- #print(get_fao_participant_oi("04-06-2021"))
911
- def get_fao_participant_oi(date):
912
- date = date.replace("-","")
913
- payload=pd.read_csv("https://archives.nseindia.com/content/nsccl/fao_participant_oi_"+date+".csv")
914
- return payload
915
-
916
- #https://forum.unofficed.com/t/how-to-check-if-the-market-is-open-today-or-not/1268/1
917
- def is_market_open(segment = "FO"): #COM,CD,CB,CMOT,COM,FO,IRD,MF,NDM,NTRP,SLBS
918
-
919
- holiday_json = nse_holidays()[segment]
920
-
921
- # Get today's date in the format 'dd-Mon-yyyy'
922
- today_date = datetime.date.today().strftime('%d-%b-%Y')
923
-
924
- # Check if today's date is in the holiday_json
925
- for holiday in holiday_json:
926
- if holiday['tradingDate'] != today_date:
927
- print("FNO Market is open today. Have a Nice Trade!")
928
- return True
929
- if holiday['tradingDate'] == today_date:
930
- print(f"Market is closed today because of {holiday['description']}")
931
- return False
932
-
933
- def nse_expirydetails_by_symbol(symbol,meta ="Futures",i=0):
934
- payload = nse_quote(symbol)
935
-
936
- if(meta=="Futures"):
937
- selected_key = next((key for key in payload["expiryDatesByInstrument"] if "futures" in key.lower()), None)
938
- if(meta=="Options"):
939
- selected_key = next((key for key in payload["expiryDatesByInstrument"] if "options" in key.lower()), None)
940
-
941
- expiry_dates=payload["expiryDatesByInstrument"][selected_key]
942
- expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
943
- expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
944
-
945
- currentExpiry=expiry_dates[i]
946
- currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date()
947
- dte = (currentExpiry - datetime.datetime.now().date()).days
948
- return currentExpiry,dte
949
-
950
- def security_wise_archive(from_date, to_date, symbol, series="ALL"):
951
- base_url = "https://www.nseindia.com/api/historical/securityArchives"
952
- url = f"{base_url}?from={from_date}&to={to_date}&symbol={symbol.upper()}&dataType=priceVolumeDeliverable&series={series.upper()}"
953
- payload = nsefetch(url)
1
+ import os,sys
2
+ # os.chdir(os.path.dirname(os.path.abspath(__file__)))
3
+ # sys.path.insert(1, os.path.join(sys.path[0], '..'))
4
+
5
+ import requests
6
+ import pandas as pd
7
+ import json
8
+ import random
9
+ import datetime,time
10
+ import logging
11
+ import re
12
+ import urllib.parse
13
+
14
+ mode ='local'
15
+
16
+ if mode == "vpn":
17
+ def nsefetch(payload: str):
18
+ def encode(url: str) -> str:
19
+ if "%26" in url or "%20" in url:
20
+ return url
21
+ return urllib.parse.quote(url, safe=":/?&=")
22
+
23
+ def refresh_cookies():
24
+ os.popen(f'curl -c cookies.txt "https://www.nseindia.com" {curl_headers}').read()
25
+ os.popen(f'curl -b cookies.txt -c cookies.txt "https://www.nseindia.com/option-chain" {curl_headers}').read()
26
+
27
+ if not os.path.exists("cookies.txt"):
28
+ refresh_cookies()
29
+
30
+ encoded_url = encode(payload)
31
+ cmd = f'curl -b cookies.txt "{encoded_url}" {curl_headers}'
32
+ raw = os.popen(cmd).read()
33
+
34
+ try:
35
+ return json.loads(raw)
36
+ except ValueError:
37
+ refresh_cookies()
38
+ raw = os.popen(cmd).read()
39
+ try:
40
+ return json.loads(raw)
41
+ except ValueError:
42
+ return {}
43
+
44
+ if(mode=='local'):
45
+ def nsefetch(payload):
46
+
47
+ try:
48
+ s = requests.Session()
49
+ s.get("https://www.nseindia.com", headers=headers, timeout=10)
50
+ s.get("https://www.nseindia.com/option-chain", headers=headers, timeout=10)
51
+ output = s.get(payload, headers=headers, timeout=10).json()
52
+ except ValueError:
53
+ output = {}
54
+ return output
55
+
56
+
57
+ # headers = {
58
+ # 'Connection': 'keep-alive',
59
+ # 'Cache-Control': 'max-age=0',
60
+ # 'DNT': '1',
61
+ # 'Upgrade-Insecure-Requests': '1',
62
+ # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36',
63
+ # 'Sec-Fetch-User': '?1',
64
+ # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
65
+ # 'Sec-Fetch-Site': 'none',
66
+ # 'Sec-Fetch-Mode': 'navigate',
67
+ # 'Accept-Encoding': 'gzip, deflate, br',
68
+ # 'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
69
+ # }
70
+
71
+ #Rahul_Mittal's entry
72
+ headers = {
73
+ "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
74
+ "accept-language": "en-US,en;q=0.9,en-IN;q=0.8,en-GB;q=0.7",
75
+ "cache-control": "max-age=0",
76
+ "priority": "u=0, i",
77
+ "sec-ch-ua": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
78
+ "sec-ch-ua-mobile": "?0",
79
+ "sec-ch-ua-platform": '"Windows"',
80
+ "sec-fetch-dest": "document",
81
+ "sec-fetch-mode": "navigate",
82
+ "sec-fetch-site": "none",
83
+ "sec-fetch-user": "?1",
84
+ "upgrade-insecure-requests": "1",
85
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0"
86
+ }
87
+
88
+
89
+
90
+ #Curl headers
91
+ curl_headers = ''' -H "authority: beta.nseindia.com" -H "cache-control: max-age=0" -H "dnt: 1" -H "upgrade-insecure-requests: 1" -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36" -H "sec-fetch-user: ?1" -H "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" -H "sec-fetch-site: none" -H "sec-fetch-mode: navigate" -H "accept-encoding: gzip, deflate, br" -H "accept-language: en-US,en;q=0.9,hi;q=0.8" --compressed'''
92
+
93
+ run_time=datetime.datetime.now()
94
+
95
+ #Constants
96
+ indices = ['NIFTY','FINNIFTY','BANKNIFTY']
97
+
98
+ def running_status():
99
+ start_now=datetime.datetime.now().replace(hour=9, minute=15, second=0, microsecond=0)
100
+ end_now=datetime.datetime.now().replace(hour=15, minute=30, second=0, microsecond=0)
101
+ return start_now<datetime.datetime.now()<end_now
102
+
103
+ #Getting FNO Symboles
104
+ def fnolist():
105
+ # df = pd.read_csv("https://www1.nseindia.com/content/fo/fo_mktlots.csv")
106
+ # return [x.strip(' ') for x in df.drop(df.index[3]).iloc[:,1].to_list()]
107
+
108
+ positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
109
+
110
+ nselist=['NIFTY','NIFTYIT','BANKNIFTY']
111
+
112
+ i=0
113
+ for x in range(i, len(positions['data'])):
114
+ nselist=nselist+[positions['data'][x]['symbol']]
115
+
116
+ return nselist
117
+
118
+ def nsesymbolpurify(symbol):
119
+ symbol = symbol.replace('&','%26') #URL Parse for Stocks Like M&M Finance
120
+ return symbol
121
+
122
+ def nse_optionchain_scrapper(symbol):
123
+ symbol = nsesymbolpurify(symbol)
124
+ if any(x in symbol for x in indices):
125
+ payload = nsefetch('https://www.nseindia.com/api/option-chain-indices?symbol='+symbol)
126
+ else:
127
+ payload = nsefetch('https://www.nseindia.com/api/option-chain-equities?symbol='+symbol)
128
+ return payload
129
+
130
+
131
+ def oi_chain_builder(symbol,expiry="latest",oi_mode="full"):
132
+
133
+ payload = nse_optionchain_scrapper(symbol)
134
+
135
+ if(oi_mode=='compact'):
136
+ col_names = ['CALLS_OI','CALLS_Chng in OI','CALLS_Volume','CALLS_IV','CALLS_LTP','CALLS_Net Chng','Strike Price','PUTS_OI','PUTS_Chng in OI','PUTS_Volume','PUTS_IV','PUTS_LTP','PUTS_Net Chng']
137
+ if(oi_mode=='full'):
138
+ col_names = ['CALLS_Chart','CALLS_OI','CALLS_Chng in OI','CALLS_Volume','CALLS_IV','CALLS_LTP','CALLS_Net Chng','CALLS_Bid Qty','CALLS_Bid Price','CALLS_Ask Price','CALLS_Ask Qty','Strike Price','PUTS_Bid Qty','PUTS_Bid Price','PUTS_Ask Price','PUTS_Ask Qty','PUTS_Net Chng','PUTS_LTP','PUTS_IV','PUTS_Volume','PUTS_Chng in OI','PUTS_OI','PUTS_Chart']
139
+ oi_data = pd.DataFrame(columns = col_names)
140
+
141
+ #oi_row = {'CALLS_OI':0, 'CALLS_Chng in OI':0, 'CALLS_Volume':0, 'CALLS_IV':0, 'CALLS_LTP':0, 'CALLS_Net Chng':0, 'Strike Price':0, 'PUTS_OI':0, 'PUTS_Chng in OI':0, 'PUTS_Volume':0, 'PUTS_IV':0, 'PUTS_LTP':0, 'PUTS_Net Chng':0}
142
+ oi_row = {'CALLS_OI':0, 'CALLS_Chng in OI':0, 'CALLS_Volume':0, 'CALLS_IV':0, 'CALLS_LTP':0, 'CALLS_Net Chng':0, 'CALLS_Bid Qty':0,'CALLS_Bid Price':0,'CALLS_Ask Price':0,'CALLS_Ask Qty':0,'Strike Price':0, 'PUTS_OI':0, 'PUTS_Chng in OI':0, 'PUTS_Volume':0, 'PUTS_IV':0, 'PUTS_LTP':0, 'PUTS_Net Chng':0,'PUTS_Bid Qty':0,'PUTS_Bid Price':0,'PUTS_Ask Price':0,'PUTS_Ask Qty':0}
143
+ if(expiry=="latest"):
144
+ expiry = payload['records']['expiryDates'][0]
145
+ m=0
146
+ for m in range(len(payload['records']['data'])):
147
+ if(payload['records']['data'][m]['expiryDate']==expiry):
148
+ if(1>0):
149
+ try:
150
+ oi_row['CALLS_OI']=payload['records']['data'][m]['CE']['openInterest']
151
+ oi_row['CALLS_Chng in OI']=payload['records']['data'][m]['CE']['changeinOpenInterest']
152
+ oi_row['CALLS_Volume']=payload['records']['data'][m]['CE']['totalTradedVolume']
153
+ oi_row['CALLS_IV']=payload['records']['data'][m]['CE']['impliedVolatility']
154
+ oi_row['CALLS_LTP']=payload['records']['data'][m]['CE']['lastPrice']
155
+ oi_row['CALLS_Net Chng']=payload['records']['data'][m]['CE']['change']
156
+ if(oi_mode=='full'):
157
+ oi_row['CALLS_Bid Qty']=payload['records']['data'][m]['CE']['bidQty']
158
+ oi_row['CALLS_Bid Price']=payload['records']['data'][m]['CE']['bidprice']
159
+ oi_row['CALLS_Ask Price']=payload['records']['data'][m]['CE']['askPrice']
160
+ oi_row['CALLS_Ask Qty']=payload['records']['data'][m]['CE']['askQty']
161
+ except KeyError:
162
+ oi_row['CALLS_OI'], oi_row['CALLS_Chng in OI'], oi_row['CALLS_Volume'], oi_row['CALLS_IV'], oi_row['CALLS_LTP'],oi_row['CALLS_Net Chng']=0,0,0,0,0,0
163
+ if(oi_mode=='full'):
164
+ oi_row['CALLS_Bid Qty'],oi_row['CALLS_Bid Price'],oi_row['CALLS_Ask Price'],oi_row['CALLS_Ask Qty']=0,0,0,0
165
+ pass
166
+
167
+ oi_row['Strike Price']=payload['records']['data'][m]['strikePrice']
168
+
169
+ try:
170
+ oi_row['PUTS_OI']=payload['records']['data'][m]['PE']['openInterest']
171
+ oi_row['PUTS_Chng in OI']=payload['records']['data'][m]['PE']['changeinOpenInterest']
172
+ oi_row['PUTS_Volume']=payload['records']['data'][m]['PE']['totalTradedVolume']
173
+ oi_row['PUTS_IV']=payload['records']['data'][m]['PE']['impliedVolatility']
174
+ oi_row['PUTS_LTP']=payload['records']['data'][m]['PE']['lastPrice']
175
+ oi_row['PUTS_Net Chng']=payload['records']['data'][m]['PE']['change']
176
+ if(oi_mode=='full'):
177
+ oi_row['PUTS_Bid Qty']=payload['records']['data'][m]['PE']['bidQty']
178
+ oi_row['PUTS_Bid Price']=payload['records']['data'][m]['PE']['bidprice']
179
+ oi_row['PUTS_Ask Price']=payload['records']['data'][m]['PE']['askPrice']
180
+ oi_row['PUTS_Ask Qty']=payload['records']['data'][m]['PE']['askQty']
181
+ except KeyError:
182
+ oi_row['PUTS_OI'], oi_row['PUTS_Chng in OI'], oi_row['PUTS_Volume'], oi_row['PUTS_IV'], oi_row['PUTS_LTP'],oi_row['PUTS_Net Chng']=0,0,0,0,0,0
183
+ if(oi_mode=='full'):
184
+ oi_row['PUTS_Bid Qty'],oi_row['PUTS_Bid Price'],oi_row['PUTS_Ask Price'],oi_row['PUTS_Ask Qty']=0,0,0,0
185
+ else:
186
+ logging.info(m)
187
+
188
+ if(oi_mode=='full'):
189
+ oi_row['CALLS_Chart'],oi_row['PUTS_Chart']=0,0
190
+ #oi_data = oi_data.append(oi_row, ignore_index=True)
191
+ #oi_data = pd.concat([oi_data, oi_row], ignore_index=True)
192
+ oi_data = pd.concat([oi_data, pd.DataFrame([oi_row])], ignore_index=True)
193
+
194
+
195
+
196
+ oi_data['time_stamp']=payload['records']['timestamp']
197
+ return oi_data,float(payload['records']['underlyingValue']),payload['records']['timestamp']
198
+
199
+
200
+ def nse_quote(symbol,section=""):
201
+ #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
202
+ symbol = nsesymbolpurify(symbol)
203
+
204
+ if(section==""):
205
+ if any(x in symbol for x in fnolist()):
206
+ payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
207
+ else:
208
+ payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
209
+ return payload
210
+
211
+ if(section!=""):
212
+ payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol+'&section='+section)
213
+ return payload
214
+
215
+
216
+ def nse_expirydetails(payload,i=0): #Can make problem. Use nse_expirydetails_by_symbol()
217
+
218
+ expiry_dates = payload['records']['expiryDates']
219
+ expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
220
+ expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
221
+ currentExpiry=expiry_dates[i]
222
+ currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date() # converting json datetime to alice datetime
223
+ date_today = run_time.strftime('%Y-%m-%d') # required to remove hh:mm:ss
224
+ date_today = datetime.datetime.strptime(date_today,'%Y-%m-%d').date()
225
+ dte = (currentExpiry - date_today).days
226
+ return currentExpiry,dte
227
+
228
+ def pcr(payload,inp='0'):
229
+ ce_oi = 0
230
+ pe_oi = 0
231
+ for i in payload['records']['data']:
232
+ if i['expiryDate'] == payload['records']['expiryDates'][inp]:
233
+ try:
234
+ ce_oi += i['CE']['openInterest']
235
+ pe_oi += i['PE']['openInterest']
236
+ except KeyError:
237
+ pass
238
+ return pe_oi / ce_oi
239
+
240
+ #forum.unofficed.com/t/unable-to-find-nse-quote-meta-api/702/4
241
+ #Refer https://forum.unofficed.com/t/changed-the-nse-quote-ltp-function/1276
242
+ def nse_quote_ltp(symbol,expiryDate="latest",optionType="-",strikePrice=0):
243
+ payload = nse_quote(symbol)
244
+
245
+ meta = "Options"
246
+ if(optionType=="Fut"): meta = "Futures"
247
+ if(optionType=="PE"):optionType="Put"
248
+ if(optionType=="CE"):optionType="Call"
249
+
250
+ if(expiryDate=="latest") or (expiryDate=="next"):
251
+
252
+ if(meta=="Futures"):
253
+ selected_key = next((key for key in payload["expiryDatesByInstrument"] if "futures" in key.lower()), None)
254
+ if(meta=="Options"):
255
+ selected_key = next((key for key in payload["expiryDatesByInstrument"] if "options" in key.lower()), None)
256
+
257
+ expiry_dates=payload["expiryDatesByInstrument"][selected_key]
258
+ expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
259
+ expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
260
+ if(expiryDate=="latest"): expiryDate=expiry_dates[0]
261
+ if(expiryDate=="next"): expiryDate=expiry_dates[1]
262
+
263
+
264
+ if(optionType!="-"):
265
+ for i in payload['stocks']:
266
+ if meta in i['metadata']['instrumentType']:
267
+ #print(i['metadata'])
268
+ if(optionType=="Fut"):
269
+ if(i['metadata']['expiryDate']==expiryDate):
270
+ lastPrice = i['metadata']['lastPrice']
271
+
272
+ if((optionType=="Put")or(optionType=="Call")):
273
+ if (i['metadata']["expiryDate"]==expiryDate):
274
+ if (i['metadata']["optionType"]==optionType):
275
+ if (i['metadata']["strikePrice"]==strikePrice):
276
+ #print(i['metadata'])
277
+ lastPrice = i['metadata']['lastPrice']
278
+
279
+ if(optionType=="-"):
280
+ lastPrice = payload['underlyingValue']
281
+
282
+ return lastPrice
283
+
284
+ # print(nse_quote_ltp("RELIANCE"))
285
+ # print(nse_quote_ltp("RELIANCE","latest","Fut"))
286
+ # print(nse_quote_ltp("RELIANCE","next","Fut"))
287
+ # print(nse_quote_ltp("BANKNIFTY","latest","PE",32000))
288
+ # print(nse_quote_ltp("BANKNIFTY","next","PE",32000))
289
+ # print(nse_quote_ltp("BANKNIFTY","10-Jun-2021","PE",32000))
290
+ # print(nse_quote_ltp("BANKNIFTY","17-Jun-2021","PE",32000))
291
+ # print(nse_quote_ltp("RELIANCE","latest","PE",2300))
292
+ # print(nse_quote_ltp("RELIANCE","next","PE",2300))
293
+
294
+ def nse_quote_meta(symbol,expiryDate="latest",optionType="-",strikePrice=0):
295
+ payload = nse_quote(symbol)
296
+ #https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists
297
+ #https://stackoverflow.com/questions/19199984/sort-a-list-in-python
298
+
299
+ #BankNIFTY and NIFTY has weekly options. Using this Jugaad which has primary base of assumption that Reliance will not step out of FNO.
300
+ #forum.unofficed.com/t/unable-to-find-nse-quote-meta-api/702/4
301
+ if((symbol in indices) and (optionType=="Fut")):
302
+ dates = expiry_list("RELIANCE","list")
303
+ if(expiryDate=="latest"): expiryDate=dates[0]
304
+ if(expiryDate=="next"): expiryDate=dates[1]
305
+
306
+ if(expiryDate=="latest") or (expiryDate=="next"):
307
+ dates=list(set((payload["expiryDates"])))
308
+ dates.sort(key = lambda date: datetime.datetime.strptime(date, '%d-%b-%Y'))
309
+ if(expiryDate=="latest"): expiryDate=dates[0]
310
+ if(expiryDate=="next"): expiryDate=dates[1]
311
+
312
+ meta = "Options"
313
+ if(optionType=="Fut"): meta = "Futures"
314
+ if(optionType=="PE"):optionType="Put"
315
+ if(optionType=="CE"):optionType="Call"
316
+
317
+ if(optionType!="-"):
318
+ for i in payload['stocks']:
319
+ if meta in i['metadata']['instrumentType']:
320
+ #print(i['metadata'])
321
+ if(optionType=="Fut"):
322
+ if(i['metadata']['expiryDate']==expiryDate):
323
+ metadata = i['metadata']
324
+
325
+ if((optionType=="Put")or(optionType=="Call")):
326
+ if (i['metadata']["expiryDate"]==expiryDate):
327
+ if (i['metadata']["optionType"]==optionType):
328
+ if (i['metadata']["strikePrice"]==strikePrice):
329
+ #print(i['metadata'])
330
+ metadata = i['metadata']
331
+
332
+ if(optionType=="-"):
333
+ metadata = i['metadata']
334
+
335
+ return metadata
336
+
337
+ def nse_optionchain_ltp(payload,strikePrice,optionType,inp=0,intent=""):
338
+ expiry_dates = payload['records']['expiryDates']
339
+ expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
340
+ expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
341
+ expiryDate=expiry_dates[inp]
342
+ for x in range(len(payload['records']['data'])):
343
+ if((payload['records']['data'][x]['strikePrice']==strikePrice) & (payload['records']['data'][x]['expiryDate']==expiryDate)):
344
+ if(intent==""): return payload['records']['data'][x][optionType]['lastPrice']
345
+ if(intent=="sell"): return payload['records']['data'][x][optionType]['bidprice']
346
+ if(intent=="buy"): return payload['records']['data'][x][optionType]['askPrice']
347
+
348
+ def nse_eq(symbol):
349
+ symbol = nsesymbolpurify(symbol)
350
+ try:
351
+ payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
352
+ try:
353
+ if(payload['error']=={}):
354
+ print("Please use nse_fno() function to reduce latency.")
355
+ payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
356
+ except:
357
+ pass
358
+ except KeyError:
359
+ print("Getting Error While Fetching.")
360
+ return payload
361
+
362
+
363
+ def nse_fno(symbol):
364
+ symbol = nsesymbolpurify(symbol)
365
+ try:
366
+ payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
367
+ try:
368
+ if(payload['error']=={}):
369
+ print("Please use nse_eq() function to reduce latency.")
370
+ payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
371
+ except KeyError:
372
+ pass
373
+ except KeyError:
374
+ print("Getting Error While Fetching.")
375
+ return payload
376
+
377
+ def quote_equity(symbol):
378
+ return nse_eq(symbol)
379
+
380
+ def quote_derivative(symbol):
381
+ return nse_fno(symbol)
382
+
383
+ def option_chain(symbol):
384
+ return nse_optionchain_scrapper(symbol)
385
+
386
+ def nse_holidays(type="trading"):
387
+ if(type=="clearing"):
388
+ payload = nsefetch('https://www.nseindia.com/api/holiday-master?type=clearing')
389
+ if(type=="trading"):
390
+ payload = nsefetch('https://www.nseindia.com/api/holiday-master?type=trading')
391
+ return payload
392
+
393
+ def holiday_master(type="trading"):
394
+ return nse_holidays(type)
395
+
396
+ def nse_results(index="equities",period="Quarterly"):
397
+ if(index=="equities") or (index=="debt") or (index=="sme"):
398
+ if(period=="Quarterly") or (period=="Annual")or (period=="Half-Yearly")or (period=="Others"):
399
+ payload = nsefetch('https://www.nseindia.com/api/corporates-financial-results?index='+index+'&period='+period)
400
+ return pd.json_normalize(payload)
401
+ else:
402
+ print("Give Correct Period Input")
403
+ else:
404
+ print("Give Correct Index Input")
405
+
406
+ def nse_events():
407
+ output = nsefetch('https://www.nseindia.com/api/event-calendar')
408
+ return pd.json_normalize(output)
409
+
410
+ def nse_past_results(symbol):
411
+ symbol = nsesymbolpurify(symbol)
412
+ return nsefetch('https://www.nseindia.com/api/results-comparision?symbol='+symbol)
413
+
414
+ def expiry_list(symbol,type="list"):
415
+ logging.info("Getting Expiry List of: "+ symbol)
416
+
417
+ if(type!="list"):
418
+ payload = nse_optionchain_scrapper(symbol)
419
+ payload = pd.DataFrame({'Date':payload['records']['expiryDates']})
420
+ return payload
421
+
422
+ if(type=="list"):
423
+ payload = nse_quote(symbol)
424
+ dates=list(set((payload["expiryDates"])))
425
+ dates.sort(key = lambda date: datetime.datetime.strptime(date, '%d-%b-%Y'))
426
+ return dates
427
+
428
+
429
+ def nse_custom_function_secfno(symbol,attribute="lastPrice"):
430
+ positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
431
+ endp = len(positions['data'])
432
+ for x in range(0, endp):
433
+ if(positions['data'][x]['symbol']==symbol.upper()):
434
+ return positions['data'][x][attribute]
435
+
436
+ def nse_blockdeal():
437
+ payload = nsefetch('https://nseindia.com/api/block-deal')
438
+ return payload
439
+
440
+ def nse_marketStatus():
441
+ payload = nsefetch('https://nseindia.com/api/marketStatus')
442
+ return payload
443
+
444
+ def nse_circular(mode="latest"):
445
+ if(mode=="latest"):
446
+ payload = nsefetch('https://nseindia.com/api/latest-circular')
447
+ else:
448
+ payload = nsefetch('https://www.nseindia.com/api/circulars')
449
+ return payload
450
+
451
+ def nse_fiidii(mode="pandas"):
452
+ try:
453
+ if(mode=="pandas"):
454
+ return pd.DataFrame(nsefetch('https://www.nseindia.com/api/fiidiiTradeReact'))
455
+ else:
456
+ return nsefetch('https://www.nseindia.com/api/fiidiiTradeReact')
457
+ except:
458
+ logger.info("Pandas is not working for some reason.")
459
+ return nsefetch('https://www.nseindia.com/api/fiidiiTradeReact')
460
+
461
+ def nsetools_get_quote(symbol):
462
+ payload = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
463
+ for m in range(len(payload['data'])):
464
+ if(payload['data'][m]['symbol']==symbol.upper()):
465
+ return payload['data'][m]
466
+
467
+
468
+ def nse_index():
469
+ payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
470
+ payload = pd.DataFrame(payload["data"])
471
+ return payload
472
+
473
+ def nse_get_index_list():
474
+ payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
475
+ payload = pd.DataFrame(payload["data"])
476
+ return payload["indexName"].tolist()
477
+
478
+ def nse_get_index_quote(index):
479
+ payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
480
+ for m in range(len(payload['data'])):
481
+ if(payload['data'][m]["indexName"] == index.upper()):
482
+ return payload['data'][m]
483
+
484
+ def nse_get_advances_declines(mode="pandas"):
485
+ try:
486
+ if(mode=="pandas"):
487
+ positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
488
+ return pd.DataFrame(positions['data'])
489
+ else:
490
+ return nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
491
+ except:
492
+ logger.info("Pandas is not working for some reason.")
493
+ return nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
494
+
495
+ def nse_get_top_losers():
496
+ positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
497
+ df = pd.DataFrame(positions['data'])
498
+ df = df.sort_values(by="pChange")
499
+ return df.head(5)
500
+
501
+ def nse_get_top_gainers():
502
+ positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
503
+ df = pd.DataFrame(positions['data'])
504
+ df = df.sort_values(by="pChange" , ascending = False)
505
+ return df.head(5)
506
+
507
+ def nse_get_fno_lot_sizes(symbol="all",mode="list"):
508
+ url="https://archives.nseindia.com/content/fo/fo_mktlots.csv"
509
+
510
+ if(mode=="list"):
511
+ s=requests.get(url).text
512
+ res_dict = {}
513
+ for line in s.split('\n'):
514
+ if line != '' and re.search(',', line) and (line.casefold().find('symbol') == -1):
515
+ (code, name) = [x.strip() for x in line.split(',')[1:3]]
516
+ res_dict[code] = int(name)
517
+ if(symbol=="all"):
518
+ return res_dict
519
+ if(symbol!=""):
520
+ return res_dict[symbol.upper()]
521
+
522
+ if(mode=="pandas"):
523
+ payload = pd.read_csv(url)
524
+ if(symbol=="all"):
525
+ return payload
526
+ else:
527
+ payload = payload[(payload.iloc[:, 1] == symbol.upper())]
528
+ return payload
529
+
530
+ def whoistheboss():
531
+ return "subhash"
532
+
533
+ def indiavix():
534
+ payload = nsefetch("https://www.nseindia.com/api/allIndices")
535
+ for x in range(0, len(payload["data"])):
536
+ if(payload["data"][x]["index"]=="INDIA VIX"):
537
+ return payload["data"][x]["last"]
538
+
539
+ def index_info(index):
540
+ payload = nsefetch("https://www.nseindia.com/api/allIndices")
541
+ for x in range(0, len(payload["data"])):
542
+ if(payload["data"][x]["index"]==index):
543
+ return payload["data"][x]
544
+
545
+ import math
546
+ from scipy.stats import norm
547
+
548
+ def black_scholes_dexter(S0,X,t,σ="",r=10,q=0.0,td=365):
549
+
550
+ if(σ==""):σ =indiavix()
551
+
552
+ S0,X,σ,r,q,t = float(S0),float(X),float(σ/100),float(r/100),float(q/100),float(t/td)
553
+ #https://unofficed.com/black-scholes-model-options-calculator-google-sheet/
554
+
555
+ d1 = (math.log(S0/X)+(r-q+0.5*σ**2)*t)/(σ*math.sqrt(t))
556
+ #stackoverflow.com/questions/34258537/python-typeerror-unsupported-operand-types-for-float-and-int
557
+
558
+ #stackoverflow.com/questions/809362/how-to-calculate-cumulative-normal-distribution
559
+ Nd1 = (math.exp((-d1**2)/2))/math.sqrt(2*math.pi)
560
+ d2 = d1-σ*math.sqrt(t)
561
+ Nd2 = norm.cdf(d2)
562
+ call_theta =(-((S0*σ*math.exp(-q*t))/(2*math.sqrt(t))*(1/(math.sqrt(2*math.pi)))*math.exp(-(d1*d1)/2))-(r*X*math.exp(-r*t)*norm.cdf(d2))+(q*math.exp(-q*t)*S0*norm.cdf(d1)))/td
563
+ put_theta =(-((S0*σ*math.exp(-q*t))/(2*math.sqrt(t))*(1/(math.sqrt(2*math.pi)))*math.exp(-(d1*d1)/2))+(r*X*math.exp(-r*t)*norm.cdf(-d2))-(q*math.exp(-q*t)*S0*norm.cdf(-d1)))/td
564
+ call_premium =math.exp(-q*t)*S0*norm.cdf(d1)-X*math.exp(-r*t)*norm.cdf(d1-σ*math.sqrt(t))
565
+ put_premium =X*math.exp(-r*t)*norm.cdf(-d2)-math.exp(-q*t)*S0*norm.cdf(-d1)
566
+ call_delta =math.exp(-q*t)*norm.cdf(d1)
567
+ put_delta =math.exp(-q*t)*(norm.cdf(d1)-1)
568
+ gamma =(math.exp(-r*t)/(S0*σ*math.sqrt(t)))*(1/(math.sqrt(2*math.pi)))*math.exp(-(d1*d1)/2)
569
+ vega = ((1/100)*S0*math.exp(-r*t)*math.sqrt(t))*(1/(math.sqrt(2*math.pi))*math.exp(-(d1*d1)/2))
570
+ call_rho =(1/100)*X*t*math.exp(-r*t)*norm.cdf(d2)
571
+ put_rho =(-1/100)*X*t*math.exp(-r*t)*norm.cdf(-d2)
572
+
573
+ return call_theta,put_theta,call_premium,put_premium,call_delta,put_delta,gamma,vega,call_rho,put_rho
574
+
575
+ def equity_history_virgin(symbol,series,start_date,end_date):
576
+ #url="https://www.nseindia.com/api/historical/cm/equity?symbol="+symbol+"&series=[%22"+series+"%22]&from="+str(start_date)+"&to="+str(end_date)+""
577
+ url = 'https://www.nseindia.com/api/historical/cm/equity?symbol=' + symbol + '&series=["' + series + '"]&from=' + start_date + '&to=' + end_date
578
+
579
+ payload = nsefetch(url)
580
+ return pd.DataFrame.from_records(payload["data"])
581
+
582
+ # You shall see beautiful use the logger function.
583
+ def equity_history(symbol,series,start_date,end_date):
584
+ #We are getting the input in text. So it is being converted to Datetime object from String.
585
+ start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
586
+ end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
587
+ logging.info("Starting Date: "+str(start_date))
588
+ logging.info("Ending Date: "+str(end_date))
589
+
590
+ #We are calculating the difference between the days
591
+ diff = end_date-start_date
592
+ logging.info("Total Number of Days: "+str(diff.days))
593
+ logging.info("Total FOR Loops in the program: "+str(int(diff.days/40)))
594
+ logging.info("Remainder Loop: " + str(diff.days-(int(diff.days/40)*40)))
595
+
596
+
597
+ total=pd.DataFrame()
598
+ for i in range (0,int(diff.days/40)):
599
+
600
+ temp_date = (start_date+datetime.timedelta(days=(40))).strftime("%d-%m-%Y")
601
+ start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
602
+
603
+ logging.info("Loop = "+str(i))
604
+ logging.info("====")
605
+ logging.info("Starting Date: "+str(start_date))
606
+ logging.info("Ending Date: "+str(temp_date))
607
+ logging.info("====")
608
+
609
+ #total=total.append(equity_history_virgin(symbol,series,start_date,temp_date))
610
+ #total=total.concat(equity_history_virgin(symbol,series,start_date,temp_date))
611
+ total = pd.concat([total, equity_history_virgin(symbol, series, start_date, temp_date)])
612
+
613
+
614
+ logging.info("Length of the Table: "+ str(len(total)))
615
+
616
+ #Preparation for the next loop
617
+ start_date = datetime.datetime.strptime(temp_date, "%d-%m-%Y")
618
+
619
+
620
+ start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
621
+ end_date = datetime.datetime.strftime(end_date, "%d-%m-%Y")
622
+
623
+ logging.info("End Loop")
624
+ logging.info("====")
625
+ logging.info("Starting Date: "+str(start_date))
626
+ logging.info("Ending Date: "+str(end_date))
627
+ logging.info("====")
628
+
629
+ #total=total.append(equity_history_virgin(symbol,series,start_date,end_date))
630
+ #total=total.concat(equity_history_virgin(symbol,series,start_date,end_date))
631
+ total = pd.concat([total, equity_history_virgin(symbol, series, start_date, end_date)])
632
+
633
+
634
+ logging.info("Finale")
635
+ logging.info("Length of the Total Dataset: "+ str(len(total)))
636
+ payload = total.iloc[::-1].reset_index(drop=True)
637
+ return payload
638
+
639
+ def derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice="",optionType=""):
640
+
641
+ instrumentType = instrumentType.lower()
642
+
643
+ if(instrumentType=="options"):
644
+ instrumentType="OPTSTK"
645
+ if("NIFTY" in symbol): instrumentType="OPTIDX"
646
+
647
+ if(instrumentType=="futures"):
648
+ instrumentType="FUTSTK"
649
+ if("NIFTY" in symbol): instrumentType="FUTIDX"
650
+
651
+
652
+ #if(((instrumentType=="OPTIDX")or (instrumentType=="OPTSTK")) and (expiry_date!="")):
653
+ if(strikePrice!=""):
654
+ strikePrice = "%.2f" % strikePrice
655
+ strikePrice = str(strikePrice)
656
+
657
+ nsefetch_url = "https://www.nseindia.com/api/historical/fo/derivatives?&from="+str(start_date)+"&to="+str(end_date)+"&optionType="+optionType+"&strikePrice="+strikePrice+"&expiryDate="+expiry_date+"&instrumentType="+instrumentType+"&symbol="+symbol+""
658
+ payload = nsefetch(nsefetch_url)
659
+ logging.info(nsefetch_url)
660
+ logging.info(payload)
661
+ return pd.DataFrame.from_records(payload["data"])
662
+
663
+ def derivative_history(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice="",optionType=""):
664
+ #We are getting the input in text. So it is being converted to Datetime object from String.
665
+ start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
666
+ end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
667
+ logging.info("Starting Date: "+str(start_date))
668
+ logging.info("Ending Date: "+str(end_date))
669
+
670
+ #We are calculating the difference between the days
671
+ diff = end_date-start_date
672
+ logging.info("Total Number of Days: "+str(diff.days))
673
+ logging.info("Total FOR Loops in the program: "+str(int(diff.days/40)))
674
+ logging.info("Remainder Loop: " + str(diff.days-(int(diff.days/40)*40)))
675
+
676
+
677
+ total=pd.DataFrame()
678
+ for i in range (0,int(diff.days/40)):
679
+
680
+ temp_date = (start_date+datetime.timedelta(days=(40))).strftime("%d-%m-%Y")
681
+ start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
682
+
683
+ logging.info("Loop = "+str(i))
684
+ logging.info("====")
685
+ logging.info("Starting Date: "+str(start_date))
686
+ logging.info("Ending Date: "+str(temp_date))
687
+ logging.info("====")
688
+
689
+ #total=total.append(derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType))
690
+ #total=total.concat([total, derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType)])
691
+ total = pd.concat([total, derivative_history_virgin(symbol, start_date, temp_date, instrumentType, expiry_date, strikePrice, optionType)])
692
+
693
+
694
+ logging.info("Length of the Table: "+ str(len(total)))
695
+
696
+ #Preparation for the next loop
697
+ start_date = datetime.datetime.strptime(temp_date, "%d-%m-%Y")
698
+
699
+
700
+ start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
701
+ end_date = datetime.datetime.strftime(end_date, "%d-%m-%Y")
702
+
703
+ logging.info("End Loop")
704
+ logging.info("====")
705
+ logging.info("Starting Date: "+str(start_date))
706
+ logging.info("Ending Date: "+str(end_date))
707
+ logging.info("====")
708
+
709
+ #total=total.append(derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType))
710
+ #total = total.concat([total, derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType)])
711
+ total = pd.concat([total, derivative_history_virgin(symbol, start_date, end_date, instrumentType, expiry_date, strikePrice, optionType)])
712
+
713
+
714
+
715
+ logging.info("Finale")
716
+ logging.info("Length of the Total Dataset: "+ str(len(total)))
717
+ payload = total.iloc[::-1].reset_index(drop=True)
718
+ return payload
719
+
720
+
721
+ def expiry_history(symbol,start_date="",end_date="",type="options"):
722
+ if(end_date==""):end_date=end_date
723
+ nsefetch_url = "https://www.nseindia.com/api/historical/fo/derivatives/meta?&from="+start_date+"&to="+end_date+"&symbol="+symbol+""
724
+ payload = nsefetch(nsefetch_url)
725
+
726
+ #print(payload)
727
+
728
+ for key, value in payload['expiryDatesByInstrument'].items():
729
+ if type.lower() == "options" and "OPT" in key:
730
+ payload_data = payload['expiryDatesByInstrument'][key]
731
+ break
732
+ elif type.lower() == "futures" and "FUT" in key:
733
+ payload_data = payload['expiryDatesByInstrument'][key]
734
+ break
735
+
736
+ # Convert start_date and end_date to datetime objects
737
+ start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
738
+ end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
739
+
740
+ # Initialize an empty list to store filtered dates
741
+ filtered_date_payload = []
742
+
743
+ # Initialize a flag to check if the first date after end_date has been added
744
+ added_after_end_date = False
745
+
746
+ # Iterate through date_payload and filter dates within the range
747
+ for date_str in payload_data:
748
+ date_obj = datetime.datetime.strptime(date_str, "%d-%b-%Y")
749
+ if start_date <= date_obj <= end_date:
750
+ filtered_date_payload.append(date_str)
751
+ elif date_obj > end_date and not added_after_end_date:
752
+ filtered_date_payload.append(date_str)
753
+ added_after_end_date = True
754
+
755
+ return filtered_date_payload
756
+
757
+ # # Nifty Indicies Site
758
+
759
+ niftyindices_headers = {
760
+ 'Connection': 'keep-alive',
761
+ 'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
762
+ 'Accept': 'application/json, text/javascript, */*; q=0.01',
763
+ 'DNT': '1',
764
+ 'X-Requested-With': 'XMLHttpRequest',
765
+ 'sec-ch-ua-mobile': '?0',
766
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
767
+ 'Content-Type': 'application/json; charset=UTF-8',
768
+ 'Origin': 'https://niftyindices.com',
769
+ 'Sec-Fetch-Site': 'same-origin',
770
+ 'Sec-Fetch-Mode': 'cors',
771
+ 'Sec-Fetch-Dest': 'empty',
772
+ 'Referer': 'https://niftyindices.com/reports/historical-data',
773
+ 'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
774
+ }
775
+
776
+ def index_history(symbol,start_date,end_date):
777
+ data = {'cinfo': "{'name':'" + symbol + "','startDate':'" + start_date + "','endDate':'" + end_date + "','indexName':'" + symbol + "'}"}
778
+ payload = requests.post('https://niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString', headers=niftyindices_headers, json=data).json()
779
+ payload = json.loads(payload["d"])
780
+ payload=pd.DataFrame.from_records(payload)
781
+ return payload
782
+
783
+ def index_pe_pb_div(symbol,start_date,end_date):
784
+ data = {'cinfo': "{'name':'" + symbol + "','startDate':'" + start_date + "','endDate':'" + end_date + "','indexName':'" + symbol + "'}"}
785
+ payload = requests.post('https://niftyindices.com/Backpage.aspx/getpepbHistoricaldataDBtoString', headers=niftyindices_headers, json=data).json()
786
+ payload = json.loads(payload["d"])
787
+ payload=pd.DataFrame.from_records(payload)
788
+ return payload
789
+
790
+ def index_total_returns(symbol,start_date,end_date):
791
+ data = {'cinfo': "{'name':'" + symbol + "','startDate':'" + start_date + "','endDate':'" + end_date + "','indexName':'" + symbol + "'}"}
792
+ payload = requests.post('https://niftyindices.com/Backpage.aspx/getTotalReturnIndexString', headers=niftyindices_headers, json=data).json()
793
+ payload = json.loads(payload["d"])
794
+ payload=pd.DataFrame.from_records(payload)
795
+ return payload
796
+
797
+ def get_bhavcopy(date):
798
+ date = date.replace("-","")
799
+ payload=pd.read_csv("https://archives.nseindia.com/products/content/sec_bhavdata_full_"+date+".csv")
800
+ return payload
801
+
802
+ def get_bulkdeals():
803
+ payload=pd.read_csv("https://archives.nseindia.com/content/equities/bulk.csv")
804
+ return payload
805
+
806
+ def get_blockdeals():
807
+ payload=pd.read_csv("https://archives.nseindia.com/content/equities/block.csv")
808
+ return payload
809
+
810
+ #Request from subhash
811
+ ## https://unofficed.com/how-to-find-the-beta-of-indian-stocks-using-python/
812
+ def get_beta_df_maker(symbol,days):
813
+ if("NIFTY" in symbol):
814
+ end_date = datetime.datetime.now().strftime("%d-%b-%Y")
815
+ end_date = str(end_date)
816
+
817
+ start_date = (datetime.datetime.now()- datetime.timedelta(days=days)).strftime("%d-%b-%Y")
818
+ start_date = str(start_date)
819
+
820
+ df2=index_history(symbol,start_date,end_date)
821
+ df2["daily_change"]=df2["CLOSE"].astype(float).pct_change()
822
+ df2=df2[['HistoricalDate','daily_change']]
823
+ df2 = df2.iloc[1: , :]
824
+ return df2
825
+ else:
826
+ end_date = datetime.datetime.now().strftime("%d-%m-%Y")
827
+ end_date = str(end_date)
828
+
829
+ start_date = (datetime.datetime.now()- datetime.timedelta(days=days)).strftime("%d-%m-%Y")
830
+ start_date = str(start_date)
831
+
832
+ df = equity_history(symbol,"EQ",start_date,end_date)
833
+
834
+ df["daily_change"]=df["CH_CLOSING_PRICE"].pct_change()
835
+ df=df[['CH_TIMESTAMP','daily_change']]
836
+ df = df.iloc[1: , :] #thispointer.com/drop-first-row-of-pandas-dataframe-3-ways/
837
+ return df
838
+
839
+ def getbeta(symbol,days=365,symbol2="NIFTY 50"):
840
+ return get_beta(symbol,days,symbol2)
841
+
842
+ def get_beta(symbol,days=365,symbol2="NIFTY 50"):
843
+ #Default is 248 days. (Input of Subhash)
844
+ df = get_beta_df_maker(symbol,days)
845
+ df2 = get_beta_df_maker(symbol2,days)
846
+
847
+ x=df["daily_change"].tolist()
848
+ y=df2["daily_change"].tolist()
849
+ #stackoverflow.com/questions/42670055/is-there-any-better-way-to-calculate-the-covariance-of-two-lists-than-this
850
+ mean_x = sum(x) / len(x)
851
+ mean_y = sum(y) / len(y)
852
+ covariance = sum((a - mean_x) * (b - mean_y) for (a,b) in zip(x,y)) / len(x)
853
+
854
+ mean = sum(y) / len(y)
855
+ variance = sum((i - mean) ** 2 for i in y) / len(y)
856
+
857
+ beta = covariance/variance
858
+ return round(beta,3)
859
+
860
+ def nse_preopen(key="NIFTY",type="pandas"):
861
+ payload = nsefetch("https://www.nseindia.com/api/market-data-pre-open?key="+key+"")
862
+ if(type=="pandas"):
863
+ payload = pd.DataFrame(payload['data'])
864
+ payload = pd.json_normalize(payload['metadata'])
865
+ return payload
866
+ else:
867
+ return payload
868
+
869
+ #By Avinash https://forum.unofficed.com/t/nsepython-documentation/376/102?u=dexter
870
+ def nse_preopen_movers(key="FO",filter=1.5):
871
+ preOpen_gainer=nse_preopen(key)
872
+ return preOpen_gainer[preOpen_gainer['pChange'] >1.5],preOpen_gainer[preOpen_gainer['pChange'] <-1.5]
873
+
874
+ # type = "securities"
875
+ # type = "etf"
876
+ # type = "sme"
877
+ #
878
+ # sort = "volume"
879
+ # sort = "value"
880
+
881
+ def nse_most_active(type="securities",sort="value"):
882
+ payload = nsefetch("https://www.nseindia.com/api/live-analysis-most-active-"+type+"?index="+sort+"")
883
+ payload = pd.DataFrame(payload["data"])
884
+ return payload
885
+
886
+
887
+ def nse_eq_symbols():
888
+ #https://forum.unofficed.com/t/feature-request-stocklist-api/1073/11
889
+ eq_list_pd = pd.read_csv('https://archives.nseindia.com/content/equities/EQUITY_L.csv')
890
+ return eq_list_pd['SYMBOL'].tolist()
891
+
892
+ def nse_price_band_hitters(bandtype="both",view="AllSec"):
893
+ payload = nsefetch("https://www.nseindia.com/api/live-analysis-price-band-hitter")
894
+
895
+ #bandtype can be upper, lower, both
896
+ #view can be AllSec,SecGtr20,SecLwr20
897
+ return pd.DataFrame(payload[bandtype][view]["data"])
898
+
899
+ def nse_largedeals(mode="bulk_deals"):
900
+ payload = nsefetch('https://www.nseindia.com/api/snapshot-capital-market-largedeal')
901
+ if(mode=="bulk_deals"):
902
+ return pd.DataFrame(payload["BULK_DEALS_DATA"])
903
+ if(mode=="short_deals"):
904
+ return pd.DataFrame(payload["SHORT_DEALS_DATA"])
905
+ if(mode=="block_deals"):
906
+ return pd.DataFrame(payload["BLOCK_DEALS_DATA"])
907
+
908
+ def nse_largedeals_historical(from_date, to_date, mode="bulk_deals"):
909
+ if mode == "bulk_deals":
910
+ mode = "bulk-deals"
911
+ elif mode == "short_deals":
912
+ mode = "short-selling"
913
+ elif mode == "block_deals":
914
+ mode = "block-deals"
915
+
916
+ url='https://www.nseindia.com/api/historical/' + mode + '?from=' + from_date + '&to=' + to_date
917
+ logging.info("Fetching " + str(url))
918
+ payload = nsefetch(url)
919
+ return pd.DataFrame(payload["data"])
920
+
921
+ #https://forum.unofficed.com/t/feature-request-nse-fno-participant-wise-oi/1179/7
922
+ #print(get_fao_participant_oi("04-06-2021"))
923
+ def get_fao_participant_oi(date):
924
+ date = date.replace("-","")
925
+ payload=pd.read_csv("https://archives.nseindia.com/content/nsccl/fao_participant_oi_"+date+".csv")
926
+ return payload
927
+
928
+ #https://forum.unofficed.com/t/how-to-check-if-the-market-is-open-today-or-not/1268/1
929
+ def is_market_open(segment = "FO"): #COM,CD,CB,CMOT,COM,FO,IRD,MF,NDM,NTRP,SLBS
930
+
931
+ holiday_json = nse_holidays()[segment]
932
+
933
+ # Get today's date in the format 'dd-Mon-yyyy'
934
+ today_date = datetime.date.today().strftime('%d-%b-%Y')
935
+
936
+ # Check if today's date is in the holiday_json
937
+ for holiday in holiday_json:
938
+ if holiday['tradingDate'] != today_date:
939
+ print("FNO Market is open today. Have a Nice Trade!")
940
+ return True
941
+ if holiday['tradingDate'] == today_date:
942
+ print(f"Market is closed today because of {holiday['description']}")
943
+ return False
944
+
945
+ def nse_expirydetails_by_symbol(symbol,meta ="Futures",i=0):
946
+ payload = nse_quote(symbol)
947
+
948
+ if(meta=="Futures"):
949
+ selected_key = next((key for key in payload["expiryDatesByInstrument"] if "futures" in key.lower()), None)
950
+ if(meta=="Options"):
951
+ selected_key = next((key for key in payload["expiryDatesByInstrument"] if "options" in key.lower()), None)
952
+
953
+ expiry_dates=payload["expiryDatesByInstrument"][selected_key]
954
+ expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]
955
+ expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now().date()]
956
+
957
+ currentExpiry=expiry_dates[i]
958
+ currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date()
959
+ dte = (currentExpiry - datetime.datetime.now().date()).days
960
+ return currentExpiry,dte
961
+
962
+ def security_wise_archive(from_date, to_date, symbol, series="ALL"):
963
+ base_url = "https://www.nseindia.com/api/historical/securityArchives"
964
+ url = f"{base_url}?from={from_date}&to={to_date}&symbol={symbol.upper()}&dataType=priceVolumeDeliverable&series={series.upper()}"
965
+ payload = nsefetch(url)
954
966
  return pd.DataFrame(payload['data'])