Skip to content

Commit 8583b83

Browse files
Merge pull request #2 from yashksaini-coder/kush
Top Stocks API endpoint
2 parents b69f0d3 + 7955409 commit 8583b83

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

main.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import groq
33
import os
44
from dotenv import load_dotenv
5+
from fastapi.middleware.cors import CORSMiddleware
6+
from topStocks import get_top_stocks
57
# Load API key from .env file
68

79
load_dotenv(dotenv_path=".env")
@@ -15,6 +17,14 @@
1517

1618
app = FastAPI()
1719

20+
app.add_middleware(
21+
CORSMiddleware,
22+
allow_origins=["*"],
23+
allow_credentials=True,
24+
allow_methods=["*"],
25+
allow_headers=["*"],
26+
)
27+
1828
@app.get("/ask")
1929
def ask(query: str):
2030
"""
@@ -34,4 +44,10 @@ def ask(query: str):
3444
return {"question": query, "answer": answer}
3545

3646
except Exception as e:
37-
return {"error": str(e)}
47+
return {"error": str(e)}
48+
49+
@app.get("/top-stocks")
50+
async def read_top_stocks():
51+
top_stocks = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA']
52+
stock_info = get_top_stocks(top_stocks)
53+
return stock_info

topStocks.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import yfinance as yf
2+
3+
def get_top_stocks(symbols):
4+
stock_data = []
5+
for symbol in symbols:
6+
try:
7+
ticker = yf.Ticker(symbol)
8+
info = ticker.info
9+
stock_info = {
10+
'symbol': symbol,
11+
'name': info.get('shortName', 'N/A'),
12+
'currentPrice': info.get('currentPrice', 'N/A'),
13+
'previousClose': info.get('previousClose', 'N/A'),
14+
'sector': info.get('sector', 'N/A')
15+
}
16+
stock_data.append(stock_info)
17+
except Exception as e:
18+
print(f"Error fetching {symbol}: {e}")
19+
return stock_data

0 commit comments

Comments
 (0)