Skip to content

Commit e9b0146

Browse files
adding api to fetch detailed information on a particular stock
1 parent 8e3a768 commit e9b0146

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

app.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import json
1616
from redis import asyncio as aioredis
1717
# Custom imports
18-
from topStocks import get_top_stocks
18+
from topStocks import get_top_stocks, get_stock
1919
from ask import groq_chat
2020
from stockNews import fetch_news
2121
from agents import multi_ai
@@ -79,11 +79,11 @@ async def read_top_stocks(cache: RedisBackend = Depends(get_cache)):
7979
return json.loads(cached_result)
8080

8181
top_stocks = ['AAPL', 'MSFT', 'AMZN', 'GOOGL']
82-
stock = " ".join(top_stocks)
83-
stock_info = get_top_stocks(stock)
82+
stocks = " ".join(top_stocks)
83+
stocks_info = get_top_stocks(stocks)
8484

85-
await cache.set(cache_key, json.dumps(stock_info), 10)
86-
return stock_info
85+
await cache.set(cache_key, json.dumps(stocks_info), 10)
86+
return stocks_info
8787

8888
@app.get("/stock-news")
8989
async def stock_news(cache: RedisBackend = Depends(get_cache)):
@@ -95,6 +95,15 @@ async def stock_news(cache: RedisBackend = Depends(get_cache)):
9595
await cache.set(cache_key, json.dumps(news_stack), 300)
9696
return news_stack
9797

98+
@app.get("stocks/{name}")
99+
async def read_stock(name: str, cache: RedisBackend = Depends(get_cache)):
100+
cache_key = "stock"
101+
cached_result = await cache.get(cache_key)
102+
if cached_result:
103+
return json.loads(cached_result)
104+
stock_info = get_stock(name)
105+
await cache.set(cache_key, json.dumps(stock_info), 10)
106+
98107

99108
@app.get("health/") # Changed to GET since it's retrieving status
100109
async def health_check():

topStocks.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,25 @@ def get_top_stocks(symbols):
2424

2525
stock_data.append(stock_info)
2626
print("✅ Data fetching done successfully!")
27+
return stock_data
2728
except Exception as e:
2829
print(f"❌ Error fetching {symbols}: {e}")
2930
time.sleep(5)
30-
return stock_data
31+
32+
33+
def get_stock(symbol):
34+
try:
35+
stock = yf.Ticker(symbol)
36+
info = stock.info
37+
stock_info = {
38+
'symbol': symbol,
39+
'name': info.get('shortName', 'N/A'),
40+
'currentPrice': info.get('currentPrice', 'N/A'),
41+
'previousClose': info.get('previousClose', 'N/A'),
42+
'sector': info.get('sector', 'N/A')
43+
}
44+
print("✅ Data fetching done successfully!")
45+
return stock_info
46+
except Exception as e:
47+
print(f"❌ Error fetching {symbol}: {e}")
48+
time.sleep(5)

0 commit comments

Comments
 (0)