eshan6704 commited on
Commit
4d2f491
·
verified ·
1 Parent(s): bcb038d

Update index_live_html.py

Browse files
Files changed (1) hide show
  1. index_live_html.py +24 -35
index_live_html.py CHANGED
@@ -1,34 +1,22 @@
1
  from nsepython import *
2
  import pandas as pd
3
- import os
4
- from datetime import datetime
5
 
6
- # ----------------- CACHE CONFIG -----------------
7
- CACHE_DIR = "./cache_html"
8
- os.makedirs(CACHE_DIR, exist_ok=True)
9
- CACHE_FILE = os.path.join(CACHE_DIR, "index_NIFTY50.html")
10
 
11
- def _is_valid_daily(path):
12
- if not os.path.exists(path):
13
- return False
14
- mtime = datetime.fromtimestamp(os.path.getmtime(path))
15
- return mtime.date() == datetime.now().date()
16
 
17
- def _read_html(path):
18
- with open(path, "r", encoding="utf-8") as f:
19
- return f.read()
20
-
21
- def _write_html(path, html):
22
- with open(path, "w", encoding="utf-8") as f:
23
- f.write(html)
24
-
25
- # ----------------- MAIN FUNCTION -----------------
26
  def build_index_live_html():
27
- # ===== 1️⃣ CACHE CHECK =====
28
- if _is_valid_daily(CACHE_FILE):
29
- return _read_html(CACHE_FILE)
30
 
31
- # ===== 2️⃣ LIVE FETCH =====
 
 
 
 
 
32
  index_name = "NIFTY 50"
33
  p = nse_index_live(index_name)
34
 
@@ -45,13 +33,11 @@ def build_index_live_html():
45
  if not const_df.empty:
46
  const_df = const_df.iloc[:, 1:]
47
 
48
- # Move segment / time cols
49
- move_to_info = [c for c in ['segment', 'equityTime', 'preOpenTime'] if c in const_df.columns]
50
  if move_to_info:
51
  rem_df = pd.concat([rem_df, const_df[move_to_info].iloc[[0]]], axis=1)
52
  const_df = const_df.drop(columns=move_to_info)
53
 
54
- # Drop cols (constituents)
55
  drop_cols_const = [
56
  "identifier","ffmc","stockIndClosePrice","lastUpdateTime",
57
  "chartTodayPath","chart30dPath","chart365dPath","series",
@@ -62,7 +48,6 @@ def build_index_live_html():
62
  ]
63
  const_df = const_df.drop(columns=[c for c in drop_cols_const if c in const_df.columns])
64
 
65
- # Drop cols (main)
66
  drop_cols_main = [
67
  "series","symbol_meta","companyName","industry",
68
  "activeSeries","debtSeries","isFNOSec","isCASec",
@@ -73,11 +58,11 @@ def build_index_live_html():
73
  ]
74
  main_df = main_df.drop(columns=[c for c in drop_cols_main if c in main_df.columns])
75
 
76
- if 'pChange' in const_df.columns:
77
- const_df['pChange'] = pd.to_numeric(const_df['pChange'], errors='coerce')
78
- const_df = const_df.sort_values('pChange', ascending=False)
79
 
80
- # ===== Helper: Color HTML =====
81
  def df_to_html_color(df, metric_col=None):
82
  df_html = df.copy()
83
  top3_up, top3_down = [], []
@@ -138,7 +123,7 @@ def build_index_live_html():
138
  </div>
139
  """
140
 
141
- # ===== FINAL HTML =====
142
  html = f"""
143
  <!DOCTYPE html>
144
  <html>
@@ -179,6 +164,10 @@ th, td {{ border: 1px solid #bbb; padding: 5px 8px; }}
179
  </html>
180
  """
181
 
182
- # ===== 3️⃣ SAVE CACHE =====
183
- _write_html(CACHE_FILE, html)
 
 
 
 
184
  return html
 
1
  from nsepython import *
2
  import pandas as pd
3
+ from datetime import datetime as dt
 
4
 
5
+ # persist helpers (already exist)
6
+ from persist import exists, load, save
 
 
7
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
 
 
9
  def build_index_live_html():
10
+ # ================= CACHE =================
11
+ cache_key = "index_live_NIFTY50"
12
+ today = dt.now().strftime("%Y-%m-%d")
13
 
14
+ if exists(cache_key):
15
+ cached = load(cache_key)
16
+ if isinstance(cached, dict) and cached.get("date") == today:
17
+ return cached.get("html")
18
+
19
+ # ================= LIVE FETCH =================
20
  index_name = "NIFTY 50"
21
  p = nse_index_live(index_name)
22
 
 
33
  if not const_df.empty:
34
  const_df = const_df.iloc[:, 1:]
35
 
36
+ move_to_info = [c for c in ['segment','equityTime','preOpenTime'] if c in const_df.columns]
 
37
  if move_to_info:
38
  rem_df = pd.concat([rem_df, const_df[move_to_info].iloc[[0]]], axis=1)
39
  const_df = const_df.drop(columns=move_to_info)
40
 
 
41
  drop_cols_const = [
42
  "identifier","ffmc","stockIndClosePrice","lastUpdateTime",
43
  "chartTodayPath","chart30dPath","chart365dPath","series",
 
48
  ]
49
  const_df = const_df.drop(columns=[c for c in drop_cols_const if c in const_df.columns])
50
 
 
51
  drop_cols_main = [
52
  "series","symbol_meta","companyName","industry",
53
  "activeSeries","debtSeries","isFNOSec","isCASec",
 
58
  ]
59
  main_df = main_df.drop(columns=[c for c in drop_cols_main if c in main_df.columns])
60
 
61
+ if "pChange" in const_df.columns:
62
+ const_df["pChange"] = pd.to_numeric(const_df["pChange"], errors="coerce")
63
+ const_df = const_df.sort_values("pChange", ascending=False)
64
 
65
+ # ================= HTML HELPERS =================
66
  def df_to_html_color(df, metric_col=None):
67
  df_html = df.copy()
68
  top3_up, top3_down = [], []
 
123
  </div>
124
  """
125
 
126
+ # ================= FINAL HTML =================
127
  html = f"""
128
  <!DOCTYPE html>
129
  <html>
 
164
  </html>
165
  """
166
 
167
+ # ================= SAVE CACHE =================
168
+ save(cache_key, {
169
+ "date": today,
170
+ "html": html
171
+ })
172
+
173
  return html