Spaces:
Running
Running
Create build_nse_fno.py
Browse files- build_nse_fno.py +116 -0
build_nse_fno.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# build_nse_fno.py
|
| 2 |
+
import subprocess, zipfile, pandas as pd, datetime, os, tempfile
|
| 3 |
+
|
| 4 |
+
# ----------------- Fetch Bhavcopy -----------------
|
| 5 |
+
def fo_bhavcopy(date_input) -> pd.DataFrame:
|
| 6 |
+
if isinstance(date_input, str):
|
| 7 |
+
date = datetime.datetime.strptime(date_input, "%d-%m-%Y").date()
|
| 8 |
+
elif isinstance(date_input, datetime.datetime):
|
| 9 |
+
date = date_input.date()
|
| 10 |
+
elif isinstance(date_input, datetime.date):
|
| 11 |
+
date = date_input
|
| 12 |
+
else:
|
| 13 |
+
raise ValueError("Invalid date format. Use dd-mm-yyyy")
|
| 14 |
+
|
| 15 |
+
ymd = date.strftime("%Y%m%d")
|
| 16 |
+
file_name = f"BhavCopy_NSE_FO_0_0_0_{ymd}_F_0000.csv"
|
| 17 |
+
zip_name = f"{file_name}.zip"
|
| 18 |
+
url = f"https://nsearchives.nseindia.com/content/fo/{zip_name}"
|
| 19 |
+
|
| 20 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 21 |
+
zip_path = os.path.join(tmpdir, zip_name)
|
| 22 |
+
cmd = ["curl", "-L", "-A", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
|
| 23 |
+
"--tlsv1.2", "--compressed", "-o", zip_path, url]
|
| 24 |
+
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 25 |
+
if res.returncode != 0 or not os.path.exists(zip_path) or os.path.getsize(zip_path) < 1024:
|
| 26 |
+
raise RuntimeError("Download failed or blocked")
|
| 27 |
+
with zipfile.ZipFile(zip_path) as z, z.open(file_name) as f:
|
| 28 |
+
df = pd.read_csv(f)
|
| 29 |
+
return df
|
| 30 |
+
|
| 31 |
+
# ----------------- Build Option Chain -----------------
|
| 32 |
+
def build_option_chain(opt_df):
|
| 33 |
+
drop = ["FininstrmActlXpryDt","FinInstrmTp","TckrSymb","TtlNbOfTxsExctd",
|
| 34 |
+
"NewBrdLotQty","EXP_DMY","SttlmPric",'OpnPric','HghPric','LwPric','TtlTrfVal']
|
| 35 |
+
rename = {"ClsPric":"close","PrvsClsgPric":"pre","OpnIntrst":"oi",
|
| 36 |
+
"ChngInOpnIntrst":"oi_chg","TtlTradgVol":"vol"}
|
| 37 |
+
opt_df = opt_df.drop(drop, axis=1).rename(columns=rename)
|
| 38 |
+
|
| 39 |
+
ce = opt_df[opt_df['OptnTp']=='CE'].rename(columns={c:f"ce_{c}" for c in opt_df.columns})
|
| 40 |
+
pe = opt_df[opt_df['OptnTp']=='PE'].rename(columns={c:f"pe_{c}" for c in opt_df.columns})
|
| 41 |
+
|
| 42 |
+
chain = pd.merge(ce, pe, left_on='ce_StrkPric', right_on='pe_StrkPric', how='outer')
|
| 43 |
+
chain['StrkPric'] = chain['ce_StrkPric'].combine_first(chain['pe_StrkPric'])
|
| 44 |
+
chain.drop(columns=['ce_StrkPric','pe_StrkPric','ce_OptnTp','pe_OptnTp','ce_UndrlygPric','pe_UndrlygPric'], inplace=True)
|
| 45 |
+
chain = chain.fillna(0).sort_values('StrkPric').reset_index(drop=True)
|
| 46 |
+
|
| 47 |
+
cols = ['ce_oi','ce_oi_chg','ce_vol','ce_close','ce_pre','StrkPric',
|
| 48 |
+
'pe_pre','pe_close','pe_vol','pe_oi_chg','pe_oi']
|
| 49 |
+
df = chain[cols].copy()
|
| 50 |
+
for c in ['ce_close','ce_pre','pe_close','pe_pre']:
|
| 51 |
+
df[c] = df[c].apply(lambda x: f"{x:.2f}")
|
| 52 |
+
for c in ['ce_oi','ce_oi_chg','ce_vol','pe_vol','pe_oi_chg','pe_oi','StrkPric']:
|
| 53 |
+
df[c] = df[c].astype(int)
|
| 54 |
+
return df
|
| 55 |
+
|
| 56 |
+
# ----------------- HTML Rendering -----------------
|
| 57 |
+
def df_to_html(df, title=None):
|
| 58 |
+
style = (
|
| 59 |
+
"<style>"
|
| 60 |
+
"table {border-collapse: collapse; width: 100%; font-family: Arial, sans-serif;}"
|
| 61 |
+
"th, td {border: 1px solid #ddd; padding: 8px; text-align: center;}"
|
| 62 |
+
"th {background-color: #4CAF50; color: white;}"
|
| 63 |
+
"tr:nth-child(even){background-color: #f2f2f2;}"
|
| 64 |
+
"tr:hover {background-color: #ddd;}"
|
| 65 |
+
"</style>"
|
| 66 |
+
)
|
| 67 |
+
html = df.to_html(index=False, escape=False)
|
| 68 |
+
if title: html = f"<h3>{title}</h3>" + html
|
| 69 |
+
return style + html
|
| 70 |
+
|
| 71 |
+
# ----------------- Main Combined Function -----------------
|
| 72 |
+
def nse_fno_html(fo_date, symbol):
|
| 73 |
+
"""
|
| 74 |
+
Fetch NSE F&O data and return a single HTML string
|
| 75 |
+
containing common, future, and option tables
|
| 76 |
+
"""
|
| 77 |
+
fo_df = fo_bhavcopy(fo_date)
|
| 78 |
+
fo = fo_df.copy().drop(['ISIN','Rmks','SctySrs','Rsvd1','Rsvd2','Rsvd3','Rsvd4'], axis=1, errors='ignore')
|
| 79 |
+
|
| 80 |
+
# Common Info
|
| 81 |
+
drop_cols = ['TradDt','BizDt','Sgmt','Src','SsnId','FinInstrmId','XpryDt','FinInstrmNm','LastPric']
|
| 82 |
+
common_df = pd.DataFrame([fo.loc[fo.index[1], drop_cols]])
|
| 83 |
+
|
| 84 |
+
# Determine expiry
|
| 85 |
+
exp = pd.to_datetime(fo['FininstrmActlXpryDt'], errors='coerce')
|
| 86 |
+
today = pd.Timestamp.today().normalize()
|
| 87 |
+
monthly_exp = exp[exp>=today].groupby([exp.dt.year, exp.dt.month]).max().sort_values()
|
| 88 |
+
if monthly_exp.empty: return "<h3>No valid expiry found</h3>"
|
| 89 |
+
expiry = monthly_exp.iloc[0].strftime("%d-%m-%Y")
|
| 90 |
+
common_df.insert(0, 'Expiry', expiry)
|
| 91 |
+
|
| 92 |
+
# Filter by symbol + expiry
|
| 93 |
+
fo['EXP_DMY'] = pd.to_datetime(fo['FininstrmActlXpryDt']).dt.strftime("%d-%m-%Y")
|
| 94 |
+
df = fo[(fo['TckrSymb']==symbol) & (fo['EXP_DMY']==expiry)].copy()
|
| 95 |
+
df.drop(columns=drop_cols, inplace=True, errors='ignore')
|
| 96 |
+
|
| 97 |
+
future_df = df[(df['FinInstrmTp']=='STF') | (df['FinInstrmTp']=='IDF')].copy()
|
| 98 |
+
option_df = df[(df['FinInstrmTp']=='STO') | (df['FinInstrmTp']=='IDO')].copy()
|
| 99 |
+
option_chain_df = build_option_chain(option_df)
|
| 100 |
+
|
| 101 |
+
# Build combined HTML
|
| 102 |
+
html = df_to_html(common_df, "Common Info") + "<br><br>"
|
| 103 |
+
html += df_to_html(future_df, "Future Contracts") + "<br><br>"
|
| 104 |
+
html += df_to_html(option_chain_df, "Option Chain")
|
| 105 |
+
return html
|
| 106 |
+
'''
|
| 107 |
+
# ----------------- Example Usage -----------------
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
date_str = "16-12-2025"
|
| 110 |
+
symbol = "NIFTY"
|
| 111 |
+
html_output = nse_fno_html(date_str, symbol)
|
| 112 |
+
# Save to file or render in web page
|
| 113 |
+
with open("fno.html", "w") as f:
|
| 114 |
+
f.write(html_output)
|
| 115 |
+
print("HTML saved to fno.html")
|
| 116 |
+
'''
|