Dmitry Beresnev
commited on
Commit
·
a6e7f4a
1
Parent(s):
156858e
add breaking news scorer
Browse files- app/components/news.py +23 -3
- app/pages/05_Dashboard.py +19 -2
- app/utils/breaking_news_scorer.py +364 -0
app/components/news.py
CHANGED
|
@@ -351,7 +351,7 @@ def display_category_breakdown(stats: dict):
|
|
| 351 |
|
| 352 |
|
| 353 |
def display_breaking_news_banner(df: pd.DataFrame):
|
| 354 |
-
"""Display breaking news banner at the top with TradingView styling."""
|
| 355 |
|
| 356 |
breaking = df[df['is_breaking'] == True] if not df.empty and 'is_breaking' in df.columns else pd.DataFrame()
|
| 357 |
|
|
@@ -363,6 +363,24 @@ def display_breaking_news_banner(df: pd.DataFrame):
|
|
| 363 |
source = html_module.escape(latest['source'])
|
| 364 |
url = html_module.escape(latest['url'])
|
| 365 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
# Calculate time ago
|
| 367 |
time_diff = datetime.now() - latest['timestamp']
|
| 368 |
if time_diff.seconds < 60:
|
|
@@ -373,7 +391,7 @@ def display_breaking_news_banner(df: pd.DataFrame):
|
|
| 373 |
hours = time_diff.seconds // 3600
|
| 374 |
time_ago = f"{hours}h ago" if hours < 24 else f"{time_diff.days}d ago"
|
| 375 |
|
| 376 |
-
# TradingView-style breaking news banner (no leading whitespace)
|
| 377 |
banner_html = f"""<style>
|
| 378 |
@keyframes pulse-glow {{
|
| 379 |
0%, 100% {{ box-shadow: 0 0 20px rgba(242, 54, 69, 0.6); }}
|
|
@@ -391,10 +409,12 @@ to {{ transform: translateX(0); opacity: 1; }}
|
|
| 391 |
<div style="font-size: 32px; animation: pulse-glow 1s ease-in-out infinite; filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.3));">🚨</div>
|
| 392 |
<div style="flex: 1;">
|
| 393 |
<div style="color: white; font-size: 14px; font-weight: 700; letter-spacing: 1.5px; text-transform: uppercase; margin-bottom: 4px; font-family: -apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif; text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);">⚡ Breaking News</div>
|
| 394 |
-
<div style="color: rgba(255, 255, 255, 0.9); font-size: 11px; display: flex; align-items: center; gap: 8px;">
|
| 395 |
<span style="background: rgba(255, 255, 255, 0.2); padding: 2px 8px; border-radius: 4px; font-weight: 600;">{source}</span>
|
| 396 |
<span style="opacity: 0.8;">•</span>
|
| 397 |
<span style="opacity: 0.8;">{time_ago}</span>
|
|
|
|
|
|
|
| 398 |
</div>
|
| 399 |
</div>
|
| 400 |
<a href="{url}" target="_blank" style="background: white; color: #F23645; padding: 10px 20px; border-radius: 6px; font-size: 13px; font-weight: 700; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s ease; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 12px rgba(0, 0, 0, 0.3)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 8px rgba(0, 0, 0, 0.2)';">READ NOW →</a>
|
|
|
|
| 351 |
|
| 352 |
|
| 353 |
def display_breaking_news_banner(df: pd.DataFrame):
|
| 354 |
+
"""Display breaking news banner at the top with TradingView styling and ML-based impact score."""
|
| 355 |
|
| 356 |
breaking = df[df['is_breaking'] == True] if not df.empty and 'is_breaking' in df.columns else pd.DataFrame()
|
| 357 |
|
|
|
|
| 363 |
source = html_module.escape(latest['source'])
|
| 364 |
url = html_module.escape(latest['url'])
|
| 365 |
|
| 366 |
+
# Get impact score if available
|
| 367 |
+
impact_score = latest.get('breaking_score', 0)
|
| 368 |
+
score_display = f"{impact_score:.1f}" if impact_score > 0 else "N/A"
|
| 369 |
+
|
| 370 |
+
# Determine score color and label
|
| 371 |
+
if impact_score >= 80:
|
| 372 |
+
score_color = "#FF3B30" # Critical red
|
| 373 |
+
score_label = "CRITICAL"
|
| 374 |
+
elif impact_score >= 60:
|
| 375 |
+
score_color = "#FF9500" # High orange
|
| 376 |
+
score_label = "HIGH"
|
| 377 |
+
elif impact_score >= 40:
|
| 378 |
+
score_color = "#FFCC00" # Medium yellow
|
| 379 |
+
score_label = "MEDIUM"
|
| 380 |
+
else:
|
| 381 |
+
score_color = "#34C759" # Low green
|
| 382 |
+
score_label = "LOW"
|
| 383 |
+
|
| 384 |
# Calculate time ago
|
| 385 |
time_diff = datetime.now() - latest['timestamp']
|
| 386 |
if time_diff.seconds < 60:
|
|
|
|
| 391 |
hours = time_diff.seconds // 3600
|
| 392 |
time_ago = f"{hours}h ago" if hours < 24 else f"{time_diff.days}d ago"
|
| 393 |
|
| 394 |
+
# TradingView-style breaking news banner with impact score (no leading whitespace)
|
| 395 |
banner_html = f"""<style>
|
| 396 |
@keyframes pulse-glow {{
|
| 397 |
0%, 100% {{ box-shadow: 0 0 20px rgba(242, 54, 69, 0.6); }}
|
|
|
|
| 409 |
<div style="font-size: 32px; animation: pulse-glow 1s ease-in-out infinite; filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.3));">🚨</div>
|
| 410 |
<div style="flex: 1;">
|
| 411 |
<div style="color: white; font-size: 14px; font-weight: 700; letter-spacing: 1.5px; text-transform: uppercase; margin-bottom: 4px; font-family: -apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif; text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);">⚡ Breaking News</div>
|
| 412 |
+
<div style="color: rgba(255, 255, 255, 0.9); font-size: 11px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
|
| 413 |
<span style="background: rgba(255, 255, 255, 0.2); padding: 2px 8px; border-radius: 4px; font-weight: 600;">{source}</span>
|
| 414 |
<span style="opacity: 0.8;">•</span>
|
| 415 |
<span style="opacity: 0.8;">{time_ago}</span>
|
| 416 |
+
<span style="opacity: 0.8;">•</span>
|
| 417 |
+
<span style="background: {score_color}; color: white; padding: 2px 8px; border-radius: 4px; font-weight: 700; font-size: 10px; letter-spacing: 0.5px;">📊 IMPACT: {score_display}/100 ({score_label})</span>
|
| 418 |
</div>
|
| 419 |
</div>
|
| 420 |
<a href="{url}" target="_blank" style="background: white; color: #F23645; padding: 10px 20px; border-radius: 6px; font-size: 13px; font-weight: 700; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s ease; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 12px rgba(0, 0, 0, 0.3)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 8px rgba(0, 0, 0, 0.2)';">READ NOW →</a>
|
app/pages/05_Dashboard.py
CHANGED
|
@@ -17,6 +17,7 @@ from components.news import (
|
|
| 17 |
display_breaking_news_banner,
|
| 18 |
display_scrollable_news_section
|
| 19 |
)
|
|
|
|
| 20 |
|
| 21 |
# Import news scrapers
|
| 22 |
try:
|
|
@@ -315,9 +316,25 @@ if not twitter_reddit_df.empty:
|
|
| 315 |
# Combine all for breaking news banner
|
| 316 |
all_news_df = pd.concat([twitter_filtered, reddit_filtered, rss_all_filtered], ignore_index=True) if not twitter_filtered.empty or not reddit_filtered.empty or not rss_all_filtered.empty else pd.DataFrame()
|
| 317 |
|
| 318 |
-
# Display breaking news banner
|
| 319 |
if not all_news_df.empty:
|
| 320 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
|
| 322 |
st.markdown("---")
|
| 323 |
|
|
|
|
| 17 |
display_breaking_news_banner,
|
| 18 |
display_scrollable_news_section
|
| 19 |
)
|
| 20 |
+
from utils.breaking_news_scorer import get_breaking_news_scorer
|
| 21 |
|
| 22 |
# Import news scrapers
|
| 23 |
try:
|
|
|
|
| 316 |
# Combine all for breaking news banner
|
| 317 |
all_news_df = pd.concat([twitter_filtered, reddit_filtered, rss_all_filtered], ignore_index=True) if not twitter_filtered.empty or not reddit_filtered.empty or not rss_all_filtered.empty else pd.DataFrame()
|
| 318 |
|
| 319 |
+
# Display breaking news banner with ML-based scoring
|
| 320 |
if not all_news_df.empty:
|
| 321 |
+
# Initialize the breaking news scorer
|
| 322 |
+
scorer = get_breaking_news_scorer()
|
| 323 |
+
|
| 324 |
+
# Convert DataFrame to list of dicts for scoring
|
| 325 |
+
all_news_list = all_news_df.to_dict('records')
|
| 326 |
+
|
| 327 |
+
# Get top breaking news using multi-factor impact scoring
|
| 328 |
+
# Only show news with impact score >= 40 (medium-high impact threshold)
|
| 329 |
+
breaking_news_items = scorer.get_breaking_news(all_news_list, top_n=1)
|
| 330 |
+
|
| 331 |
+
if breaking_news_items and breaking_news_items[0]['breaking_score'] >= 40.0:
|
| 332 |
+
# Display the highest-impact news in the banner
|
| 333 |
+
breaking_df = pd.DataFrame([breaking_news_items[0]])
|
| 334 |
+
display_breaking_news_banner(breaking_df)
|
| 335 |
+
else:
|
| 336 |
+
# If no high-impact news found, show informational message
|
| 337 |
+
st.info("📊 Monitoring financial markets - no high-impact breaking news at this time.")
|
| 338 |
|
| 339 |
st.markdown("---")
|
| 340 |
|
app/utils/breaking_news_scorer.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Breaking News Scoring System
|
| 3 |
+
Identifies highest-impact financial news using multi-factor weighted scoring
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import re
|
| 7 |
+
from datetime import datetime, timedelta
|
| 8 |
+
from typing import Dict, List
|
| 9 |
+
import logging
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class BreakingNewsScorer:
|
| 15 |
+
"""
|
| 16 |
+
Sophisticated scoring system for breaking financial news
|
| 17 |
+
Uses weighted factors to identify market-moving events
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
# Critical keywords with high market impact (weight: 3.0)
|
| 21 |
+
CRITICAL_KEYWORDS = [
|
| 22 |
+
# Central Bank Actions
|
| 23 |
+
'rate hike', 'rate cut', 'interest rate', 'fed raises', 'fed cuts',
|
| 24 |
+
'fomc decision', 'monetary policy', 'quantitative easing', 'qe',
|
| 25 |
+
'emergency meeting', 'powell', 'lagarde', 'yellen',
|
| 26 |
+
|
| 27 |
+
# Market Events
|
| 28 |
+
'market crash', 'flash crash', 'circuit breaker', 'trading halt',
|
| 29 |
+
'all-time high', 'all time high', 'record high', 'record low',
|
| 30 |
+
'biggest drop', 'biggest gain', 'historic', 'unprecedented',
|
| 31 |
+
|
| 32 |
+
# Economic Data
|
| 33 |
+
'gdp', 'jobs report', 'unemployment', 'inflation',
|
| 34 |
+
'cpi', 'ppi', 'nonfarm payroll', 'nfp',
|
| 35 |
+
|
| 36 |
+
# Corporate Events
|
| 37 |
+
'earnings beat', 'earnings miss', 'profit warning',
|
| 38 |
+
'bankruptcy', 'chapter 11', 'delisted',
|
| 39 |
+
'merger', 'acquisition', 'takeover', 'buyout',
|
| 40 |
+
|
| 41 |
+
# Geopolitical
|
| 42 |
+
'war', 'invasion', 'sanctions', 'trade war',
|
| 43 |
+
'embargo', 'default', 'debt ceiling', 'shutdown',
|
| 44 |
+
'impeachment', 'coup', 'terrorist attack'
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
# High-impact keywords (weight: 2.0)
|
| 48 |
+
HIGH_IMPACT_KEYWORDS = [
|
| 49 |
+
# Market Movement
|
| 50 |
+
'surge', 'plunge', 'soar', 'tumble', 'rally', 'selloff',
|
| 51 |
+
'volatility', 'whipsaw', 'correction', 'bear market', 'bull market',
|
| 52 |
+
|
| 53 |
+
# Economic Indicators
|
| 54 |
+
'retail sales', 'housing starts', 'consumer confidence',
|
| 55 |
+
'manufacturing index', 'pmi', 'trade deficit',
|
| 56 |
+
|
| 57 |
+
# Corporate
|
| 58 |
+
'revenue beat', 'guidance', 'dividend', 'stock split',
|
| 59 |
+
'ipo', 'listing', 'secondary offering',
|
| 60 |
+
|
| 61 |
+
# Crypto/Tech
|
| 62 |
+
'bitcoin', 'crypto crash', 'hack', 'breach',
|
| 63 |
+
'antitrust', 'regulation', 'sec investigation',
|
| 64 |
+
|
| 65 |
+
# Commodities
|
| 66 |
+
'oil', 'gold', 'crude', 'opec', 'energy crisis',
|
| 67 |
+
'supply chain', 'shortage', 'surplus'
|
| 68 |
+
]
|
| 69 |
+
|
| 70 |
+
# Medium-impact keywords (weight: 1.5)
|
| 71 |
+
MEDIUM_IMPACT_KEYWORDS = [
|
| 72 |
+
'analyst', 'upgrade', 'downgrade', 'target price',
|
| 73 |
+
'forecast', 'outlook', 'projection', 'estimate',
|
| 74 |
+
'conference call', 'ceo', 'cfo', 'executive',
|
| 75 |
+
'lawsuit', 'settlement', 'fine', 'penalty',
|
| 76 |
+
'product launch', 'partnership', 'deal', 'contract'
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
# Premium source weights (multipliers)
|
| 80 |
+
SOURCE_WEIGHTS = {
|
| 81 |
+
# Tier 1: Breaking News Specialists (2.0x)
|
| 82 |
+
'walter_bloomberg': 2.0,
|
| 83 |
+
'fxhedge': 2.0,
|
| 84 |
+
'deitaone': 2.0,
|
| 85 |
+
'firstsquawk': 1.9,
|
| 86 |
+
'livesquawk': 1.9,
|
| 87 |
+
|
| 88 |
+
# Tier 2: Major Financial Media (1.8x)
|
| 89 |
+
'reuters': 1.8,
|
| 90 |
+
'bloomberg': 1.8,
|
| 91 |
+
'ft': 1.7,
|
| 92 |
+
'wsj': 1.7,
|
| 93 |
+
|
| 94 |
+
# Tier 3: Mainstream Media (1.5x)
|
| 95 |
+
'cnbc': 1.5,
|
| 96 |
+
'bbc': 1.5,
|
| 97 |
+
'marketwatch': 1.5,
|
| 98 |
+
|
| 99 |
+
# Tier 4: Alternative/Community (1.2x)
|
| 100 |
+
'zerohedge': 1.2,
|
| 101 |
+
'wallstreetbets': 1.2,
|
| 102 |
+
'reddit': 1.2,
|
| 103 |
+
|
| 104 |
+
# Default
|
| 105 |
+
'default': 1.0
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
# Ticker mention bonus (companies that move markets)
|
| 109 |
+
MAJOR_TICKERS = [
|
| 110 |
+
'SPY', 'QQQ', 'DIA', 'IWM', # Market indices
|
| 111 |
+
'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'NVDA', 'TSLA', 'META', # Mega caps
|
| 112 |
+
'JPM', 'BAC', 'GS', 'MS', 'WFC', # Banks
|
| 113 |
+
'XOM', 'CVX', 'COP', # Energy
|
| 114 |
+
'BTC', 'ETH', 'BTCUSD', 'ETHUSD' # Crypto
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
def __init__(self):
|
| 118 |
+
"""Initialize the breaking news scorer"""
|
| 119 |
+
logger.info("BreakingNewsScorer initialized")
|
| 120 |
+
|
| 121 |
+
def calculate_impact_score(self, news_item: Dict) -> float:
|
| 122 |
+
"""
|
| 123 |
+
Calculate comprehensive impact score for a news item
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
news_item: Dictionary containing news metadata
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
Impact score (0-100, higher = more impactful)
|
| 130 |
+
"""
|
| 131 |
+
score = 0.0
|
| 132 |
+
|
| 133 |
+
# Extract key fields
|
| 134 |
+
title = news_item.get('title', '').lower()
|
| 135 |
+
summary = news_item.get('summary', '').lower()
|
| 136 |
+
source = news_item.get('source', '').lower()
|
| 137 |
+
timestamp = news_item.get('timestamp', datetime.now())
|
| 138 |
+
sentiment = news_item.get('sentiment', 'neutral')
|
| 139 |
+
impact_level = news_item.get('impact', 'low')
|
| 140 |
+
category = news_item.get('category', 'markets')
|
| 141 |
+
|
| 142 |
+
# Combine title and summary for keyword analysis
|
| 143 |
+
text = f"{title} {summary}"
|
| 144 |
+
|
| 145 |
+
# 1. KEYWORD SCORING (30 points max)
|
| 146 |
+
keyword_score = self._score_keywords(text)
|
| 147 |
+
score += keyword_score
|
| 148 |
+
|
| 149 |
+
# 2. RECENCY SCORING (20 points max)
|
| 150 |
+
recency_score = self._score_recency(timestamp)
|
| 151 |
+
score += recency_score
|
| 152 |
+
|
| 153 |
+
# 3. SOURCE CREDIBILITY (20 points max)
|
| 154 |
+
source_score = self._score_source(source)
|
| 155 |
+
score += source_score
|
| 156 |
+
|
| 157 |
+
# 4. ENGAGEMENT SCORING (15 points max)
|
| 158 |
+
engagement_score = self._score_engagement(news_item)
|
| 159 |
+
score += engagement_score
|
| 160 |
+
|
| 161 |
+
# 5. SENTIMENT EXTREMITY (10 points max)
|
| 162 |
+
sentiment_score = self._score_sentiment(sentiment)
|
| 163 |
+
score += sentiment_score
|
| 164 |
+
|
| 165 |
+
# 6. CATEGORY RELEVANCE (5 points max)
|
| 166 |
+
category_score = self._score_category(category)
|
| 167 |
+
score += category_score
|
| 168 |
+
|
| 169 |
+
# 7. TICKER MENTIONS (bonus up to 10 points)
|
| 170 |
+
ticker_score = self._score_tickers(text)
|
| 171 |
+
score += ticker_score
|
| 172 |
+
|
| 173 |
+
# 8. URGENCY INDICATORS (bonus up to 10 points)
|
| 174 |
+
urgency_score = self._score_urgency(text)
|
| 175 |
+
score += urgency_score
|
| 176 |
+
|
| 177 |
+
# 9. EXISTING IMPACT LEVEL (weight existing classification)
|
| 178 |
+
if impact_level == 'high':
|
| 179 |
+
score *= 1.2
|
| 180 |
+
elif impact_level == 'medium':
|
| 181 |
+
score *= 1.1
|
| 182 |
+
|
| 183 |
+
# Cap at 100
|
| 184 |
+
score = min(score, 100.0)
|
| 185 |
+
|
| 186 |
+
logger.debug(f"News '{title[:50]}...' scored: {score:.2f}")
|
| 187 |
+
|
| 188 |
+
return score
|
| 189 |
+
|
| 190 |
+
def _score_keywords(self, text: str) -> float:
|
| 191 |
+
"""Score based on keyword presence and frequency"""
|
| 192 |
+
score = 0.0
|
| 193 |
+
|
| 194 |
+
# Critical keywords (3.0 points each, max 18)
|
| 195 |
+
critical_matches = sum(1 for kw in self.CRITICAL_KEYWORDS if kw in text)
|
| 196 |
+
score += min(critical_matches * 3.0, 18.0)
|
| 197 |
+
|
| 198 |
+
# High-impact keywords (2.0 points each, max 8)
|
| 199 |
+
high_matches = sum(1 for kw in self.HIGH_IMPACT_KEYWORDS if kw in text)
|
| 200 |
+
score += min(high_matches * 2.0, 8.0)
|
| 201 |
+
|
| 202 |
+
# Medium-impact keywords (1.0 points each, max 4)
|
| 203 |
+
medium_matches = sum(1 for kw in self.MEDIUM_IMPACT_KEYWORDS if kw in text)
|
| 204 |
+
score += min(medium_matches * 1.0, 4.0)
|
| 205 |
+
|
| 206 |
+
return min(score, 30.0)
|
| 207 |
+
|
| 208 |
+
def _score_recency(self, timestamp: datetime) -> float:
|
| 209 |
+
"""Score based on how recent the news is"""
|
| 210 |
+
try:
|
| 211 |
+
if isinstance(timestamp, str):
|
| 212 |
+
timestamp = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
|
| 213 |
+
|
| 214 |
+
age_seconds = (datetime.now() - timestamp.replace(tzinfo=None)).total_seconds()
|
| 215 |
+
age_minutes = age_seconds / 60
|
| 216 |
+
|
| 217 |
+
# Exponential decay: most recent = highest score
|
| 218 |
+
if age_minutes < 5:
|
| 219 |
+
return 20.0 # Within 5 minutes: full score
|
| 220 |
+
elif age_minutes < 15:
|
| 221 |
+
return 18.0 # 5-15 minutes
|
| 222 |
+
elif age_minutes < 30:
|
| 223 |
+
return 15.0 # 15-30 minutes
|
| 224 |
+
elif age_minutes < 60:
|
| 225 |
+
return 10.0 # 30-60 minutes
|
| 226 |
+
elif age_minutes < 180:
|
| 227 |
+
return 5.0 # 1-3 hours
|
| 228 |
+
else:
|
| 229 |
+
return 1.0 # Older than 3 hours
|
| 230 |
+
except:
|
| 231 |
+
return 5.0 # Default if timestamp parsing fails
|
| 232 |
+
|
| 233 |
+
def _score_source(self, source: str) -> float:
|
| 234 |
+
"""Score based on source credibility"""
|
| 235 |
+
source = source.lower().replace(' ', '_').replace('/', '').replace('@', '')
|
| 236 |
+
|
| 237 |
+
# Check for known sources
|
| 238 |
+
for source_key, weight in self.SOURCE_WEIGHTS.items():
|
| 239 |
+
if source_key in source:
|
| 240 |
+
return weight * 10.0 # Scale to max 20 points
|
| 241 |
+
|
| 242 |
+
return self.SOURCE_WEIGHTS['default'] * 10.0
|
| 243 |
+
|
| 244 |
+
def _score_engagement(self, news_item: Dict) -> float:
|
| 245 |
+
"""Score based on social engagement metrics"""
|
| 246 |
+
engagement = news_item.get('engagement', {})
|
| 247 |
+
|
| 248 |
+
if not engagement:
|
| 249 |
+
return 5.0 # Default score if no engagement data
|
| 250 |
+
|
| 251 |
+
score = 0.0
|
| 252 |
+
|
| 253 |
+
# Twitter engagement
|
| 254 |
+
if 'likes' in engagement:
|
| 255 |
+
likes = engagement['likes']
|
| 256 |
+
score += min(likes / 1000, 5.0) # Max 5 points for likes
|
| 257 |
+
|
| 258 |
+
if 'retweets' in engagement:
|
| 259 |
+
retweets = engagement['retweets']
|
| 260 |
+
score += min(retweets / 500, 5.0) # Max 5 points for retweets
|
| 261 |
+
|
| 262 |
+
# Reddit engagement
|
| 263 |
+
if 'score' in engagement:
|
| 264 |
+
reddit_score = engagement['score']
|
| 265 |
+
score += min(reddit_score / 1000, 5.0) # Max 5 points for score
|
| 266 |
+
|
| 267 |
+
if 'comments' in engagement:
|
| 268 |
+
comments = engagement['comments']
|
| 269 |
+
score += min(comments / 200, 5.0) # Max 5 points for comments
|
| 270 |
+
|
| 271 |
+
return min(score, 15.0)
|
| 272 |
+
|
| 273 |
+
def _score_sentiment(self, sentiment: str) -> float:
|
| 274 |
+
"""Score based on sentiment extremity (extreme = more impactful)"""
|
| 275 |
+
if sentiment == 'positive':
|
| 276 |
+
return 8.0 # Strong positive news moves markets
|
| 277 |
+
elif sentiment == 'negative':
|
| 278 |
+
return 10.0 # Negative news tends to have more impact
|
| 279 |
+
else:
|
| 280 |
+
return 3.0 # Neutral news less impactful
|
| 281 |
+
|
| 282 |
+
def _score_category(self, category: str) -> float:
|
| 283 |
+
"""Score based on category relevance"""
|
| 284 |
+
if category == 'macro':
|
| 285 |
+
return 5.0 # Macro news affects entire market
|
| 286 |
+
elif category == 'markets':
|
| 287 |
+
return 4.0 # Direct market news
|
| 288 |
+
elif category == 'geopolitical':
|
| 289 |
+
return 3.0 # Geopolitical can be high impact
|
| 290 |
+
else:
|
| 291 |
+
return 2.0 # Other categories
|
| 292 |
+
|
| 293 |
+
def _score_tickers(self, text: str) -> float:
|
| 294 |
+
"""Bonus score for mentioning major market-moving tickers"""
|
| 295 |
+
text_upper = text.upper()
|
| 296 |
+
|
| 297 |
+
# Count major ticker mentions
|
| 298 |
+
ticker_mentions = sum(1 for ticker in self.MAJOR_TICKERS if ticker in text_upper)
|
| 299 |
+
|
| 300 |
+
# 2 points per ticker, max 10 points
|
| 301 |
+
return min(ticker_mentions * 2.0, 10.0)
|
| 302 |
+
|
| 303 |
+
def _score_urgency(self, text: str) -> float:
|
| 304 |
+
"""Bonus score for urgency indicators"""
|
| 305 |
+
urgency_patterns = [
|
| 306 |
+
r'\bbreaking\b', r'\balert\b', r'\burgent\b', r'\bjust in\b',
|
| 307 |
+
r'\bemergency\b', r'\bimmediate\b', r'\bnow\b', r'\btoday\b',
|
| 308 |
+
r'‼️', r'🚨', r'⚠️', r'🔴', r'❗'
|
| 309 |
+
]
|
| 310 |
+
|
| 311 |
+
score = 0.0
|
| 312 |
+
for pattern in urgency_patterns:
|
| 313 |
+
if re.search(pattern, text, re.IGNORECASE):
|
| 314 |
+
score += 2.0
|
| 315 |
+
|
| 316 |
+
return min(score, 10.0)
|
| 317 |
+
|
| 318 |
+
def get_breaking_news(self, news_items: List[Dict], top_n: int = 1) -> List[Dict]:
|
| 319 |
+
"""
|
| 320 |
+
Identify top breaking news from a list
|
| 321 |
+
|
| 322 |
+
Args:
|
| 323 |
+
news_items: List of news item dictionaries
|
| 324 |
+
top_n: Number of top items to return
|
| 325 |
+
|
| 326 |
+
Returns:
|
| 327 |
+
List of top breaking news items with scores
|
| 328 |
+
"""
|
| 329 |
+
if not news_items:
|
| 330 |
+
return []
|
| 331 |
+
|
| 332 |
+
# Calculate scores for all items
|
| 333 |
+
scored_items = []
|
| 334 |
+
for item in news_items:
|
| 335 |
+
score = self.calculate_impact_score(item)
|
| 336 |
+
scored_items.append({
|
| 337 |
+
**item,
|
| 338 |
+
'breaking_score': score
|
| 339 |
+
})
|
| 340 |
+
|
| 341 |
+
# Sort by score (descending)
|
| 342 |
+
scored_items.sort(key=lambda x: x['breaking_score'], reverse=True)
|
| 343 |
+
|
| 344 |
+
# Log top items
|
| 345 |
+
logger.info(f"Top {top_n} breaking news:")
|
| 346 |
+
for i, item in enumerate(scored_items[:top_n], 1):
|
| 347 |
+
logger.info(f" {i}. [{item['breaking_score']:.1f}] {item['title'][:60]}...")
|
| 348 |
+
|
| 349 |
+
return scored_items[:top_n]
|
| 350 |
+
|
| 351 |
+
def get_breaking_threshold(self) -> float:
|
| 352 |
+
"""Get minimum score threshold for breaking news display"""
|
| 353 |
+
return 40.0 # Only show news with score >= 40 (out of 100)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# Singleton instance
|
| 357 |
+
_scorer_instance = None
|
| 358 |
+
|
| 359 |
+
def get_breaking_news_scorer() -> BreakingNewsScorer:
|
| 360 |
+
"""Get singleton instance of BreakingNewsScorer"""
|
| 361 |
+
global _scorer_instance
|
| 362 |
+
if _scorer_instance is None:
|
| 363 |
+
_scorer_instance = BreakingNewsScorer()
|
| 364 |
+
return _scorer_instance
|