eshan6704 commited on
Commit
fff5460
·
verified ·
1 Parent(s): 2a1ebf2

Create index_live_html.py

Browse files
Files changed (1) hide show
  1. app/index_live_html.py +185 -0
app/index_live_html.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from nsepython import *
2
+ import pandas as pd
3
+ from datetime import datetime as dt
4
+
5
+ # persist helpers (HF only)
6
+ from persist import exists, load, save
7
+
8
+
9
+ def build_index_live_html():
10
+ """
11
+ Live HTML for NIFTY 50
12
+ - Intraday TTL (15 minutes)
13
+ - HTML only cache
14
+ - persist.py controls validity
15
+ """
16
+
17
+ # ================= CACHE (TTL via persist) =================
18
+ cache_name = "INTRADAY_INDEX_LIVE_NIFTY50"
19
+
20
+ if exists(cache_name, "html"):
21
+ cached_html = load(cache_name, "html")
22
+ if isinstance(cached_html, str):
23
+ return cached_html
24
+
25
+ # ================= LIVE FETCH =================
26
+ index_name = "NIFTY 50"
27
+ p = nse_index_live(index_name)
28
+
29
+ full_df = p.get("data", pd.DataFrame())
30
+ rem_df = p.get("rem", pd.DataFrame())
31
+
32
+ if full_df.empty:
33
+ main_df = pd.DataFrame()
34
+ const_df = pd.DataFrame()
35
+ else:
36
+ main_df = full_df.iloc[[0]]
37
+ const_df = full_df.iloc[1:]
38
+
39
+ if not const_df.empty:
40
+ const_df = const_df.iloc[:, 1:]
41
+
42
+ move_to_info = [c for c in ["segment", "equityTime", "preOpenTime"] if c in const_df.columns]
43
+ if move_to_info:
44
+ rem_df = pd.concat([rem_df, const_df[move_to_info].iloc[[0]]], axis=1)
45
+ const_df = const_df.drop(columns=move_to_info)
46
+
47
+ drop_cols_const = [
48
+ "identifier","ffmc","stockIndClosePrice","lastUpdateTime",
49
+ "chartTodayPath","chart30dPath","chart365dPath","series",
50
+ "symbol_meta","activeSeries","debtSeries","isFNOSec",
51
+ "isCASec","isSLBSec","isDebtSec","isSuspended",
52
+ "tempSuspendedSeries","isETFSec","isDelisted",
53
+ "slb_isin","isMunicipalBond","isHybridSymbol","QuotePreOpenFlag"
54
+ ]
55
+ const_df = const_df.drop(columns=[c for c in drop_cols_const if c in const_df.columns])
56
+
57
+ drop_cols_main = [
58
+ "series","symbol_meta","companyName","industry",
59
+ "activeSeries","debtSeries","isFNOSec","isCASec",
60
+ "isSLBSec","isDebtSec","isSuspended","tempSuspendedSeries",
61
+ "isETFSec","isDelisted","isin","slb_isin","listingDate",
62
+ "isMunicipalBond","isHybridSymbol",
63
+ "segment","equityTime","preOpenTime","QuotePreOpenFlag"
64
+ ]
65
+ main_df = main_df.drop(columns=[c for c in drop_cols_main if c in main_df.columns])
66
+
67
+ if "pChange" in const_df.columns:
68
+ const_df["pChange"] = pd.to_numeric(const_df["pChange"], errors="coerce")
69
+ const_df = const_df.sort_values("pChange", ascending=False)
70
+
71
+ # ================= HTML HELPERS =================
72
+ def df_to_html_color(df, metric_col=None):
73
+ df_html = df.copy()
74
+ top_up, top_down = [], []
75
+
76
+ if metric_col and metric_col in df_html.columns:
77
+ col_num = pd.to_numeric(df_html[metric_col], errors="coerce").dropna()
78
+ top_up = col_num.nlargest(3).index.tolist()
79
+ top_down = col_num.nsmallest(3).index.tolist()
80
+
81
+ for idx, row in df_html.iterrows():
82
+ for col in df_html.columns:
83
+ val = row[col]
84
+ cls = ""
85
+ if isinstance(val, (int, float)):
86
+ val_fmt = f"{val:.2f}"
87
+ if val > 0:
88
+ cls = "numeric-positive"
89
+ elif val < 0:
90
+ cls = "numeric-negative"
91
+ if metric_col and col == metric_col:
92
+ if idx in top_up:
93
+ cls += " top-up"
94
+ elif idx in top_down:
95
+ cls += " top-down"
96
+ df_html.at[idx, col] = f'<span class="{cls.strip()}">{val_fmt}</span>'
97
+ else:
98
+ df_html.at[idx, col] = str(val)
99
+
100
+ return df_html.to_html(index=False, escape=False, classes="compact-table")
101
+
102
+ def build_info_cards(rem_df, main_df):
103
+ combined = pd.concat([rem_df, main_df], axis=1)
104
+ combined = combined.loc[:, ~combined.columns.duplicated()]
105
+
106
+ html = '<div class="mini-card-container">'
107
+ for col in combined.columns:
108
+ val = combined.at[0, col] if not combined.empty else ""
109
+ html += f"""
110
+ <div class="mini-card">
111
+ <div class="card-key">{col}</div>
112
+ <div class="card-val">{val}</div>
113
+ </div>
114
+ """
115
+ html += "</div>"
116
+ return html
117
+
118
+ info_cards_html = build_info_cards(rem_df, main_df)
119
+ cons_html = df_to_html_color(const_df)
120
+
121
+ metric_cols = [
122
+ "pChange","totalTradedValue","nearWKH",
123
+ "nearWKL","perChange365d","perChange30d"
124
+ ]
125
+
126
+ metric_tables = ""
127
+ for col in metric_cols:
128
+ if col not in const_df.columns:
129
+ continue
130
+ df_m = const_df[["symbol", col]].copy()
131
+ df_m[col] = pd.to_numeric(df_m[col], errors="coerce")
132
+ df_m = df_m.sort_values(col, ascending=False)
133
+
134
+ metric_tables += f"""
135
+ <div class="small-table">
136
+ <div class="st-title">{col}</div>
137
+ <div class="st-body">{df_to_html_color(df_m, col)}</div>
138
+ </div>
139
+ """
140
+
141
+ # ================= FINAL HTML =================
142
+ html_out = f"""
143
+ <!DOCTYPE html>
144
+ <html>
145
+ <head>
146
+ <meta charset="UTF-8">
147
+ <style>
148
+ body {{ font-family: Arial; margin: 12px; background: #f5f5f5; font-size: 14px; }}
149
+ table {{ border-collapse: collapse; width: 100%; }}
150
+ th, td {{ border: 1px solid #bbb; padding: 5px 8px; }}
151
+ .numeric-positive {{ color: green; font-weight: bold; }}
152
+ .numeric-negative {{ color: red; font-weight: bold; }}
153
+ .top-up {{ background: #a8f0a5; }}
154
+ .top-down {{ background: #f0a8a8; }}
155
+ .mini-card-container {{ display: flex; flex-wrap: wrap; gap: 10px; }}
156
+ .mini-card {{ background: #fff; padding: 8px; border-radius: 6px; }}
157
+ .grid {{ display: grid; grid-template-columns: repeat(5, 1fr); gap: 12px; }}
158
+ .small-table {{ background: white; padding: 8px; border-radius: 6px; }}
159
+ .st-title {{ background: #222; color: white; text-align: center; padding: 5px; }}
160
+ .st-body {{ max-height: 300px; overflow-y: auto; }}
161
+ </style>
162
+ </head>
163
+ <body>
164
+
165
+ <h2>Live Index Data: NIFTY 50</h2>
166
+
167
+ <h3>Index Info</h3>
168
+ {info_cards_html}
169
+
170
+ <h3>Constituents</h3>
171
+ {cons_html}
172
+
173
+ <h3>Metric Tables</h3>
174
+ <div class="grid">
175
+ {metric_tables}
176
+ </div>
177
+
178
+ </body>
179
+ </html>
180
+ """
181
+
182
+ # ================= SAVE (HTML ONLY) =================
183
+ save(cache_name, html_out, "html")
184
+
185
+ return html_out