NEXAS commited on
Commit
be855af
·
verified ·
1 Parent(s): 8639c97

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py CHANGED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template_string
2
+ import yfinance as yf
3
+ import re
4
+ import threading
5
+ import time
6
+ import os
7
+
8
+ app = Flask(__name__)
9
+ HTML_FILE = "NEW_AI_INFRA.html"
10
+ SYNC_INTERVAL = 60 # Seconds (Recommended: 60+)
11
+
12
+ def sync_logic():
13
+ """Background task to sync prices."""
14
+ while True:
15
+ print(f"🔄 [Background Sync] Starting update at {time.ctime()}...")
16
+ try:
17
+ with open(HTML_FILE, 'r', encoding='utf-8') as f:
18
+ content = f.read()
19
+
20
+ match = re.search(r'const\s+companies\s*=\s*\[(.*?)\]\s*;', content, re.DOTALL)
21
+ if match:
22
+ raw_array = match.group(1)
23
+ tickers = re.findall(r'ticker:\s*"([^"]+)"', raw_array)
24
+
25
+ # Batch fetch is faster
26
+ data_map = {}
27
+ for ticker in tickers:
28
+ try:
29
+ stock = yf.Ticker(ticker)
30
+ hist = stock.history(period="2d")
31
+ if not hist.empty:
32
+ price = hist['Close'].iloc[-1]
33
+ change = ((price - hist['Close'].iloc[-2]) / hist['Close'].iloc[-2]) * 100 if len(hist) > 1 else 0
34
+ data_map[ticker] = {"p": round(price, 2), "c": round(change, 2)}
35
+ except: continue
36
+
37
+ def update_entry(m):
38
+ block = m.group(0)
39
+ t_match = re.search(r'ticker:\s*"([^"]+)"', block)
40
+ if t_match and t_match.group(1) in data_map:
41
+ ticker = t_match.group(1)
42
+ block = re.sub(r'price:\s*[\d\.\-]+', f'price: {data_map[ticker]["p"]}', block)
43
+ block = re.sub(r'change:\s*[\d\.\-]+', f'change: {data_map[ticker]["c"]}', block)
44
+ return block
45
+
46
+ updated_array = re.sub(r'\{.*?\}(?=\s*,|\s*\])', update_entry, raw_array, flags=re.DOTALL)
47
+ updated_content = content.replace(raw_array, updated_array)
48
+
49
+ with open(HTML_FILE, 'w', encoding='utf-8') as f:
50
+ f.write(updated_content)
51
+ print("✅ [Background Sync] HTML File Updated.")
52
+ except Exception as e:
53
+ print(f"❌ [Background Sync] Error: {e}")
54
+
55
+ time.sleep(SYNC_INTERVAL)
56
+
57
+ @app.route('/')
58
+ def index():
59
+ with open(HTML_FILE, 'r', encoding='utf-8') as f:
60
+ return render_template_string(f.read())
61
+
62
+ if __name__ == "__main__":
63
+ # Start the background sync thread
64
+ threading.Thread(target=sync_logic, daemon=True).start()
65
+ # Run Flask
66
+ app.run(debug=True, host='0.0.0.0', port=5000)