diff --git a/.github/workflows/price-provenance.yml b/.github/workflows/price-provenance.yml new file mode 100644 index 0000000..93d8ff3 --- /dev/null +++ b/.github/workflows/price-provenance.yml @@ -0,0 +1,42 @@ +name: Price provenance checks + +on: + pull_request: + paths: + - 'backend/**' + - 'frontend/**' + - '.github/workflows/price-provenance.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + backend: + runs-on: ubuntu-latest + defaults: + run: + working-directory: backend + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - run: pip install -r requirements.txt + - run: python -m compileall -q models routers services tests + - run: python -m unittest discover -s tests -v + frontend: + runs-on: ubuntu-latest + defaults: + run: + working-directory: frontend + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20' + cache: npm + cache-dependency-path: frontend/package-lock.json + - run: npm ci + - run: npm run type-check + - run: npm run build diff --git a/backend/models/commodity.py b/backend/models/commodity.py index 3e05028..fb38f28 100644 --- a/backend/models/commodity.py +++ b/backend/models/commodity.py @@ -1,4 +1,4 @@ -from pydantic import BaseModel +from pydantic import BaseModel, Field from typing import Literal @@ -13,14 +13,20 @@ class Commodity(BaseModel): ticker: str unit: str category: Literal["energy", "metals", "agriculture", "other"] - price: float - previousClose: float - change: float - changePercent: float - high24h: float - low24h: float - volume: float - marketStatus: Literal["open", "closed", "pre-market"] - lastUpdated: str - history: list[PricePoint] + price: float | None = None + previousClose: float | None = None + change: float | None = None + changePercent: float | None = None + high24h: float | None = None + low24h: float | None = None + volume: float | None = None + marketStatus: Literal["open", "closed", "pre-market", "unknown"] = "unknown" + lastUpdated: str | None = None + history: list[PricePoint] = Field(default_factory=list) currency: str = "USD" + source: Literal["yahoo_finance"] | None = None + sourceTimestamp: str | None = None + fetchedAt: str | None = None + dataStatus: Literal["provider", "stale", "unavailable"] + isStale: bool = False + isSimulated: bool = False diff --git a/backend/routers/analyst.py b/backend/routers/analyst.py index 2917565..6542efa 100644 --- a/backend/routers/analyst.py +++ b/backend/routers/analyst.py @@ -47,22 +47,25 @@ class AnalystResponse(BaseModel): persona: str model: str live_context_used: bool + provider_context_used: bool = False def _build_price_context(commodities) -> str: - lines = ["Current live commodity prices:"] + lines = ["Observed provider quotes (may be delayed; never assume real-time):"] for c in commodities: - direction = "up" if c.changePercent >= 0 else "down" - lines.append( - f" {c.name}: ${c.price:.2f} ({c.changePercent:+.2f}% today, {direction})" - ) + if c.price is None or c.isSimulated: + lines.append(f" {c.name}: unavailable") + continue + lines.append(f" {c.name}: {c.currency} {c.price} {c.unit}; " + f"source={c.source}; status={c.dataStatus}; observed={c.sourceTimestamp}") return "\n".join(lines) @router.post("/analyst", response_model=AnalystResponse) async def ask_analyst(req: AnalystRequest): persona = req.persona if req.persona in PERSONA_PROMPTS else "normal" - system_prompt = PERSONA_PROMPTS[persona] + system_prompt = PERSONA_PROMPTS[persona] + (" Never describe provider quotes as live. " + "Disclose stale or missing prices and their timestamps. Do not invent market data.") # Inject live prices as context commodities = await get_all_prices() @@ -113,7 +116,8 @@ async def ask_analyst(req: AnalystRequest): answer=answer, persona=persona, model=MODEL, - live_context_used=bool(price_context), + live_context_used=False, + provider_context_used=any(c.price is not None and not c.isSimulated for c in commodities), ) except Exception as exc: diff --git a/backend/routers/correlation.py b/backend/routers/correlation.py index 77ae78d..3261f3b 100644 --- a/backend/routers/correlation.py +++ b/backend/routers/correlation.py @@ -29,6 +29,8 @@ async def correlation_matrix(): series: dict[str, list[float]] = {} labels: dict[str, str] = {} for c in commodities: + if c.isSimulated or c.dataStatus == "unavailable": + continue prices = [p.price for p in c.history if p.price > 0] if prices: series[c.id] = prices @@ -48,4 +50,6 @@ async def correlation_matrix(): "corr": corr, }) - return {"ids": ids, "labels": labels, "matrix": matrix} + return {"ids": ids, "labels": labels, "matrix": matrix, + "provenance": {c.id: c.model_dump(include={"source", "sourceTimestamp", "fetchedAt", "dataStatus", "isStale", "isSimulated"}) for c in commodities}, + "note": "Only observed provider histories included. Stale histories may be older; unavailable markets excluded."} diff --git a/backend/routers/export.py b/backend/routers/export.py index 2ad6bfb..1b4805c 100644 --- a/backend/routers/export.py +++ b/backend/routers/export.py @@ -11,6 +11,11 @@ router = APIRouter(prefix="/api", tags=["export"]) +PROVENANCE = ("source", "sourceTimestamp", "fetchedAt", "dataStatus", "isStale", "isSimulated") + +def _provenance(c): + return {key: getattr(c, key) for key in PROVENANCE} + @router.get("/export/{commodity_id}") async def export_prices( @@ -32,6 +37,7 @@ async def export_prices( "unit": commodity.unit, "exported_at": datetime.now(timezone.utc).isoformat(), "current_price": commodity.price, + **_provenance(commodity), "history": [{"date": p.timestamp[:10], "price": p.price} for p in history], } return StreamingResponse( @@ -43,9 +49,11 @@ async def export_prices( # CSV output = io.StringIO() writer = csv.writer(output) - writer.writerow(["date", "price", "currency", "commodity", "unit"]) + writer.writerow(["date", "price", "currency", "commodity", "unit", *PROVENANCE]) for p in history: - writer.writerow([p.timestamp[:10], p.price, commodity.currency, commodity.name, commodity.unit]) + writer.writerow([p.timestamp[:10], p.price, commodity.currency, commodity.name, commodity.unit, *_provenance(commodity).values()]) + if not history: + writer.writerow([None, None, commodity.currency, commodity.name, commodity.unit, *_provenance(commodity).values()]) return StreamingResponse( io.BytesIO(output.getvalue().encode()), @@ -69,6 +77,7 @@ async def export_all(format: str = Query(default="csv", enum=["csv", "json"])): "price": c.price, "change_pct": c.changePercent, "currency": c.currency, "unit": c.unit, "high_24h": c.high24h, "low_24h": c.low24h, + **_provenance(c), } for c in commodities ], @@ -81,9 +90,9 @@ async def export_all(format: str = Query(default="csv", enum=["csv", "json"])): output = io.StringIO() writer = csv.writer(output) - writer.writerow(["id", "name", "ticker", "price", "change_pct", "currency", "unit", "high_24h", "low_24h"]) + writer.writerow(["id", "name", "ticker", "price", "change_pct", "currency", "unit", "high_24h", "low_24h", *PROVENANCE]) for c in commodities: - writer.writerow([c.id, c.name, c.ticker, c.price, c.changePercent, c.currency, c.unit, c.high24h, c.low24h]) + writer.writerow([c.id, c.name, c.ticker, c.price, c.changePercent, c.currency, c.unit, c.high24h, c.low24h, *_provenance(c).values()]) return StreamingResponse( io.BytesIO(output.getvalue().encode()), diff --git a/backend/routers/india.py b/backend/routers/india.py index 9f91ff8..c0301d5 100644 --- a/backend/routers/india.py +++ b/backend/routers/india.py @@ -60,7 +60,9 @@ async def india_prices(): """City-wise petrol and diesel prices adjusted for current crude oil price.""" crude = await get_price_by_id("crude-wti") - crude_price = crude.price if crude else CRUDE_REFERENCE_PRICE + crude_price = crude.price if crude and crude.price is not None else CRUDE_REFERENCE_PRICE + crude_source = crude.source if crude and crude.price is not None else "reference_assumption" + crude_status = crude.dataStatus if crude and crude.price is not None else "unavailable" deviation = crude_price - CRUDE_REFERENCE_PRICE adjustment = deviation * PASS_THROUGH_RATE @@ -75,6 +77,9 @@ async def india_prices(): }) return { + "crude_source": crude_source, + "crude_data_status": crude_status, + "crude_source_timestamp": crude.sourceTimestamp if crude else None, "crude_reference": CRUDE_REFERENCE_PRICE, "crude_current": round(crude_price, 2), "crude_deviation": round(deviation, 2), @@ -88,7 +93,9 @@ async def india_prices(): async def india_macro(): """India macro indicators + crude oil dependency metrics.""" crude = await get_price_by_id("crude-wti") - crude_price = crude.price if crude else CRUDE_REFERENCE_PRICE + crude_price = crude.price if crude and crude.price is not None else CRUDE_REFERENCE_PRICE + crude_source = crude.source if crude and crude.price is not None else "reference_assumption" + crude_status = crude.dataStatus if crude and crude.price is not None else "unavailable" deviation = crude_price - CRUDE_REFERENCE_PRICE # Adjust macro for current crude @@ -101,6 +108,9 @@ async def india_macro(): } return { + "crude_source": crude_source, + "crude_data_status": crude_status, + "crude_source_timestamp": crude.sourceTimestamp if crude else None, "macro": adjusted, "price_breakdown": PRICE_BREAKDOWN, "as_of": datetime.now(timezone.utc).isoformat(), diff --git a/backend/routers/prices.py b/backend/routers/prices.py index 974d86f..074bf3f 100644 --- a/backend/routers/prices.py +++ b/backend/routers/prices.py @@ -31,6 +31,7 @@ async def ticker(): "price": c.price, "changePercent": c.changePercent, "currency": c.currency, + **c.model_dump(include={"source", "sourceTimestamp", "fetchedAt", "dataStatus", "isStale", "isSimulated"}), } for c in commodities ] diff --git a/backend/services/commodity_service.py b/backend/services/commodity_service.py index 661666b..a59232c 100644 --- a/backend/services/commodity_service.py +++ b/backend/services/commodity_service.py @@ -1,174 +1,147 @@ -""" -Commodity service — yfinance for all real prices. -Falls back to GBM simulation if yfinance call fails. -""" - +"""Observed Yahoo Finance quotes; no automatic synthetic fallback.""" import asyncio import logging import math -import os -import random -import time from datetime import datetime, timezone, timedelta -from typing import Optional import yfinance as yf - from models.commodity import Commodity, PricePoint logger = logging.getLogger(__name__) COMMODITIES_CONFIG = [ - {"id": "crude-wti", "name": "Crude Oil WTI", "ticker": "WTI", "yf_symbol": "CL=F", "unit": "per barrel", "category": "energy", "currency": "USD", "seed": 111.00, "vol": 0.012}, - {"id": "crude-brent", "name": "Brent Crude", "ticker": "BRENT", "yf_symbol": "BZ=F", "unit": "per barrel", "category": "energy", "currency": "USD", "seed": 110.00, "vol": 0.011}, - {"id": "natural-gas", "name": "Natural Gas", "ticker": "NG=F", "yf_symbol": "NG=F", "unit": "per MMBtu", "category": "energy", "currency": "USD", "seed": 3.80, "vol": 0.022}, - {"id": "gold", "name": "Gold", "ticker": "GC=F", "yf_symbol": "GC=F", "unit": "per troy oz", "category": "metals", "currency": "USD", "seed": 4630.00,"vol": 0.006}, - {"id": "silver", "name": "Silver", "ticker": "SI=F", "yf_symbol": "SI=F", "unit": "per troy oz", "category": "metals", "currency": "USD", "seed": 72.00, "vol": 0.014}, - {"id": "copper", "name": "Copper", "ticker": "HG=F", "yf_symbol": "HG=F", "unit": "per lb", "category": "metals", "currency": "USD", "seed": 4.80, "vol": 0.009}, - {"id": "aluminium", "name": "Aluminium", "ticker": "ALI=F", "yf_symbol": "ALI=F", "unit": "per lb", "category": "metals", "currency": "USD", "seed": 1.12, "vol": 0.008}, - {"id": "platinum", "name": "Platinum", "ticker": "PL=F", "yf_symbol": "PL=F", "unit": "per troy oz", "category": "metals", "currency": "USD", "seed": 980.00, "vol": 0.010}, + {"id": "crude-wti", "name": "Crude Oil WTI", "ticker": "WTI", "yf_symbol": "CL=F", "unit": "per barrel", "category": "energy", "currency": "USD"}, + {"id": "crude-brent", "name": "Brent Crude", "ticker": "BRENT", "yf_symbol": "BZ=F", "unit": "per barrel", "category": "energy", "currency": "USD"}, + {"id": "natural-gas", "name": "Natural Gas", "ticker": "NG=F", "yf_symbol": "NG=F", "unit": "per MMBtu", "category": "energy", "currency": "USD"}, + {"id": "gold", "name": "Gold", "ticker": "GC=F", "yf_symbol": "GC=F", "unit": "per troy oz", "category": "metals", "currency": "USD"}, + {"id": "silver", "name": "Silver", "ticker": "SI=F", "yf_symbol": "SI=F", "unit": "per troy oz", "category": "metals", "currency": "USD"}, + {"id": "copper", "name": "Copper", "ticker": "HG=F", "yf_symbol": "HG=F", "unit": "per lb", "category": "metals", "currency": "USD"}, + {"id": "aluminium", "name": "Aluminium", "ticker": "ALI=F", "yf_symbol": "ALI=F", "unit": "per lb", "category": "metals", "currency": "USD"}, + {"id": "platinum", "name": "Platinum", "ticker": "PL=F", "yf_symbol": "PL=F", "unit": "per troy oz", "category": "metals", "currency": "USD"}, ] -_cache: dict[str, Commodity] = {} -_cache_ts: Optional[datetime] = None -_price_state: dict[str, float] = {} + CACHE_TTL = 60 +STALE_AFTER = timedelta(minutes=30) +_cache: dict[str, Commodity] = {} +_last_real: dict[str, Commodity] = {} +_cache_ts: datetime | None = None +_refresh_lock = asyncio.Lock() -# ── yfinance fetch ─────────────────────────────────────────────── +def _now() -> datetime: + return datetime.now(timezone.utc) -def _fetch_yfinance(symbol: str) -> Optional[dict]: - try: - tk = yf.Ticker(symbol) - info = tk.fast_info - price = info.last_price - if not price or math.isnan(price): - return None +def _finite(value): + try: + number = float(value) + return number if math.isfinite(number) else None + except (TypeError, ValueError, OverflowError): + return None - prev_close = info.previous_close or price - day_high = info.day_high or price - day_low = info.day_low or price - hist = tk.history(period="30d", interval="1d") +def _fetch_yfinance(symbol: str) -> dict | None: + """Price and timestamp come from the same observed intraday bar.""" + try: + ticker = yf.Ticker(symbol) + bars = ticker.history(period="5d", interval="5m", auto_adjust=False, timeout=10) + observations = [] + for idx, row in bars.iterrows(): + price = _finite(row.get("Close")) + if price is not None and idx.tzinfo is not None: + observations.append((idx, row, price)) + if not observations: + return None + observations.sort(key=lambda item: item[0]) + idx, row, price = observations[-1] + stamp = idx.to_pydatetime().astimezone(timezone.utc) + if stamp > _now() + timedelta(minutes=5): + return None history = [] - for idx, row in hist.iterrows(): - close = row["Close"] - if close and not math.isnan(close): - history.append(PricePoint( - timestamp=idx.strftime("%Y-%m-%d"), - price=round(float(close), 4) - )) - - return { - "price": round(float(price), 4), - "prev_close": round(float(prev_close), 4), - "high24": round(float(day_high), 4), - "low24": round(float(day_low), 4), - "history": history, - } - + previous_close = None + try: + daily = ticker.history(period="30d", interval="1d", auto_adjust=False, timeout=10) + for day, record in daily.sort_index().iterrows(): + close = _finite(record.get("Close")) + if close is None: + continue + history.append(PricePoint(timestamp=day.strftime("%Y-%m-%d"), price=close)) + if day.date() < idx.date(): + previous_close = close + except Exception as exc: + logger.warning("Daily history unavailable for %s: %s", symbol, type(exc).__name__) + window = [r for t, r, _ in observations if t >= idx - timedelta(hours=24)] + highs = [v for r in window if (v := _finite(r.get("High"))) is not None] + lows = [v for r in window if (v := _finite(r.get("Low"))) is not None] + return dict(price=price, previousClose=previous_close, + high24h=max(highs) if highs else None, + low24h=min(lows) if lows else None, + history=history, sourceTimestamp=stamp.isoformat()) except Exception as exc: - logger.warning("yfinance error for %s: %s", symbol, exc) + logger.warning("Yahoo Finance unavailable for %s: %s", symbol, type(exc).__name__) return None -# ── GBM simulation fallback ────────────────────────────────────── - -def _simulate_price(cid: str, seed: float, vol: float) -> float: - current = _price_state.get(cid, seed) - drift = 0.0001 * (seed - current) / seed - shock = random.gauss(drift, vol * 0.3) - new_p = max(seed * 0.85, min(seed * 1.15, current * math.exp(shock))) - _price_state[cid] = new_p - return round(new_p, 4) - - -def _build_history(cid: str, price: float, seed: float, vol: float) -> list[PricePoint]: - pts, p = [], price * random.uniform(0.94, 1.06) - now = datetime.now(timezone.utc) - for i in range(30, -1, -1): - p = max(seed * 0.82, min(seed * 1.18, p * math.exp(random.gauss(0, vol * 0.5)))) - pts.append(PricePoint(timestamp=(now - timedelta(days=i)).strftime("%Y-%m-%d"), price=round(p, 4))) - pts[-1] = PricePoint(timestamp=now.strftime("%Y-%m-%d"), price=price) - return pts - - -# ── Build Commodity object ─────────────────────────────────────── - -def _build_commodity(cfg: dict, price: float, prev_close: float, high24: float, low24: float, history: list, is_live: bool) -> Commodity: - change = round(price - prev_close, 4) - change_pct = round((change / prev_close * 100) if prev_close else 0.0, 4) - source = "live" if is_live else "sim" - logger.info("%s %-14s $%10.4f %+.2f%% [%s]", "OK" if is_live else "SIM", cfg["id"], price, change_pct, source) - return Commodity( - id=cfg["id"], - name=cfg["name"], - ticker=cfg["ticker"], - unit=cfg["unit"], - category=cfg["category"], - currency=cfg["currency"], - price=price, - previousClose=round(prev_close, 4), - change=change, - changePercent=change_pct, - high24h=round(high24, 4), - low24h=round(low24, 4), - volume=round(random.uniform(80_000, 250_000), 0), - marketStatus="open", - lastUpdated=datetime.now(timezone.utc).isoformat(), - history=history, - ) - - -# ── Main fetch ─────────────────────────────────────────────────── +def _identity(cfg): + return {key: cfg[key] for key in ("id", "name", "ticker", "unit", "category", "currency")} -async def _fetch_all() -> list[Commodity]: - loop = asyncio.get_event_loop() - results = [] - for i, cfg in enumerate(COMMODITIES_CONFIG): - if i > 0: - await asyncio.sleep(0.3) +def _mark_age(quote: Commodity) -> Commodity: + if quote.sourceTimestamp and quote.dataStatus == "provider": + if _now() - datetime.fromisoformat(quote.sourceTimestamp) > STALE_AFTER: + return quote.model_copy(update={"dataStatus": "stale", "isStale": True}) + return quote - yf_data = await loop.run_in_executor(None, _fetch_yfinance, cfg["yf_symbol"]) - if yf_data: - c = _build_commodity( - cfg, - yf_data["price"], yf_data["prev_close"], - yf_data["high24"], yf_data["low24"], - yf_data["history"], is_live=True - ) - else: - price = _simulate_price(cfg["id"], cfg["seed"], cfg["vol"]) - prev = price / math.exp(random.gauss(0, cfg["vol"] * 0.4)) - hist = _build_history(cfg["id"], price, cfg["seed"], cfg["vol"]) - c = _build_commodity(cfg, price, prev, price * 1.005, price * 0.995, hist, is_live=False) +def _observed(cfg, data) -> Commodity: + price, previous = data["price"], data["previousClose"] + change = round(price - previous, 4) if previous is not None else None + pct = round(change / previous * 100, 4) if change is not None and previous else None + return _mark_age(Commodity( + **_identity(cfg), price=price, previousClose=previous, change=change, + changePercent=pct, high24h=data["high24h"], low24h=data["low24h"], + volume=None, marketStatus="unknown", history=data["history"], + source="yahoo_finance", sourceTimestamp=data["sourceTimestamp"], + lastUpdated=data["sourceTimestamp"], fetchedAt=_now().isoformat(), + dataStatus="provider", isStale=False, isSimulated=False, + )) - results.append(c) +async def _fetch_all() -> list[Commodity]: + results = [] + for cfg in COMMODITIES_CONFIG: + data = await asyncio.to_thread(_fetch_yfinance, cfg["yf_symbol"]) + cid = cfg["id"] + if data is not None: + quote = _observed(cfg, data) + previous = _last_real.get(cid) + if previous and datetime.fromisoformat(quote.sourceTimestamp) < datetime.fromisoformat(previous.sourceTimestamp): + quote = previous.model_copy(update={"dataStatus": "stale", "isStale": True}) + else: + _last_real[cid] = quote + elif cid in _last_real: + quote = _last_real[cid].model_copy(update={"dataStatus": "stale", "isStale": True}) + else: + quote = Commodity(**_identity(cfg), dataStatus="unavailable") + results.append(quote) return results -# ── Cache ──────────────────────────────────────────────────────── - def _stale() -> bool: - if not _cache_ts: - return True - return (datetime.now(timezone.utc) - _cache_ts).total_seconds() > CACHE_TTL + return _cache_ts is None or (_now() - _cache_ts).total_seconds() >= CACHE_TTL async def get_all_prices() -> list[Commodity]: global _cache, _cache_ts if _stale(): - fresh = await _fetch_all() - if fresh: - _cache = {c.id: c for c in fresh} - _cache_ts = datetime.now(timezone.utc) - logger.info("Cache updated — %d commodities", len(fresh)) - return list(_cache.values()) + async with _refresh_lock: + if _stale(): + fresh = await _fetch_all() + _cache = {c.id: c for c in fresh} + _cache_ts = _now() + return [_mark_age(c) for c in _cache.values()] -async def get_price_by_id(cid: str) -> Optional[Commodity]: - return next((c for c in await get_all_prices() if c.id == cid), None) \ No newline at end of file +async def get_price_by_id(cid: str) -> Commodity | None: + return next((c for c in await get_all_prices() if c.id == cid), None) diff --git a/backend/tests/test_price_provenance.py b/backend/tests/test_price_provenance.py new file mode 100644 index 0000000..ee7542e --- /dev/null +++ b/backend/tests/test_price_provenance.py @@ -0,0 +1,99 @@ +import csv +import io +import json +import unittest +from datetime import datetime, timezone, timedelta +from unittest.mock import patch + +from services import commodity_service as svc +from routers import analyst, export, prices, correlation + + +def quote(minutes=0): + return dict(price=101.25, previousClose=100.0, high24h=103.0, low24h=99.0, + history=[], sourceTimestamp=(datetime.now(timezone.utc) - timedelta(minutes=minutes)).isoformat()) + + +async def body(response): + return b"".join([chunk async for chunk in response.body_iterator]) + + +class PriceProvenanceTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + svc._cache.clear() + svc._last_real.clear() + svc._cache_ts = None + + async def test_cold_failure_is_unavailable(self): + with patch.object(svc, "_fetch_yfinance", return_value=None): + result = await svc.get_all_prices() + self.assertEqual(len(result), len(svc.COMMODITIES_CONFIG)) + for c in result: + self.assertEqual(c.dataStatus, "unavailable") + self.assertIsNone(c.price) + self.assertIsNone(c.sourceTimestamp) + self.assertIsNone(c.volume) + self.assertEqual(c.marketStatus, "unknown") + self.assertFalse(c.isSimulated) + self.assertEqual(c.history, []) + + async def test_partial_failure_and_recovery(self): + first = quote() + with patch.object(svc, "_fetch_yfinance", side_effect=lambda symbol: first if symbol == "CL=F" else None): + initial = await svc.get_all_prices() + self.assertEqual(initial[0].dataStatus, "provider") + self.assertEqual(initial[1].dataStatus, "unavailable") + self.assertIsNone(initial[0].volume) + self.assertEqual(initial[0].lastUpdated, first["sourceTimestamp"]) + svc._cache_ts = None + with patch.object(svc, "_fetch_yfinance", return_value=None): + failed = await svc.get_all_prices() + self.assertEqual(failed[0].dataStatus, "stale") + self.assertTrue(failed[0].isStale) + self.assertEqual(failed[0].price, initial[0].price) + self.assertEqual(failed[0].fetchedAt, initial[0].fetchedAt) + self.assertEqual(failed[0].sourceTimestamp, initial[0].sourceTimestamp) + svc._cache_ts = None + with patch.object(svc, "_fetch_yfinance", return_value=quote()): + recovered = await svc.get_all_prices() + self.assertTrue(all(c.dataStatus == "provider" for c in recovered)) + + async def test_old_provider_bar_and_ai_context(self): + with patch.object(svc, "_fetch_yfinance", return_value=quote(120)): + result = await svc.get_all_prices() + self.assertTrue(all(c.isStale for c in result)) + context = analyst._build_price_context(result) + self.assertIn("status=stale", context) + self.assertIn("source=yahoo_finance", context) + matrix = await correlation.correlation_matrix() + self.assertEqual(matrix["ids"], []) + self.assertEqual(matrix["provenance"][result[0].id]["dataStatus"], "stale") + + async def test_missing_previous_close_remains_null(self): + data = quote() + data["previousClose"] = None + with patch.object(svc, "_fetch_yfinance", return_value=data): + result = await svc.get_all_prices() + self.assertIsNone(result[0].change) + self.assertIsNone(result[0].changePercent) + self.assertEqual(result[0].price, 101.25) + + async def test_ticker_and_exports_preserve_provenance(self): + with patch.object(svc, "_fetch_yfinance", return_value=None): + await svc.get_all_prices() + ticker = await prices.ticker() + self.assertIsNone(ticker[0]["price"]) + self.assertEqual(ticker[0]["dataStatus"], "unavailable") + payload = json.loads(await body(await export.export_all(format="json"))) + self.assertEqual(payload["commodities"][0]["dataStatus"], "unavailable") + self.assertIsNone(payload["commodities"][0]["price"]) + individual = json.loads(await body(await export.export_prices("gold", format="json"))) + self.assertEqual(individual["dataStatus"], "unavailable") + self.assertIsNone(individual["current_price"]) + rows = list(csv.DictReader(io.StringIO((await body(await export.export_prices("gold", format="csv"))).decode()))) + self.assertEqual(rows[0]["dataStatus"], "unavailable") + self.assertEqual(rows[0]["price"], "") + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/price-data-contract.md b/docs/price-data-contract.md new file mode 100644 index 0000000..e7142dd --- /dev/null +++ b/docs/price-data-contract.md @@ -0,0 +1,14 @@ +# Price data contract + +CommodityChain uses Yahoo Finance futures bars, which may be delayed. It is not an exchange-certified streaming feed. Each configured commodity is returned even when the quote is missing. + +- `dataStatus: provider`: observed intraday price; bar timestamp no more than 30 minutes old. This is not a guarantee that the exchange is open or the quote is live. +- `dataStatus: stale`: last-known observed quote on upstream failure, regression to an older provider bar, or observation age exceeding 30 minutes. Cache is in memory and does not survive restarts. +- `dataStatus: unavailable`: no observed quote; price and other numeric fields are null, history is empty. +- `sourceTimestamp` and `lastUpdated`: UTC timestamp of the observed 5-minute provider bar (bar start); `fetchedAt`: time that observation was retrieved. Do not substitute the HTTP response time. +- `source`: yahoo_finance when a quote is observed, null otherwise. `isSimulated`: always false for this endpoint. The scenario simulator is separate. +- Missing previous close, change, percentage, high/low, and volume are null, never zero placeholders. Volume and exchange state are deliberately unavailable until authoritative data is integrated. 24h high/low use observed intraday bars up to the quote timestamp. +- REST, WebSocket, ticker and exports carry provenance. The UI excludes incomplete numeric quotes from calculations, labels stale and unavailable records, and does not treat socket connection as live market data. Correlation uses observed histories, including explicitly identified stale histories. +- India fuel/macro calculations remain modeled estimates; when crude is unavailable the reference assumption is explicit. Replacing macro baselines is tracked separately in #6. + +Tests: from backend, run `python -m unittest discover -s tests -v`. These tests mock provider responses and need no API credentials. Actual Yahoo Finance availability, market calendar correctness, symbol/unit validation, deployment compatibility and browser interactions still require separate verification. diff --git a/frontend/src/app/alerts/page.tsx b/frontend/src/app/alerts/page.tsx index 30d3100..4b991a0 100644 --- a/frontend/src/app/alerts/page.tsx +++ b/frontend/src/app/alerts/page.tsx @@ -26,7 +26,7 @@ function saveAlerts(a: Alert[]) { } export default function AlertsPage() { - const { commodities, isConnected, lastUpdated } = usePrices(); + const { commodities, isConnected, lastUpdated, priceNotice } = usePrices(); const [alerts, setAlerts] = useState([]); const [selId, setSelId] = useState(""); const [type, setType] = useState<"above" | "below">("above"); @@ -47,7 +47,7 @@ export default function AlertsPage() { for (const alert of updated) { if (alert.triggered) continue; const com = commodities.find(c => c.id === alert.commodityId); - if (!com) continue; + if (!com || com.isStale) continue; const prev = prevPrices.current[com.id]; const now = com.price; const hit = alert.type === "above" ? now >= alert.targetPrice : now <= alert.targetPrice; @@ -70,7 +70,7 @@ export default function AlertsPage() { saveAlerts(updated); setAlerts([...updated]); } else { - commodities.forEach(c => { prevPrices.current[c.id] = c.price; }); + commodities.filter(c => !c.isStale).forEach(c => { prevPrices.current[c.id] = c.price; }); } }, [commodities]); @@ -124,7 +124,7 @@ export default function AlertsPage() { return (
- +
diff --git a/frontend/src/app/analyst/page.tsx b/frontend/src/app/analyst/page.tsx index b0e25d0..f82ecfe 100644 --- a/frontend/src/app/analyst/page.tsx +++ b/frontend/src/app/analyst/page.tsx @@ -31,7 +31,7 @@ const SUGGESTED = [ ]; export default function AnalystPage() { - const { isConnected, lastUpdated } = usePrices(); + const { isConnected, lastUpdated, priceNotice } = usePrices(); const [messages, setMessages] = useState([]); const [input, setInput] = useState(""); const [persona, setPersona] = useState("normal"); @@ -83,14 +83,14 @@ export default function AnalystPage() { return (
- +
{/* Header */}

AI Price Analyst

-

Ask anything about commodity markets — powered by Groq Llama 3.3 70B with live price context

+

Ask anything about commodity markets — powered by Groq Llama 3.3 70B with timestamped provider price context

{/* Persona selector */} diff --git a/frontend/src/app/converter/page.tsx b/frontend/src/app/converter/page.tsx index a88f2cf..453ffc6 100644 --- a/frontend/src/app/converter/page.tsx +++ b/frontend/src/app/converter/page.tsx @@ -15,7 +15,7 @@ const CURRENCY_NAMES: Record = { }; export default function ConverterPage() { - const { commodities, isConnected, lastUpdated } = usePrices(); + const { commodities, isConnected, lastUpdated, priceNotice } = usePrices(); const [rates, setRates] = useState({}); const [loadingRates, setLoadingRates] = useState(true); @@ -93,7 +93,7 @@ export default function ConverterPage() { return (
- +
diff --git a/frontend/src/app/correlation/page.tsx b/frontend/src/app/correlation/page.tsx index 903bcec..f315d31 100644 --- a/frontend/src/app/correlation/page.tsx +++ b/frontend/src/app/correlation/page.tsx @@ -5,7 +5,7 @@ import { Navbar } from "@/components/Navbar"; import { usePrices } from "@/hooks/usePrices"; interface CorrCell { a: string; b: string; name_a: string; name_b: string; corr: number; } -interface CorrData { ids: string[]; labels: Record; matrix: CorrCell[]; } +interface CorrData { ids: string[]; labels: Record; matrix: CorrCell[]; note?: string; provenance?: Record; } function corrColor(v: number): string { if (v >= 0.7) return "#22C55E"; @@ -36,7 +36,7 @@ const SHORT: Record = { }; export default function CorrelationPage() { - const { isConnected, lastUpdated } = usePrices(); + const { isConnected, lastUpdated, priceNotice } = usePrices(); const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [hovered, setHovered] = useState<{ a: string; b: string } | null>(null); @@ -57,16 +57,19 @@ export default function CorrelationPage() { return (
- +

Correlation Matrix

-

Pearson correlation of 30-day daily price returns between all commodity pairs

+

Pearson correlation of observed daily prices; unavailable markets are excluded

+ {data?.note &&

{data.note} {Object.entries(data.provenance ?? {}).filter(([, p]) => p.dataStatus === "stale").map(([id]) => data.labels[id] ?? id).join(", ") && `Stale histories: ${Object.entries(data.provenance ?? {}).filter(([, p]) => p.dataStatus === "stale").map(([id]) => data.labels[id] ?? id).join(", ")}.`}

} {loading ? (
Computing correlations...
+ ) : data && data.ids.length === 0 ? ( +
No observed provider histories available for correlation.
) : data && (
diff --git a/frontend/src/app/explorer/page.tsx b/frontend/src/app/explorer/page.tsx index 65fe2db..93599c4 100644 --- a/frontend/src/app/explorer/page.tsx +++ b/frontend/src/app/explorer/page.tsx @@ -38,7 +38,7 @@ function MiniChart({ data, width, height }: { data: { timestamp: string; price: } export default function ExplorerPage() { - const { commodities, isConnected, lastUpdated } = usePrices(); + const { commodities, isConnected, lastUpdated, priceNotice } = usePrices(); const [selected, setSelected] = useState("gold"); const [range, setRange] = useState("1M"); const { has, add, remove, get } = useWatchlist(); @@ -69,7 +69,7 @@ export default function ExplorerPage() { return (
- +
@@ -110,6 +110,7 @@ export default function ExplorerPage() {
{formatPrice(commodity.price, commodity.currency)} + {commodity.isStale ? "Stale" : "Provider quote"} · Yahoo Finance · {commodity.sourceTimestamp ? new Date(commodity.sourceTimestamp).toLocaleString("en-IN") : "Unknown time"} {formatPercent(commodity.changePercent)} {formatChange(commodity.change, commodity.currency)}
{commodity.unit} · {commodity.currency}
@@ -156,7 +157,7 @@ export default function ExplorerPage() { { label: "PREV CLOSE", value: formatPrice(commodity.previousClose, commodity.currency), color: "var(--text-primary)" }, { label: "24H HIGH", value: formatPrice(commodity.high24h, commodity.currency), color: "var(--up)" }, { label: "24H LOW", value: formatPrice(commodity.low24h, commodity.currency), color: "var(--down)" }, - { label: "VOLUME", value: commodity.volume > 0 ? commodity.volume.toLocaleString() : "N/A", color: "var(--text-secondary)" }, + { label: "VOLUME", value: commodity.volume !== null ? commodity.volume.toLocaleString() : "N/A", color: "var(--text-secondary)" }, ].map(s => (
{s.label}
diff --git a/frontend/src/app/export/page.tsx b/frontend/src/app/export/page.tsx index 7a533e7..36cf08d 100644 --- a/frontend/src/app/export/page.tsx +++ b/frontend/src/app/export/page.tsx @@ -6,7 +6,7 @@ import { usePrices } from "@/hooks/usePrices"; import { formatPrice, formatPercent } from "@/lib/utils"; export default function ExportPage() { - const { commodities, isConnected, lastUpdated } = usePrices(); + const { commodities, isConnected, lastUpdated, priceNotice } = usePrices(); const [downloading, setDownloading] = useState(null); const BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000"; @@ -38,7 +38,7 @@ export default function ExportPage() { return (
- +
diff --git a/frontend/src/app/india/page.tsx b/frontend/src/app/india/page.tsx index 87bd29f..1107745 100644 --- a/frontend/src/app/india/page.tsx +++ b/frontend/src/app/india/page.tsx @@ -6,10 +6,16 @@ import { usePrices } from "@/hooks/usePrices"; interface CityPrice { city: string; state: string; petrol: number; diesel: number; } interface IndiaData { + crude_source: string; + crude_data_status: string; + crude_source_timestamp: string | null; crude_reference: number; crude_current: number; crude_deviation: number; adjustment_inr: number; cities: CityPrice[]; } interface MacroData { + crude_source: string; + crude_data_status: string; + crude_source_timestamp: string | null; macro: Record; price_breakdown: Record; } @@ -26,7 +32,7 @@ const MACRO_LABELS: Record(null); const [macroData, setMacroData] = useState(null); const [loading, setLoading] = useState(true); @@ -57,7 +63,7 @@ export default function IndiaPage() { return (
- +
@@ -70,7 +76,7 @@ export default function IndiaPage() {
- Crude WTI is {isUp ? "above" : "below"} reference price (${indiaData.crude_reference}/barrel) + {indiaData.crude_source === "reference_assumption" ? "Reference assumption (provider unavailable)" : `Yahoo Finance crude (${indiaData.crude_data_status})`} is {isUp ? "above" : "below"} reference price (${indiaData.crude_reference}/barrel)
{isUp ? "+" : ""}{indiaData.crude_deviation.toFixed(2)} USD/barrel deviation @@ -171,7 +177,7 @@ export default function IndiaPage() { {/* Macro indicators */} {macroData && (
-
India Macro (adjusted for crude)
+
India Macro (modeled estimates; {macroData.crude_source === "reference_assumption" ? "reference assumption" : macroData.crude_data_status + " crude quote"})
{Object.entries(macroData.macro) .filter(([k]) => MACRO_LABELS[k]) .map(([key, val]) => { diff --git a/frontend/src/app/learn/page.tsx b/frontend/src/app/learn/page.tsx index a0bf57f..176d67a 100644 --- a/frontend/src/app/learn/page.tsx +++ b/frontend/src/app/learn/page.tsx @@ -150,7 +150,7 @@ const ARTICLES: Article[] = [ const DIFFICULTY_COLORS = { Beginner: "#22C55E", Intermediate: "#F59E0B", Advanced: "#EF4444" }; export default function LearnPage() { - const { isConnected, lastUpdated } = usePrices(); + const { isConnected, lastUpdated, priceNotice } = usePrices(); const [selected, setSelected] = useState(null); const [filter, setFilter] = useState("All"); @@ -160,7 +160,7 @@ export default function LearnPage() { return (
- +
diff --git a/frontend/src/app/map/page.tsx b/frontend/src/app/map/page.tsx index a45d30d..2f91be2 100644 --- a/frontend/src/app/map/page.tsx +++ b/frontend/src/app/map/page.tsx @@ -59,7 +59,7 @@ function isVisible(iso: string, filter: string): boolean { } export default function MapPage() { - const { isConnected, lastUpdated } = usePrices(); + const { isConnected, lastUpdated, priceNotice } = usePrices(); const svgRef = useRef(null); const [selected, setSelected] = useState(null); const [hovered, setHovered] = useState(null); @@ -169,7 +169,7 @@ export default function MapPage() { return ( <> - +

Global Commodity Map

diff --git a/frontend/src/app/news/page.tsx b/frontend/src/app/news/page.tsx index 553d8c0..6418662 100644 --- a/frontend/src/app/news/page.tsx +++ b/frontend/src/app/news/page.tsx @@ -28,7 +28,7 @@ function timeAgo(iso: string) { } export default function NewsPage() { - const { isConnected, lastUpdated } = usePrices(); + const { isConnected, lastUpdated, priceNotice } = usePrices(); const [articles, setArticles] = useState([]); const [filter, setFilter] = useState("all"); const [loading, setLoading] = useState(true); @@ -43,7 +43,7 @@ export default function NewsPage() { return (
- +
diff --git a/frontend/src/app/page.tsx b/frontend/src/app/page.tsx index 0034b5f..95f1f26 100644 --- a/frontend/src/app/page.tsx +++ b/frontend/src/app/page.tsx @@ -80,6 +80,11 @@ function PriceCard({ c, index }: { c: Commodity; index: number }) { {formatPrice(c.price, c.currency)}
+
+ {c.isStale ? "Stale / last known" : "Provider quote"} · Yahoo Finance + {c.sourceTimestamp && " · " + new Date(c.sourceTimestamp).toLocaleString("en-IN")} +
+ {/* Change row */}
{formatPercent(c.changePercent)} @@ -129,7 +134,7 @@ function MoverRow({ c, rank }: { c: Commodity; rank: number }) { /* ─── Main page ──────────────────────────────────────────── */ export default function DashboardPage() { - const { commodities, loading, error, lastUpdated, isConnected, refresh } = usePrices(); + const { commodities, loading, error, lastUpdated, isConnected, refresh, priceNotice, records } = usePrices(); const [cat, setCat] = useState("all"); const filtered = cat === "all" ? commodities : commodities.filter(c => c.category === cat); @@ -146,9 +151,9 @@ export default function DashboardPage() { <> @@ -165,7 +170,7 @@ export default function DashboardPage() { {/* Page heading */}

Market Dashboard

-

Real-time prices — updated every 60 seconds

+

Yahoo Finance quotes — provider delays and market closures may affect freshness

{/* Error */} @@ -176,7 +181,7 @@ export default function DashboardPage() { {/* Stats row — 5 cards */}
{[ - { label: "Total Markets", value: commodities.length, col: "var(--text-1)", mono: true }, + { label: "Available Quotes", value: commodities.length, col: "var(--text-1)", mono: true }, { label: "Gainers", value: gainers, col: "var(--up)", mono: true }, { label: "Losers", value: losers, col: "var(--dn)", mono: true }, { label: "Top Gainer", value: topGain?.name ?? "—", sub: topGain ? formatPercent(topGain.changePercent) : "", col: "var(--up)", mono: false }, @@ -218,11 +223,22 @@ export default function DashboardPage() { {!loading && (
{filtered.map((c, i) => )} + {records.filter(c => (cat === "all" || c.category === cat) && !filtered.some(q => q.id === c.id)).map(c => ( +
+ {c.name} +
{formatPrice(c.price, c.currency)}
+
+ {c.dataStatus === "unavailable" ? "Provider data unavailable" : "Incomplete quote — change unavailable"} + {c.isStale && " (stale)"} +
+ {c.sourceTimestamp &&
Yahoo Finance · {new Date(c.sourceTimestamp).toLocaleString("en-IN")}
} +
+ ))}
)} - {!loading && filtered.length === 0 && ( -
No commodities in this category.
+ {!loading && !records.some(c => cat === "all" || c.category === cat) && ( +
No commodity quotes available in this category.
)}
@@ -251,7 +267,7 @@ export default function DashboardPage() {
losers ? "var(--up)" : "var(--dn)" }}> - {gainers > losers ? "Mostly Bullish" : gainers < losers ? "Mostly Bearish" : "Mixed"} + {!commodities.length ? "No data" : gainers > losers ? "Mostly Bullish" : gainers < losers ? "Mostly Bearish" : "Mixed"}
@@ -293,7 +309,7 @@ export default function DashboardPage() { {/* Footer */}
- CommodityChain v4 — Data: metals.live + GBM simulation + CommodityChain v4 — Data: Yahoo Finance (no simulated fallback) Prices indicative — not financial advice
diff --git a/frontend/src/app/simulator/page.tsx b/frontend/src/app/simulator/page.tsx index 5cbeeda..d0d0bc5 100644 --- a/frontend/src/app/simulator/page.tsx +++ b/frontend/src/app/simulator/page.tsx @@ -38,14 +38,14 @@ function Bar({ baseline, shocked, isPositive }: { baseline: number; shocked: num } export default function SimulatorPage() { - const { commodities, isConnected, lastUpdated } = usePrices(); + const { commodities, isConnected, lastUpdated, priceNotice } = usePrices(); const [selectedId, setSelectedId] = useState("crude-wti"); const [shockPrice, setShockPrice] = useState(null); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); const commodity = commodities.find(c => c.id === selectedId); - const basePrice = commodity?.price ?? 82.5; + const basePrice = commodity?.price ?? 0; // Init shock price when commodity loads useEffect(() => { @@ -92,7 +92,7 @@ export default function SimulatorPage() { return (
- +
@@ -119,40 +119,40 @@ export default function SimulatorPage() {
-
BASE PRICE (CURRENT)
-
{formatPrice(basePrice)}
+
{commodity ? (commodity.isStale ? "BASE PRICE (STALE QUOTE)" : "BASE PRICE (PROVIDER QUOTE)") : "BASE PRICE UNAVAILABLE"}
+
{formatPrice(commodity ? basePrice : null)}
PRICE CHANGE
- {isIncrease ? "+" : ""}{formatPrice(priceChange)} ({priceChangePct.toFixed(1)}%) + {commodity ? `${isIncrease ? "+" : ""}${formatPrice(priceChange)} (${priceChangePct.toFixed(1)}%)` : "—"}
SHOCK PRICE
- {shockPrice !== null ? formatPrice(shockPrice) : "—"} + {commodity && shockPrice !== null ? formatPrice(shockPrice) : "—"}
{/* Slider */}
- setShockPrice(parseFloat(e.target.value))} style={{ width: "100%", accentColor: "var(--orange-mid)", height: "6px" }} />
- {formatPrice(sliderMin)} + {formatPrice(commodity ? sliderMin : null)} Base: {formatPrice(basePrice)} - {formatPrice(sliderMax)} + {formatPrice(commodity ? sliderMax : null)}
{/* Quick presets */}
{[-30, -20, -10, 0, +10, +20, +30, +50].map(pct => ( - @@ -161,7 +161,7 @@ export default function SimulatorPage() {
{/* Metrics grid */} - {result && ( + {result && commodity && result.commodity_id === selectedId && result.base_price === basePrice && (
India macro impact — {isIncrease ? "price increase" : "price drop"} scenario diff --git a/frontend/src/app/watchlist/page.tsx b/frontend/src/app/watchlist/page.tsx index 487b670..3172b25 100644 --- a/frontend/src/app/watchlist/page.tsx +++ b/frontend/src/app/watchlist/page.tsx @@ -6,7 +6,7 @@ import { useWatchlist } from "@/hooks/useWatchlist"; import { formatPrice, formatPercent } from "@/lib/utils"; export default function WatchlistPage() { - const { commodities, isConnected, lastUpdated } = usePrices(); + const { commodities, isConnected, lastUpdated, priceNotice } = usePrices(); const { items, remove } = useWatchlist(); const entries = items.map(item => { @@ -21,7 +21,7 @@ export default function WatchlistPage() { return (
- +
diff --git a/frontend/src/components/Navbar.tsx b/frontend/src/components/Navbar.tsx index 81f3d87..1f84bf2 100644 --- a/frontend/src/components/Navbar.tsx +++ b/frontend/src/components/Navbar.tsx @@ -41,10 +41,11 @@ const ALL_ITEMS = NAV_GROUPS.flatMap(g => g.items); interface NavbarProps { isConnected: boolean; lastUpdated: Date | null; + priceNotice?: string; activePage?: string; } -export function Navbar({ isConnected, lastUpdated, activePage }: NavbarProps) { +export function Navbar({ isConnected, lastUpdated, activePage, priceNotice }: NavbarProps) { const { theme, toggle } = useTheme(); const router = useRouter(); const pathname = usePathname(); @@ -54,6 +55,7 @@ export function Navbar({ isConnected, lastUpdated, activePage }: NavbarProps) { href === "/" ? pathname === "/" : pathname?.startsWith(href); return ( + <>
@@ -108,7 +110,7 @@ export function Navbar({ isConnected, lastUpdated, activePage }: NavbarProps) { {isConnected &&
}
- {isConnected ? "Live" : "Polling"}{lastUpdated ? " " + lastUpdated.toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit", second: "2-digit" }) : ""} + {isConnected ? "Socket connected" : "Polling"}{lastUpdated ? " · Quote " + lastUpdated.toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit", second: "2-digit" }) : ""}
+ {priceNotice &&
{priceNotice}
} + ); } diff --git a/frontend/src/components/Topbar.tsx b/frontend/src/components/Topbar.tsx index f71a10c..43973c0 100644 --- a/frontend/src/components/Topbar.tsx +++ b/frontend/src/components/Topbar.tsx @@ -5,11 +5,13 @@ interface TopbarProps { subtitle: string; isConnected: boolean; lastUpdated: Date | null; + priceNotice?: string; actions?: React.ReactNode; } -export function Topbar({ title, subtitle, isConnected, lastUpdated, actions }: TopbarProps) { +export function Topbar({ title, subtitle, isConnected, lastUpdated, actions, priceNotice }: TopbarProps) { return ( + <>
{/* Title & Subtitle */}
@@ -40,16 +42,18 @@ export function Topbar({ title, subtitle, isConnected, lastUpdated, actions }: T )}
- {isConnected ? "Live" : "Polling"} + {isConnected ? "Socket connected" : "Polling"} {lastUpdated && ( - {lastUpdated.toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit", second: "2-digit" })} + Quote {lastUpdated.toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit", second: "2-digit" })} )}
{actions}
+ {priceNotice &&
{priceNotice}
} + ); } \ No newline at end of file diff --git a/frontend/src/hooks/usePrices.ts b/frontend/src/hooks/usePrices.ts index 421e5cc..0a63996 100644 --- a/frontend/src/hooks/usePrices.ts +++ b/frontend/src/hooks/usePrices.ts @@ -1,12 +1,14 @@ "use client"; -import { useCallback, useEffect, useRef, useState } from "react"; -import { Commodity } from "@/types"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { Commodity, CommodityQuote } from "@/types"; import { api } from "@/lib/api"; import { POLL_INTERVAL_MS, WS_BASE_URL, WS_RECONNECT_DELAY_MS } from "@/lib/constants"; interface UsePricesReturn { commodities: Commodity[]; + records: CommodityQuote[]; + priceNotice: string; loading: boolean; error: string | null; lastUpdated: Date | null; @@ -15,29 +17,45 @@ interface UsePricesReturn { } export function usePrices(): UsePricesReturn { - const [commodities, setCommodities] = useState([]); + const [records, setRecords] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); - const [lastUpdated, setLastUpdated] = useState(null); const [isConnected, setIsConnected] = useState(false); const wsRef = useRef(null); const pollRef = useRef(null); const reconnectRef = useRef(null); + const acceptPrices = useCallback((data: CommodityQuote[]) => { + // Fail closed for an older API or unmarked simulated data. + setRecords(data.map(c => { + if (c.source !== "yahoo_finance" || !c.sourceTimestamp || c.isSimulated !== false || + !["provider", "stale"].includes(c.dataStatus) || !Number.isFinite(Date.parse(c.sourceTimestamp))) { + return { ...c, price: null, previousClose: null, change: null, changePercent: null, + high24h: null, low24h: null, volume: null, history: [], marketStatus: "unknown", + source: null, sourceTimestamp: null, fetchedAt: null, lastUpdated: null, + dataStatus: "unavailable", isStale: false, isSimulated: false }; + } + if (Date.now() - Date.parse(c.sourceTimestamp) > 30 * 60 * 1000) + return { ...c, dataStatus: "stale", isStale: true }; + return c; + })); + setError(null); + setLoading(false); + }, []); + const fetchPrices = useCallback(async () => { try { const data = await api.getPrices(); - setCommodities(data); - setLastUpdated(new Date()); - setError(null); + acceptPrices(data); } catch (err) { - setError("Failed to fetch prices. Retrying..."); + setError("Failed to fetch prices. Showing last-known data if available."); + setRecords(old => old.map(c => c.dataStatus === "unavailable" ? c : { ...c, dataStatus: "stale", isStale: true })); console.error(err); } finally { setLoading(false); } - }, []); + }, [acceptPrices]); const connectWS = useCallback(() => { if (wsRef.current?.readyState === WebSocket.OPEN) return; @@ -48,7 +66,6 @@ export function usePrices(): UsePricesReturn { ws.onopen = () => { setIsConnected(true); - setError(null); if (reconnectRef.current) clearTimeout(reconnectRef.current); }; @@ -57,8 +74,7 @@ export function usePrices(): UsePricesReturn { const parsed = JSON.parse(event.data); // Ignore keepalive ping messages if (!Array.isArray(parsed)) return; - setCommodities(parsed as Commodity[]); - setLastUpdated(new Date()); + acceptPrices(parsed as CommodityQuote[]); } catch { console.warn("WS parse error", event.data); } @@ -76,7 +92,7 @@ export function usePrices(): UsePricesReturn { setIsConnected(false); reconnectRef.current = setTimeout(connectWS, WS_RECONNECT_DELAY_MS); } - }, []); + }, [acceptPrices]); useEffect(() => { fetchPrices(); @@ -91,8 +107,24 @@ export function usePrices(): UsePricesReturn { }; }, [fetchPrices, connectWS]); + const commodities = useMemo(() => records.filter((c): c is Commodity => + c.dataStatus !== "unavailable" && [c.price, c.previousClose, c.change, c.changePercent] + .every(v => typeof v === "number" && Number.isFinite(v))), [records]); + const times = records.map(c => c.sourceTimestamp ? Date.parse(c.sourceTimestamp) : NaN).filter(Number.isFinite); + const lastUpdated = times.length ? new Date(Math.max(...times)) : null; + const missing = records.filter(c => c.dataStatus === "unavailable").map(c => c.name); + const stale = records.filter(c => c.isStale).map(c => c.name); + const incomplete = records.filter(c => c.dataStatus !== "unavailable" && !commodities.some(q => q.id === c.id)).map(c => c.name); + const priceNotice = [ + "Yahoo Finance provider quotes may be delayed; connection status is not market status.", + !loading && !records.length ? "No quotes available." : "", + missing.length ? "Unavailable: " + missing.join(", ") + "." : "", + stale.length ? "Stale: " + stale.join(", ") + "." : "", + incomplete.length ? "Incomplete quote (excluded from calculations): " + incomplete.join(", ") + "." : "", + error ?? "", + ].filter(Boolean).join(" "); return { - commodities, + commodities, records, priceNotice, loading, error, lastUpdated, diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 5255b80..04ee815 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -1,4 +1,4 @@ -import { Commodity, NewsArticle, FxRates } from "@/types"; +import { CommodityQuote, NewsArticle, FxRates } from "@/types"; const BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000"; @@ -9,9 +9,9 @@ async function get(path: string): Promise { } export const api = { - getPrices: () => get("/api/prices"), - getCommodity: (id: string) => get(`/api/prices/${id}`), - getTicker: () => get<{ id: string; name: string; price: number; changePercent: number; currency: string }[]>("/api/ticker"), + getPrices: () => get("/api/prices"), + getCommodity: (id: string) => get(`/api/prices/${id}`), + getTicker: () => get[]>("/api/ticker"), getNews: (commodity = "all") => get(`/api/news?commodity=${commodity}&limit=12`), getRates: () => get("/api/rates"), }; diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 38b60be..7b9900e 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -1,6 +1,7 @@ import { VolatilityLevel, PricePoint } from "@/types"; -export function formatPrice(price: number, currency = "USD"): string { +export function formatPrice(price: number | null, currency = "USD"): string { + if (price === null || !Number.isFinite(price)) return "—"; return new Intl.NumberFormat("en-US", { style: "currency", currency, minimumFractionDigits: 2, maximumFractionDigits: 2, @@ -17,7 +18,8 @@ export function formatPercent(pct: number): string { return `${sign}${pct.toFixed(2)}%`; } -export function formatVolume(vol: number): string { +export function formatVolume(vol: number | null): string { + if (vol === null || !Number.isFinite(vol)) return "N/A"; if (vol >= 1_000_000) return `${(vol / 1_000_000).toFixed(1)}M`; if (vol >= 1_000) return `${(vol / 1_000).toFixed(1)}K`; return vol.toFixed(0); @@ -59,7 +61,8 @@ export function getSparklinePath(points: PricePoint[], w: number, h: number): st return `M${coords.join("L")}`; } -export function timeAgo(iso: string): string { +export function timeAgo(iso: string | null): string { + if (!iso) return "Unknown"; const diff = Math.floor((Date.now() - new Date(iso).getTime()) / 1000); if (diff < 60) return `${diff}s ago`; if (diff < 3600) return `${Math.floor(diff / 60)}m ago`; diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 5bd0703..1130205 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1,20 +1,34 @@ -export interface Commodity { +export interface CommodityQuote { id: string; name: string; ticker: string; unit: string; category: "energy" | "metals" | "agriculture" | "other"; + price: number | null; + previousClose: number | null; + change: number | null; + changePercent: number | null; + high24h: number | null; + low24h: number | null; + volume: number | null; + marketStatus: "open" | "closed" | "pre-market" | "unknown"; + lastUpdated: string | null; + source: "yahoo_finance" | null; + sourceTimestamp: string | null; + fetchedAt: string | null; + dataStatus: "provider" | "stale" | "unavailable"; + isStale: boolean; + isSimulated: boolean; + history: PricePoint[]; + currency: string; +} + +// Numeric consumers may only receive complete, observed quotes. +export interface Commodity extends CommodityQuote { price: number; previousClose: number; change: number; changePercent: number; - high24h: number; - low24h: number; - volume: number; - marketStatus: "open" | "closed" | "pre-market"; - lastUpdated: string; - history: PricePoint[]; - currency: string; } export interface PricePoint {