eshan6704 commited on
Commit
92e3270
Β·
verified Β·
1 Parent(s): 77e4438

Update nse.py

Browse files
Files changed (1) hide show
  1. nse.py +98 -51
nse.py CHANGED
@@ -106,18 +106,34 @@ def indices():
106
  # ---------------------------------------------------
107
  # Specific Index β†’ DataFrames
108
  # ---------------------------------------------------
109
- def nse_index_df(index_name="NIFTY 50"):
110
  url = f"https://www.nseindia.com/api/equity-stockIndices?index={index_name.replace(' ', '%20')}"
111
  data = fetch_data(url)
112
  if data is None:
113
- return None, None, None, None
114
 
 
115
  df_market = pd.DataFrame([data["marketStatus"]])
116
- df_adv = pd.DataFrame([data["advance"]])
117
- df_meta = pd.DataFrame([data["metadata"]])
118
- df_data = pd.DataFrame(data["data"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
- return df_market, df_adv, df_meta, df_data
121
 
122
  # ---------------------------------------------------
123
  # Option Chain DF (Raw CE/PE)
@@ -136,22 +152,31 @@ def fetch_option_chain_df(symbol="NIFTY"):
136
  # ---------------------------------------------------
137
  # Pre-open market β†’ DataFrame
138
  # ---------------------------------------------------
139
- def nse_preopen_df(key="NIFTY"):
140
  url = f"https://www.nseindia.com/api/market-data-pre-open?key={key}"
141
  data = fetch_data(url)
142
- if data:
143
- return pd.DataFrame(data.get("data", []))
144
- return None
 
 
 
 
 
 
 
 
 
145
 
146
  # ---------------------------------------------------
147
  # FNO Quote β†’ DataFrames
148
  # ---------------------------------------------------
149
- def nse_fno_df(symbol):
150
- payload = nsepython.nse_quote(symbol) # Direct call
151
  if not payload:
152
  return None
153
 
154
- # info + timestamps + volatility info
155
  info_keys = list(payload["info"].keys()) + [
156
  "fut_timestamp",
157
  "opt_timestamp",
@@ -170,18 +195,30 @@ def nse_fno_df(symbol):
170
 
171
  df_info = pd.DataFrame([info_values], columns=info_keys)
172
 
 
173
  df_mcap = pd.DataFrame(payload["underlyingInfo"].get("marketCap", {}))
 
 
174
  df_fno_list = pd.DataFrame(payload.get("allSymbol", []), columns=["FNO_Symbol"])
175
 
176
- # Core stock depth
177
  df_stock = process_stocks_df(payload["stocks"])
178
 
179
- return {
180
- "info": df_info,
181
- "mcap": df_mcap,
182
- "fno": df_fno_list,
183
- "stock": df_stock
184
- }
 
 
 
 
 
 
 
 
 
185
 
186
  # ---------------------------------------------------
187
  # Handle nested stock β†’ DF
@@ -275,8 +312,7 @@ def to_numeric_safe(series):
275
  series = series.astype(str).str.replace(',', '')
276
  return pd.to_numeric(series, errors='coerce').fillna(0)
277
 
278
-
279
- def nse_del(symbol, start_date_str=None, end_date_str=None):
280
  # Default end date is today
281
  end_date = datetime.now()
282
  if end_date_str:
@@ -286,7 +322,7 @@ def nse_del(symbol, start_date_str=None, end_date_str=None):
286
  print(f"Warning: Invalid end date format '{end_date_str}'. Using today's date.")
287
  end_date = datetime.now()
288
 
289
- # Default start date is one year prior to end_date
290
  start_date = end_date - timedelta(days=365)
291
  if start_date_str:
292
  try:
@@ -295,41 +331,52 @@ def nse_del(symbol, start_date_str=None, end_date_str=None):
295
  print(f"Warning: Invalid start date format '{start_date_str}'. Using default start date.")
296
  start_date = end_date - timedelta(days=365)
297
 
298
- # Ensure start_date is not after end_date
299
  if start_date > end_date:
300
  print("Warning: Start date is after end date. Swapping dates.")
301
  start_date, end_date = end_date, start_date
302
 
303
  url = url_nse_del(symbol, start_date, end_date)
304
- headers = {
305
- 'User-Agent': 'Mozilla/5.0'
306
- }
307
  try:
308
  response = requests.get(url, headers=headers)
309
  response.raise_for_status()
310
- if response.content:
311
- df = pd.read_csv(io.StringIO(response.content.decode('utf-8'))).round(2)
312
- df.columns = df.columns.str.strip()
313
- df.rename(columns=nse_del_key_map, inplace=True)
314
-
315
- # Capitalize the first letter of ALL column names after renaming
316
- df.columns = [col.capitalize() for col in df.columns]
317
-
318
- # Remove 'Symbol', 'Series', 'Avgprice', and 'Last' columns (now capitalized)
319
- df.drop(columns=['Symbol','Series','Avgprice','Last'], errors='ignore', inplace=True)
320
-
321
- # Convert 'Date' column to datetime objects
322
- df['Date'] = pd.to_datetime(df['Date'], format='%d-%b-%Y').dt.strftime('%Y-%m-%d')
323
-
324
- numeric_cols = ['Close', 'Preclose', 'Open', 'High', 'Low', 'Volume', 'Delivery', 'Turnover', 'Trades']
325
- # Ensure numeric_cols are capitalized before checking and conversion
326
- numeric_cols_capitalized = [col.capitalize() for col in numeric_cols]
327
- for col in numeric_cols_capitalized:
328
- if col in df.columns:
329
- df[col] = to_numeric_safe(df[col])
330
- else:
331
- df[col] = 0
332
- return df
 
 
 
 
 
 
 
 
 
 
 
333
  except Exception as e:
334
  print(f"Error fetching data from NSE for {symbol}: {e}")
335
- return None
 
 
106
  # ---------------------------------------------------
107
  # Specific Index β†’ DataFrames
108
  # ---------------------------------------------------
109
+ def open(index_name="NIFTY 50"):
110
  url = f"https://www.nseindia.com/api/equity-stockIndices?index={index_name.replace(' ', '%20')}"
111
  data = fetch_data(url)
112
  if data is None:
113
+ return None
114
 
115
+ # Create DataFrames
116
  df_market = pd.DataFrame([data["marketStatus"]])
117
+ df_adv = pd.DataFrame([data["advance"]])
118
+ df_meta = pd.DataFrame([data["metadata"]])
119
+ df_data = pd.DataFrame(data["data"])
120
+
121
+ # Convert to HTML
122
+ html_market = df_market.to_html(index=False, border=1)
123
+ html_adv = df_adv.to_html(index=False, border=1)
124
+ html_meta = df_meta.to_html(index=False, border=1)
125
+ html_data = df_data.to_html(index=False, border=1)
126
+
127
+ # Combine all into single HTML string
128
+ full_html = (
129
+ "<h3>Market Status</h3>" + html_market +
130
+ "<br><h3>Advance / Decline</h3>" + html_adv +
131
+ "<br><h3>Metadata</h3>" + html_meta +
132
+ "<br><h3>Index Data</h3>" + html_data
133
+ )
134
+
135
+ return full_html
136
 
 
137
 
138
  # ---------------------------------------------------
139
  # Option Chain DF (Raw CE/PE)
 
152
  # ---------------------------------------------------
153
  # Pre-open market β†’ DataFrame
154
  # ---------------------------------------------------
155
+ def preopen(key="NIFTY"):
156
  url = f"https://www.nseindia.com/api/market-data-pre-open?key={key}"
157
  data = fetch_data(url)
158
+ if not data:
159
+ return None
160
+
161
+ df = pd.DataFrame(data.get("data", []))
162
+
163
+ # Convert to one HTML table
164
+ html_table = df.to_html(index=False, border=1)
165
+
166
+ # Wrap into single block
167
+ full_html = "<h3>Pre-Open Market Data</h3>" + html_table
168
+
169
+ return full_html
170
 
171
  # ---------------------------------------------------
172
  # FNO Quote β†’ DataFrames
173
  # ---------------------------------------------------
174
+ def fno(symbol):
175
+ payload = nsepython.nse_quote(symbol)
176
  if not payload:
177
  return None
178
 
179
+ # ---------- INFO ----------
180
  info_keys = list(payload["info"].keys()) + [
181
  "fut_timestamp",
182
  "opt_timestamp",
 
195
 
196
  df_info = pd.DataFrame([info_values], columns=info_keys)
197
 
198
+ # ---------- MCAP ----------
199
  df_mcap = pd.DataFrame(payload["underlyingInfo"].get("marketCap", {}))
200
+
201
+ # ---------- FNO LIST ----------
202
  df_fno_list = pd.DataFrame(payload.get("allSymbol", []), columns=["FNO_Symbol"])
203
 
204
+ # ---------- STOCK DEPTH ----------
205
  df_stock = process_stocks_df(payload["stocks"])
206
 
207
+ # Convert all to HTML
208
+ html_info = df_info.to_html(index=False, border=1)
209
+ html_mcap = df_mcap.to_html(index=False, border=1)
210
+ html_fno = df_fno_list.to_html(index=False, border=1)
211
+ html_stock = df_stock.to_html(index=False, border=1)
212
+
213
+ # Combine into full HTML block
214
+ full_html = (
215
+ "<h3>FNO Info</h3>" + html_info +
216
+ "<br><h3>Market Cap</h3>" + html_mcap +
217
+ "<br><h3>FNO Symbol List</h3>" + html_fno +
218
+ "<br><h3>Stock Depth</h3>" + html_stock
219
+ )
220
+
221
+ return full_html
222
 
223
  # ---------------------------------------------------
224
  # Handle nested stock β†’ DF
 
312
  series = series.astype(str).str.replace(',', '')
313
  return pd.to_numeric(series, errors='coerce').fillna(0)
314
 
315
+ def nse_daily(symbol, start_date_str=None, end_date_str=None):
 
316
  # Default end date is today
317
  end_date = datetime.now()
318
  if end_date_str:
 
322
  print(f"Warning: Invalid end date format '{end_date_str}'. Using today's date.")
323
  end_date = datetime.now()
324
 
325
+ # Default start date is one year prior
326
  start_date = end_date - timedelta(days=365)
327
  if start_date_str:
328
  try:
 
331
  print(f"Warning: Invalid start date format '{start_date_str}'. Using default start date.")
332
  start_date = end_date - timedelta(days=365)
333
 
334
+ # Swap if needed
335
  if start_date > end_date:
336
  print("Warning: Start date is after end date. Swapping dates.")
337
  start_date, end_date = end_date, start_date
338
 
339
  url = url_nse_del(symbol, start_date, end_date)
340
+ headers = {"User-Agent": "Mozilla/5.0"}
341
+
 
342
  try:
343
  response = requests.get(url, headers=headers)
344
  response.raise_for_status()
345
+
346
+ if not response.content:
347
+ return None
348
+
349
+ # Build DataFrame
350
+ df = pd.read_csv(io.StringIO(response.content.decode("utf-8"))).round(2)
351
+ df.columns = df.columns.str.strip()
352
+ df.rename(columns=nse_del_key_map, inplace=True)
353
+
354
+ # Capitalize column names
355
+ df.columns = [col.capitalize() for col in df.columns]
356
+
357
+ # Remove unwanted columns
358
+ df.drop(columns=["Symbol", "Series", "Avgprice", "Last"], errors="ignore", inplace=True)
359
+
360
+ # Format date
361
+ df["Date"] = pd.to_datetime(df["Date"], format="%d-%b-%Y").dt.strftime("%Y-%m-%d")
362
+
363
+ # Ensure numeric columns
364
+ numeric_cols = ['Close', 'Preclose', 'Open', 'High', 'Low', 'Volume', 'Delivery', 'Turnover', 'Trades']
365
+ numeric_cols_cap = [c.capitalize() for c in numeric_cols]
366
+
367
+ for col in numeric_cols_cap:
368
+ if col in df.columns:
369
+ df[col] = to_numeric_safe(df[col])
370
+ else:
371
+ df[col] = 0
372
+
373
+ # Convert to HTML
374
+ html_table = df.to_html(index=False, border=1)
375
+
376
+ full_html = "<h3>Daily Data</h3>" + html_table
377
+ return full_html
378
+
379
  except Exception as e:
380
  print(f"Error fetching data from NSE for {symbol}: {e}")
381
+ return None
382
+