# News Analysis & Alert System Guide

## Overview

The enhanced Gold Trading Simulator now includes a comprehensive news analysis and alerting system that provides real-time market intelligence and automated notifications for significant events.

## Key Features

### 1. **Real-Time News Feed**
- Aggregates news from multiple sources (Alpha Vantage, Finnhub)
- Automatic sentiment analysis using TextBlob
- Relevance scoring for gold-specific news
- Impact assessment (HIGH, MEDIUM, LOW)
- Category classification (MONETARY_POLICY, GEOPOLITICS, ECONOMIC_DATA, etc.)

### 2. **Intelligent Alerts**
- Price movement alerts (spikes, drops)
- Support/resistance breach detection
- High volatility warnings
- Breaking news notifications
- Economic event reminders

### 3. **News-Price Correlation**
- Tracks how news events affect gold prices
- Measures correlation strength
- Identifies significant market-moving events

## News Feed Features

### Sentiment Analysis

The system analyzes every article and assigns:
- **Sentiment**: POSITIVE, NEGATIVE, or NEUTRAL
- **Sentiment Score**: -1.0 to +1.0 scale
- **Overall Market Sentiment**: Aggregated across all articles

### Impact Classification

News articles are scored for gold market impact:
- **HIGH**: Federal Reserve decisions, major geopolitical events, significant inflation data
- **MEDIUM**: Economic indicators, central bank commentary, moderate policy changes
- **LOW**: General market news with indirect gold correlation

### Content Categories

- **MONETARY_POLICY**: Fed meetings, interest rate decisions, QE announcements
- **GEOPOLITICS**: Wars, conflicts, sanctions, international tensions
- **ECONOMIC_DATA**: CPI, GDP, employment reports, PMI data
- **MARKET_SENTIMENT**: Risk appetite, safe-haven flows, VIX movements
- **COMMODITY**: Gold-specific news, mining sector, ETF flows

### Filtering Options

Filter news by:
- All articles
- Bullish (positive sentiment)
- Bearish (negative sentiment)
- Neutral articles

### Auto-Refresh

Enable automatic refresh every 5 minutes to stay current with breaking news.

## Alert System

### Alert Types

**PRICE_SPIKE**
- Triggered when price increases ≥ 1% (default threshold)
- Severity: HIGH if ≥ 2%, MEDIUM if ≥ 1%

**PRICE_DROP**
- Triggered when price decreases ≥ 1%
- Severity: HIGH if ≤ -2%, MEDIUM if ≥ -1%

**NEWS_BREAKING**
- High-impact news articles (impact_on_gold = HIGH)
- Severity: CRITICAL
- Includes link to original article

**SUPPORT_BREACH**
- Price breaks below identified support level
- Severity: HIGH
- Action required: Consider position adjustment

**RESISTANCE_BREACH**
- Price breaks above identified resistance level
- Severity: HIGH
- Action required: Potential breakout trade

**HIGH_VOLATILITY**
- Current price range exceeds 2x average range
- Severity: MEDIUM
- Indicates increased market uncertainty

**ECONOMIC_EVENT**
- Upcoming scheduled events (Fed meetings, CPI releases, etc.)
- Severity varies by importance

### Severity Levels

- **CRITICAL**: Immediate attention required, major market event
- **HIGH**: Significant event requiring awareness
- **MEDIUM**: Notable event worth monitoring
- **LOW**: Informational alert

## API Keys & Configuration

### Required API Keys

**Alpha Vantage** (Required)
- Provides: Market data + News Sentiment API
- Free tier: 500 calls/day
- Get key: https://www.alphavantage.co/support/#api-key
- Includes gold price data AND news/sentiment

**OpenRouter** (Required)
- Provides: Claude 3.5 Sonnet AI analysis
- Pay-per-use pricing
- Get key: https://openrouter.ai/

### Optional API Keys

**Finnhub** (Optional - Enhanced News)
- Provides: Additional financial news coverage
- Free tier: 60 calls/minute
- Get key: https://finnhub.io/register
- Adds more news sources and broader coverage

**NewsAPI** (Reserved for future)
- Currently not implemented
- Placeholder for additional news source

### Environment Configuration

Add to `backend/.env`:

```bash
# Required
ALPHA_VANTAGE_API_KEY=your_key_here
OPENROUTER_API_KEY=your_key_here

# Optional (for more news coverage)
FINNHUB_API_KEY=your_key_here
NEWS_API_KEY=
```

## API Endpoints

### News Feed
```
GET /api/news/feed?limit=50
```

Returns:
- Array of news articles
- Bullish/bearish/neutral counts
- Overall market sentiment
- Average sentiment score

### Alerts
```
GET /api/news/alerts?limit=50
```

Returns:
- Recent alerts
- Critical alert count
- Unread alert count

### Economic Calendar
```
GET /api/news/economic-calendar
```

Returns:
- Upcoming economic events
- High-impact event count

### Clear Alerts
```
POST /api/news/alerts/clear
```

Removes alerts older than 24 hours.

## News Relevance Scoring

The system uses a sophisticated algorithm to score news relevance:

### High Relevance Keywords (0.4 points each)
- gold, xau, precious metals, bullion, gold price
- gold market, gold trading, gold miners, gold etf

### Medium Relevance Keywords (0.2 points each)
- federal reserve, fed, inflation, interest rates
- dollar, usd, monetary policy, central bank
- jerome powell, treasury, bonds

### Context Relevance Keywords (0.1 points each)
- geopolitics, war, sanctions, recession
- crisis, safe haven, risk off, uncertainty

**Minimum Threshold**: Articles with relevance score < 0.3 are filtered out

## Sentiment Analysis Details

Uses TextBlob for natural language processing:

**Polarity Score Calculation:**
- Range: -1.0 (most negative) to +1.0 (most positive)
- Analyzes: Title + Description + Summary

**Classification:**
- **POSITIVE**: polarity > 0.1 → Bullish for gold
- **NEGATIVE**: polarity < -0.1 → Bearish for gold
- **NEUTRAL**: -0.1 ≤ polarity ≤ 0.1

**Note**: For gold as a safe-haven asset, negative news (recession, crisis) often = positive for gold prices.

## Alert Configuration

### Customizable Thresholds

In `backend/app/config.py`:

```python
# Price change threshold for alerts (percentage)
PRICE_ALERT_THRESHOLD: float = 1.0

# News refresh interval (seconds)
NEWS_REFRESH_INTERVAL: int = 300  # 5 minutes
```

### Support/Resistance Levels

Set via AI analysis or manually:

```python
from app.services.alert_service import alert_service

alert_service.set_support_resistance(
    support=[4000, 3950, 3900],
    resistance=[4100, 4150, 4200]
)
```

## News-Price Correlation

The correlation analyzer:

1. **Captures news timestamp**
2. **Finds price before news** (within 1 hour)
3. **Finds price after news** (within 1 hour)
4. **Calculates price change**
5. **Determines correlation strength**:
   - STRONG: |change| > 1.0%
   - MODERATE: |change| > 0.5%
   - WEAK: |change| ≤ 0.5%

## Best Practices

### For Scalpers (M1-M15 timeframes)
- Enable auto-refresh on news feed
- Filter for HIGH impact news only
- Watch for PRICE_SPIKE/DROP alerts
- Monitor volatility alerts during news releases

### For Swing Traders (H4-D1 timeframes)
- Review news feed 2-3x daily
- Focus on MONETARY_POLICY and GEOPOLITICS categories
- Monitor support/resistance breach alerts
- Track upcoming economic events

### Risk Management
- Reduce position size before high-impact events
- Set wider stops during high volatility periods
- Avoid trading during major news releases unless experienced
- Use correlation analysis to understand typical price reactions

## Troubleshooting

### "No news articles found"
- Check Alpha Vantage API key is valid
- Verify API hasn't hit daily limit (500 calls)
- Check internet connection
- Review backend logs for errors

### "Alerts not appearing"
- Ensure backend is running
- Check price data is updating
- Verify support/resistance levels are set (via AI analysis)
- Check browser console for errors

### "News sentiment seems incorrect"
- TextBlob uses general sentiment (not gold-specific)
- Negative news can be positive for gold (safe haven)
- Use category + impact rating for better context
- Review article manually if sentiment seems wrong

## API Rate Limits

### Alpha Vantage
- **Free tier**: 500 calls/day, 5 calls/minute
- **News endpoint**: Counts as 1 call
- **Tip**: Cache news for 5 minutes to reduce calls

### Finnhub (if configured)
- **Free tier**: 60 calls/minute
- **News endpoint**: 1 call
- **Generous limits** for development

### OpenRouter
- **No rate limits** (reasonable use)
- **Pay-per-use**: ~$0.01-0.05 per AI analysis
- **Very affordable** for news analysis

## Future Enhancements

- [ ] Real-time WebSocket news stream
- [ ] Custom alert rules builder
- [ ] Email/SMS alert notifications
- [ ] Historical news backtesting
- [ ] Machine learning sentiment models
- [ ] Economic calendar integration (Forex Factory, Investing.com)
- [ ] News event impact prediction
- [ ] Social media sentiment (Twitter/X gold mentions)

## Example Workflow

### Morning Routine
1. Open simulator
2. Review overnight news (filter: ALL)
3. Check critical alerts
4. Review economic calendar for today
5. Note high-impact events scheduled

### During Trading Session
1. Monitor alerts panel for price movements
2. Check news feed every 30-60 minutes
3. Watch for breaking news notifications
4. Adjust positions before scheduled events

### End of Day
1. Review news-price correlations
2. Analyze which news moved the market
3. Clear old alerts
4. Note patterns for future trading

---

**Remember**: News and alerts are decision support tools. Always verify information and maintain your own trading discipline. The simulator is for educational purposes only.
