Files
2026-11-17 20:07:31 +01:00

91 lines
3.5 KiB
Python

"""Real market prices for demo mode, from Yahoo Finance's public chart endpoint.
No account or key needed. It is an unofficial endpoint: fine for a demo, but it can
rate-limit or change without notice, so every failure is caught and the demo just
tries again on the next poll.
"""
import time
from dataclasses import dataclass
import httpx
URL = "https://query1.finance.yahoo.com/v8/finance/chart/{symbol}"
HEADERS = {"User-Agent": "Mozilla/5.0 (yote-in-vest demo)"}
INTERVAL_SECONDS = {"15m": 900, "30m": 1800, "1h": 3600, "1d": 86400}
RANGE_FOR = {"15m": "5d", "30m": "1mo", "1h": "1mo", "1d": "1y"}
@dataclass
class Candle:
ts: int
high: float
low: float
close: float
volume: float
def parse_chart(data: dict, interval: str, now: float | None = None) -> tuple[list[Candle], str]:
"""Turn Yahoo's chart JSON into closed candles (the still-forming one is dropped)."""
res = (data.get("chart") or {}).get("result") or []
if not res:
err = (data.get("chart") or {}).get("error") or "empty response"
raise ValueError(f"Yahoo: {err}")
r = res[0]
currency = (r.get("meta") or {}).get("currency", "")
ts = r.get("timestamp") or []
q = ((r.get("indicators") or {}).get("quote") or [{}])[0]
now = time.time() if now is None else now
step = INTERVAL_SECONDS.get(interval, 3600)
out = []
for i, t in enumerate(ts):
h, l, c = q.get("high", [None])[i], q.get("low", [None])[i], q.get("close", [None])[i]
v = (q.get("volume") or [0] * len(ts))[i] or 0
if None in (h, l, c) or t + step > now: # gaps, or a candle that hasn't closed yet
continue
out.append(Candle(int(t), float(h), float(l), float(c), float(v)))
# Yahoo often reports the newest candle(s) with volume 0 until the volume is filled in later.
# Treat those as "not final yet": drop them, and they arrive with real volume on a later poll.
# (A market that never has volume at all keeps its candles; the health panel flags it.)
if any(c.volume > 0 for c in out):
while out and out[-1].volume == 0:
out.pop()
return out, currency
def fetch(symbol: str, interval: str = "1h", range_: str | None = None) -> tuple[list[Candle], str]:
"""Closed candles for a Yahoo symbol. `range_` is Yahoo's range text ("1mo", "2y", "5y"...);
the default depends on the candle size."""
resp = httpx.get(URL.format(symbol=symbol), headers=HEADERS, timeout=15,
params={"interval": interval, "range": range_ or RANGE_FOR.get(interval, "1mo")})
resp.raise_for_status()
return parse_chart(resp.json(), interval)
# Yahoo symbols for "units of currency per 1 euro".
FX_SYMBOLS = {"USD": "EURUSD=X", "GBP": "EURGBP=X"}
def fx_rates() -> dict[str, float]:
"""Live euro exchange rates. Currencies that fail to load are simply missing."""
out = {}
for cur, sym in FX_SYMBOLS.items():
try:
candles, _ = fetch(sym, "1h")
if candles:
out[cur] = candles[-1].close
except Exception:
pass
return out
def to_eur(price: float, currency: str, rates: dict[str, float]) -> float:
"""Convert a quoted price to euros. London shares are quoted in pence (GBp/GBX)."""
if currency in ("GBp", "GBX"):
price, currency = price / 100, "GBP"
if not currency or currency == "EUR":
return price
rate = rates.get(currency)
if not rate:
raise ValueError(f"no EUR exchange rate for {currency}")
return price / rate