121 lines
4.4 KiB
Python
121 lines
4.4 KiB
Python
"""Live prices: Yahoo Finance (stocks/ETFs, gold futures, FX) and CoinGecko (crypto). All values in EUR."""
|
|
import logging
|
|
import os
|
|
from datetime import date, datetime
|
|
from decimal import Decimal
|
|
|
|
import httpx
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from models import Asset, PortfolioSnapshot
|
|
|
|
log = logging.getLogger("prices")
|
|
UA = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) finance-dashboard"}
|
|
TROY_OUNCE_G = Decimal("31.1034768")
|
|
|
|
|
|
def _client() -> httpx.Client:
|
|
return httpx.Client(timeout=15, headers=UA, follow_redirects=True)
|
|
|
|
|
|
def yahoo_quote(c: httpx.Client, symbol: str) -> tuple[Decimal, str]:
|
|
r = c.get(f"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}", params={"interval": "1d", "range": "5d"})
|
|
r.raise_for_status()
|
|
res = (r.json().get("chart") or {}).get("result")
|
|
if not res:
|
|
raise ValueError(f"Yahoo has no data for {symbol!r}")
|
|
meta = res[0]["meta"]
|
|
return Decimal(str(meta["regularMarketPrice"])), meta.get("currency") or "USD"
|
|
|
|
|
|
def fx_to_eur(c: httpx.Client, currency: str, cache: dict) -> Decimal:
|
|
if currency == "EUR":
|
|
return Decimal(1)
|
|
divisor = Decimal(1)
|
|
if currency in ("GBp", "GBX"): # London quotes in pence
|
|
currency, divisor = "GBP", Decimal(100)
|
|
if currency not in cache:
|
|
cache[currency], _ = yahoo_quote(c, f"{currency}EUR=X")
|
|
return cache[currency] / divisor
|
|
|
|
|
|
def gold_eur_per_gram(c: httpx.Client, symbol: str, cache: dict) -> Decimal:
|
|
key = f"metal:{symbol}"
|
|
if key not in cache:
|
|
usd_oz, cur = yahoo_quote(c, symbol or "GC=F")
|
|
cache[key] = usd_oz * fx_to_eur(c, cur, cache) / TROY_OUNCE_G
|
|
return cache[key]
|
|
|
|
|
|
def coingecko(c: httpx.Client, ids: list[str]) -> dict[str, Decimal]:
|
|
if not ids:
|
|
return {}
|
|
headers = {}
|
|
if key := os.getenv("COINGECKO_API_KEY"):
|
|
headers["x-cg-demo-api-key"] = key
|
|
r = c.get("https://api.coingecko.com/api/v3/simple/price",
|
|
params={"ids": ",".join(ids), "vs_currencies": "eur"}, headers=headers)
|
|
r.raise_for_status()
|
|
return {k: Decimal(str(v["eur"])) for k, v in r.json().items() if "eur" in v}
|
|
|
|
|
|
def unit_price(asset: Asset, c: httpx.Client, cache: dict, crypto: dict) -> Decimal:
|
|
if asset.kind == "crypto":
|
|
if not crypto:
|
|
raise ValueError("no CoinGecko prices available right now")
|
|
if asset.symbol.lower() not in crypto:
|
|
raise ValueError(f"CoinGecko id {asset.symbol!r} not found (use ids like 'bitcoin', 'ethereum')")
|
|
return crypto[asset.symbol.lower()]
|
|
if asset.kind == "gold":
|
|
per_gram = gold_eur_per_gram(c, asset.symbol, cache)
|
|
grams = TROY_OUNCE_G if asset.unit == "oz" else Decimal(1)
|
|
return per_gram * grams * (asset.purity or Decimal(1))
|
|
price, cur = yahoo_quote(c, asset.symbol)
|
|
return price * fx_to_eur(c, cur, cache)
|
|
|
|
|
|
def refresh_prices(db: Session) -> list[str]:
|
|
assets = list(db.scalars(select(Asset)))
|
|
errors: list[str] = []
|
|
cache: dict = {}
|
|
with _client() as c:
|
|
try:
|
|
crypto = coingecko(c, sorted({a.symbol.lower() for a in assets if a.kind == "crypto"}))
|
|
except Exception as e: # noqa: BLE001
|
|
crypto = {}
|
|
errors.append(f"CoinGecko: {e}")
|
|
for a in assets:
|
|
if a.manual_price is not None:
|
|
continue
|
|
try:
|
|
a.last_price = unit_price(a, c, cache, crypto).quantize(Decimal("0.000001"))
|
|
a.last_price_at = datetime.now()
|
|
a.price_error = None
|
|
except Exception as e: # noqa: BLE001
|
|
a.price_error = str(e)[:300]
|
|
errors.append(f"{a.name}: {e}")
|
|
db.commit()
|
|
snapshot(db)
|
|
for e in errors:
|
|
log.warning(e)
|
|
return errors
|
|
|
|
|
|
def snapshot(db: Session) -> None:
|
|
"""Store today's value/cost per asset kind (one row per kind per day) for the history chart."""
|
|
from portfolio import holdings, totals # local import to avoid a cycle
|
|
|
|
today = date.today()
|
|
t = totals(holdings(db))
|
|
for kind, v in t.items():
|
|
if kind == "all":
|
|
continue
|
|
row = db.scalar(select(PortfolioSnapshot).where(PortfolioSnapshot.date == today,
|
|
PortfolioSnapshot.kind == kind))
|
|
if row is None:
|
|
row = PortfolioSnapshot(date=today, kind=kind, value=0, cost=0)
|
|
db.add(row)
|
|
row.value, row.cost = v["value"], v["cost"]
|
|
db.commit()
|