Skip to content

Commit 11c1fb2

Browse files
Merge pull request #9 from yashksaini-coder/kush2
Add Stock news api endpoint
2 parents 32f82fe + 1343748 commit 11c1fb2

File tree

2 files changed

+53
-10
lines changed

2 files changed

+53
-10
lines changed

app.py

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@
1414
from contextlib import asynccontextmanager
1515
import json
1616
from redis import asyncio as aioredis
17-
1817
# Custom imports
1918
from topStocks import get_top_stocks
2019
from ask import groq_chat
20+
from stockNews import fetch_news
2121
from agents import multi_ai
2222
from agno.agent import RunResponse
2323

@@ -29,7 +29,6 @@
2929

3030
if not GROQ_API_KEY:
3131
raise ValueError("Please provide a GROQ API key")
32-
3332
REDIS_URL = os.getenv("REDIS_URL")
3433

3534
@asynccontextmanager
@@ -54,8 +53,7 @@ async def lifespan(_: FastAPI):
5453
print(f"❌ Error while closing Redis: {e}")
5554

5655

57-
app = FastAPI(lifespan=lifespan) # Pass the lifespan context manager to FastAPI
58-
56+
app = FastAPI(lifespan=lifespan)
5957
app.add_middleware(
6058
CORSMiddleware,
6159
allow_origins=["*"],
@@ -87,7 +85,18 @@ async def read_top_stocks(cache: RedisBackend = Depends(get_cache)):
8785
await cache.set(cache_key, json.dumps(stock_info), 10)
8886
return stock_info
8987

90-
@app.get("/health") # Changed to GET since it's retrieving status
88+
@app.get("/stock-news")
89+
async def stock_news(cache: RedisBackend = Depends(get_cache)):
90+
cache_key = "stock_news"
91+
cached_result = await cache.get(cache_key)
92+
if cached_result:
93+
return json.loads(cached_result)
94+
news_stack = fetch_news()
95+
await cache.set(cache_key, json.dumps(news_stack), 300)
96+
return news_stack
97+
98+
99+
@app.get("health/") # Changed to GET since it's retrieving status
91100
async def health_check():
92101
try:
93102
return {
@@ -96,7 +105,6 @@ async def health_check():
96105
"uptime": "OK",
97106
"api": {
98107
"groq_api": "connected" if GROQ_API_KEY else "not configured",
99-
"redis_cache": "connected" if REDIS_URL else "not configured",
100108
},
101109
"ip": requests.get('https://api.ipify.org').text,
102110
"services": {
@@ -118,10 +126,18 @@ def chat(query: str):
118126
"""
119127
API endpoint to handle user investment-related questions and return AI-generated insights.
120128
"""
121-
129+
if not query:
130+
return {"error": "Query parameter is required"}
131+
122132
try:
123-
answer = groq_chat(query)
124-
return answer
133+
response = groq_client.chat.completions.create(
134+
model="llama-3.3-70b-versatile",
135+
messages=[{"role": "system", "content": "You are an AI investment assistant."},
136+
{"role": "user", "content": query}]
137+
)
138+
139+
answer = response.choices[0].message.content
140+
return {"question": query, "answer": answer}
125141

126142
except Exception as e:
127143
return {"error": str(e)}
@@ -142,4 +158,4 @@ def ask(query: str):
142158
return {"question": query, "answer": answer}
143159

144160
except Exception as e:
145-
return {"error": str(e)}
161+
return {"error": str(e)}

stockNews.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import finnhub
2+
import time
3+
import requests
4+
from dotenv import load_dotenv
5+
import os
6+
load_dotenv()
7+
NEWS_API_KEY = os.getenv("NEWS_API_KEY")
8+
if not NEWS_API_KEY:
9+
raise ValueError("Please provide a NEWS API key")
10+
session = requests.Session()
11+
session.headers.update({
12+
"User-Agent": "Chrome/122.0.0.0"
13+
})
14+
def fetch_news():
15+
try:
16+
17+
finnhub_client = finnhub.Client(api_key=NEWS_API_KEY)
18+
19+
news_list =finnhub_client.general_news('general', min_id=4)
20+
news_stack=[]
21+
for news in news_list[:10]:
22+
news_stack.append([news['headline'],news['url']])
23+
print("✅ Data fetching done successfully!")
24+
return news_stack
25+
except Exception as e:
26+
print(f"❌ Error fetching news: {e}")
27+
time.sleep(5)

0 commit comments

Comments
 (0)