eshan6704 commited on
Commit
c9073bf
·
verified ·
1 Parent(s): eb782b9

Update indices_html.py

Browse files
Files changed (1) hide show
  1. indices_html.py +181 -264
indices_html.py CHANGED
@@ -1,272 +1,189 @@
1
  import json
2
  import pandas as pd
3
  from nsepython import *
 
4
 
5
- def build_indices_html():
6
-
7
- p = indices()
8
-
9
- data_df = p["data"]
10
- dates_df = p["dates"]
11
-
12
- data_json = json.dumps(data_df.to_dict(orient="records"), ensure_ascii=False)
13
- dates_json = json.dumps(dates_df.to_dict(orient="records"), ensure_ascii=False)
14
-
15
- DEFAULT_KEY = "INDICES ELIGIBLE IN DERIVATIVES"
16
- DEFAULT_SYMBOL = "NIFTY 50"
17
-
18
- html = f"""
19
- <!DOCTYPE html>
20
- <html>
21
- <head>
22
- <meta charset="UTF-8">
23
- <title>NSE Indices Dashboard</title>
24
-
25
- <style>
26
- body {{
27
- font-family: Arial, sans-serif;
28
- padding: 20px;
29
- }}
30
-
31
- button {{
32
- padding: 7px 14px;
33
- margin-bottom: 10px;
34
- cursor: pointer;
35
- }}
36
-
37
- .scroll-table {{
38
- width: 100%;
39
- overflow: auto;
40
- border: 1px solid #ccc;
41
- max-height: 450px;
42
- margin-bottom: 20px;
43
- }}
44
-
45
- table {{
46
- border-collapse: collapse;
47
- width: max-content;
48
- min-width: 100%;
49
- }}
50
-
51
- th, td {{
52
- border: 1px solid #ddd;
53
- padding: 8px;
54
- white-space: nowrap;
55
- }}
56
-
57
- th {{
58
- background-color: #007bff;
59
- color: white;
60
- position: sticky;
61
- top: 0;
62
- z-index: 5;
63
- }}
64
-
65
- .chart-grid {{
66
- display: grid;
67
- grid-template-columns: 1fr 1fr;
68
- grid-template-rows: 200px 200px;
69
- gap: 20px;
70
- }}
71
-
72
- .chart-box {{
73
- width: 100%;
74
- height: 100%;
75
- border: 1px solid #ccc;
76
- }}
77
-
78
- #chart365 {{
79
- grid-column: 1 / 3;
80
- }}
81
-
82
- select {{
83
- padding: 6px;
84
- margin: 8px 0;
85
- }}
86
- </style>
87
-
88
- </head>
89
- <body>
90
-
91
- <h2>NSE Indices Dashboard</h2>
92
-
93
- <script>
94
- const records = {data_json};
95
- const dates = {dates_json};
96
- const DEFAULT_KEY = "{DEFAULT_KEY}";
97
- const DEFAULT_SYMBOL = "{DEFAULT_SYMBOL}";
98
- </script>
99
-
100
- <!-- MAIN TABLE -->
101
- <h3>Main Full Indices Table</h3>
102
- <button onclick="toggleMainTable()">Show / Hide Main Table</button>
103
-
104
- <div id="mainTableSection" class="scroll-table" style="display:none;">
105
- <table id="mainTable"></table>
106
- </div>
107
-
108
- <hr>
109
-
110
- <!-- FILTERED TABLE -->
111
- <h3>Filter Table by Category</h3>
112
-
113
- <label><b>Select Index Category:</b></label>
114
- <select id="keyDropdown"></select>
115
-
116
- <div id="altTableSection" class="scroll-table">
117
- <table id="altTable"></table>
118
- </div>
119
-
120
- <hr>
121
-
122
- <!-- CHARTS -->
123
- <h3>Charts Based on Index</h3>
124
-
125
- <label><b>Select Index:</b></label>
126
- <select id="chartDropdown"></select>
127
-
128
- <div class="chart-grid">
129
- <iframe id="chartToday" class="chart-box"></iframe>
130
- <iframe id="chart30" class="chart-box"></iframe>
131
- <iframe id="chart365" class="chart-box"></iframe>
132
- </div>
133
-
134
- <script>
135
-
136
- // ================= MAIN TABLE =================
137
-
138
- function buildMainTable() {{
139
- const table = document.getElementById("mainTable");
140
- const cols = Object.keys(records[0]);
141
-
142
- let header = "<tr>";
143
- cols.forEach(c => header += `<th>${{c}}</th>`);
144
- header += "</tr>";
145
-
146
- let rows = "";
147
- records.forEach(r => {{
148
- rows += "<tr>";
149
- cols.forEach(c => rows += `<td>${{r[c]}}</td>`);
150
- rows += "</tr>";
151
- }});
152
 
153
- table.innerHTML = header + rows;
154
- }}
155
-
156
- function toggleMainTable() {{
157
- const sec = document.getElementById("mainTableSection");
158
- sec.style.display = sec.style.display === "none" ? "block" : "none";
159
- }}
160
-
161
- buildMainTable();
162
-
163
-
164
- // ================= FILTERED TABLE =================
165
-
166
- const keyDropdown = document.getElementById("keyDropdown");
167
- const chartDropdown = document.getElementById("chartDropdown");
168
-
169
- const keyList = [...new Set(records.map(r => r.key))];
170
- keyList.forEach(k => {{
171
- const opt = document.createElement("option");
172
- opt.value = k;
173
- opt.textContent = k;
174
- if (k === DEFAULT_KEY) opt.selected = true;
175
- keyDropdown.appendChild(opt);
176
- }});
177
-
178
- function buildAltTable(keyName) {{
179
- const table = document.getElementById("altTable");
180
-
181
- const filtered = records.filter(r => r.key === keyName);
182
-
183
- if (!filtered.length) {{
184
- table.innerHTML = "<tr><td>No Data</td></tr>";
185
- return;
186
- }}
187
-
188
- const hiddenCols = [
189
  "key","chartTodayPath","chart30dPath","chart30Path","chart365dPath",
190
  "date365dAgo","date30dAgo","previousDay","oneWeekAgo","oneMonthAgoVal",
191
  "oneWeekAgoVal","oneYearAgoVal","index","indicativeClose"
192
- ];
193
-
194
- const cols = Object.keys(filtered[0]).filter(c => !hiddenCols.includes(c));
195
-
196
- let header = "<tr>";
197
- cols.forEach(c => header += `<th>${{c}}</th>`);
198
- header += "</tr>";
199
-
200
- let rows = "";
201
- filtered.forEach(obj => {{
202
- rows += "<tr>";
203
- cols.forEach(c => rows += `<td>${{obj[c]}}</td>`);
204
- rows += "</tr>";
205
- }});
206
-
207
- table.innerHTML = header + rows;
208
- }}
209
-
210
-
211
- // ================= CHARTS =================
212
-
213
- function populateChartDropdown(keyVal) {{
214
- chartDropdown.innerHTML = "";
215
-
216
- records.filter(r => r.key === keyVal).forEach(r => {{
217
- const opt = document.createElement("option");
218
- opt.value = r.indexSymbol;
219
- opt.textContent = r.index;
220
- chartDropdown.appendChild(opt);
221
- }});
222
-
223
- // auto select default
224
- [...chartDropdown.options].forEach(opt => {{
225
- if (opt.textContent.toUpperCase().includes(DEFAULT_SYMBOL.toUpperCase()))
226
- opt.selected = true;
227
- }});
228
- }}
229
-
230
- function loadCharts(symbol) {{
231
- const row = records.find(r => r.indexSymbol === symbol);
232
- if (!row) return;
233
-
234
- document.getElementById("chartToday").src = row.chartTodayPath;
235
- document.getElementById("chart30").src = row.chart30dPath || row.chart30Path;
236
- document.getElementById("chart365").src = row.chart365dPath;
237
- }}
238
-
239
-
240
- // ================= EVENT HANDLERS =================
241
-
242
- keyDropdown.addEventListener("change", () => {{
243
- const keyVal = keyDropdown.value;
244
- buildAltTable(keyVal);
245
- populateChartDropdown(keyVal);
246
- loadCharts(chartDropdown.value);
247
- }});
248
-
249
- chartDropdown.addEventListener("change", () => {{
250
- loadCharts(chartDropdown.value);
251
- }});
252
-
253
-
254
- // ================= INITIAL LOAD =================
255
-
256
- buildAltTable(DEFAULT_KEY);
257
- populateChartDropdown(DEFAULT_KEY);
258
-
259
- let initial = records.find(
260
- r => r.index.toUpperCase().includes(DEFAULT_SYMBOL.toUpperCase())
261
- );
262
-
263
- if (!initial) initial = records[0];
264
-
265
- loadCharts(initial.indexSymbol);
266
-
267
- </script>
268
-
269
- </body>
270
- </html>
271
- """
272
- return html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import json
2
  import pandas as pd
3
  from nsepython import *
4
+ import html
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ def build_indices_html():
8
+ """
9
+ Generate a single, fully-rendered HTML string (no <script>) containing:
10
+ - main indices table
11
+ - dates table (if present)
12
+ - one table per category/key
13
+ - for each index record, a chart grid with 3 iframes (if paths exist) or placeholders
14
+
15
+ Requires: indices() function available in scope which returns dict with keys:
16
+ - "data": DataFrame of records (each row a dict with fields including at least 'key', 'index', 'indexSymbol')
17
+ - "dates": DataFrame (optional)
18
+ """
19
+ p = indices() # must exist in your module
20
+ data_df = p.get("data", pd.DataFrame())
21
+ dates_df = p.get("dates", pd.DataFrame())
22
+
23
+ # Convert records to list of dicts for iteration
24
+ records = data_df.to_dict(orient="records") if not data_df.empty else []
25
+
26
+ # Hidden columns we don't want to show in per-category tables
27
+ hidden_cols = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  "key","chartTodayPath","chart30dPath","chart30Path","chart365dPath",
29
  "date365dAgo","date30dAgo","previousDay","oneWeekAgo","oneMonthAgoVal",
30
  "oneWeekAgoVal","oneYearAgoVal","index","indicativeClose"
31
+ }
32
+
33
+ def build_table_from_records(recs, cols=None):
34
+ """Return HTML <table> string for recs (list of dicts). If cols provided, use that order."""
35
+ if not recs:
36
+ return "<p>No data available.</p>"
37
+
38
+ # Determine columns
39
+ if cols is None:
40
+ # union of keys preserving insertion order from first record
41
+ cols = []
42
+ for r in recs:
43
+ for k in r.keys():
44
+ if k not in cols:
45
+ cols.append(k)
46
+
47
+ # Build header
48
+ header_cells = "".join(f"<th>{html.escape(str(c))}</th>" for c in cols)
49
+ rows_html = []
50
+ for r in recs:
51
+ row_cells = []
52
+ for c in cols:
53
+ v = r.get(c, "")
54
+ # Convert lists/dicts to string
55
+ if isinstance(v, (list, dict)):
56
+ cell = html.escape(str(v))
57
+ else:
58
+ cell = html.escape("" if v is None else str(v))
59
+ row_cells.append(f"<td>{cell}</td>")
60
+ rows_html.append("<tr>" + "".join(row_cells) + "</tr>")
61
+
62
+ table_html = "<table>\n<thead>\n<tr>" + header_cells + "</tr>\n</thead>\n<tbody>\n" + "\n".join(rows_html) + "\n</tbody>\n</table>"
63
+ return table_html
64
+
65
+ def build_chart_grid_for_record(r):
66
+ """
67
+ Build a 3-panel grid for charts for a single record r.
68
+ Uses r.get('chartTodayPath'), r.get('chart30dPath' or 'chart30Path'), r.get('chart365dPath').
69
+ If a path is missing, show a placeholder box with text.
70
+ """
71
+ def iframe_or_placeholder(src, label):
72
+ if src and isinstance(src, str) and src.strip():
73
+ # escape src only in attribute context
74
+ return f'<div class="chart-cell"><iframe src="{html.escape(src)}" frameborder="0" loading="lazy" title="{html.escape(label)}" style="width:100%;height:100%;"></iframe></div>'
75
+ else:
76
+ return f'<div class="chart-cell placeholder"><div class="ph-inner">{html.escape(label)}<br/>(no chart)</div></div>'
77
+
78
+ today_src = r.get("chartTodayPath") or r.get("chartToday") or ""
79
+ month30_src = r.get("chart30dPath") or r.get("chart30Path") or r.get("chart30") or ""
80
+ year365_src = r.get("chart365dPath") or r.get("chart365Path") or r.get("chart365") or ""
81
+
82
+ idx_name = r.get("index") or r.get("indexSymbol") or r.get("symbol") or ""
83
+
84
+ grid = (
85
+ '<div class="chart-grid-record">\n'
86
+ f' <div class="chart-header"><strong>{html.escape(str(idx_name))}</strong></div>\n'
87
+ ' <div class="chart-row">\n'
88
+ f' {iframe_or_placeholder(today_src, "Today Chart")}\n'
89
+ f' {iframe_or_placeholder(month30_src, "30d Chart")}\n'
90
+ ' </div>\n'
91
+ ' <div class="chart-row">\n'
92
+ f' {iframe_or_placeholder(year365_src, "365d Chart")}\n'
93
+ ' </div>\n'
94
+ '</div>\n'
95
+ )
96
+ return grid
97
+
98
+ # Build main full table (all columns present in records)
99
+ main_table_html = build_table_from_records(records)
100
+
101
+ # Build dates table if dates_df present
102
+ dates_table_html = ""
103
+ if not dates_df.empty:
104
+ dates_records = dates_df.to_dict(orient="records")
105
+ dates_table_html = build_table_from_records(dates_records)
106
+
107
+ # Group records by 'key' (category)
108
+ from collections import defaultdict
109
+ groups = defaultdict(list)
110
+ for r in records:
111
+ k = r.get("key") or "UNCLASSIFIED"
112
+ groups[k].append(r)
113
+
114
+ # Build per-key tables and per-record chart grids
115
+ per_key_sections = []
116
+ for key_name, recs in groups.items():
117
+ # Columns to show: all keys from first record except hidden_cols, preserving order
118
+ first = recs[0] if recs else {}
119
+ cols = [c for c in first.keys() if c not in hidden_cols]
120
+ # But ensure some useful order: indexSymbol/index/name first if present
121
+ preferred = ["indexSymbol","index","symbol","name"]
122
+ cols_sorted = []
123
+ for p in preferred:
124
+ if p in cols:
125
+ cols_sorted.append(p)
126
+ for c in cols:
127
+ if c not in cols_sorted:
128
+ cols_sorted.append(c)
129
+
130
+ table_html = build_table_from_records(recs, cols_sorted)
131
+ # Build chart block for all recs in this key
132
+ charts_html = "\n".join(build_chart_grid_for_record(r) for r in recs)
133
+
134
+ section_html = f"""
135
+ <section class="key-section">
136
+ <h3>Category: {html.escape(str(key_name))} (Total: {len(recs)})</h3>
137
+ <div class="key-table">{table_html}</div>
138
+ <div class="key-charts">{charts_html}</div>
139
+ </section>
140
+ """
141
+ per_key_sections.append(section_html)
142
+
143
+ # CSS for layout (no JS)
144
+ css = """
145
+ <style>
146
+ body { font-family: Arial, sans-serif; padding: 16px; color: #111; background: #fff; }
147
+ h1,h2,h3 { color: #0b69a3; margin: 8px 0; }
148
+ table { border-collapse: collapse; width: 100%; margin-bottom: 12px; font-size: 13px; }
149
+ th, td { border: 1px solid #d0d0d0; padding: 6px 8px; text-align: left; vertical-align: top; }
150
+ th { background: #007bff; color: #fff; position: sticky; top: 0; z-index: 2; }
151
+ .scroll { max-height: 420px; overflow: auto; border: 1px solid #eee; padding: 8px; background: #fafafa; margin-bottom: 18px; }
152
+ .key-section { margin-bottom: 28px; padding: 8px 6px; border: 1px solid #e6eef6; background: #fbfeff; border-radius: 6px; }
153
+ .chart-grid-record { border: 1px solid #e0e0e0; padding: 6px; margin: 8px 0; border-radius: 6px; background: #fff; }
154
+ .chart-header { margin-bottom: 6px; }
155
+ .chart-row { display: flex; gap: 8px; margin-bottom: 8px; }
156
+ .chart-cell { flex: 1 1 0; height: 200px; border: 1px solid #ddd; }
157
+ .chart-cell.iframe-wrap iframe { width:100%; height:100%; border:0; }
158
+ .placeholder { display:flex; align-items:center; justify-content:center; background:#f6f6f6; color:#666; font-size:13px; }
159
+ .ph-inner { text-align:center; padding:8px; }
160
+ .meta { font-size: 13px; color: #444; margin-bottom: 8px; }
161
+ </style>
162
+ """
163
+
164
+ # HTML assembly
165
+ html_parts = []
166
+ html_parts.append("<!DOCTYPE html>")
167
+ html_parts.append("<html><head><meta charset='utf-8'><title>NSE Indices (Static)</title>")
168
+ html_parts.append(css)
169
+ html_parts.append("</head><body>")
170
+ html_parts.append("<h1>NSE Indices — Full Static Render</h1>")
171
+ html_parts.append(f"<div class='meta'>Generated: {html.escape(pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S'))}</div>")
172
+
173
+ html_parts.append("<h2>Main Indices Table</h2>")
174
+ html_parts.append("<div class='scroll'>")
175
+ html_parts.append(main_table_html)
176
+ html_parts.append("</div>")
177
+
178
+ if dates_table_html:
179
+ html_parts.append("<h2>Dates / Meta</h2>")
180
+ html_parts.append("<div class='scroll'>")
181
+ html_parts.append(dates_table_html)
182
+ html_parts.append("</div>")
183
+
184
+ html_parts.append("<h2>Categories & Charts (All)</h2>")
185
+ html_parts.extend(per_key_sections)
186
+
187
+ html_parts.append("</body></html>")
188
+
189
+ return "\n".join(html_parts)