Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from typing import List
|
3 |
+
import requests
|
4 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
5 |
+
from datetime import datetime, timedelta
|
6 |
+
import numpy as np
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
import os
|
9 |
+
|
10 |
+
app = FastAPI()
|
11 |
+
|
12 |
+
# Load FinBERT model and tokenizer
|
13 |
+
model_name = "ProsusAI/finbert"
|
14 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
15 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
16 |
+
sentiment_analyzer = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)
|
17 |
+
|
18 |
+
# Load environment variables
|
19 |
+
load_dotenv()
|
20 |
+
api_key = os.getenv('NEWS_API_KEY')
|
21 |
+
|
22 |
+
def fetch_stock_news(company: str, days: int = 2):
|
23 |
+
today = datetime.now().date()
|
24 |
+
from_date = (today - timedelta(days=days)).strftime('%Y-%m-%d')
|
25 |
+
to_date = today.strftime('%Y-%m-%d')
|
26 |
+
|
27 |
+
query = f"{company} stock OR {company} shares"
|
28 |
+
|
29 |
+
url = (
|
30 |
+
f'https://newsapi.org/v2/everything?q={query}'
|
31 |
+
f'&from={from_date}&to={to_date}'
|
32 |
+
f'&language=en'
|
33 |
+
f'&sortBy=publishedAt&apiKey={api_key}'
|
34 |
+
)
|
35 |
+
|
36 |
+
response = requests.get(url)
|
37 |
+
news_data = response.json()
|
38 |
+
|
39 |
+
if news_data['status'] != 'ok':
|
40 |
+
raise HTTPException(status_code=400, detail=news_data.get('message', 'Unknown error'))
|
41 |
+
|
42 |
+
return news_data['articles']
|
43 |
+
|
44 |
+
def analyze_sentiment(articles):
|
45 |
+
results = []
|
46 |
+
for article in articles:
|
47 |
+
text = f"{article['title']}. {article['description']}"
|
48 |
+
sentiment = sentiment_analyzer(text)[0]
|
49 |
+
score = sentiment['score'] if sentiment['label'] == 'positive' else -sentiment['score']
|
50 |
+
results.append({
|
51 |
+
'title': article['title'],
|
52 |
+
'description': article['description'],
|
53 |
+
'sentiment_score': score
|
54 |
+
})
|
55 |
+
return results
|
56 |
+
|
57 |
+
@app.get("/")
|
58 |
+
def home():
|
59 |
+
return {"message":"welcome to stock sentiment analysis"}
|
60 |
+
|
61 |
+
@app.get("/sentiment/{company}", response_model=List[dict])
|
62 |
+
def get_sentiment(company: str):
|
63 |
+
articles = fetch_stock_news(company)
|
64 |
+
sentiments = analyze_sentiment(articles)
|
65 |
+
return sentiments
|
66 |
+
|
67 |
+
@app.get("/top_articles/{company}", response_model=List[dict])
|
68 |
+
def get_top_articles(company: str):
|
69 |
+
articles = fetch_stock_news(company)
|
70 |
+
sentiments = analyze_sentiment(articles)
|
71 |
+
sorted_articles = sorted(sentiments, key=lambda x: abs(x['sentiment_score']), reverse=True)[:5]
|
72 |
+
return sorted_articles
|
73 |
+
|
74 |
+
@app.get("/average_sentiment/{company}")
|
75 |
+
def get_average_sentiment(company: str):
|
76 |
+
articles = fetch_stock_news(company)
|
77 |
+
sentiments = analyze_sentiment(articles)
|
78 |
+
scores = [article['sentiment_score'] for article in sentiments]
|
79 |
+
average_score = np.mean(scores)
|
80 |
+
return {"average_sentiment_score": average_score}
|