Harisri commited on
Commit
74953cc
Β·
verified Β·
1 Parent(s): 60fe166

Update services/news_service.py

Browse files
Files changed (1) hide show
  1. services/news_service.py +57 -28
services/news_service.py CHANGED
@@ -1,39 +1,68 @@
1
- import requests
2
  import os
3
- from datetime import datetime, timedelta
4
- from services.sdg_llm import analyze_sdg_text
5
 
6
- FINNHUB_API_KEY = os.environ.get("FINNHUB_API_KEY")
 
7
 
8
- def get_company_news(symbol):
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
- articles = []
 
 
 
 
23
 
24
- for a in data[:10]: # limit to 10 items
25
- text = f"{a.get('headline','')} {a.get('summary','')}"
26
- sdg = analyze_sdg_text(text)
 
27
 
28
- articles.append({
29
- "title": a.get("headline", ""),
30
- "description": a.get("summary", ""),
31
- "url": a.get("url", ""),
32
- "sdg": sdg # βœ… SDG data added
33
- })
34
 
35
- return articles
 
 
 
 
 
 
 
36
 
37
  except Exception as e:
38
- print("News fetch error:", e)
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