Create sentiment_agent.py
Browse files- sentiment_agent.py +26 -0
sentiment_agent.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
from textblob import TextBlob
|
| 3 |
+
|
| 4 |
+
class SentimentAgent:
|
| 5 |
+
def run(self, symbol="AAPL"):
|
| 6 |
+
try:
|
| 7 |
+
url = f"https://finance.yahoo.com/quote/{symbol}?p={symbol}"
|
| 8 |
+
r = requests.get(url, timeout=5)
|
| 9 |
+
text = r.text
|
| 10 |
+
|
| 11 |
+
# Simulate headlines from raw HTML (for demo purposes)
|
| 12 |
+
headlines = [line.strip() for line in text.splitlines() if "news" in line.lower()]
|
| 13 |
+
headlines = [h for h in headlines if len(h) > 20][:5]
|
| 14 |
+
|
| 15 |
+
sentiments = [TextBlob(h).sentiment.polarity for h in headlines]
|
| 16 |
+
avg_score = sum(sentiments) / len(sentiments) if sentiments else 0.0
|
| 17 |
+
|
| 18 |
+
tone = "Positive" if avg_score > 0.1 else "Negative" if avg_score < -0.1 else "Neutral"
|
| 19 |
+
|
| 20 |
+
return {
|
| 21 |
+
"sentiment": tone,
|
| 22 |
+
"score": round(avg_score, 2)
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
except Exception as e:
|
| 26 |
+
return {"sentiment": "Unavailable", "score": 0.0}
|