Spaces:
Sleeping
Sleeping
Update services/news_service.py
Browse files- services/news_service.py +57 -28
services/news_service.py
CHANGED
|
@@ -1,39 +1,68 @@
|
|
| 1 |
-
import requests
|
| 2 |
import os
|
| 3 |
-
|
| 4 |
-
from
|
| 5 |
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
try:
|
| 10 |
-
# Use last 7 days of news
|
| 11 |
-
today = datetime.now()
|
| 12 |
-
last_week = today - timedelta(days=7)
|
| 13 |
|
| 14 |
-
url = (
|
| 15 |
-
f"https://finnhub.io/api/v1/company-news?symbol={symbol}"
|
| 16 |
-
f"&from={last_week.strftime('%Y-%m-%d')}"
|
| 17 |
-
f"&to={today.strftime('%Y-%m-%d')}&token={FINNHUB_API_KEY}"
|
| 18 |
-
)
|
| 19 |
-
res = requests.get(url)
|
| 20 |
-
data = res.json()
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
})
|
| 34 |
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
except Exception as e:
|
| 38 |
-
print("
|
| 39 |
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import requests
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
|
| 5 |
+
# Load environment variables from .env file
|
| 6 |
+
load_dotenv()
|
| 7 |
|
| 8 |
+
NEWS_API_KEY = os.environ.get("NEWS_API_KEY")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
def get_company_news(query="GOOG", limit=5):
|
| 12 |
+
"""
|
| 13 |
+
Fetches latest news articles using a specific query string (symbol or full company name).
|
| 14 |
+
Always returns a list. Never raises exceptions.
|
| 15 |
+
"""
|
| 16 |
|
| 17 |
+
# β
Safety: Key missing
|
| 18 |
+
if not NEWS_API_KEY:
|
| 19 |
+
print("Warning: NEWS_API_KEY is not set. News fetching skipped.")
|
| 20 |
+
return []
|
| 21 |
|
| 22 |
+
# β
Quotes improve multi-word search
|
| 23 |
+
url = (
|
| 24 |
+
f"https://newsapi.org/v2/everything?"
|
| 25 |
+
f"q=\"{query}\"&sortBy=publishedAt&language=en&apiKey={NEWS_API_KEY}"
|
| 26 |
+
)
|
|
|
|
| 27 |
|
| 28 |
+
try:
|
| 29 |
+
response = requests.get(url)
|
| 30 |
+
# β
If API returns HTML (rate limit, outage)
|
| 31 |
+
if response.headers.get("content-type", "").startswith("text/html"):
|
| 32 |
+
print("NewsAPI returned HTML instead of JSON β ignoring.")
|
| 33 |
+
return []
|
| 34 |
+
|
| 35 |
+
resp = response.json()
|
| 36 |
|
| 37 |
except Exception as e:
|
| 38 |
+
print(f"Exception while fetching news: {e}")
|
| 39 |
return []
|
| 40 |
+
|
| 41 |
+
# β
Safety: API error or invalid key
|
| 42 |
+
if resp.get("status") != "ok":
|
| 43 |
+
print(f"NewsAPI Error: {resp.get('message')}")
|
| 44 |
+
return []
|
| 45 |
+
|
| 46 |
+
# β
Extract clean articles
|
| 47 |
+
articles = []
|
| 48 |
+
for a in resp.get("articles", []):
|
| 49 |
+
if len(articles) >= limit:
|
| 50 |
+
break
|
| 51 |
+
|
| 52 |
+
title = a.get("title")
|
| 53 |
+
desc = a.get("description")
|
| 54 |
+
|
| 55 |
+
# β
Safety: ensure both title & description exist AND are strings
|
| 56 |
+
if not title or not isinstance(title, str):
|
| 57 |
+
continue
|
| 58 |
+
if not desc or not isinstance(desc, str):
|
| 59 |
+
continue
|
| 60 |
+
|
| 61 |
+
articles.append({
|
| 62 |
+
"title": title.strip(),
|
| 63 |
+
"description": desc.strip(),
|
| 64 |
+
"url": a.get("url", "")
|
| 65 |
+
})
|
| 66 |
+
|
| 67 |
+
print(f"Fetched {len(articles)} articles from NewsAPI for query: \"{query}\"")
|
| 68 |
+
return articles
|