Darshanpurohit commited on
Commit
cd70db0
Β·
verified Β·
1 Parent(s): 7f7602c

added multi threading

Browse files
Files changed (1) hide show
  1. main.py +126 -139
main.py CHANGED
@@ -1,40 +1,38 @@
 
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from typing import Dict, List
4
  from datetime import datetime, timedelta
5
  import pandas as pd
6
  import logging
7
  import time
8
-
9
  from nsepython import nse_quote, nsefetch
10
  from dotenv import load_dotenv
 
11
 
12
  # ─────────────────────────────────────────
13
  # SIMPLE ROUNDING (INLINE - NO IMPORTS)
14
  # ─────────────────────────────────────────
15
  def round_money(x):
16
- return round(float(x), 2)
 
 
 
17
 
18
  def round_percent(x):
19
- return round(float(x), 2)
 
 
 
20
 
21
  def round_price(x):
22
- return round(float(x), 2)
 
 
 
23
 
24
  def safe_divide(a, b):
25
- return (a / b) if b else 0.0
26
-
27
- def calculate_scenario_value(qty, price, invested_per_unit=0):
28
- value = qty * price
29
- invested = qty * invested_per_unit
30
- pnl = value - invested
31
- pnl_pct = (pnl / invested * 100) if invested else 0.0
32
-
33
- return {
34
- "value": round_money(value),
35
- "pnl": round_money(pnl),
36
- "pnlPercent": round_percent(pnl_pct),
37
- }
38
 
39
  load_dotenv()
40
 
@@ -44,7 +42,7 @@ load_dotenv()
44
  logging.basicConfig(level=logging.INFO)
45
  logger = logging.getLogger(__name__)
46
 
47
- app = FastAPI(title="Portfolio API", version="3.0.0")
48
 
49
  app.add_middleware(
50
  CORSMiddleware,
@@ -55,123 +53,135 @@ app.add_middleware(
55
  )
56
 
57
  # ─────────────────────────────────────────
58
- # Cache
59
  # ─────────────────────────────────────────
60
- price_cache: Dict[str, Dict] = {}
61
- CACHE_TTL = 60
62
-
 
63
 
64
- def is_cache_valid(symbol: str) -> bool:
 
65
  if symbol not in price_cache:
66
- return False
67
- return (datetime.now() - price_cache[symbol]["cached_at"]).total_seconds() < CACHE_TTL
68
-
 
 
 
 
 
 
 
69
 
70
  def _nse_symbol(symbol: str) -> str:
71
  return symbol.upper().replace(".NS", "").replace(".BO", "")
72
 
73
  # ─────────────────────────────────────────
74
- # FETCH QUOTE
75
- # ─────────────────────────────────────────
76
- def _fetch_quote(nse_sym: str) -> Dict:
77
- url = f"https://www.nseindia.com/api/quote-equity?symbol={nse_sym}"
78
- data = nsefetch(url)
79
-
80
- price_info = data.get("priceInfo", {})
81
- if not price_info:
82
- raise ValueError("No priceInfo returned")
83
-
84
- intra = price_info.get("intraDayHighLow", {})
85
- week = price_info.get("weekHighLow", {})
86
-
87
- current = float(price_info.get("lastPrice", 0))
88
- open_price = float(price_info.get("open", 0))
89
- prev_close = float(price_info.get("previousClose", 0))
90
-
91
- day_high = float(intra.get("max", 0))
92
- day_low = float(intra.get("min", 0))
93
-
94
- high_52w = float(week.get("max", 0))
95
- low_52w = float(week.get("min", 0))
96
-
97
- change = current - prev_close
98
- change_pct = safe_divide(change, prev_close) * 100.0
99
-
100
- return {
101
- "current": round_price(current),
102
- "open": round_price(open_price),
103
- "prevClose": round_price(prev_close),
104
- "dayHigh": round_price(day_high),
105
- "dayLow": round_price(day_low),
106
- "high52w": round_price(high_52w),
107
- "low52w": round_price(low_52w),
108
- "change": round_percent(change),
109
- "changePct": round_percent(change_pct),
110
- }
111
-
112
- # ─────────────────────────────────────────
113
- # HISTORY
114
- # ─────────────────────────────────────────
115
- def _fetch_history(nse_sym: str) -> List[Dict]:
116
- to_date = datetime.now()
117
- from_date = to_date - timedelta(days=365)
118
-
119
- url = (
120
- f"https://www.nseindia.com/api/historical/cm/equity"
121
- f'?symbol={nse_sym}&series=["EQ","BE","ETF"]'
122
- f'&from={from_date.strftime("%d-%m-%Y")}'
123
- f'&to={to_date.strftime("%d-%m-%Y")}'
124
- f'&csv=false'
125
- )
126
-
127
- try:
128
- response = nsefetch(url)
129
- rows = response.get("data", [])
130
-
131
- return [
132
- {
133
- "date": row.get("CH_TIMESTAMP", ""),
134
- "close": float(row.get("CH_CLOSING_PRICE", 0)),
135
- }
136
- for row in rows[-30:]
137
- ]
138
- except Exception:
139
- return []
140
-
141
- # ─────────────────────────────────────────
142
- # FETCH SINGLE
143
  # ─────────────────────────────────────────
144
- def fetch_single(symbol: str) -> Dict:
 
145
  nse_sym = _nse_symbol(symbol)
146
-
147
  try:
148
- quote = _fetch_quote(nse_sym)
149
- history = _fetch_history(nse_sym)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
  result = {
152
  "symbol": symbol,
153
- "currentPrice": quote["current"],
154
- "dayHigh": quote["dayHigh"],
155
- "dayLow": quote["dayLow"],
156
- "high52w": quote["high52w"],
157
- "low52w": quote["low52w"],
158
- "previousClose": quote["prevClose"],
159
- "change": quote["change"],
160
- "changePercent": quote["changePct"],
161
  "volume": 0,
162
- "openPrice": quote["open"],
163
  "history": history,
164
  "source": "NSE India",
165
  "error": False,
166
  "cachedAt": datetime.now().isoformat(),
167
  }
168
-
169
  price_cache[symbol] = {"data": result, "cached_at": datetime.now()}
170
  return result
171
-
172
  except Exception as e:
173
- return _error_result(symbol, str(e))
 
174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
  def _error_result(symbol: str, msg: str) -> Dict:
177
  return {
@@ -192,33 +202,13 @@ def _error_result(symbol: str, msg: str) -> Dict:
192
  "errorMsg": msg,
193
  }
194
 
195
- # ─────────────────────────────────────────
196
- # BULK FETCH
197
- # ─────────────────────────────────────────
198
- def get_stock_data_bulk(symbols: List[str]) -> Dict[str, Dict]:
199
- results = {}
200
- to_fetch = []
201
-
202
- for s in symbols:
203
- if is_cache_valid(s):
204
- results[s] = price_cache[s]["data"]
205
- else:
206
- to_fetch.append(s)
207
-
208
- for i, symbol in enumerate(to_fetch):
209
- results[symbol] = fetch_single(symbol)
210
- if i < len(to_fetch) - 1:
211
- time.sleep(0.3)
212
-
213
- return results
214
-
215
  # ─────────────────────────────────────────
216
  # ROUTES
217
  # ─────────────────────────────────────────
218
 
219
  @app.get("/")
220
  async def root():
221
- return {"status": "ok"}
222
 
223
  @app.get("/api/stocks/quote")
224
  async def get_quotes(symbols: str):
@@ -226,7 +216,7 @@ async def get_quotes(symbols: str):
226
  raise HTTPException(status_code=400, detail="No symbols")
227
 
228
  symbol_list = [s.strip().upper() for s in symbols.split(",")]
229
- return get_stock_data_bulk(symbol_list)
230
 
231
  @app.post("/api/stocks/portfolio")
232
  async def get_portfolio(data: Dict):
@@ -235,7 +225,7 @@ async def get_portfolio(data: Dict):
235
  raise HTTPException(status_code=400, detail="No data")
236
 
237
  symbol_map = {h["symbol"]: h for h in portfolio}
238
- stock_data = get_stock_data_bulk(list(symbol_map.keys()))
239
 
240
  results = []
241
  total_invested = 0
@@ -244,7 +234,7 @@ async def get_portfolio(data: Dict):
244
  for symbol, h in symbol_map.items():
245
  qty = float(h["qty"])
246
  buy = float(h["buyPrice"])
247
- current = float(stock_data[symbol]["currentPrice"])
248
 
249
  invested = qty * buy
250
  value = qty * current
@@ -277,9 +267,6 @@ async def get_portfolio(data: Dict):
277
  }
278
  }
279
 
280
- # ─────────────────────────────────────────
281
- # RUN
282
- # ─────────────────────────────────────────
283
  if __name__ == "__main__":
284
  import uvicorn
285
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ import asyncio
2
  from fastapi import FastAPI, HTTPException
3
  from fastapi.middleware.cors import CORSMiddleware
4
+ from typing import Dict, List, Any, Optional, Tuple
5
  from datetime import datetime, timedelta
6
  import pandas as pd
7
  import logging
8
  import time
 
9
  from nsepython import nse_quote, nsefetch
10
  from dotenv import load_dotenv
11
+ from concurrent.futures import ThreadPoolExecutor
12
 
13
  # ─────────────────────────────────────────
14
  # SIMPLE ROUNDING (INLINE - NO IMPORTS)
15
  # ─────────────────────────────────────────
16
  def round_money(x):
17
+ try:
18
+ return round(float(x), 2)
19
+ except (TypeError, ValueError):
20
+ return 0.0
21
 
22
  def round_percent(x):
23
+ try:
24
+ return round(float(x), 2)
25
+ except (TypeError, ValueError):
26
+ return 0.0
27
 
28
  def round_price(x):
29
+ try:
30
+ return round(float(x), 2)
31
+ except (TypeError, ValueError):
32
+ return 0.0
33
 
34
  def safe_divide(a, b):
35
+ return (a / b) if b and b != 0 else 0.0
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  load_dotenv()
38
 
 
42
  logging.basicConfig(level=logging.INFO)
43
  logger = logging.getLogger(__name__)
44
 
45
+ app = FastAPI(title="Portfolio API", version="5.0.0")
46
 
47
  app.add_middleware(
48
  CORSMiddleware,
 
53
  )
54
 
55
  # ─────────────────────────────────────────
56
+ # Cache & Configuration
57
  # ─────────────────────────────────────────
58
+ price_cache: Dict[str, Dict[str, Any]] = {}
59
+ CACHE_TTL = 60 # 1 minute for fresh data
60
+ STALE_TTL = 300 # 5 minutes for stale fallback
61
+ executor = ThreadPoolExecutor(max_workers=20)
62
 
63
+ def get_from_cache(symbol: str) -> Tuple[Optional[Dict[str, Any]], bool]:
64
+ """Returns (data, is_fresh)"""
65
  if symbol not in price_cache:
66
+ return None, False
67
+
68
+ cached_item = price_cache[symbol]
69
+ age = (datetime.now() - cached_item["cached_at"]).total_seconds()
70
+
71
+ if age < CACHE_TTL:
72
+ return cached_item["data"], True
73
+ elif age < STALE_TTL:
74
+ return cached_item["data"], False
75
+ return None, False
76
 
77
  def _nse_symbol(symbol: str) -> str:
78
  return symbol.upper().replace(".NS", "").replace(".BO", "")
79
 
80
  # ─────────────────────────────────────────
81
+ # FETCH LOGIC (PARALLEL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  # ─────────────────────────────────────────
83
+ def _get_single_stock_data(symbol: str) -> Optional[Dict]:
84
+ """Blocking fetch for a single stock using nsepython"""
85
  nse_sym = _nse_symbol(symbol)
 
86
  try:
87
+ # Quote
88
+ url = f"https://www.nseindia.com/api/quote-equity?symbol={nse_sym}"
89
+ data = nsefetch(url)
90
+
91
+ price_info = data.get("priceInfo", {})
92
+ if not price_info:
93
+ return None
94
+
95
+ intra = price_info.get("intraDayHighLow", {})
96
+ week = price_info.get("weekHighLow", {})
97
+
98
+ current = float(price_info.get("lastPrice", 0))
99
+ open_price = float(price_info.get("open", 0))
100
+ prev_close = float(price_info.get("previousClose", 0))
101
+ day_high = float(intra.get("max", 0))
102
+ day_low = float(intra.get("min", 0))
103
+ high_52w = float(week.get("max", 0))
104
+ low_52w = float(week.get("min", 0))
105
+
106
+ change = current - prev_close
107
+ change_pct = safe_divide(change, prev_close) * 100.0
108
+
109
+ # History (simpler check)
110
+ history = []
111
+ try:
112
+ # We fetch short history for performance
113
+ to_date = datetime.now()
114
+ from_date = to_date - timedelta(days=40)
115
+ hist_url = (
116
+ f"https://www.nseindia.com/api/historical/cm/equity"
117
+ f'?symbol={nse_sym}&series=["EQ","BE","ETF"]'
118
+ f'&from={from_date.strftime("%d-%m-%Y")}'
119
+ f'&to={to_date.strftime("%d-%m-%Y")}'
120
+ f'&csv=false'
121
+ )
122
+ hist_data = nsefetch(hist_url)
123
+ rows = hist_data.get("data", [])
124
+ history = [
125
+ {"date": row.get("CH_TIMESTAMP", ""), "close": float(row.get("CH_CLOSING_PRICE", 0))}
126
+ for row in rows[-30:]
127
+ ]
128
+ except:
129
+ pass
130
 
131
  result = {
132
  "symbol": symbol,
133
+ "currentPrice": round_price(current),
134
+ "dayHigh": round_price(day_high),
135
+ "dayLow": round_price(day_low),
136
+ "high52w": round_price(high_52w),
137
+ "low52w": round_price(low_52w),
138
+ "previousClose": round_price(prev_close),
139
+ "change": round_percent(change),
140
+ "changePercent": round_percent(change_pct),
141
  "volume": 0,
142
+ "openPrice": round_price(open_price),
143
  "history": history,
144
  "source": "NSE India",
145
  "error": False,
146
  "cachedAt": datetime.now().isoformat(),
147
  }
148
+
149
  price_cache[symbol] = {"data": result, "cached_at": datetime.now()}
150
  return result
 
151
  except Exception as e:
152
+ logger.error(f"Error fetching {symbol}: {e}")
153
+ return None
154
 
155
+ async def get_stock_data_bulk(symbols: List[str]) -> Dict[str, Dict]:
156
+ results = {}
157
+ to_fetch = []
158
+
159
+ # 1. Check cache
160
+ for s in symbols:
161
+ data, is_fresh = get_from_cache(s)
162
+ if data:
163
+ results[s] = data
164
+ if not is_fresh:
165
+ to_fetch.append(s)
166
+ else:
167
+ to_fetch.append(s)
168
+
169
+ if not to_fetch:
170
+ return results
171
+
172
+ # 2. Parallel fetch missing/stale items
173
+ loop = asyncio.get_event_loop()
174
+ tasks = [loop.run_in_executor(executor, _get_single_stock_data, s) for s in to_fetch]
175
+
176
+ if tasks:
177
+ fetched_results = await asyncio.gather(*tasks)
178
+ for i, s in enumerate(to_fetch):
179
+ if fetched_results[i]:
180
+ results[s] = fetched_results[i]
181
+ elif s not in results:
182
+ results[s] = _error_result(s, "Fetch failed")
183
+
184
+ return results
185
 
186
  def _error_result(symbol: str, msg: str) -> Dict:
187
  return {
 
202
  "errorMsg": msg,
203
  }
204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  # ─────────────────────────────────────────
206
  # ROUTES
207
  # ─────────────────────────────────────────
208
 
209
  @app.get("/")
210
  async def root():
211
+ return {"status": "ok", "version": "5.0.0", "engine": "nsepython-parallel"}
212
 
213
  @app.get("/api/stocks/quote")
214
  async def get_quotes(symbols: str):
 
216
  raise HTTPException(status_code=400, detail="No symbols")
217
 
218
  symbol_list = [s.strip().upper() for s in symbols.split(",")]
219
+ return await get_stock_data_bulk(symbol_list)
220
 
221
  @app.post("/api/stocks/portfolio")
222
  async def get_portfolio(data: Dict):
 
225
  raise HTTPException(status_code=400, detail="No data")
226
 
227
  symbol_map = {h["symbol"]: h for h in portfolio}
228
+ stock_data = await get_stock_data_bulk(list(symbol_map.keys()))
229
 
230
  results = []
231
  total_invested = 0
 
234
  for symbol, h in symbol_map.items():
235
  qty = float(h["qty"])
236
  buy = float(h["buyPrice"])
237
+ current = float(stock_data.get(symbol, {}).get("currentPrice", 0))
238
 
239
  invested = qty * buy
240
  value = qty * current
 
267
  }
268
  }
269
 
 
 
 
270
  if __name__ == "__main__":
271
  import uvicorn
272
  uvicorn.run(app, host="0.0.0.0", port=7860)