Changed news engine code a little

This commit is contained in:
Harwinder
2026-05-05 22:33:43 -04:00
parent f561311f14
commit 0bb52083a3
3 changed files with 76 additions and 10 deletions
+40 -10
View File
@@ -1,6 +1,4 @@
"""
Forex Signal Intelligence Platform - News & Sentiment Engine
=============================================================
Monitors economic calendar events and news sentiment to provide
fundamental context for technical signals.
@@ -16,6 +14,9 @@ from typing import Dict, List, Optional, Tuple
import requests
# Import the transformers pipeline for FinBERT
from transformers import pipeline
from config import NewsConfig
logger = logging.getLogger(__name__)
@@ -78,7 +79,7 @@ class NewsEngine:
Provides fundamental context that modifies technical signal confidence.
"""
# Keywords that indicate directional sentiment
# Keywords that indicate directional sentiment (kept for fallback and keyword extraction)
BULLISH_KEYWORDS = {
"rate hike", "hawkish", "strong growth", "beat expectations",
"above forecast", "surplus", "expansion", "employment gains",
@@ -120,6 +121,16 @@ class NewsEngine:
self._session.headers.update({
"User-Agent": "Mozilla/5.0 (compatible; ForexIntel/1.0)"
})
# Initialize the FinBERT LLM Pipeline
try:
logger.info("Initializing FinBERT NLP model. This may take a moment on startup...")
# We use ProsusAI/finbert as it is specifically fine-tuned on financial tone
self.nlp_pipeline = pipeline("sentiment-analysis", model="ProsusAI/finbert")
logger.info("FinBERT successfully loaded.")
except Exception as e:
logger.error(f"Failed to load FinBERT model: {e}. Defaulting to basic keyword analysis.")
self.nlp_pipeline = None
def get_fundamental_context(
self, currencies: Optional[List[str]] = None
@@ -348,14 +359,33 @@ class NewsEngine:
def _analyze_headline_sentiment(self, headline: str) -> float:
"""
Simple keyword-based sentiment analysis.
Analyze headline sentiment using the FinBERT NLP model.
Returns -1.0 (very bearish) to +1.0 (very bullish).
Note: This is intentionally simple. NLP models like FinBERT
would be more accurate but require large dependencies. This catches
the most impactful sentiment signals from headlines.
"""
if self.nlp_pipeline is None:
# Fallback to simple keyword logic if the LLM failed to load
return self._fallback_keyword_sentiment(headline)
try:
# The pipeline returns a list with a dict, e.g.: [{'label': 'positive', 'score': 0.85}]
result = self.nlp_pipeline(headline)[0]
label = result['label'].lower()
confidence = result['score']
if label == 'positive':
return confidence # e.g., +0.85
elif label == 'negative':
return -confidence # e.g., -0.85
else:
# Neutral label
return 0.0
except Exception as e:
logger.debug(f"FinBERT sentiment analysis failed for '{headline}': {e}")
return self._fallback_keyword_sentiment(headline)
def _fallback_keyword_sentiment(self, headline: str) -> float:
"""Original keyword-based fallback if FinBERT is unavailable."""
headline_lower = headline.lower()
bullish_score = sum(1 for kw in self.BULLISH_KEYWORDS if kw in headline_lower)
bearish_score = sum(1 for kw in self.BEARISH_KEYWORDS if kw in headline_lower)
@@ -424,4 +454,4 @@ class NewsEngine:
"CAD": ["USDCAD=X", "CADJPY=X"],
"NZD": ["NZDUSD=X"],
}
return pairs.get(currency, [])
return pairs.get(currency, [])