nsepython 0.0.973__tar.gz → 1.1__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: nsepython
3
- Version: 0.0.973
3
+ Version: 1.1
4
4
  Summary: Python library for NSE India APIs
5
5
  Home-page: https://github.com/aeron7/nsepython
6
6
  Author: Aeron7
@@ -30,9 +30,7 @@ License-File: LICENSE
30
30
  </a>
31
31
  </p>
32
32
 
33
- The library gets constant updates based on feedbacks. <br/>
34
- So many of the functions are in beta phase. <br/>
35
- But to see all beta functions You can see - [https://forum.unofficed.com/t/nsepython-documentation/376/107](https://forum.unofficed.com/t/nsepython-documentation/376/107)
33
+ For Support and Beta Functions - [https://forum.unofficed.com/t/nsepython-documentation/376/107](https://forum.unofficed.com/t/nsepython-documentation/376/107)
36
34
 
37
35
  ## Installation
38
36
 
@@ -45,13 +43,12 @@ pip install nsepython
45
43
  All the functions of the two famous packages NsepY and NSETools are also migrated here with same function name. <br/>
46
44
  They were both unmaintained since long time.
47
45
 
48
- ## Advanced Usecases
46
+ ## Advanced Usecases
49
47
  [Calculate any Option Greek using Black Scholes Formula in Python](https://unofficed.com/black-scholes-formula-in-python/)
50
48
 
51
49
  [ How to find the beta of Indian stocks using Python?](https://unofficed.com/how-to-find-the-beta-of-indian-stocks-using-python/)
52
50
 
51
+ [How to get Historical PE, PB and Dividend Ratio of any index using Python](https://unofficed.com/nse-python/documentation/nsepy/#index_pe_pb_div)
52
+
53
53
  ## Contributing
54
54
  For Discussion and Improving this Code, Join - https://www.unofficed.com/chat/
55
-
56
- ## License
57
- [MIT](https://choosealicense.com/licenses/mit/)
@@ -12,9 +12,7 @@
12
12
  </a>
13
13
  </p>
14
14
 
15
- The library gets constant updates based on feedbacks. <br/>
16
- So many of the functions are in beta phase. <br/>
17
- But to see all beta functions You can see - [https://forum.unofficed.com/t/nsepython-documentation/376/107](https://forum.unofficed.com/t/nsepython-documentation/376/107)
15
+ For Support and Beta Functions - [https://forum.unofficed.com/t/nsepython-documentation/376/107](https://forum.unofficed.com/t/nsepython-documentation/376/107)
18
16
 
19
17
  ## Installation
20
18
 
@@ -27,13 +25,12 @@ pip install nsepython
27
25
  All the functions of the two famous packages NsepY and NSETools are also migrated here with same function name. <br/>
28
26
  They were both unmaintained since long time.
29
27
 
30
- ## Advanced Usecases
28
+ ## Advanced Usecases
31
29
  [Calculate any Option Greek using Black Scholes Formula in Python](https://unofficed.com/black-scholes-formula-in-python/)
32
30
 
33
31
  [ How to find the beta of Indian stocks using Python?](https://unofficed.com/how-to-find-the-beta-of-indian-stocks-using-python/)
34
32
 
33
+ [How to get Historical PE, PB and Dividend Ratio of any index using Python](https://unofficed.com/nse-python/documentation/nsepy/#index_pe_pb_div)
34
+
35
35
  ## Contributing
36
36
  For Discussion and Improving this Code, Join - https://www.unofficed.com/chat/
37
-
38
- ## License
39
- [MIT](https://choosealicense.com/licenses/mit/)
@@ -10,47 +10,53 @@ import datetime,time
10
10
  import logging
11
11
  import re
12
12
 
13
- mode ='local'
14
-
15
- if(mode=='local'):
16
13
 
17
- headers = {
18
- 'Connection': 'keep-alive',
19
- 'Cache-Control': 'max-age=0',
20
- 'DNT': '1',
21
- 'Upgrade-Insecure-Requests': '1',
22
- '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',
23
- 'Sec-Fetch-User': '?1',
24
- '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',
25
- 'Sec-Fetch-Site': 'none',
26
- 'Sec-Fetch-Mode': 'navigate',
27
- 'Accept-Encoding': 'gzip, deflate, br',
28
- 'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
29
- }
14
+ mode ='local'
30
15
 
16
+ if(mode=='vpn'):
31
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 + ''
32
23
  try:
33
- output = requests.get(payload,headers=headers).json()
34
- #print(output)
35
- except ValueError:
36
- s =requests.Session()
37
- output = s.get("http://nseindia.com",headers=headers)
38
- output = s.get(payload,headers=headers).json()
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
+ output = requests.get(payload,headers=headers).json()
39
36
  return output
40
-
41
- run_time=datetime.datetime.now()
42
-
43
- #Constants
44
- indices = ['NIFTY','FINNIFTY','BANKNIFTY']
45
-
46
-
47
-
48
-
49
37
 
50
38
 
39
+ headers = {
40
+ 'Connection': 'keep-alive',
41
+ 'Cache-Control': 'max-age=0',
42
+ 'DNT': '1',
43
+ 'Upgrade-Insecure-Requests': '1',
44
+ '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',
45
+ 'Sec-Fetch-User': '?1',
46
+ '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',
47
+ 'Sec-Fetch-Site': 'none',
48
+ 'Sec-Fetch-Mode': 'navigate',
49
+ 'Accept-Encoding': 'gzip, deflate, br',
50
+ 'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
51
+ }
51
52
 
53
+ #Curl headers
54
+ 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'''
52
55
 
56
+ run_time=datetime.datetime.now()
53
57
 
58
+ #Constants
59
+ indices = ['NIFTY','FINNIFTY','BANKNIFTY']
54
60
 
55
61
  def running_status():
56
62
  start_now=datetime.datetime.now().replace(hour=9, minute=15, second=0, microsecond=0)
@@ -85,7 +91,7 @@ def nse_optionchain_scrapper(symbol):
85
91
  return payload
86
92
 
87
93
 
88
- def oi_chain_builder (symbol,expiry="latest",oi_mode="full"):
94
+ def oi_chain_builder(symbol,expiry="latest",oi_mode="full"):
89
95
 
90
96
  payload = nse_optionchain_scrapper(symbol)
91
97
 
@@ -144,19 +150,31 @@ def oi_chain_builder (symbol,expiry="latest",oi_mode="full"):
144
150
 
145
151
  if(oi_mode=='full'):
146
152
  oi_row['CALLS_Chart'],oi_row['PUTS_Chart']=0,0
147
- oi_data = oi_data.append(oi_row, ignore_index=True)
153
+ #oi_data = oi_data.append(oi_row, ignore_index=True)
154
+ #oi_data = pd.concat([oi_data, oi_row], ignore_index=True)
155
+ oi_data = pd.concat([oi_data, pd.DataFrame([oi_row])], ignore_index=True)
148
156
 
157
+
158
+
159
+ oi_data['time_stamp']=payload['records']['timestamp']
149
160
  return oi_data,float(payload['records']['underlyingValue']),payload['records']['timestamp']
150
161
 
151
162
 
152
- def nse_quote(symbol):
163
+ def nse_quote(symbol,section=""):
164
+ #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
153
165
  symbol = nsesymbolpurify(symbol)
154
166
 
155
- if any(x in symbol for x in fnolist()):
156
- payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
157
- else:
158
- payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
159
- return payload
167
+ if(section==""):
168
+ if any(x in symbol for x in fnolist()):
169
+ payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
170
+ else:
171
+ payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
172
+ return payload
173
+
174
+ if(section!=""):
175
+ payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol+'&section='+section)
176
+ return payload
177
+
160
178
 
161
179
  def nse_expirydetails(payload,i=0):
162
180
  currentExpiry = payload['records']['expiryDates'][i]
@@ -510,7 +528,9 @@ def black_scholes_dexter(S0,X,t,σ="",r=10,q=0.0,td=365):
510
528
  return call_theta,put_theta,call_premium,put_premium,call_delta,put_delta,gamma,vega,call_rho,put_rho
511
529
 
512
530
  def equity_history_virgin(symbol,series,start_date,end_date):
513
- url="https://www.nseindia.com/api/historical/cm/equity?symbol="+symbol+"&series=[%22"+series+"%22]&from="+str(start_date)+"&to="+str(end_date)+""
531
+ #url="https://www.nseindia.com/api/historical/cm/equity?symbol="+symbol+"&series=[%22"+series+"%22]&from="+str(start_date)+"&to="+str(end_date)+""
532
+ url = 'https://www.nseindia.com/api/historical/cm/equity?symbol=' + symbol + '&series=["' + series + '"]&from=' + start_date + '&to=' + end_date
533
+
514
534
  payload = nsefetch(url)
515
535
  return pd.DataFrame.from_records(payload["data"])
516
536
 
@@ -541,7 +561,10 @@ def equity_history(symbol,series,start_date,end_date):
541
561
  logging.info("Ending Date: "+str(temp_date))
542
562
  logging.info("====")
543
563
 
544
- total=total.append(equity_history_virgin(symbol,series,start_date,temp_date))
564
+ #total=total.append(equity_history_virgin(symbol,series,start_date,temp_date))
565
+ #total=total.concat(equity_history_virgin(symbol,series,start_date,temp_date))
566
+ total = pd.concat([total, equity_history_virgin(symbol, series, start_date, temp_date)])
567
+
545
568
 
546
569
  logging.info("Length of the Table: "+ str(len(total)))
547
570
 
@@ -558,7 +581,10 @@ def equity_history(symbol,series,start_date,end_date):
558
581
  logging.info("Ending Date: "+str(end_date))
559
582
  logging.info("====")
560
583
 
561
- total=total.append(equity_history_virgin(symbol,series,start_date,end_date))
584
+ #total=total.append(equity_history_virgin(symbol,series,start_date,end_date))
585
+ #total=total.concat(equity_history_virgin(symbol,series,start_date,end_date))
586
+ total = pd.concat([total, equity_history_virgin(symbol, series, start_date, end_date)])
587
+
562
588
 
563
589
  logging.info("Finale")
564
590
  logging.info("Length of the Total Dataset: "+ str(len(total)))
@@ -582,6 +608,7 @@ def derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_d
582
608
 
583
609
  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+""
584
610
  payload = nsefetch(nsefetch_url)
611
+ logging.info(nsefetch_url)
585
612
  logging.info(payload)
586
613
  return pd.DataFrame.from_records(payload["data"])
587
614
 
@@ -611,7 +638,10 @@ def derivative_history(symbol,start_date,end_date,instrumentType,expiry_date,str
611
638
  logging.info("Ending Date: "+str(temp_date))
612
639
  logging.info("====")
613
640
 
614
- total=total.append(derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType))
641
+ #total=total.append(derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType))
642
+ #total=total.concat([total, derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType)])
643
+ total = pd.concat([total, derivative_history_virgin(symbol, start_date, temp_date, instrumentType, expiry_date, strikePrice, optionType)])
644
+
615
645
 
616
646
  logging.info("Length of the Table: "+ str(len(total)))
617
647
 
@@ -628,7 +658,11 @@ def derivative_history(symbol,start_date,end_date,instrumentType,expiry_date,str
628
658
  logging.info("Ending Date: "+str(end_date))
629
659
  logging.info("====")
630
660
 
631
- total=total.append(derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType))
661
+ #total=total.append(derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType))
662
+ #total = total.concat([total, derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType)])
663
+ total = pd.concat([total, derivative_history_virgin(symbol, start_date, end_date, instrumentType, expiry_date, strikePrice, optionType)])
664
+
665
+
632
666
 
633
667
  logging.info("Finale")
634
668
  logging.info("Length of the Total Dataset: "+ str(len(total)))
@@ -770,3 +804,9 @@ def nse_most_active(type="securities",sort="value"):
770
804
  payload = nsefetch("https://www.nseindia.com/api/live-analysis-most-active-"+type+"?index="+sort+"")
771
805
  payload = pd.DataFrame(payload["data"])
772
806
  return payload
807
+
808
+
809
+ def nse_eq_symbols():
810
+ #https://forum.unofficed.com/t/feature-request-stocklist-api/1073/11
811
+ eq_list_pd = pd.read_csv('https://archives.nseindia.com/content/equities/EQUITY_L.csv')
812
+ return eq_list_pd['SYMBOL'].tolist()
@@ -0,0 +1,812 @@
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
+
13
+
14
+ mode ='vpn'
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
+ output = requests.get(payload,headers=headers).json()
36
+ return output
37
+
38
+
39
+ headers = {
40
+ 'Connection': 'keep-alive',
41
+ 'Cache-Control': 'max-age=0',
42
+ 'DNT': '1',
43
+ 'Upgrade-Insecure-Requests': '1',
44
+ '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',
45
+ 'Sec-Fetch-User': '?1',
46
+ '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',
47
+ 'Sec-Fetch-Site': 'none',
48
+ 'Sec-Fetch-Mode': 'navigate',
49
+ 'Accept-Encoding': 'gzip, deflate, br',
50
+ 'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
51
+ }
52
+
53
+ #Curl headers
54
+ 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'''
55
+
56
+ run_time=datetime.datetime.now()
57
+
58
+ #Constants
59
+ indices = ['NIFTY','FINNIFTY','BANKNIFTY']
60
+
61
+ def running_status():
62
+ start_now=datetime.datetime.now().replace(hour=9, minute=15, second=0, microsecond=0)
63
+ end_now=datetime.datetime.now().replace(hour=15, minute=30, second=0, microsecond=0)
64
+ return start_now<datetime.datetime.now()<end_now
65
+
66
+ #Getting FNO Symboles
67
+ def fnolist():
68
+ # df = pd.read_csv("https://www1.nseindia.com/content/fo/fo_mktlots.csv")
69
+ # return [x.strip(' ') for x in df.drop(df.index[3]).iloc[:,1].to_list()]
70
+
71
+ positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
72
+
73
+ nselist=['NIFTY','NIFTYIT','BANKNIFTY']
74
+
75
+ i=0
76
+ for x in range(i, len(positions['data'])):
77
+ nselist=nselist+[positions['data'][x]['symbol']]
78
+
79
+ return nselist
80
+
81
+ def nsesymbolpurify(symbol):
82
+ symbol = symbol.replace('&','%26') #URL Parse for Stocks Like M&M Finance
83
+ return symbol
84
+
85
+ def nse_optionchain_scrapper(symbol):
86
+ symbol = nsesymbolpurify(symbol)
87
+ if any(x in symbol for x in indices):
88
+ payload = nsefetch('https://www.nseindia.com/api/option-chain-indices?symbol='+symbol)
89
+ else:
90
+ payload = nsefetch('https://www.nseindia.com/api/option-chain-equities?symbol='+symbol)
91
+ return payload
92
+
93
+
94
+ def oi_chain_builder(symbol,expiry="latest",oi_mode="full"):
95
+
96
+ payload = nse_optionchain_scrapper(symbol)
97
+
98
+ if(oi_mode=='compact'):
99
+ 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']
100
+ if(oi_mode=='full'):
101
+ 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']
102
+ oi_data = pd.DataFrame(columns = col_names)
103
+
104
+ #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}
105
+ 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}
106
+ if(expiry=="latest"):
107
+ expiry = payload['records']['expiryDates'][0]
108
+ m=0
109
+ for m in range(len(payload['records']['data'])):
110
+ if(payload['records']['data'][m]['expiryDate']==expiry):
111
+ if(1>0):
112
+ try:
113
+ oi_row['CALLS_OI']=payload['records']['data'][m]['CE']['openInterest']
114
+ oi_row['CALLS_Chng in OI']=payload['records']['data'][m]['CE']['changeinOpenInterest']
115
+ oi_row['CALLS_Volume']=payload['records']['data'][m]['CE']['totalTradedVolume']
116
+ oi_row['CALLS_IV']=payload['records']['data'][m]['CE']['impliedVolatility']
117
+ oi_row['CALLS_LTP']=payload['records']['data'][m]['CE']['lastPrice']
118
+ oi_row['CALLS_Net Chng']=payload['records']['data'][m]['CE']['change']
119
+ if(oi_mode=='full'):
120
+ oi_row['CALLS_Bid Qty']=payload['records']['data'][m]['CE']['bidQty']
121
+ oi_row['CALLS_Bid Price']=payload['records']['data'][m]['CE']['bidprice']
122
+ oi_row['CALLS_Ask Price']=payload['records']['data'][m]['CE']['askPrice']
123
+ oi_row['CALLS_Ask Qty']=payload['records']['data'][m]['CE']['askQty']
124
+ except KeyError:
125
+ 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
126
+ if(oi_mode=='full'):
127
+ oi_row['CALLS_Bid Qty'],oi_row['CALLS_Bid Price'],oi_row['CALLS_Ask Price'],oi_row['CALLS_Ask Qty']=0,0,0,0
128
+ pass
129
+
130
+ oi_row['Strike Price']=payload['records']['data'][m]['strikePrice']
131
+
132
+ try:
133
+ oi_row['PUTS_OI']=payload['records']['data'][m]['PE']['openInterest']
134
+ oi_row['PUTS_Chng in OI']=payload['records']['data'][m]['PE']['changeinOpenInterest']
135
+ oi_row['PUTS_Volume']=payload['records']['data'][m]['PE']['totalTradedVolume']
136
+ oi_row['PUTS_IV']=payload['records']['data'][m]['PE']['impliedVolatility']
137
+ oi_row['PUTS_LTP']=payload['records']['data'][m]['PE']['lastPrice']
138
+ oi_row['PUTS_Net Chng']=payload['records']['data'][m]['PE']['change']
139
+ if(oi_mode=='full'):
140
+ oi_row['PUTS_Bid Qty']=payload['records']['data'][m]['PE']['bidQty']
141
+ oi_row['PUTS_Bid Price']=payload['records']['data'][m]['PE']['bidprice']
142
+ oi_row['PUTS_Ask Price']=payload['records']['data'][m]['PE']['askPrice']
143
+ oi_row['PUTS_Ask Qty']=payload['records']['data'][m]['PE']['askQty']
144
+ except KeyError:
145
+ 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
146
+ if(oi_mode=='full'):
147
+ oi_row['PUTS_Bid Qty'],oi_row['PUTS_Bid Price'],oi_row['PUTS_Ask Price'],oi_row['PUTS_Ask Qty']=0,0,0,0
148
+ else:
149
+ logging.info(m)
150
+
151
+ if(oi_mode=='full'):
152
+ oi_row['CALLS_Chart'],oi_row['PUTS_Chart']=0,0
153
+ #oi_data = oi_data.append(oi_row, ignore_index=True)
154
+ #oi_data = pd.concat([oi_data, oi_row], ignore_index=True)
155
+ oi_data = pd.concat([oi_data, pd.DataFrame([oi_row])], ignore_index=True)
156
+
157
+
158
+
159
+ oi_data['time_stamp']=payload['records']['timestamp']
160
+ return oi_data,float(payload['records']['underlyingValue']),payload['records']['timestamp']
161
+
162
+
163
+ def nse_quote(symbol,section=""):
164
+ #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
165
+ symbol = nsesymbolpurify(symbol)
166
+
167
+ if(section==""):
168
+ if any(x in symbol for x in fnolist()):
169
+ payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
170
+ else:
171
+ payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
172
+ return payload
173
+
174
+ if(section!=""):
175
+ payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol+'&section='+section)
176
+ return payload
177
+
178
+
179
+ def nse_expirydetails(payload,i=0):
180
+ currentExpiry = payload['records']['expiryDates'][i]
181
+ currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date() # converting json datetime to alice datetime
182
+ date_today = run_time.strftime('%Y-%m-%d') # required to remove hh:mm:ss
183
+ date_today = datetime.datetime.strptime(date_today,'%Y-%m-%d').date()
184
+ dte = (currentExpiry - date_today).days
185
+ return currentExpiry,dte
186
+
187
+ def pcr(payload,inp='0'):
188
+ ce_oi = 0
189
+ pe_oi = 0
190
+ for i in payload['records']['data']:
191
+ if i['expiryDate'] == payload['records']['expiryDates'][inp]:
192
+ try:
193
+ ce_oi += i['CE']['openInterest']
194
+ pe_oi += i['PE']['openInterest']
195
+ except KeyError:
196
+ pass
197
+ return pe_oi / ce_oi
198
+
199
+ def nse_quote_ltp(symbol,expiryDate="latest",optionType="-",strikePrice=0):
200
+ payload = nse_quote(symbol)
201
+ #https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists
202
+ #https://stackoverflow.com/questions/19199984/sort-a-list-in-python
203
+
204
+ #BankNIFTY and NIFTY has weekly options. Using this Jugaad which has primary base of assumption that Reliance will not step out of FNO.
205
+ #forum.unofficed.com/t/unable-to-find-nse-quote-meta-api/702/4
206
+ if((symbol in indices) and (optionType=="Fut")):
207
+ dates = expiry_list("RELIANCE","list")
208
+ if(expiryDate=="latest"): expiryDate=dates[0]
209
+ if(expiryDate=="next"): expiryDate=dates[1]
210
+
211
+ if(expiryDate=="latest") or (expiryDate=="next"):
212
+ dates=list(set((payload["expiryDates"])))
213
+ dates.sort(key = lambda date: datetime.datetime.strptime(date, '%d-%b-%Y'))
214
+ if(expiryDate=="latest"): expiryDate=dates[0]
215
+ if(expiryDate=="next"): expiryDate=dates[1]
216
+
217
+ meta = "Options"
218
+ if(optionType=="Fut"): meta = "Futures"
219
+ if(optionType=="PE"):optionType="Put"
220
+ if(optionType=="CE"):optionType="Call"
221
+
222
+ if(optionType!="-"):
223
+ for i in payload['stocks']:
224
+ if meta in i['metadata']['instrumentType']:
225
+ #print(i['metadata'])
226
+ if(optionType=="Fut"):
227
+ if(i['metadata']['expiryDate']==expiryDate):
228
+ lastPrice = i['metadata']['lastPrice']
229
+
230
+ if((optionType=="Put")or(optionType=="Call")):
231
+ if (i['metadata']["expiryDate"]==expiryDate):
232
+ if (i['metadata']["optionType"]==optionType):
233
+ if (i['metadata']["strikePrice"]==strikePrice):
234
+ #print(i['metadata'])
235
+ lastPrice = i['metadata']['lastPrice']
236
+
237
+ if(optionType=="-"):
238
+ lastPrice = payload['underlyingValue']
239
+
240
+ return lastPrice
241
+
242
+ # print(nse_quote_ltp("RELIANCE"))
243
+ # print(nse_quote_ltp("RELIANCE","latest","Fut"))
244
+ # print(nse_quote_ltp("RELIANCE","next","Fut"))
245
+ # print(nse_quote_ltp("BANKNIFTY","latest","PE",32000))
246
+ # print(nse_quote_ltp("BANKNIFTY","next","PE",32000))
247
+ # print(nse_quote_ltp("BANKNIFTY","10-Jun-2021","PE",32000))
248
+ # print(nse_quote_ltp("BANKNIFTY","17-Jun-2021","PE",32000))
249
+ # print(nse_quote_ltp("RELIANCE","latest","PE",2300))
250
+ # print(nse_quote_ltp("RELIANCE","next","PE",2300))
251
+
252
+ def nse_quote_meta(symbol,expiryDate="latest",optionType="-",strikePrice=0):
253
+ payload = nse_quote(symbol)
254
+ #https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists
255
+ #https://stackoverflow.com/questions/19199984/sort-a-list-in-python
256
+
257
+ #BankNIFTY and NIFTY has weekly options. Using this Jugaad which has primary base of assumption that Reliance will not step out of FNO.
258
+ #forum.unofficed.com/t/unable-to-find-nse-quote-meta-api/702/4
259
+ if((symbol in indices) and (optionType=="Fut")):
260
+ dates = expiry_list("RELIANCE","list")
261
+ if(expiryDate=="latest"): expiryDate=dates[0]
262
+ if(expiryDate=="next"): expiryDate=dates[1]
263
+
264
+ if(expiryDate=="latest") or (expiryDate=="next"):
265
+ dates=list(set((payload["expiryDates"])))
266
+ dates.sort(key = lambda date: datetime.datetime.strptime(date, '%d-%b-%Y'))
267
+ if(expiryDate=="latest"): expiryDate=dates[0]
268
+ if(expiryDate=="next"): expiryDate=dates[1]
269
+
270
+ meta = "Options"
271
+ if(optionType=="Fut"): meta = "Futures"
272
+ if(optionType=="PE"):optionType="Put"
273
+ if(optionType=="CE"):optionType="Call"
274
+
275
+ if(optionType!="-"):
276
+ for i in payload['stocks']:
277
+ if meta in i['metadata']['instrumentType']:
278
+ #print(i['metadata'])
279
+ if(optionType=="Fut"):
280
+ if(i['metadata']['expiryDate']==expiryDate):
281
+ metadata = i['metadata']
282
+
283
+ if((optionType=="Put")or(optionType=="Call")):
284
+ if (i['metadata']["expiryDate"]==expiryDate):
285
+ if (i['metadata']["optionType"]==optionType):
286
+ if (i['metadata']["strikePrice"]==strikePrice):
287
+ #print(i['metadata'])
288
+ metadata = i['metadata']
289
+
290
+ if(optionType=="-"):
291
+ metadata = i['metadata']
292
+
293
+ return metadata
294
+
295
+ def nse_optionchain_ltp(payload,strikePrice,optionType,inp=0,intent=""):
296
+ expiryDate=payload['records']['expiryDates'][inp]
297
+ for x in range(len(payload['records']['data'])):
298
+ if((payload['records']['data'][x]['strikePrice']==strikePrice) & (payload['records']['data'][x]['expiryDate']==expiryDate)):
299
+ if(intent==""): return payload['records']['data'][x][optionType]['lastPrice']
300
+ if(intent=="sell"): return payload['records']['data'][x][optionType]['bidprice']
301
+ if(intent=="buy"): return payload['records']['data'][x][optionType]['askPrice']
302
+
303
+ def nse_eq(symbol):
304
+ symbol = nsesymbolpurify(symbol)
305
+ try:
306
+ payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
307
+ try:
308
+ if(payload['error']=={}):
309
+ print("Please use nse_fno() function to reduce latency.")
310
+ payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
311
+ except:
312
+ pass
313
+ except KeyError:
314
+ print("Getting Error While Fetching.")
315
+ return payload
316
+
317
+
318
+ def nse_fno(symbol):
319
+ symbol = nsesymbolpurify(symbol)
320
+ try:
321
+ payload = nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+symbol)
322
+ try:
323
+ if(payload['error']=={}):
324
+ print("Please use nse_eq() function to reduce latency.")
325
+ payload = nsefetch('https://www.nseindia.com/api/quote-equity?symbol='+symbol)
326
+ except KeyError:
327
+ pass
328
+ except KeyError:
329
+ print("Getting Error While Fetching.")
330
+ return payload
331
+
332
+ def quote_equity(symbol):
333
+ return nse_eq(symbol)
334
+
335
+ def quote_derivative(symbol):
336
+ return nse_fno(symbol)
337
+
338
+ def option_chain(symbol):
339
+ return nse_optionchain_scrapper(symbol)
340
+
341
+ def nse_holidays(type="trading"):
342
+ if(type=="clearing"):
343
+ payload = nsefetch('https://www.nseindia.com/api/holiday-master?type=clearing')
344
+ if(type=="trading"):
345
+ payload = nsefetch('https://www.nseindia.com/api/holiday-master?type=trading')
346
+ return payload
347
+
348
+ def holiday_master(type="trading"):
349
+ return nse_holidays(type)
350
+
351
+ def nse_results(index="equities",period="Quarterly"):
352
+ if(index=="equities") or (index=="debt") or (index=="sme"):
353
+ if(period=="Quarterly") or (period=="Annual")or (period=="Half-Yearly")or (period=="Others"):
354
+ payload = nsefetch('https://www.nseindia.com/api/corporates-financial-results?index='+index+'&period='+period)
355
+ return pd.json_normalize(payload)
356
+ else:
357
+ print("Give Correct Period Input")
358
+ else:
359
+ print("Give Correct Index Input")
360
+
361
+ def nse_events():
362
+ output = nsefetch('https://www.nseindia.com/api/event-calendar')
363
+ return pd.json_normalize(output)
364
+
365
+ def nse_past_results(symbol):
366
+ symbol = nsesymbolpurify(symbol)
367
+ return nsefetch('https://www.nseindia.com/api/results-comparision?symbol='+symbol)
368
+
369
+ def expiry_list(symbol,type="list"):
370
+ logging.info("Getting Expiry List of: "+ symbol)
371
+
372
+ if(type!="list"):
373
+ payload = nse_optionchain_scrapper(symbol)
374
+ payload = pd.DataFrame({'Date':payload['records']['expiryDates']})
375
+ return payload
376
+
377
+ if(type=="list"):
378
+ payload = nse_quote(symbol)
379
+ dates=list(set((payload["expiryDates"])))
380
+ dates.sort(key = lambda date: datetime.datetime.strptime(date, '%d-%b-%Y'))
381
+ return dates
382
+
383
+
384
+ def nse_custom_function_secfno(symbol,attribute="lastPrice"):
385
+ positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
386
+ endp = len(positions['data'])
387
+ for x in range(0, endp):
388
+ if(positions['data'][x]['symbol']==symbol.upper()):
389
+ return positions['data'][x][attribute]
390
+
391
+ def nse_blockdeal():
392
+ payload = nsefetch('https://nseindia.com/api/block-deal')
393
+ return payload
394
+
395
+ def nse_marketStatus():
396
+ payload = nsefetch('https://nseindia.com/api/marketStatus')
397
+ return payload
398
+
399
+ def nse_circular(mode="latest"):
400
+ if(mode=="latest"):
401
+ payload = nsefetch('https://nseindia.com/api/latest-circular')
402
+ else:
403
+ payload = nsefetch('https://www.nseindia.com/api/circulars')
404
+ return payload
405
+
406
+ def nse_fiidii(mode="pandas"):
407
+ try:
408
+ if(mode=="pandas"):
409
+ return pd.DataFrame(nsefetch('https://www.nseindia.com/api/fiidiiTradeReact'))
410
+ else:
411
+ return nsefetch('https://www.nseindia.com/api/fiidiiTradeReact')
412
+ except:
413
+ logger.info("Pandas is not working for some reason.")
414
+ return nsefetch('https://www.nseindia.com/api/fiidiiTradeReact')
415
+
416
+ def nsetools_get_quote(symbol):
417
+ payload = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
418
+ for m in range(len(payload['data'])):
419
+ if(payload['data'][m]['symbol']==symbol.upper()):
420
+ return payload['data'][m]
421
+
422
+
423
+ def nse_index():
424
+ payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
425
+ payload = pd.DataFrame(payload["data"])
426
+ return payload
427
+
428
+ def nse_get_index_list():
429
+ payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
430
+ payload = pd.DataFrame(payload["data"])
431
+ return payload["indexName"].tolist()
432
+
433
+ def nse_get_index_quote(index):
434
+ payload = nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
435
+ for m in range(len(payload['data'])):
436
+ if(payload['data'][m]["indexName"] == index.upper()):
437
+ return payload['data'][m]
438
+
439
+ def nse_get_advances_declines(mode="pandas"):
440
+ try:
441
+ if(mode=="pandas"):
442
+ positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
443
+ return pd.DataFrame(positions['data'])
444
+ else:
445
+ return nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
446
+ except:
447
+ logger.info("Pandas is not working for some reason.")
448
+ return nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
449
+
450
+ def nse_get_top_losers():
451
+ positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
452
+ df = pd.DataFrame(positions['data'])
453
+ df = df.sort_values(by="pChange")
454
+ return df.head(5)
455
+
456
+ def nse_get_top_gainers():
457
+ positions = nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
458
+ df = pd.DataFrame(positions['data'])
459
+ df = df.sort_values(by="pChange" , ascending = False)
460
+ return df.head(5)
461
+
462
+ def nse_get_fno_lot_sizes(symbol="all",mode="list"):
463
+ url="https://archives.nseindia.com/content/fo/fo_mktlots.csv"
464
+
465
+ if(mode=="list"):
466
+ s=requests.get(url).text
467
+ res_dict = {}
468
+ for line in s.split('\n'):
469
+ if line != '' and re.search(',', line) and (line.casefold().find('symbol') == -1):
470
+ (code, name) = [x.strip() for x in line.split(',')[1:3]]
471
+ res_dict[code] = int(name)
472
+ if(symbol=="all"):
473
+ return res_dict
474
+ if(symbol!=""):
475
+ return res_dict[symbol.upper()]
476
+
477
+ if(mode=="pandas"):
478
+ payload = pd.read_csv(url)
479
+ if(symbol=="all"):
480
+ return payload
481
+ else:
482
+ payload = payload[(payload.iloc[:, 1] == symbol.upper())]
483
+ return payload
484
+
485
+ def whoistheboss():
486
+ return "subhash"
487
+
488
+ def indiavix():
489
+ payload = nsefetch("https://www.nseindia.com/api/allIndices")
490
+ for x in range(0, len(payload["data"])):
491
+ if(payload["data"][x]["index"]=="INDIA VIX"):
492
+ return payload["data"][x]["last"]
493
+
494
+ def index_info(index):
495
+ payload = nsefetch("https://www.nseindia.com/api/allIndices")
496
+ for x in range(0, len(payload["data"])):
497
+ if(payload["data"][x]["index"]==index):
498
+ return payload["data"][x]
499
+
500
+ import math
501
+ from scipy.stats import norm
502
+
503
+ def black_scholes_dexter(S0,X,t,σ="",r=10,q=0.0,td=365):
504
+
505
+ if(σ==""):σ =indiavix()
506
+
507
+ S0,X,σ,r,q,t = float(S0),float(X),float(σ/100),float(r/100),float(q/100),float(t/td)
508
+ #https://unofficed.com/black-scholes-model-options-calculator-google-sheet/
509
+
510
+ d1 = (math.log(S0/X)+(r-q+0.5*σ**2)*t)/(σ*math.sqrt(t))
511
+ #stackoverflow.com/questions/34258537/python-typeerror-unsupported-operand-types-for-float-and-int
512
+
513
+ #stackoverflow.com/questions/809362/how-to-calculate-cumulative-normal-distribution
514
+ Nd1 = (math.exp((-d1**2)/2))/math.sqrt(2*math.pi)
515
+ d2 = d1-σ*math.sqrt(t)
516
+ Nd2 = norm.cdf(d2)
517
+ 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
518
+ 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
519
+ call_premium =math.exp(-q*t)*S0*norm.cdf(d1)-X*math.exp(-r*t)*norm.cdf(d1-σ*math.sqrt(t))
520
+ put_premium =X*math.exp(-r*t)*norm.cdf(-d2)-math.exp(-q*t)*S0*norm.cdf(-d1)
521
+ call_delta =math.exp(-q*t)*norm.cdf(d1)
522
+ put_delta =math.exp(-q*t)*(norm.cdf(d1)-1)
523
+ gamma =(math.exp(-r*t)/(S0*σ*math.sqrt(t)))*(1/(math.sqrt(2*math.pi)))*math.exp(-(d1*d1)/2)
524
+ vega = ((1/100)*S0*math.exp(-r*t)*math.sqrt(t))*(1/(math.sqrt(2*math.pi))*math.exp(-(d1*d1)/2))
525
+ call_rho =(1/100)*X*t*math.exp(-r*t)*norm.cdf(d2)
526
+ put_rho =(-1/100)*X*t*math.exp(-r*t)*norm.cdf(-d2)
527
+
528
+ return call_theta,put_theta,call_premium,put_premium,call_delta,put_delta,gamma,vega,call_rho,put_rho
529
+
530
+ def equity_history_virgin(symbol,series,start_date,end_date):
531
+ #url="https://www.nseindia.com/api/historical/cm/equity?symbol="+symbol+"&series=[%22"+series+"%22]&from="+str(start_date)+"&to="+str(end_date)+""
532
+ url = 'https://www.nseindia.com/api/historical/cm/equity?symbol=' + symbol + '&series=["' + series + '"]&from=' + start_date + '&to=' + end_date
533
+
534
+ payload = nsefetch(url)
535
+ return pd.DataFrame.from_records(payload["data"])
536
+
537
+ # You shall see beautiful use the logger function.
538
+ def equity_history(symbol,series,start_date,end_date):
539
+ #We are getting the input in text. So it is being converted to Datetime object from String.
540
+ start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
541
+ end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
542
+ logging.info("Starting Date: "+str(start_date))
543
+ logging.info("Ending Date: "+str(end_date))
544
+
545
+ #We are calculating the difference between the days
546
+ diff = end_date-start_date
547
+ logging.info("Total Number of Days: "+str(diff.days))
548
+ logging.info("Total FOR Loops in the program: "+str(int(diff.days/40)))
549
+ logging.info("Remainder Loop: " + str(diff.days-(int(diff.days/40)*40)))
550
+
551
+
552
+ total=pd.DataFrame()
553
+ for i in range (0,int(diff.days/40)):
554
+
555
+ temp_date = (start_date+datetime.timedelta(days=(40))).strftime("%d-%m-%Y")
556
+ start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
557
+
558
+ logging.info("Loop = "+str(i))
559
+ logging.info("====")
560
+ logging.info("Starting Date: "+str(start_date))
561
+ logging.info("Ending Date: "+str(temp_date))
562
+ logging.info("====")
563
+
564
+ #total=total.append(equity_history_virgin(symbol,series,start_date,temp_date))
565
+ #total=total.concat(equity_history_virgin(symbol,series,start_date,temp_date))
566
+ total = pd.concat([total, equity_history_virgin(symbol, series, start_date, temp_date)])
567
+
568
+
569
+ logging.info("Length of the Table: "+ str(len(total)))
570
+
571
+ #Preparation for the next loop
572
+ start_date = datetime.datetime.strptime(temp_date, "%d-%m-%Y")
573
+
574
+
575
+ start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
576
+ end_date = datetime.datetime.strftime(end_date, "%d-%m-%Y")
577
+
578
+ logging.info("End Loop")
579
+ logging.info("====")
580
+ logging.info("Starting Date: "+str(start_date))
581
+ logging.info("Ending Date: "+str(end_date))
582
+ logging.info("====")
583
+
584
+ #total=total.append(equity_history_virgin(symbol,series,start_date,end_date))
585
+ #total=total.concat(equity_history_virgin(symbol,series,start_date,end_date))
586
+ total = pd.concat([total, equity_history_virgin(symbol, series, start_date, end_date)])
587
+
588
+
589
+ logging.info("Finale")
590
+ logging.info("Length of the Total Dataset: "+ str(len(total)))
591
+ payload = total.iloc[::-1].reset_index(drop=True)
592
+ return payload
593
+
594
+ def derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice="",optionType=""):
595
+
596
+ instrumentType = instrumentType.lower()
597
+
598
+ if(instrumentType=="options"):
599
+ if("NIFTY" in symbol): instrumentType="FUTSTK"
600
+ instrumentType="OPTSTK"
601
+ if(instrumentType=="futures"):
602
+ if("NIFTY" in symbol): instrumentType="OPTIDX"
603
+ instrumentType="FUTIDX"
604
+
605
+ if(((instrumentType=="OPTIDX")or (instrumentType=="OPTSTK")) and (expiry_date!="")):
606
+ strikePrice = "%.2f" % strikePrice
607
+ strikePrice = str(strikePrice)
608
+
609
+ 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+""
610
+ payload = nsefetch(nsefetch_url)
611
+ logging.info(nsefetch_url)
612
+ logging.info(payload)
613
+ return pd.DataFrame.from_records(payload["data"])
614
+
615
+ def derivative_history(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice="",optionType=""):
616
+ #We are getting the input in text. So it is being converted to Datetime object from String.
617
+ start_date = datetime.datetime.strptime(start_date, "%d-%m-%Y")
618
+ end_date = datetime.datetime.strptime(end_date, "%d-%m-%Y")
619
+ logging.info("Starting Date: "+str(start_date))
620
+ logging.info("Ending Date: "+str(end_date))
621
+
622
+ #We are calculating the difference between the days
623
+ diff = end_date-start_date
624
+ logging.info("Total Number of Days: "+str(diff.days))
625
+ logging.info("Total FOR Loops in the program: "+str(int(diff.days/40)))
626
+ logging.info("Remainder Loop: " + str(diff.days-(int(diff.days/40)*40)))
627
+
628
+
629
+ total=pd.DataFrame()
630
+ for i in range (0,int(diff.days/40)):
631
+
632
+ temp_date = (start_date+datetime.timedelta(days=(40))).strftime("%d-%m-%Y")
633
+ start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
634
+
635
+ logging.info("Loop = "+str(i))
636
+ logging.info("====")
637
+ logging.info("Starting Date: "+str(start_date))
638
+ logging.info("Ending Date: "+str(temp_date))
639
+ logging.info("====")
640
+
641
+ #total=total.append(derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType))
642
+ #total=total.concat([total, derivative_history_virgin(symbol,start_date,temp_date,instrumentType,expiry_date,strikePrice,optionType)])
643
+ total = pd.concat([total, derivative_history_virgin(symbol, start_date, temp_date, instrumentType, expiry_date, strikePrice, optionType)])
644
+
645
+
646
+ logging.info("Length of the Table: "+ str(len(total)))
647
+
648
+ #Preparation for the next loop
649
+ start_date = datetime.datetime.strptime(temp_date, "%d-%m-%Y")
650
+
651
+
652
+ start_date = datetime.datetime.strftime(start_date, "%d-%m-%Y")
653
+ end_date = datetime.datetime.strftime(end_date, "%d-%m-%Y")
654
+
655
+ logging.info("End Loop")
656
+ logging.info("====")
657
+ logging.info("Starting Date: "+str(start_date))
658
+ logging.info("Ending Date: "+str(end_date))
659
+ logging.info("====")
660
+
661
+ #total=total.append(derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType))
662
+ #total = total.concat([total, derivative_history_virgin(symbol,start_date,end_date,instrumentType,expiry_date,strikePrice,optionType)])
663
+ total = pd.concat([total, derivative_history_virgin(symbol, start_date, end_date, instrumentType, expiry_date, strikePrice, optionType)])
664
+
665
+
666
+
667
+ logging.info("Finale")
668
+ logging.info("Length of the Total Dataset: "+ str(len(total)))
669
+ payload = total.iloc[::-1].reset_index(drop=True)
670
+ return payload
671
+
672
+
673
+ def expiry_history(symbol,start_date="",end_date=""):
674
+ if(end_date==""):end_date=end_date
675
+ nsefetch_url = "https://www.nseindia.com/api/historical/fo/derivatives/meta?&from="+start_date+"&to="+end_date+"&symbol="+symbol+""
676
+ payload = nsefetch(nsefetch_url)
677
+ return payload['data'][2]
678
+
679
+ # # Nifty Indicies Site
680
+
681
+ niftyindices_headers = {
682
+ 'Connection': 'keep-alive',
683
+ 'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
684
+ 'Accept': 'application/json, text/javascript, */*; q=0.01',
685
+ 'DNT': '1',
686
+ 'X-Requested-With': 'XMLHttpRequest',
687
+ 'sec-ch-ua-mobile': '?0',
688
+ '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',
689
+ 'Content-Type': 'application/json; charset=UTF-8',
690
+ 'Origin': 'https://niftyindices.com',
691
+ 'Sec-Fetch-Site': 'same-origin',
692
+ 'Sec-Fetch-Mode': 'cors',
693
+ 'Sec-Fetch-Dest': 'empty',
694
+ 'Referer': 'https://niftyindices.com/reports/historical-data',
695
+ 'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
696
+ }
697
+
698
+ def index_history(symbol,start_date,end_date):
699
+ data = "{'name':'"+symbol+"','startDate':'"+start_date+"','endDate':'"+end_date+"'}"
700
+ payload = requests.post('https://niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString', headers=niftyindices_headers, data=data).json()
701
+ payload = json.loads(payload["d"])
702
+ payload=pd.DataFrame.from_records(payload)
703
+ return payload
704
+
705
+ def index_pe_pb_div(symbol,start_date,end_date):
706
+ data = "{'name':'"+symbol+"','startDate':'"+start_date+"','endDate':'"+end_date+"'}"
707
+ payload = requests.post('https://niftyindices.com/Backpage.aspx/getpepbHistoricaldataDBtoString', headers=niftyindices_headers, data=data).json()
708
+ payload = json.loads(payload["d"])
709
+ payload=pd.DataFrame.from_records(payload)
710
+ return payload
711
+
712
+ def index_total_returns(symbol,start_date,end_date):
713
+ data = "{'name':'"+symbol+"','startDate':'"+start_date+"','endDate':'"+end_date+"'}"
714
+ payload = requests.post('https://niftyindices.com/Backpage.aspx/getTotalReturnIndexString', headers=niftyindices_headers, data=data).json()
715
+ payload = json.loads(payload["d"])
716
+ payload=pd.DataFrame.from_records(payload)
717
+ return payload
718
+
719
+ def get_bhavcopy(date):
720
+ date = date.replace("-","")
721
+ payload=pd.read_csv("https://archives.nseindia.com/products/content/sec_bhavdata_full_"+date+".csv")
722
+ return payload
723
+
724
+ def get_bulkdeals():
725
+ payload=pd.read_csv("https://archives.nseindia.com/content/equities/bulk.csv")
726
+ return payload
727
+
728
+ def get_blockdeals():
729
+ payload=pd.read_csv("https://archives.nseindia.com/content/equities/block.csv")
730
+ return payload
731
+
732
+ #Request from subhash
733
+ ## https://unofficed.com/how-to-find-the-beta-of-indian-stocks-using-python/
734
+ def get_beta_df_maker(symbol,days):
735
+ if("NIFTY" in symbol):
736
+ end_date = datetime.datetime.now().strftime("%d-%b-%Y")
737
+ end_date = str(end_date)
738
+
739
+ start_date = (datetime.datetime.now()- datetime.timedelta(days=days)).strftime("%d-%b-%Y")
740
+ start_date = str(start_date)
741
+
742
+ df2=index_history(symbol,start_date,end_date)
743
+ df2["daily_change"]=df2["CLOSE"].astype(float).pct_change()
744
+ df2=df2[['HistoricalDate','daily_change']]
745
+ df2 = df2.iloc[1: , :]
746
+ return df2
747
+ else:
748
+ end_date = datetime.datetime.now().strftime("%d-%m-%Y")
749
+ end_date = str(end_date)
750
+
751
+ start_date = (datetime.datetime.now()- datetime.timedelta(days=days)).strftime("%d-%m-%Y")
752
+ start_date = str(start_date)
753
+
754
+ df = equity_history(symbol,"EQ",start_date,end_date)
755
+
756
+ df["daily_change"]=df["CH_CLOSING_PRICE"].pct_change()
757
+ df=df[['CH_TIMESTAMP','daily_change']]
758
+ df = df.iloc[1: , :] #thispointer.com/drop-first-row-of-pandas-dataframe-3-ways/
759
+ return df
760
+
761
+ def getbeta(symbol,days=365,symbol2="NIFTY 50"):
762
+ return get_beta(symbol,days,symbol2)
763
+
764
+ def get_beta(symbol,days=365,symbol2="NIFTY 50"):
765
+ #Default is 248 days. (Input of Subhash)
766
+ df = get_beta_df_maker(symbol,days)
767
+ df2 = get_beta_df_maker(symbol2,days)
768
+
769
+ x=df["daily_change"].tolist()
770
+ y=df2["daily_change"].tolist()
771
+ #stackoverflow.com/questions/42670055/is-there-any-better-way-to-calculate-the-covariance-of-two-lists-than-this
772
+ mean_x = sum(x) / len(x)
773
+ mean_y = sum(y) / len(y)
774
+ covariance = sum((a - mean_x) * (b - mean_y) for (a,b) in zip(x,y)) / len(x)
775
+
776
+ mean = sum(y) / len(y)
777
+ variance = sum((i - mean) ** 2 for i in y) / len(y)
778
+
779
+ beta = covariance/variance
780
+ return round(beta,3)
781
+
782
+ def nse_preopen(key="NIFTY",type="pandas"):
783
+ payload = nsefetch("https://www.nseindia.com/api/market-data-pre-open?key="+key+"")
784
+ if(type=="pandas"):
785
+ payload = pd.DataFrame(payload['data'])
786
+ payload = pd.json_normalize(payload['metadata'])
787
+ return payload
788
+ else:
789
+ return payload
790
+
791
+ #By Avinash https://forum.unofficed.com/t/nsepython-documentation/376/102?u=dexter
792
+ def nse_preopen_movers(key="FO",filter=1.5):
793
+ preOpen_gainer=nse_preopen(key)
794
+ return preOpen_gainer[preOpen_gainer['pChange'] >1.5],preOpen_gainer[preOpen_gainer['pChange'] <-1.5]
795
+
796
+ # type = "securities"
797
+ # type = "etf"
798
+ # type = "sme"
799
+ #
800
+ # sort = "volume"
801
+ # sort = "value"
802
+
803
+ def nse_most_active(type="securities",sort="value"):
804
+ payload = nsefetch("https://www.nseindia.com/api/live-analysis-most-active-"+type+"?index="+sort+"")
805
+ payload = pd.DataFrame(payload["data"])
806
+ return payload
807
+
808
+
809
+ def nse_eq_symbols():
810
+ #https://forum.unofficed.com/t/feature-request-stocklist-api/1073/11
811
+ eq_list_pd = pd.read_csv('https://archives.nseindia.com/content/equities/EQUITY_L.csv')
812
+ return eq_list_pd['SYMBOL'].tolist()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: nsepython
3
- Version: 0.0.973
3
+ Version: 1.1
4
4
  Summary: Python library for NSE India APIs
5
5
  Home-page: https://github.com/aeron7/nsepython
6
6
  Author: Aeron7
@@ -30,9 +30,7 @@ License-File: LICENSE
30
30
  </a>
31
31
  </p>
32
32
 
33
- The library gets constant updates based on feedbacks. <br/>
34
- So many of the functions are in beta phase. <br/>
35
- But to see all beta functions You can see - [https://forum.unofficed.com/t/nsepython-documentation/376/107](https://forum.unofficed.com/t/nsepython-documentation/376/107)
33
+ For Support and Beta Functions - [https://forum.unofficed.com/t/nsepython-documentation/376/107](https://forum.unofficed.com/t/nsepython-documentation/376/107)
36
34
 
37
35
  ## Installation
38
36
 
@@ -45,13 +43,12 @@ pip install nsepython
45
43
  All the functions of the two famous packages NsepY and NSETools are also migrated here with same function name. <br/>
46
44
  They were both unmaintained since long time.
47
45
 
48
- ## Advanced Usecases
46
+ ## Advanced Usecases
49
47
  [Calculate any Option Greek using Black Scholes Formula in Python](https://unofficed.com/black-scholes-formula-in-python/)
50
48
 
51
49
  [ How to find the beta of Indian stocks using Python?](https://unofficed.com/how-to-find-the-beta-of-indian-stocks-using-python/)
52
50
 
51
+ [How to get Historical PE, PB and Dividend Ratio of any index using Python](https://unofficed.com/nse-python/documentation/nsepy/#index_pe_pb_div)
52
+
53
53
  ## Contributing
54
54
  For Discussion and Improving this Code, Join - https://www.unofficed.com/chat/
55
-
56
- ## License
57
- [MIT](https://choosealicense.com/licenses/mit/)
@@ -3,6 +3,7 @@ README.md
3
3
  setup.py
4
4
  nsepython/__init__.py
5
5
  nsepython/rahu.py
6
+ nsepython/rahuserver.py
6
7
  nsepython.egg-info/PKG-INFO
7
8
  nsepython.egg-info/SOURCES.txt
8
9
  nsepython.egg-info/dependency_links.txt
@@ -6,7 +6,7 @@ with open("README.md", "r") as fh:
6
6
  setuptools.setup(
7
7
  name = 'nsepython',
8
8
  packages=setuptools.find_packages(),
9
- version = '0.0.973',
9
+ version = '1.1',
10
10
  include_package_data=True,
11
11
  description = 'Python library for NSE India APIs',
12
12
  long_description=long_description,
File without changes
File without changes