Skip to content

Commit 78a7f4c

Browse files
adding top-stocks route that is dynamic to stocks day change %
1 parent c5e5cc5 commit 78a7f4c

File tree

2 files changed

+44
-25
lines changed

2 files changed

+44
-25
lines changed

controllers/topStocks.py

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,29 +6,50 @@
66
"User-Agent": "Chrome/122.0.0.0"
77
})
88

9-
def get_top_stocks(symbols):
9+
def get_top_stock_info():
10+
tickers_list = [
11+
"AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "TSLA", "META", "BRK-B", "JPM",
12+
"JNJ", "V", "PG", "UNH", "MA", "HD", "XOM", "PFE", "NFLX", "DIS", "PEP",
13+
"KO", "CSCO", "INTC", "ORCL", "CRM", "NKE", "WMT", "BA", "CVX", "T", "UL",
14+
"IBM", "AMD"
15+
]
1016
stock_data = []
1117
try:
12-
top_stocks = symbols.split()
13-
tickers = yf.Tickers(symbols)
14-
while top_stocks:
15-
stock = top_stocks.pop()
16-
info = tickers.tickers[stock].info
17-
stock_info = {
18+
data = yf.download(tickers_list, period="2d", interval="1d", group_by='ticker', auto_adjust=True)
19+
changes = []
20+
21+
for ticker in tickers_list:
22+
try:
23+
close_prices = data[ticker]['Close']
24+
percent_change = ((close_prices[-1] - close_prices[-2]) / close_prices[-2]) * 100
25+
changes.append((ticker, round(percent_change, 2)))
26+
except Exception:
27+
continue
28+
29+
# Sort by absolute percent change and pick top 5
30+
top_5_tickers = [ticker for ticker, _ in sorted(changes, key=lambda x: abs(x[1]), reverse=True)[:5]]
31+
tickers = yf.Tickers(top_5_tickers)
32+
while top_5_tickers:
33+
try:
34+
stock = top_5_tickers.pop()
35+
info = tickers.tickers[stock].info
36+
stock_info = {
1837
'symbol': stock,
1938
'name': info.get('shortName', 'N/A'),
2039
'currentPrice': info.get('currentPrice', 'N/A'),
2140
'previousClose': info.get('previousClose', 'N/A'),
2241
'sector': info.get('sector', 'N/A')
23-
}
24-
25-
stock_data.append(stock_info)
42+
}
43+
stock_data.append(stock_info)
44+
except Exception as e:
45+
print(f"⚠️ Could not fetch info for {stock}: {e}")
46+
2647
print("✅ Data fetching done successfully!")
2748
return stock_data
49+
2850
except Exception as e:
29-
print(f"❌ Error fetching {symbols}: {e}")
30-
time.sleep(5)
31-
51+
print(f"❌ Error fetching stock data: {e}")
52+
return []
3253

3354
def get_stock(symbol):
3455
try:

routes/stockRoutes.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from fastapi_cache import FastAPICache
33
from fastapi_cache.backends.redis import RedisBackend
44
from utils.redisCache import get_cache
5-
from controllers.topStocks import get_top_stocks, get_stock
5+
from controllers.topStocks import get_stock, get_top_stock_info
66
from controllers.stockNews import fetch_news
77
from controllers.stockAgent import stock_analyzer_agent, extract_json_from_response, create_default_stock_data, merge_stock_data
88
from fastapi.responses import JSONResponse, HTMLResponse
@@ -31,9 +31,7 @@ async def read_top_stocks(request: Request, cache: RedisBackend = Depends(get_ca
3131
if cached_result:
3232
result = json.loads(cached_result)
3333
else:
34-
top_stocks = ['AAPL', 'MSFT', 'AMZN', 'GOOGL', 'TSLA', 'META', 'NVDA']
35-
stocks = " ".join(top_stocks)
36-
result = get_top_stocks(stocks)
34+
result = get_top_stock_info()
3735
await cache.set(cache_key, json.dumps(result), 10)
3836

3937
# Check if request is from a browser
@@ -79,29 +77,29 @@ async def stock_news(request: Request, cache: RedisBackend = Depends(get_cache))
7977

8078
return result
8179

82-
@router.get("/stock/{name}")
83-
async def read_stock(request: Request, name: str, cache: RedisBackend = Depends(get_cache)):
84-
# Use f-string to properly interpolate the name variable
85-
cache_key = f"stock_{name}"
80+
@router.get("/stock/{symbol}")
81+
async def read_stock(request: Request, symbol: str, cache: RedisBackend = Depends(get_cache)):
82+
# Use f-string to properly interpolate the symbol variable
83+
cache_key = f"stock_{symbol}"
8684
cached_result = await cache.get(cache_key)
8785

8886
if cached_result:
8987
result = json.loads(cached_result)
9088
else:
91-
result = get_stock(name)
89+
result = get_stock(symbol)
9290
await cache.set(cache_key, json.dumps(result), 10)
9391

9492
# Check if request is from a browser
9593
accept_header = request.headers.get("accept", "")
9694
if "text/html" in accept_header:
9795
return templates.TemplateResponse("route.html", {
9896
"request": request,
99-
"route_path": f"/stock/{{{name}}}",
97+
"route_path": f"/stock/{{{symbol}}}",
10098
"method": "GET",
101-
"full_path": request.url.scheme + "://" + request.url.netloc + f"/stock/{name}",
99+
"full_path": request.url.scheme + "://" + request.url.netloc + f"/stock/{symbol}",
102100
"description": "Returns detailed information about a specific stock",
103101
"parameters": [
104-
{"name": "name", "type": "string", "description": "Stock symbol (e.g., AAPL, MSFT)"}
102+
{"name": "symbol", "type": "string", "description": "Stock symbol (e.g., AAPL, MSFT)"}
105103
],
106104
"example_response": json.dumps(result, indent=2),
107105
"current_year": datetime.datetime.now().year

0 commit comments

Comments
 (0)