Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
| Watchlist | Hypothetical portfolio with live unrealised PnL |
| Alerts | Browser push notification price alerts (localStorage) |
| Export Data | CSV / JSON price history download |
| News | Commodity-filtered news feed with AI sentiment labels |
| News | Commodity-filtered provider headlines with availability and freshness labels |
| Learn | Explainer articles — oil, gold, futures, copper, India context |
| Analyst | Groq Llama 3.3 70B chat with live price context + 3 persona modes |
| Simulator | India macro impact model — drag crude price, see petrol/inflation/INR |
Expand All @@ -39,7 +39,7 @@
| Price data | Twelve Data API (real-time) |
| Metals fallback | metals.live |
| FX rates | open.er-api.com |
| News | NewsAPI + curated fallback |
| News | NewsAPI + clearly marked cached feed (no mock fallback) |
| Frontend host | Vercel |
| Backend host | Azure App Service (B1 · Central India) |
| CI/CD | GitHub Actions |
Expand Down Expand Up @@ -106,7 +106,7 @@ NEXT_PUBLIC_WS_URL=ws://localhost:8000
|---|---|---|
| GET | `/api/prices` | All commodity prices |
| GET | `/api/prices/:id` | Single commodity |
| GET | `/api/news` | News feed |
| GET | `/api/news` | News feed with source, availability and fetch timestamp |
| GET | `/api/rates` | Live FX rates |
| POST | `/api/analyst` | AI analysis (Groq) |
| POST | `/api/simulate` | India macro shock model |
Expand Down
270 changes: 192 additions & 78 deletions backend/routers/news.py
Original file line number Diff line number Diff line change
@@ -1,98 +1,212 @@
"""
News router — fetches commodity-related headlines from NewsAPI.
Falls back to curated realistic headlines if API key not set.
Free tier: 100 requests/day at newsapi.org
"""

import os
"""NewsAPI headlines with explicit availability and bounded, per-filter caching."""
import asyncio
import hashlib
import logging
from datetime import datetime, timezone, timedelta
import os
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from urllib.parse import urlsplit

import httpx
from fastapi import APIRouter, Query
from fastapi import APIRouter, HTTPException, Query

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["news"])

NEWS_API_KEY = os.getenv("NEWS_API_KEY", "")

COMMODITY_QUERIES: dict[str, str] = {
"all": "commodity prices OR crude oil OR gold OR silver OR natural gas",
"crude-wti": "crude oil WTI prices",
"crude-brent": "brent crude oil",
"natural-gas": "natural gas prices energy",
"gold": "gold prices commodities",
"silver": "silver prices metals",
"copper": "copper prices metals",
"aluminium": "aluminium prices metals",
"platinum": "platinum prices metals",
COMMODITY_QUERIES = {
"all": '"commodity prices" OR "crude oil" OR "gold prices" OR "silver prices" OR "natural gas" OR "copper prices" OR "aluminium prices" OR "platinum prices"',
"crude-wti": '"crude oil" AND (WTI OR prices)',
"crude-brent": '"brent crude" OR "brent oil"',
"natural-gas": '"natural gas" AND (prices OR energy)',
"gold": '"gold prices" OR "gold futures"',
"silver": '"silver prices" OR "silver futures"',
"copper": '"copper prices" OR "copper futures"',
"aluminium": '"aluminium prices" OR "aluminum prices"',
"platinum": '"platinum prices" OR "platinum futures"',
}
# Nine filters x eight refreshes per day = 72 calls/day per continuously running
# process when healthy, below a nominal 100/day quota. Not a distributed quota.
CACHE_TTL = timedelta(hours=3)
MAX_STALE = timedelta(hours=48)
NEWS_WINDOW = timedelta(days=7)
FAILURE_TTL = timedelta(minutes=15)
RATE_LIMIT_TTL = timedelta(hours=1)
REQUEST_TIMEOUT = 10
PAGE_SIZE = 30


@dataclass
class CacheEntry:
articles: list[dict]
fetched_at: datetime


_cache: dict[str, CacheEntry] = {}
_failures: dict[str, tuple[datetime, str]] = {}
_locks = {key: asyncio.Lock() for key in COMMODITY_QUERIES}
_rate_limited_until: datetime | None = None


def _now() -> datetime:
return datetime.now(timezone.utc)


class NewsFailure(Exception):
def __init__(self, reason: str, retry_after: int | None = None):
super().__init__(reason)
self.reason = reason
self.retry_after = retry_after

MOCK_NEWS = [
{"id": "1", "title": "Gold surges above $3,300 as Fed signals rate pause", "source": "Reuters", "url": "https://reuters.com", "publishedAt": "2025-04-05T08:30:00Z", "commodity": "gold", "sentiment": "positive", "readTime": 3, "description": "Gold prices climbed to multi-week highs after Federal Reserve officials indicated a potential pause in interest rate hikes amid cooling inflation data."},
{"id": "2", "title": "Crude oil slips on demand concerns from China slowdown", "source": "Bloomberg", "url": "https://bloomberg.com", "publishedAt": "2025-04-05T07:15:00Z", "commodity": "crude-wti", "sentiment": "negative", "readTime": 4, "description": "WTI crude fell 0.8% as manufacturing data from China came in weaker than expected, raising concerns about near-term demand for energy commodities."},
{"id": "3", "title": "Natural gas prices rise on cold weather forecasts across Europe", "source": "Financial Times", "url": "https://ft.com", "publishedAt": "2025-04-05T06:00:00Z", "commodity": "natural-gas", "sentiment": "positive", "readTime": 3, "description": "European natural gas futures climbed 2.3% after weather models showed below-average temperatures forecast for the next two weeks across key consuming regions."},
{"id": "4", "title": "Copper hits 3-week high on supply disruption fears in Chile", "source": "CNBC", "url": "https://cnbc.com", "publishedAt": "2025-04-04T14:00:00Z", "commodity": "copper", "sentiment": "positive", "readTime": 3, "description": "Copper prices surged to their highest level in three weeks after reports emerged of potential strike action at Escondida, the world largest copper mine."},
{"id": "5", "title": "Silver outperforms gold as industrial demand outlook improves", "source": "Kitco", "url": "https://kitco.com", "publishedAt": "2025-04-04T11:30:00Z", "commodity": "silver", "sentiment": "positive", "readTime": 2, "description": "Silver prices outpaced gold gains this week as analysts revised upward their forecasts for solar panel production, a key driver of silver industrial demand."},
{"id": "6", "title": "OPEC maintains output cuts, Brent crude finds support at $85", "source": "Reuters", "url": "https://reuters.com", "publishedAt": "2025-04-04T09:00:00Z", "commodity": "crude-brent", "sentiment": "neutral", "readTime": 4, "description": "OPEC confirmed it would maintain current production quotas through the second quarter, providing a floor for Brent crude prices near the $85 per barrel level."},
{"id": "7", "title": "Platinum deficit expected to widen in 2025 on EV demand", "source": "World Platinum Council", "url": "https://platinuminvestment.com", "publishedAt": "2025-04-03T12:00:00Z", "commodity": "platinum", "sentiment": "positive", "readTime": 5, "description": "The World Platinum Investment Council raised its 2025 deficit forecast as hydrogen fuel cell vehicle production accelerates, consuming more platinum catalyst material."},
{"id": "8", "title": "Aluminium prices under pressure as US tariff exemptions expire", "source": "Metal Bulletin", "url": "https://metalbulletin.com", "publishedAt": "2025-04-03T08:30:00Z", "commodity": "aluminium", "sentiment": "negative", "readTime": 3, "description": "Aluminium futures dropped as temporary tariff exemptions for several major exporters are set to expire, potentially disrupting trade flows to US consumers."},
{"id": "9", "title": "India gold imports hit record high ahead of wedding season", "source": "Economic Times", "url": "https://economictimes.com", "publishedAt": "2025-04-02T10:00:00Z", "commodity": "gold", "sentiment": "positive", "readTime": 3, "description": "India gold imports surged 34% year-over-year in March as jewellers stocked ahead of the peak wedding and festival season, providing strong physical demand support."},
{"id": "10", "title": "Natural gas storage deficit narrows, tempering price rally", "source": "EIA", "url": "https://eia.gov", "publishedAt": "2025-04-02T08:00:00Z", "commodity": "natural-gas", "sentiment": "neutral", "readTime": 2, "description": "US natural gas storage levels closed the gap with the 5-year average after a warmer-than-expected end to winter, reducing the urgency of the ongoing price rally."},
{"id": "11", "title": "Copper demand from data centres to double by 2030, says Goldman", "source": "Goldman Sachs", "url": "https://goldmansachs.com", "publishedAt": "2025-04-01T14:00:00Z", "commodity": "copper", "sentiment": "positive", "readTime": 4, "description": "Goldman Sachs raised its long-term copper price target citing surging demand from AI data centre infrastructure, which requires significantly more copper wiring than traditional buildings."},
{"id": "12", "title": "Silver industrial demand hits record on photovoltaic expansion", "source": "Silver Institute", "url": "https://silverinstitute.org", "publishedAt": "2025-04-01T09:00:00Z", "commodity": "silver", "sentiment": "positive", "readTime": 3, "description": "The Silver Institute reported industrial fabrication demand reached an all-time high driven by photovoltaic panel manufacturing in China and India."},
]


async def _fetch_newsapi(query: str) -> list[dict]:
url = "https://newsapi.org/v2/everything"

def _article(raw, commodity: str, now: datetime) -> dict | None:
if not isinstance(raw, dict):
return None
title, url, published = (raw.get(k) for k in ("title", "url", "publishedAt"))
publisher = raw.get("source")
source = publisher.get("name") if isinstance(publisher, dict) else None
if not all(isinstance(v, str) and v.strip() for v in (title, url, published, source)):
return None
if any(v.strip().lower() in ("[removed]", "removed") for v in (title, source)):
return None
try:
link = urlsplit(url)
if (link.scheme not in ("http", "https") or not link.hostname
or link.username or link.password or not link.path.strip("/")
or any(ch.isspace() for ch in url)):
return None
stamp = datetime.fromisoformat(published.replace("Z", "+00:00"))
if stamp.tzinfo is None:
return None
stamp = stamp.astimezone(timezone.utc)
if stamp > now or stamp < now - NEWS_WINDOW:
return None
except (ValueError, OverflowError):
return None
description = raw.get("description")
return {
"id": hashlib.sha256(url.encode()).hexdigest(),
"title": title.strip(),
"source": source.strip(),
"url": url,
"publishedAt": stamp.isoformat(),
"commodity": commodity,
"description": description.strip() if isinstance(description, str) else "",
}


def _retry_seconds(value: str | None) -> int | None:
if not value:
return None
try:
return max(0, int(value))
except ValueError:
try:
from email.utils import parsedate_to_datetime
stamp = parsedate_to_datetime(value)
return max(0, int((stamp - _now()).total_seconds()))
except (TypeError, ValueError, OverflowError):
return None


async def _fetch_newsapi(commodity: str, key: str) -> list[dict]:
now = _now()
params = {
"q": query,
"q": COMMODITY_QUERIES[commodity],
"sortBy": "publishedAt",
"language": "en",
"pageSize": 12,
"apiKey": NEWS_API_KEY,
"pageSize": PAGE_SIZE,
"from": (now - NEWS_WINDOW).isoformat(),
}
try:
async with httpx.AsyncClient(timeout=8, follow_redirects=False) as client:
response = await asyncio.wait_for(
client.get("https://newsapi.org/v2/everything", params=params,
headers={"X-Api-Key": key}), timeout=REQUEST_TIMEOUT
)
if response.status_code == 429:
raise NewsFailure("rate_limited", _retry_seconds(response.headers.get("Retry-After")))
if response.status_code in (401, 403):
raise NewsFailure("provider_access_denied")
response.raise_for_status()
payload = response.json()
except (asyncio.TimeoutError, httpx.TimeoutException):
raise NewsFailure("timeout") from None
except (httpx.HTTPError, ValueError):
raise NewsFailure("provider_error") from None
if not isinstance(payload, dict):
raise NewsFailure("invalid_response")
if payload.get("status") != "ok":
if payload.get("code") in ("rateLimited", "apiKeyExhausted"):
raise NewsFailure("rate_limited")
if payload.get("code") in ("apiKeyInvalid", "apiKeyDisabled", "apiKeyMissing"):
raise NewsFailure("provider_access_denied")
raise NewsFailure("provider_error")
raw_articles = payload.get("articles")
if not isinstance(raw_articles, list):
raise NewsFailure("invalid_response")
articles = {}
for raw in raw_articles:
article = _article(raw, commodity, now)
if article is not None:
articles.setdefault(article["id"], article)
if raw_articles and not articles:
raise NewsFailure("no_valid_articles")
return sorted(articles.values(), key=lambda a: a["publishedAt"], reverse=True)


def _feed(commodity: str, limit: int, now: datetime, reason: str | None = None) -> dict:
entry = _cache.get(commodity)
if entry and now - entry.fetched_at <= MAX_STALE:
# Do not present articles that have aged out of the publication window.
articles = [a for a in entry.articles
if datetime.fromisoformat(a["publishedAt"]) >= now - NEWS_WINDOW]
return {
"commodity": commodity, "source": "newsapi",
"status": "stale" if reason else "provider",
"reason": reason, "fetchedAt": entry.fetched_at.isoformat(),
"articles": articles[:limit],
}
return {
"commodity": commodity, "source": None, "status": "unavailable",
"reason": reason or "provider_error", "fetchedAt": None, "articles": [],
}
async with httpx.AsyncClient(timeout=8) as client:
resp = await client.get(url, params=params)
resp.raise_for_status()
data = resp.json()
articles = data.get("articles", [])
result = []
for i, a in enumerate(articles):
result.append({
"id": str(i),
"title": a.get("title", ""),
"source": a.get("source", {}).get("name", ""),
"url": a.get("url", ""),
"publishedAt": a.get("publishedAt", ""),
"commodity": "all",
"sentiment": "neutral",
"readTime": max(2, len(a.get("description", "")) // 200),
"description": a.get("description", ""),
})
return result


@router.get("/news")
async def get_news(
commodity: str = Query(default="all"),
limit: int = Query(default=12, le=30),
limit: int = Query(default=12, ge=1, le=30),
):
if NEWS_API_KEY:
global _rate_limited_until
if commodity not in COMMODITY_QUERIES:
raise HTTPException(status_code=422, detail="Unsupported commodity filter")
# Read after dotenv initialization; never include the key in responses/logs.
key = os.getenv("NEWS_API_KEY", "").strip()
async with _locks[commodity]:
now = _now()
if not key:
return _feed(commodity, limit, now, "not_configured")
entry = _cache.get(commodity)
if entry and now - entry.fetched_at < CACHE_TTL:
return _feed(commodity, limit, now)
if _rate_limited_until and now < _rate_limited_until:
return _feed(commodity, limit, now, "rate_limited")
failure = _failures.get(commodity)
if failure and now < failure[0]:
return _feed(commodity, limit, now, failure[1])
try:
query = COMMODITY_QUERIES.get(commodity, COMMODITY_QUERIES["all"])
articles = await _fetch_newsapi(query)
return articles[:limit]
except Exception as exc:
logger.warning("NewsAPI failed: %s — returning mock data", exc)

# Filter mock by commodity
if commodity == "all":
filtered = MOCK_NEWS
else:
filtered = [n for n in MOCK_NEWS if n["commodity"] == commodity or commodity == "all"]
if not filtered:
filtered = MOCK_NEWS

return filtered[:limit]
articles = await _fetch_newsapi(commodity, key)
except NewsFailure as exc:
now = _now()
cooldown = FAILURE_TTL
if exc.reason == "rate_limited":
# Respect Retry-After, with a one-hour minimum and a safe upper bound.
cooldown = max(RATE_LIMIT_TTL, timedelta(seconds=min(exc.retry_after or 0, 86400)))
_rate_limited_until = now + cooldown
_failures[commodity] = (now + cooldown, exc.reason)
logger.warning("NewsAPI unavailable for %s: %s", commodity, exc.reason)
return _feed(commodity, limit, now, exc.reason)
now = _now()
_cache[commodity] = CacheEntry(articles, now)
_failures.pop(commodity, None)
return _feed(commodity, limit, now)
Loading
Loading