-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnews.py
More file actions
78 lines (61 loc) · 2.53 KB
/
Copy pathnews.py
File metadata and controls
78 lines (61 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import requests
from datetime import datetime, timedelta
# NewsAPI Setup (Free tier)
NEWSAPI_KEY = '' # Get one from https://newsapi.org/
# Finnhub Setup (Free tier)
FINNHUB_API_KEY = '' # Get one from https://finnhub.io/
# Sample symbols to get context for
SYMBOLS = ['AAPL', 'TSLA', 'AMD']
def get_news(symbol):
url = f'https://newsapi.org/v2/everything?q={symbol}&from={datetime.now().date()}&sortBy=publishedAt&apiKey={NEWSAPI_KEY}'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
articles = data.get('articles', [])[:3]
return [f"{a['title']} - {a['source']['name']}" for a in articles]
else:
return [f"News fetch failed for {symbol}: {response.text}"]
def get_finnhub_news(symbol):
url = f'https://finnhub.io/api/v1/company-news?symbol={symbol}&from={datetime.now().date() - timedelta(days=1)}&to={datetime.now().date()}&token={FINNHUB_API_KEY}'
response = requests.get(url)
if response.status_code == 200:
articles = response.json()[:3]
return [f"{a['headline']} - {a['source']}" for a in articles]
else:
return [f"Finnhub news fetch failed for {symbol}: {response.text}"]
def get_finnhub_sentiment(symbol):
url = f'https://finnhub.io/api/v1/news-sentiment?symbol={symbol}&token={FINNHUB_API_KEY}'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
buzz = data.get('buzz', {})
sentiment = data.get('sentiment', {})
return {
'buzz': buzz.get('buzz', 0),
'articlesInLastWeek': buzz.get('articlesInLastWeek', 0),
'sentiment_score': sentiment.get('companyNewsScore', 0)
}
else:
return { 'error': f"Sentiment fetch failed: {response.text}" }
def fetch_all_context(symbols):
print("\nFetching market context...\n")
all_data = {}
for symbol in symbols:
print(f"--- {symbol} ---")
news = get_news(symbol)
sentiment = get_finnhub_sentiment(symbol)
print("Top News Headlines:")
for n in news:
print(f"- {n}")
if 'error' not in sentiment:
print(f"Buzz Score: {sentiment['buzz']}, Articles Last Week: {sentiment['articlesInLastWeek']}, Sentiment Score: {sentiment['sentiment_score']:.2f}")
else:
print(sentiment['error'])
print()
all_data[symbol] = {
'news': news,
'sentiment': sentiment
}
return all_data
if __name__ == '__main__':
fetch_all_context(SYMBOLS)