eshan6704 commited on
Commit
a106796
·
verified ·
1 Parent(s): 9d2838a

Create nsepython.py

Browse files
Files changed (1) hide show
  1. nsepython.py +220 -0
nsepython.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys, requests, pandas as pd, json, random, datetime, time, logging, re, urllib.parse
2
+ from collections import Counter
3
+
4
+ mode = 'local'
5
+
6
+ # ------------------------- NSE FETCH -------------------------
7
+ if mode == "vpn":
8
+ def nsefetch(payload):
9
+ def encode(url): return url if "%26" in url or "%20" in url else urllib.parse.quote(url, safe=":/?&=")
10
+ def refresh_cookies():
11
+ os.popen(f'curl -c cookies.txt "https://www.nseindia.com" {curl_headers}').read()
12
+ os.popen(f'curl -b cookies.txt -c cookies.txt "https://www.nseindia.com/option-chain" {curl_headers}').read()
13
+
14
+ if not os.path.exists("cookies.txt"): refresh_cookies()
15
+ encoded = encode(payload)
16
+ cmd = f'curl -b cookies.txt "{encoded}" {curl_headers}'
17
+ raw = os.popen(cmd).read()
18
+ try: return json.loads(raw)
19
+ except:
20
+ refresh_cookies()
21
+ raw = os.popen(cmd).read()
22
+ try: return json.loads(raw)
23
+ except: return {}
24
+
25
+ if mode == 'local':
26
+ def nsefetch(payload):
27
+ try:
28
+ s = requests.Session()
29
+ s.get("https://www.nseindia.com", headers=headers, timeout=10)
30
+ s.get("https://www.nseindia.com/option-chain", headers=headers, timeout=10)
31
+ return s.get(payload, headers=headers, timeout=10).json()
32
+ except:
33
+ return {}
34
+
35
+ # ------------------------- HEADERS -------------------------
36
+ headers = {
37
+ "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",
38
+ "accept-language": "en-US,en;q=0.9,en-IN;q=0.8,en-GB;q=0.7",
39
+ "cache-control": "max-age=0",
40
+ "priority": "u=0, i",
41
+ "sec-ch-ua": '"Microsoft Edge";v="129","Not=A?Brand";v="8","Chromium";v="129"',
42
+ "sec-ch-ua-mobile": "?0",
43
+ "sec-ch-ua-platform": '"Windows"',
44
+ "sec-fetch-dest": "document",
45
+ "sec-fetch-mode": "navigate",
46
+ "sec-fetch-site": "none",
47
+ "sec-fetch-user": "?1",
48
+ "upgrade-insecure-requests": "1",
49
+ "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"
50
+ }
51
+
52
+ niftyindices_headers = {
53
+ 'Connection': 'keep-alive',
54
+ 'sec-ch-ua': '"Not;A Brand";v="99","Google Chrome";v="91","Chromium";v="91"',
55
+ 'Accept': 'application/json,text/javascript,*/*;q=0.01',
56
+ 'DNT': '1',
57
+ 'X-Requested-With': 'XMLHttpRequest',
58
+ 'sec-ch-ua-mobile': '?0',
59
+ 'User-Agent': 'Mozilla/5.0',
60
+ 'Content-Type': 'application/json; charset=UTF-8',
61
+ 'Origin': 'https://niftyindices.com',
62
+ 'Sec-Fetch-Site': 'same-origin',
63
+ 'Sec-Fetch-Mode': 'cors',
64
+ 'Sec-Fetch-Dest': 'empty',
65
+ 'Referer': 'https://niftyindices.com/reports/historical-data',
66
+ 'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8'
67
+ }
68
+
69
+ 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" -H "sec-fetch-user: ?1" -H "accept: */*" -H "sec-fetch-site: none" -H "accept-language: en-US,en;q=0.9" --compressed'''
70
+
71
+ run_time = datetime.datetime.now()
72
+ indices = ['NIFTY','FINNIFTY','BANKNIFTY']
73
+
74
+ # ------------------------- HELPERS -------------------------
75
+ def nsesymbolpurify(s): return s.replace('&','%26')
76
+
77
+ def flatten_dict(d, parent="", sep="."):
78
+ items={}
79
+ for k,v in d.items():
80
+ nk = f"{parent}{sep}{k}" if parent else k
81
+ if isinstance(v, dict): items.update(flatten_dict(v, nk, sep))
82
+ else: items[nk] = v
83
+ return items
84
+
85
+ def flatten_nested(d, prefix=""):
86
+ flat={}
87
+ for k,v in d.items():
88
+ nk = f"{prefix}{k}" if prefix=="" else f"{prefix}.{k}"
89
+ if isinstance(v, dict):
90
+ flat.update(flatten_nested(v, nk))
91
+ elif isinstance(v, list):
92
+ if v and isinstance(v[0], dict):
93
+ for i,x in enumerate(v): flat.update(flatten_nested(x, f"{nk}.{i}"))
94
+ else: flat[nk]=v
95
+ else: flat[nk]=v
96
+ return flat
97
+
98
+ def rename_col(cols):
99
+ child=[c.split('.')[-1] for c in cols]
100
+ cnt=Counter(child)
101
+ new=[]
102
+ for c,ch in zip(cols,child):
103
+ if cnt[ch]==1: new.append(ch)
104
+ else:
105
+ p=c.split('.')
106
+ new.append(f"{p[-1]}_{p[-2]}" if len(p)>=2 else p[-1])
107
+ return new
108
+
109
+ def df_from_data(data):
110
+ rows=[ flatten_nested(x) if isinstance(x,dict) else {"value":x} for x in data ]
111
+ df=pd.DataFrame(rows)
112
+ df.columns=rename_col(df.columns)
113
+ return df
114
+
115
+ # ------------------------- API FUNCTIONS -------------------------
116
+ def indices():
117
+ p=nsefetch("https://www.nseindia.com/api/allIndices")
118
+ return {"data":pd.DataFrame(p.pop("data")), "dates":pd.DataFrame([p.pop("dates")]), "indices":pd.DataFrame([p])}
119
+
120
+ def eq(symbol):
121
+ symbol=nsesymbolpurify(symbol)
122
+ df=nsefetch(f'https://www.nseindia.com/api/quote-equity?symbol={symbol}')
123
+ pre=df.pop('preOpenMarket')
124
+ out={
125
+ "securityInfo": pd.DataFrame([df["securityInfo"]]),
126
+ "priceInfo": pd.DataFrame([flatten_dict(df["priceInfo"])]),
127
+ "industryInfo": pd.DataFrame([df["industryInfo"]]),
128
+ "pdSectorIndAll": pd.DataFrame([df["metadata"].pop("pdSectorIndAll")]),
129
+ "metadata": pd.DataFrame([df["metadata"]]),
130
+ "info": pd.DataFrame([df["info"]]),
131
+ "preOpen": pd.DataFrame(pre.pop('preopen')),
132
+ "preOpenMarket": pd.DataFrame([pre])
133
+ }
134
+ return out
135
+
136
+ def eq_fno(): return nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
137
+ def eq_der(symbol): return nsefetch('https://www.nseindia.com/api/quote-derivative?symbol='+nsesymbolpurify(symbol))
138
+ def index_chain(symbol): return nsefetch('https://www.nseindia.com/api/option-chain-indices?symbol='+nsesymbolpurify(symbol))
139
+ def eq_chain(symbol): return nsefetch('https://www.nseindia.com/api/option-chain-equities?symbol='+nsesymbolpurify(symbol))
140
+ def nse_holidays(t="trading"): return nsefetch('https://www.nseindia.com/api/holiday-master?type='+t)
141
+
142
+ def nse_results(index="equities",period="Quarterly"):
143
+ if index in ["equities","debt","sme"] and period in ["Quarterly","Annual","Half-Yearly","Others"]:
144
+ return pd.json_normalize(nsefetch(f'https://www.nseindia.com/api/corporates-financial-results?index={index}&period={period}'))
145
+ print("Invalid Input")
146
+
147
+ def nse_events(): return pd.json_normalize(nsefetch('https://www.nseindia.com/api/event-calendar'))
148
+ def nse_past_results(symbol): return nsefetch('https://www.nseindia.com/api/results-comparision?symbol='+nsesymbolpurify(symbol))
149
+ def nse_blockdeal(): return nsefetch('https://nseindia.com/api/block-deal')
150
+ def nse_marketStatus(): return nsefetch('https://nseindia.com/api/marketStatus')
151
+ def nse_circular(mode="latest"):
152
+ return nsefetch('https://www.nseindia.com/api/latest-circular' if mode=="latest" else 'https://www.nseindia.com/api/circulars')
153
+
154
+ def nse_fiidii(mode="pandas"):
155
+ try:
156
+ p=nsefetch('https://www.nseindia.com/api/fiidiiTradeReact')
157
+ return pd.DataFrame(p) if mode=="pandas" else p
158
+ except:
159
+ return nsefetch('https://www.nseindia.com/api/fiidiiTradeReact')
160
+
161
+ def nsetools_get_quote(symbol):
162
+ p=nsefetch('https://www.nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O')
163
+ for x in p['data']:
164
+ if x['symbol']==symbol.upper(): return x
165
+
166
+ def nse_index():
167
+ p=nsefetch('https://iislliveblob.niftyindices.com/jsonfiles/LiveIndicesWatch.json')
168
+ return pd.DataFrame(p['data'])
169
+
170
+ def index_history(sym,sd,ed):
171
+ d={'cinfo':f"{{'name':'{sym}','startDate':'{sd}','endDate':'{ed}','indexName':'{sym}'}}"}
172
+ p=json.loads(requests.post('https://niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString', headers=niftyindices_headers, json=d).json()["d"])
173
+ return pd.DataFrame.from_records(p)
174
+
175
+ def index_pe_pb_div(sym,sd,ed):
176
+ d={'cinfo':f"{{'name':'{sym}','startDate':'{sd}','endDate':'{ed}','indexName':'{sym}'}}"}
177
+ p=json.loads(requests.post('https://niftyindices.com/Backpage.aspx/getpepbHistoricaldataDBtoString', headers=niftyindices_headers, json=d).json()["d"])
178
+ return pd.DataFrame.from_records(p)
179
+
180
+ def index_total_returns(sym,sd,ed):
181
+ d={'cinfo':f"{{'name':'{sym}','startDate':'{sd}','endDate':'{ed}','indexName':'{sym}'}}"}
182
+ p=json.loads(requests.post('https://niftyindices.com/Backpage.aspx/getTotalReturnIndexString', headers=niftyindices_headers, json=d).json()["d"])
183
+ return pd.DataFrame.from_records(p)
184
+
185
+ def get_bhavcopy(d): return pd.read_csv("https://archives.nseindia.com/products/content/sec_bhavdata_full_"+d.replace("-","")+".csv")
186
+ def get_bulkdeals(): return pd.read_csv("https://archives.nseindia.com/content/equities/bulk.csv")
187
+ def get_blockdeals(): return pd.read_csv("https://archives.nseindia.com/content/equities/block.csv")
188
+
189
+ def nse_preopen(key="NIFTY"):
190
+ p=nsefetch("https://www.nseindia.com/api/market-data-pre-open?key="+key)
191
+ return {"data":df_from_data(p.pop("data")), "rem":df_from_data([p])}
192
+
193
+ def nse_most_active(t="securities",s="value"):
194
+ return pd.DataFrame(nsefetch(f"https://www.nseindia.com/api/live-analysis-most-active-{t}?index={s}")["data"])
195
+
196
+ def nse_eq_symbols():
197
+ return pd.read_csv('https://archives.nseindia.com/content/equities/EQUITY_L.csv')['SYMBOL'].tolist()
198
+
199
+ def nse_price_band_hitters(b="both",v="AllSec"):
200
+ p=nsefetch("https://www.nseindia.com/api/live-analysis-price-band-hitter")
201
+ return {"data":pd.DataFrame(p[b][v]["data"]), "count":pd.DataFrame([p['count']])}
202
+
203
+ def nse_largedeals(mode="bulk_deals"):
204
+ p=nsefetch('https://www.nseindia.com/api/snapshot-capital-market-largedeal')
205
+ return pd.DataFrame(p["BULK_DEALS_DATA" if mode=="bulk_deals" else "SHORT_DEALS_DATA" if mode=="short_deals" else "BLOCK_DEALS_DATA"])
206
+
207
+ def nse_largedeals_historical(f,t,mode="bulk_deals"):
208
+ m = "bulk-deals" if mode=="bulk_deals" else "short-selling" if mode=="short_deals" else "block-deals"
209
+ p=nsefetch(f'https://www.nseindia.com/api/historical/{m}?from={f}&to={t}')
210
+ return pd.DataFrame(p["data"])
211
+
212
+ def stock_hist(f,t,symbol,series="ALL"):
213
+ url=f"https://www.nseindia.com/api/historical/securityArchives?from={f}&to={t}&symbol={symbol.upper()}&dataType=priceVolumeDeliverable&series={series}"
214
+ return pd.DataFrame(nsefetch(url)['data'])
215
+
216
+ def nse_index_live(name="NIFTY 50"):
217
+ p=nsefetch(f"https://www.nseindia.com/api/equity-stockIndices?index={name.replace(' ','%20')}")
218
+ return {"data":df_from_data(p.pop("data")) if "data" in p else pd.DataFrame(), "rem":df_from_data([p])}
219
+ def indices_list():
220
+ indices