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
42 changes: 42 additions & 0 deletions .github/workflows/price-provenance.yml
Original file line number Diff line number Diff line change
@@ -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
28 changes: 17 additions & 11 deletions backend/models/commodity.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pydantic import BaseModel
from pydantic import BaseModel, Field
from typing import Literal


Expand All @@ -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
18 changes: 11 additions & 7 deletions backend/routers/analyst.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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:
Expand Down
6 changes: 5 additions & 1 deletion backend/routers/correlation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."}
17 changes: 13 additions & 4 deletions backend/routers/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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(
Expand All @@ -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()),
Expand All @@ -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
],
Expand All @@ -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()),
Expand Down
14 changes: 12 additions & 2 deletions backend/routers/india.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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),
Expand All @@ -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
Expand All @@ -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(),
Expand Down
1 change: 1 addition & 0 deletions backend/routers/prices.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
]
Expand Down
Loading
Loading