Pridani stahovani kurzu a jednotneho API
- GET /{source_id} pro cnb, kb, csob, moneta, jt, mbank, ppf, trinity, fio, creditas
- jednotny tvar odpovedi s bezhotovostnimi kurzy za 1 jednotku meny
- parametr ?base pro ceny v jine mene nez CZK
- pole buy_sell_origin a middle_origin rikaji, co je stazene a co dopocitane
- pravidelne stahovani na pozadi, ukladani do JSON, priznak stale
- testy a dokumentace ve slozce documentation
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
"""Application configuration. This is the only module that reads the environment."""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_REFRESH_INTERVAL_MINUTES = 60
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
app_name: str
|
||||
app_version: str
|
||||
root_path: str
|
||||
data_dir: Path
|
||||
refresh_interval_minutes: int
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
raw_interval = os.getenv("REFRESH_INTERVAL_MINUTES", str(DEFAULT_REFRESH_INTERVAL_MINUTES))
|
||||
try:
|
||||
interval = int(raw_interval)
|
||||
except ValueError as error:
|
||||
raise ValueError(f"REFRESH_INTERVAL_MINUTES must be an integer, got {raw_interval!r}") from error
|
||||
if interval <= 0:
|
||||
raise ValueError(f"REFRESH_INTERVAL_MINUTES must be positive, got {interval}")
|
||||
|
||||
return Settings(
|
||||
app_name=os.getenv("APP_NAME", "Exchange rates"),
|
||||
app_version=os.getenv("APP_VERSION", "1.0.0"),
|
||||
root_path=os.getenv("ROOT_PATH", ""),
|
||||
data_dir=Path(os.getenv("DATA_DIR", "data")),
|
||||
refresh_interval_minutes=interval,
|
||||
)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Converts rates from the CZK quotes published by the sources to another base currency."""
|
||||
|
||||
from app.models import Rate
|
||||
|
||||
CZK = "CZK"
|
||||
# Prices of weak currencies in a strong base can be tiny, for example IDR in EUR is
|
||||
# around 0.00005, so this keeps more decimals than the CZK quotes need.
|
||||
CONVERTED_RATE_DECIMALS = 10
|
||||
|
||||
|
||||
class BaseCurrencyNotAvailable(ValueError):
|
||||
"""The source does not publish the requested base currency."""
|
||||
|
||||
|
||||
def rebase_rates(rates: list[Rate], base: str) -> list[Rate]:
|
||||
"""Goes through CZK, so the spread of both currencies is applied.
|
||||
|
||||
The bank buying X in base B means: the client sells X for CZK at X.buy and
|
||||
then pays CZK for B at B.sell. Selling X in base B is the opposite direction.
|
||||
"""
|
||||
if base == CZK:
|
||||
return rates
|
||||
|
||||
base_rate = next((rate for rate in rates if rate.currency == base), None)
|
||||
if base_rate is None:
|
||||
raise BaseCurrencyNotAvailable(base)
|
||||
|
||||
czk_rate = Rate(
|
||||
currency=CZK,
|
||||
buy=1,
|
||||
sell=1,
|
||||
middle=1,
|
||||
buy_sell_origin="computed",
|
||||
middle_origin="computed",
|
||||
)
|
||||
converted = [
|
||||
Rate(
|
||||
currency=rate.currency,
|
||||
buy=round(rate.buy / base_rate.sell, CONVERTED_RATE_DECIMALS),
|
||||
sell=round(rate.sell / base_rate.buy, CONVERTED_RATE_DECIMALS),
|
||||
middle=round(rate.middle / base_rate.middle, CONVERTED_RATE_DECIMALS),
|
||||
buy_sell_origin="computed",
|
||||
middle_origin="computed",
|
||||
)
|
||||
for rate in [*rates, czk_rate]
|
||||
if rate.currency != base
|
||||
]
|
||||
return sorted(converted, key=lambda rate: rate.currency)
|
||||
+84
-13
@@ -1,25 +1,96 @@
|
||||
import os
|
||||
from fastapi import FastAPI
|
||||
import asyncio
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager, suppress
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Path, Query
|
||||
|
||||
from app.config import load_settings
|
||||
from app.conversion import CZK, BaseCurrencyNotAvailable, rebase_rates
|
||||
from app.models import RateSheetResponse
|
||||
from app.refresh import refresh_forever
|
||||
from app.sources import SOURCES
|
||||
from app.storage import read_sheet
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
|
||||
# A single missed refresh is normal, for example a short outage on the bank side.
|
||||
# Three missed refreshes in a row mean the consumer should know about it.
|
||||
STALE_AFTER_REFRESH_INTERVALS = 3
|
||||
|
||||
settings = load_settings()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
||||
# Runs in the background, so the health check answers while the first refresh is in progress.
|
||||
task = asyncio.create_task(refresh_forever(settings.data_dir, settings.refresh_interval_minutes))
|
||||
yield
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
APP_NAME = os.getenv("APP_NAME", "Exchange rates")
|
||||
APP_VERSION = os.getenv("APP_VERSION", "1.0.0")
|
||||
ROOT_PATH = os.getenv("ROOT_PATH", "")
|
||||
|
||||
app = FastAPI(
|
||||
title=APP_NAME,
|
||||
version=APP_VERSION,
|
||||
root_path=ROOT_PATH
|
||||
title=settings.app_name,
|
||||
version=settings.app_version,
|
||||
root_path=settings.root_path,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
def health() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/version")
|
||||
def version():
|
||||
def version() -> dict[str, str]:
|
||||
return {
|
||||
"app": APP_NAME,
|
||||
"version": APP_VERSION,
|
||||
"app": settings.app_name,
|
||||
"version": settings.app_version,
|
||||
"language": "python",
|
||||
"root_path": ROOT_PATH
|
||||
"root_path": settings.root_path,
|
||||
}
|
||||
|
||||
|
||||
# Must stay the last route, otherwise it would capture the static paths above.
|
||||
@app.get(
|
||||
"/{source_id}",
|
||||
response_model=RateSheetResponse,
|
||||
responses={
|
||||
404: {"description": "Unknown source, or the source does not publish the base currency"},
|
||||
503: {"description": "The source has no stored data yet"},
|
||||
},
|
||||
)
|
||||
def get_rates(
|
||||
source_id: str = Path(description=f"Source identifier: {', '.join(SOURCES)}"),
|
||||
base: str = Query(
|
||||
default=CZK,
|
||||
pattern=r"^[A-Z]{3}$",
|
||||
description="Currency to express the prices in. Other than CZK is computed through CZK.",
|
||||
),
|
||||
) -> RateSheetResponse:
|
||||
if source_id not in SOURCES:
|
||||
raise HTTPException(status_code=404, detail=f"Unknown source. Available: {', '.join(SOURCES)}")
|
||||
|
||||
sheet = read_sheet(settings.data_dir, source_id)
|
||||
if sheet is None:
|
||||
raise HTTPException(status_code=503, detail="No data has been downloaded for this source yet")
|
||||
|
||||
try:
|
||||
rates = rebase_rates(sheet.rates, base)
|
||||
except BaseCurrencyNotAvailable as error:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Source {source_id} does not publish base currency {base}",
|
||||
) from error
|
||||
|
||||
max_age = timedelta(minutes=settings.refresh_interval_minutes * STALE_AFTER_REFRESH_INTERVALS)
|
||||
return RateSheetResponse(
|
||||
**sheet.model_dump(exclude={"rates"}),
|
||||
rates=rates,
|
||||
base=base,
|
||||
stale=datetime.now(UTC) - sheet.fetched_at > max_age,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""The universal contract: every source returns exactly this shape."""
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
# "fetched" is a value published by the source, "computed" is calculated by this service.
|
||||
Origin = Literal["fetched", "computed"]
|
||||
|
||||
|
||||
class Rate(BaseModel):
|
||||
"""All prices are for 1 unit of the currency and are always present.
|
||||
|
||||
They are in CZK as published by the sources, API responses can convert them to another base.
|
||||
"""
|
||||
|
||||
currency: str = Field(pattern=r"^[A-Z]{3}$", description="ISO 4217 currency code")
|
||||
buy: float = Field(gt=0, description="Price of 1 unit in the base currency when the bank buys")
|
||||
sell: float = Field(gt=0, description="Price of 1 unit in the base currency when the bank sells")
|
||||
middle: float = Field(gt=0, description="Middle price of 1 unit in the base currency")
|
||||
buy_sell_origin: Origin = Field(description="Whether buy and sell are fetched or computed")
|
||||
middle_origin: Origin = Field(description="Whether middle is fetched or computed")
|
||||
|
||||
|
||||
class ParsedRates(BaseModel):
|
||||
"""What a parser extracts from a single source document."""
|
||||
|
||||
valid_date: date = Field(description="Date the rates are valid for")
|
||||
rates: list[Rate] = Field(min_length=1)
|
||||
|
||||
|
||||
class RateSheet(ParsedRates):
|
||||
"""A stored result of a successful download."""
|
||||
|
||||
source: str
|
||||
source_name: str
|
||||
source_url: str
|
||||
fetched_at: datetime
|
||||
|
||||
|
||||
class RateSheetResponse(RateSheet):
|
||||
base: str = Field(description="Currency all prices in this response are expressed in")
|
||||
stale: bool = Field(description="True when recent refreshes failed and the data may be outdated")
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Downloads the sources and keeps the stored JSON files up to date."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from app.models import RateSheet
|
||||
from app.sources import SOURCES
|
||||
from app.sources.base import Source
|
||||
from app.storage import write_sheet
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Identifies the service honestly, so a bank can recognise it and decide how to treat it.
|
||||
USER_AGENT = "exchange-rates-service/1.0"
|
||||
REQUEST_TIMEOUT_SECONDS = 30.0
|
||||
|
||||
|
||||
async def refresh_source(client: httpx.AsyncClient, source: Source, data_dir: Path) -> None:
|
||||
if source.request_json is None:
|
||||
response = await client.get(source.url)
|
||||
else:
|
||||
response = await client.post(source.url, json=source.request_json)
|
||||
response.raise_for_status()
|
||||
parsed = source.parse(response.text)
|
||||
sheet = RateSheet(
|
||||
source=source.id,
|
||||
source_name=source.name,
|
||||
source_url=source.url,
|
||||
fetched_at=datetime.now(UTC),
|
||||
valid_date=parsed.valid_date,
|
||||
rates=sorted(parsed.rates, key=lambda rate: rate.currency),
|
||||
)
|
||||
write_sheet(data_dir, sheet)
|
||||
logger.info("Refreshed source %s with %d rates", source.id, len(sheet.rates))
|
||||
|
||||
|
||||
async def refresh_all(client: httpx.AsyncClient, data_dir: Path) -> None:
|
||||
"""A failed source keeps its last good file and does not affect the others."""
|
||||
for source in SOURCES.values():
|
||||
try:
|
||||
await refresh_source(client, source, data_dir)
|
||||
except Exception:
|
||||
logger.exception("Refresh of source %s failed, keeping the last stored data", source.id)
|
||||
|
||||
|
||||
async def refresh_forever(data_dir: Path, interval_minutes: int) -> None:
|
||||
async with httpx.AsyncClient(
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
timeout=REQUEST_TIMEOUT_SECONDS,
|
||||
follow_redirects=True,
|
||||
) as client:
|
||||
while True:
|
||||
await refresh_all(client, data_dir)
|
||||
await asyncio.sleep(interval_minutes * 60)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Registry of the supported sources. The key is the public URL segment."""
|
||||
|
||||
from app.sources import cnb, creditas, csob, fio, jt, kb, mbank, moneta, ppf, trinity
|
||||
from app.sources.base import Source
|
||||
|
||||
SOURCES: dict[str, Source] = {
|
||||
source.id: source
|
||||
for source in (
|
||||
Source(
|
||||
id="cnb",
|
||||
name="Česká národní banka",
|
||||
url=(
|
||||
"https://www.cnb.cz/cs/financni-trhy/devizovy-trh/kurzy-devizoveho-trhu/"
|
||||
"kurzy-devizoveho-trhu/denni_kurz.txt"
|
||||
),
|
||||
parse=cnb.parse,
|
||||
),
|
||||
Source(
|
||||
id="kb",
|
||||
name="Komerční banka",
|
||||
url="https://www.kb.cz/cs/kurzovni-listek",
|
||||
parse=kb.parse,
|
||||
),
|
||||
Source(
|
||||
id="jt",
|
||||
name="J&T Banka",
|
||||
url="https://www.jtbank.cz/kurzovni-listek",
|
||||
parse=jt.parse,
|
||||
),
|
||||
Source(
|
||||
id="mbank",
|
||||
name="mBank",
|
||||
url="https://www.mbank.cz/kurzovni-listek/",
|
||||
parse=mbank.parse,
|
||||
),
|
||||
Source(
|
||||
id="ppf",
|
||||
name="PPF banka",
|
||||
url="https://www.ppfbanka.cz/cs/kurzovni-listek",
|
||||
parse=ppf.parse,
|
||||
),
|
||||
Source(
|
||||
id="trinity",
|
||||
name="Trinity Bank",
|
||||
url="https://public.trinitybank.cz/cs/kurzovni-listek",
|
||||
parse=trinity.parse,
|
||||
),
|
||||
Source(
|
||||
id="fio",
|
||||
name="Fio banka",
|
||||
url="https://www.fio.cz/akcie-investice/dalsi-sluzby-fio/devizove-konverze",
|
||||
parse=fio.parse,
|
||||
),
|
||||
Source(
|
||||
id="creditas",
|
||||
name="Banka CREDITAS",
|
||||
url="https://www.creditas.cz/kurzovni-listek",
|
||||
parse=creditas.parse,
|
||||
),
|
||||
Source(
|
||||
id="csob",
|
||||
name="ČSOB",
|
||||
url="https://www.csob.cz/spa/exrate/exrates/-/kurzovni-listek.txt",
|
||||
parse=csob.parse,
|
||||
),
|
||||
Source(
|
||||
id="moneta",
|
||||
name="MONETA Money Bank",
|
||||
url="https://openapi.moneta.cz/openapi/unsecured/portal/exchangerate/list",
|
||||
parse=moneta.parse,
|
||||
request_json={},
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Shared building blocks of the source parsers."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.models import Origin, ParsedRates, Rate
|
||||
|
||||
# Dividing by the quoted amount (for example 100 JPY) must not lose precision
|
||||
# on small per-unit prices, while float noise from the division is rounded away.
|
||||
RATE_DECIMALS = 6
|
||||
# Czech banks state validity in local time, some sources send it as a UTC timestamp.
|
||||
PRAGUE_ZONE = ZoneInfo("Europe/Prague")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Source:
|
||||
id: str
|
||||
name: str
|
||||
url: str
|
||||
# Pure function of the downloaded document. Raises ValueError when the format changed.
|
||||
parse: Callable[[str], ParsedRates]
|
||||
# When set, the source is requested with POST and this JSON body instead of GET.
|
||||
request_json: dict[str, Any] | None = None
|
||||
|
||||
|
||||
def parse_comma_decimal(value: str) -> float:
|
||||
return float(value.replace(",", "."))
|
||||
|
||||
|
||||
def make_rate(
|
||||
currency: str,
|
||||
amount: int,
|
||||
buy: float,
|
||||
sell: float,
|
||||
middle: float | None = None,
|
||||
buy_sell_origin: Origin = "fetched",
|
||||
) -> Rate:
|
||||
"""Converts source prices to the universal form: per 1 unit, middle always present."""
|
||||
quoted_middle = middle if middle is not None else (buy + sell) / 2
|
||||
return Rate(
|
||||
currency=currency,
|
||||
buy=round(buy / amount, RATE_DECIMALS),
|
||||
sell=round(sell / amount, RATE_DECIMALS),
|
||||
middle=round(quoted_middle / amount, RATE_DECIMALS),
|
||||
buy_sell_origin=buy_sell_origin,
|
||||
middle_origin="fetched" if middle is not None else "computed",
|
||||
)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Czech National Bank: official text file with one reference rate per currency."""
|
||||
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
from app.models import ParsedRates
|
||||
from app.sources.base import make_rate, parse_comma_decimal
|
||||
|
||||
HEADER_PATTERN = re.compile(r"^(\d{2})\.(\d{2})\.(\d{4}) #\d+$")
|
||||
COLUMN_COUNT = 5
|
||||
|
||||
|
||||
def parse(document: str) -> ParsedRates:
|
||||
lines = [line.strip() for line in document.splitlines() if line.strip()]
|
||||
if len(lines) < 3:
|
||||
raise ValueError("CNB document is too short")
|
||||
|
||||
header = HEADER_PATTERN.match(lines[0])
|
||||
if header is None:
|
||||
raise ValueError(f"Unexpected CNB header: {lines[0]!r}")
|
||||
day, month, year = header.groups()
|
||||
|
||||
rates = []
|
||||
# lines[1] holds the column names
|
||||
for line in lines[2:]:
|
||||
columns = line.split("|")
|
||||
if len(columns) != COLUMN_COUNT:
|
||||
raise ValueError(f"Unexpected CNB row: {line!r}")
|
||||
_, _, amount, currency, raw_rate = columns
|
||||
rate = parse_comma_decimal(raw_rate)
|
||||
# CNB has no spread, so the reference rate fills all prices of the universal contract.
|
||||
rates.append(
|
||||
make_rate(
|
||||
currency,
|
||||
int(amount),
|
||||
buy=rate,
|
||||
sell=rate,
|
||||
middle=rate,
|
||||
buy_sell_origin="computed",
|
||||
)
|
||||
)
|
||||
|
||||
return ParsedRates(valid_date=date(int(year), int(month), int(day)), rates=rates)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Banka CREDITAS: HTML table of non-cash rates, which the bank itself calls indicative."""
|
||||
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
from app.models import ParsedRates
|
||||
from app.sources.base import make_rate, parse_comma_decimal
|
||||
|
||||
VALIDITY_PATTERN = re.compile(r"Kurzy platné k (\d{1,2})\. ?(\d{1,2})\. ?(\d{4})")
|
||||
ROW_MARKER = '<tr class="entry entry-row"'
|
||||
ROW_PATTERN = re.compile(
|
||||
r'history=(?P<currency>[A-Z]{3})">(?P=currency)</a>.*?'
|
||||
r'Jednotka</div>\s*<div class="entry-cell__value">\s*(?P<amount>\d+)\s*</div>.*?'
|
||||
r'Nakupujeme v CZK</div>\s*<div class="entry-cell__value">\s*'
|
||||
r"(?:<span[^>]*></span>)?(?P<buy>[\d,]+) CZK.*?"
|
||||
r'Prodáváme v CZK</div>\s*<div class="entry-cell__value">\s*'
|
||||
r"(?:<span[^>]*></span>)?(?P<sell>[\d,]+) CZK",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def parse(document: str) -> ParsedRates:
|
||||
validity = VALIDITY_PATTERN.search(document)
|
||||
if validity is None:
|
||||
raise ValueError("Creditas validity date not found")
|
||||
day, month, year = validity.groups()
|
||||
|
||||
# Matching row by row keeps prices of one currency from leaking into another one.
|
||||
rows = (ROW_PATTERN.search(chunk) for chunk in document.split(ROW_MARKER)[1:])
|
||||
rates = [
|
||||
make_rate(
|
||||
currency=row["currency"],
|
||||
amount=int(row["amount"]),
|
||||
buy=parse_comma_decimal(row["buy"]),
|
||||
sell=parse_comma_decimal(row["sell"]),
|
||||
)
|
||||
for row in rows
|
||||
if row is not None
|
||||
]
|
||||
return ParsedRates(valid_date=date(int(year), int(month), int(day)), rates=rates)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""ČSOB: official text export. The first three price columns are non-cash rates (devizy)."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from app.models import ParsedRates
|
||||
from app.sources.base import make_rate, parse_comma_decimal
|
||||
|
||||
ISO_DATE_LENGTH = 10
|
||||
HEADER_LINE_COUNT = 3
|
||||
MIN_COLUMN_COUNT = 7
|
||||
|
||||
|
||||
def parse(document: str) -> ParsedRates:
|
||||
lines = [line.strip() for line in document.splitlines() if line.strip()]
|
||||
if len(lines) <= HEADER_LINE_COUNT:
|
||||
raise ValueError("CSOB document is too short")
|
||||
|
||||
rates = []
|
||||
for line in lines[HEADER_LINE_COUNT:]:
|
||||
columns = line.split(";")
|
||||
if len(columns) < MIN_COLUMN_COUNT:
|
||||
raise ValueError(f"Unexpected CSOB row: {line!r}")
|
||||
_, amount, currency, _, raw_buy, raw_sell, raw_middle = columns[:MIN_COLUMN_COUNT]
|
||||
buy = parse_comma_decimal(raw_buy)
|
||||
sell = parse_comma_decimal(raw_sell)
|
||||
# The source publishes 0 for a rate it does not offer.
|
||||
if buy and sell:
|
||||
rates.append(
|
||||
make_rate(currency, int(amount), buy, sell, parse_comma_decimal(raw_middle))
|
||||
)
|
||||
|
||||
valid_date = date.fromisoformat(lines[0][:ISO_DATE_LENGTH])
|
||||
return ParsedRates(valid_date=valid_date, rates=rates)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Fio banka: HTML table of foreign exchange conversion rates, which are non-cash."""
|
||||
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
from app.models import ParsedRates
|
||||
from app.sources.base import make_rate, parse_comma_decimal
|
||||
|
||||
VALIDITY_PATTERN = re.compile(r'name="keDni_den"[^>]*value="(\d{2})\.(\d{2})\.(\d{4})"')
|
||||
# The table also has a "Kurz ČNB" column. It is not a Fio price, so the middle is computed.
|
||||
ROW_PATTERN = re.compile(
|
||||
r'class="col1">(?P<currency>[A-Z]{3})</td>\s*'
|
||||
r'<td class="tleft">[^<]*</td>\s*' # country
|
||||
r'<td class="tright">(?P<amount>\d+)</td>\s*'
|
||||
r'<td class="tright">(?P<buy>[\d,]+)</td>\s*'
|
||||
r'<td class="tright">(?P<sell>[\d,]+)</td>'
|
||||
)
|
||||
|
||||
|
||||
def parse(document: str) -> ParsedRates:
|
||||
validity = VALIDITY_PATTERN.search(document)
|
||||
if validity is None:
|
||||
raise ValueError("Fio validity date not found")
|
||||
day, month, year = validity.groups()
|
||||
|
||||
rates = [
|
||||
make_rate(
|
||||
currency=row["currency"],
|
||||
amount=int(row["amount"]),
|
||||
buy=parse_comma_decimal(row["buy"]),
|
||||
sell=parse_comma_decimal(row["sell"]),
|
||||
)
|
||||
for row in ROW_PATTERN.finditer(document)
|
||||
]
|
||||
return ParsedRates(valid_date=date(int(year), int(month), int(day)), rates=rates)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""J&T Banka: the page embeds the rates as escaped JSON objects in its page data."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
from app.models import ParsedRates
|
||||
from app.sources.base import make_rate
|
||||
|
||||
ESCAPED_RATE_PATTERN = re.compile(r'\{\\"currency\\":\\"[A-Z]{3}\\".*?\}')
|
||||
ISO_DATE_LENGTH = 10
|
||||
|
||||
|
||||
def parse(document: str) -> ParsedRates:
|
||||
# The same list can be embedded repeatedly, the first occurrence of a currency wins.
|
||||
items: dict[str, dict] = {}
|
||||
for match in ESCAPED_RATE_PATTERN.finditer(document):
|
||||
item = json.loads(match.group().replace('\\"', '"'))
|
||||
items.setdefault(item["currency"], item)
|
||||
if not items:
|
||||
raise ValueError("J&T rate list not found")
|
||||
|
||||
# The universal contract carries non-cash rates. A currency without them is not offered.
|
||||
rates = [
|
||||
make_rate(
|
||||
currency=currency,
|
||||
amount=item["unitAmount"],
|
||||
buy=item["nonCashBuy"],
|
||||
sell=item["nonCashSell"],
|
||||
)
|
||||
for currency, item in items.items()
|
||||
if item["nonCashBuy"] and item["nonCashSell"]
|
||||
]
|
||||
|
||||
first_item = next(iter(items.values()))
|
||||
valid_date = date.fromisoformat(first_item["date"][:ISO_DATE_LENGTH])
|
||||
return ParsedRates(valid_date=valid_date, rates=rates)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Komerční banka: the page embeds the rate list as JSON in WIDGETS_CONFIG."""
|
||||
|
||||
import json
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
from app.models import ParsedRates
|
||||
from app.sources.base import make_rate
|
||||
|
||||
WIDGET_MARKER = "KBExchangeRatesList"
|
||||
ITEMS_PATTERN = re.compile(r'"items":\s*(?=\[)')
|
||||
ISO_DATE_LENGTH = 10
|
||||
|
||||
|
||||
def parse(document: str) -> ParsedRates:
|
||||
widget_start = document.find(WIDGET_MARKER)
|
||||
if widget_start == -1:
|
||||
raise ValueError("KB rate list widget not found")
|
||||
items_match = ITEMS_PATTERN.search(document, widget_start)
|
||||
if items_match is None:
|
||||
raise ValueError("KB rate list items not found")
|
||||
items, _ = json.JSONDecoder().raw_decode(document, items_match.end())
|
||||
if not items:
|
||||
raise ValueError("KB rate list is empty")
|
||||
|
||||
# The universal contract carries non-cash rates. A currency without them is not offered.
|
||||
rates = [
|
||||
make_rate(
|
||||
# "curencyIso" is the real spelling used by the source
|
||||
currency=item["curencyIso"],
|
||||
amount=item["currencyUnit"],
|
||||
buy=item["nonCashBuy"],
|
||||
sell=item["nonCashSell"],
|
||||
)
|
||||
for item in items
|
||||
if item["nonCashBuy"] and item["nonCashSell"]
|
||||
]
|
||||
|
||||
valid_date = date.fromisoformat(items[0]["validDate"][:ISO_DATE_LENGTH])
|
||||
return ParsedRates(valid_date=valid_date, rates=rates)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""mBank: HTML table. The page does not state whether the rates are cash or non-cash."""
|
||||
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
from app.models import ParsedRates
|
||||
from app.sources.base import make_rate, parse_comma_decimal
|
||||
|
||||
VALIDITY_PATTERN = re.compile(r"platný k datu (\d{2})-(\d{2})-(\d{4})")
|
||||
ROW_PATTERN = re.compile(
|
||||
r"<td class='unit'><div>(?P<currency>[A-Z]{3})(?:<span[^>]*></span>)?</div></td>\s*"
|
||||
r"<td>[^<]*</td>\s*" # country
|
||||
r"<td>(?P<amount>\d+)</td>\s*"
|
||||
r"<td>(?P<buy>[\d,]+)</td>\s*"
|
||||
r"<td>(?P<sell>[\d,]+)</td>\s*"
|
||||
r"<td>(?P<middle>[\d,]+)</td>"
|
||||
)
|
||||
|
||||
|
||||
def parse(document: str) -> ParsedRates:
|
||||
validity = VALIDITY_PATTERN.search(document)
|
||||
if validity is None:
|
||||
raise ValueError("mBank validity date not found")
|
||||
day, month, year = validity.groups()
|
||||
|
||||
rates = [
|
||||
make_rate(
|
||||
currency=row["currency"],
|
||||
amount=int(row["amount"]),
|
||||
buy=parse_comma_decimal(row["buy"]),
|
||||
sell=parse_comma_decimal(row["sell"]),
|
||||
middle=parse_comma_decimal(row["middle"]),
|
||||
)
|
||||
for row in ROW_PATTERN.finditer(document)
|
||||
]
|
||||
return ParsedRates(valid_date=date(int(year), int(month), int(day)), rates=rates)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""MONETA Money Bank: the JSON endpoint used by the bank's own rate list page."""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
from app.models import ParsedRates
|
||||
from app.sources.base import PRAGUE_ZONE, make_rate
|
||||
|
||||
# Prices are already per 1 unit even when multiplyFactor says 100, for example JPY is
|
||||
# 0.13245, so dividing by the factor would make the rate a hundred times too small.
|
||||
PRICE_AMOUNT = 1
|
||||
MILLISECONDS_PER_SECOND = 1000
|
||||
|
||||
|
||||
def parse(document: str) -> ParsedRates:
|
||||
items = json.loads(document)["responseObject"]["exchangeRates"]
|
||||
if not items:
|
||||
raise ValueError("Moneta rate list is empty")
|
||||
|
||||
# A discontinued currency stays in the list with its last date, for example BGN.
|
||||
latest = max(item["effectiveDate"] for item in items)
|
||||
rates = [
|
||||
# rateAccounting is an accounting rate, not a middle of these prices, so it is not used.
|
||||
make_rate(
|
||||
currency=item["symbol"],
|
||||
amount=PRICE_AMOUNT,
|
||||
buy=item["rateCashlessBuy"],
|
||||
sell=item["rateCashlessSell"],
|
||||
)
|
||||
for item in items
|
||||
if item["effectiveDate"] == latest and item["rateCashlessBuy"] and item["rateCashlessSell"]
|
||||
]
|
||||
|
||||
valid_from = datetime.fromtimestamp(latest / MILLISECONDS_PER_SECOND, PRAGUE_ZONE)
|
||||
return ParsedRates(valid_date=valid_from.date(), rates=rates)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""PPF banka: HTML table in the "Kurzy měn" tab. The page does not state cash or non-cash."""
|
||||
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
from app.models import ParsedRates
|
||||
from app.sources.base import make_rate
|
||||
|
||||
# The second tab holds card transaction rates, which are a different product.
|
||||
CARD_RATES_TAB_MARKER = 'data-tab-content="t2"'
|
||||
ISO_DATE_LENGTH = 10
|
||||
ROW_PATTERN = re.compile(
|
||||
r'data-released="(?P<released>[^"]+)">.*?'
|
||||
r'font-weight: 600;">\s*(?P<currency>[A-Z]{3})\s*</td>\s*'
|
||||
r"<td[^>]*>\s*(?P<amount>\d+)\s*</td>\s*"
|
||||
r"<td[^>]*>\s*(?P<buy>[\d.]+)\s*</td>\s*"
|
||||
r"<td[^>]*>\s*(?P<sell>[\d.]+)\s*</td>\s*"
|
||||
r"<td[^>]*>\s*(?P<middle>[\d.]+)\s*</td>",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def parse(document: str) -> ParsedRates:
|
||||
currency_rates_tab = document.split(CARD_RATES_TAB_MARKER, maxsplit=1)[0]
|
||||
rows = list(ROW_PATTERN.finditer(currency_rates_tab))
|
||||
if not rows:
|
||||
raise ValueError("PPF rate table not found")
|
||||
|
||||
rates = [
|
||||
make_rate(
|
||||
currency=row["currency"],
|
||||
amount=int(row["amount"]),
|
||||
buy=float(row["buy"]),
|
||||
sell=float(row["sell"]),
|
||||
middle=float(row["middle"]),
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
valid_date = date.fromisoformat(rows[0]["released"][:ISO_DATE_LENGTH])
|
||||
return ParsedRates(valid_date=valid_date, rates=rates)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Trinity Bank: the page embeds non-cash rates as escaped JSON objects in its page data."""
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from app.models import ParsedRates
|
||||
from app.sources.base import PRAGUE_ZONE, make_rate
|
||||
|
||||
RATE_PATTERN = re.compile(
|
||||
r'\\"CurrencyCode\\":\\"(?P<currency>[A-Z]{3})\\",'
|
||||
r'\\"PaymentType\\":\\"CASHLESS\\",'
|
||||
r'\\"CurrencyUnit\\":\\"(?P<amount>\d+)\\",'
|
||||
r'\\"RateBuy\\":(?P<buy>[\d.]+),'
|
||||
r'\\"RateSell\\":(?P<sell>[\d.]+),'
|
||||
r'\\"RateAverage\\":(?P<middle>[\d.]+),'
|
||||
r'[^{}]*?\\"ValidFrom\\":\\"\$D(?P<valid_from>[^\\]+)\\"'
|
||||
)
|
||||
|
||||
|
||||
def parse(document: str) -> ParsedRates:
|
||||
rows = list(RATE_PATTERN.finditer(document))
|
||||
if not rows:
|
||||
raise ValueError("Trinity rate list not found")
|
||||
|
||||
rates = [
|
||||
make_rate(
|
||||
currency=row["currency"],
|
||||
amount=int(row["amount"]),
|
||||
buy=float(row["buy"]),
|
||||
sell=float(row["sell"]),
|
||||
middle=float(row["middle"]),
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
# ValidFrom is a UTC timestamp, for example 2026-11-03T23:00:00Z is 4 November in Prague.
|
||||
valid_from = datetime.fromisoformat(rows[0]["valid_from"])
|
||||
return ParsedRates(valid_date=valid_from.astimezone(PRAGUE_ZONE).date(), rates=rates)
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Stores one JSON file per source."""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from app.models import RateSheet
|
||||
|
||||
|
||||
def _sheet_path(data_dir: Path, source_id: str) -> Path:
|
||||
return data_dir / f"{source_id}.json"
|
||||
|
||||
|
||||
def write_sheet(data_dir: Path, sheet: RateSheet) -> None:
|
||||
"""Replaces the file atomically, so a reader never sees a partial write."""
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
descriptor, temp_name = tempfile.mkstemp(dir=data_dir, suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(descriptor, "wb") as temp_file:
|
||||
temp_file.write(sheet.model_dump_json(indent=2).encode("utf-8"))
|
||||
os.replace(temp_name, _sheet_path(data_dir, sheet.source))
|
||||
except BaseException:
|
||||
Path(temp_name).unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def read_sheet(data_dir: Path, source_id: str) -> RateSheet | None:
|
||||
path = _sheet_path(data_dir, source_id)
|
||||
if not path.exists():
|
||||
return None
|
||||
return RateSheet.model_validate_json(path.read_bytes())
|
||||
Reference in New Issue
Block a user