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,6 @@
|
|||||||
|
# Veřejný prefix aplikace za reverse proxy, nastavuje AppFactory.
|
||||||
|
ROOT_PATH=/apps/exchange-rates
|
||||||
|
# Složka s JSON soubory kurzů. Výchozí hodnota je data.
|
||||||
|
DATA_DIR=data
|
||||||
|
# Jak často se stahují kurzy, v minutách. Výchozí hodnota je 60.
|
||||||
|
REFRESH_INTERVAL_MINUTES=60
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
# Downloaded exchange rates
|
||||||
|
/data/
|
||||||
|
|
||||||
# ---> Python
|
# ---> Python
|
||||||
# Byte-compiled / optimized / DLL files
|
# Byte-compiled / optimized / DLL files
|
||||||
__pycache__/
|
__pycache__/
|
||||||
|
|||||||
@@ -1,3 +1,42 @@
|
|||||||
# Exchange rates
|
# Exchange rates
|
||||||
|
|
||||||
Generated by AppFactory.
|
Služba AppFactory, která pravidelně stahuje kurzy měn z ČNB a českých bank, ukládá je jako JSON a poskytuje je aplikacím přes HTTP.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
| Cesta | Popis |
|
||||||
|
| --- | --- |
|
||||||
|
| `GET /{source_id}` | Kurzy zdroje: `cnb`, `kb`, `csob`, `moneta`, `jt`, `mbank`, `ppf`, `trinity`, `fio`, `creditas`. Tvar odpovědi je pro všechny stejný. Volitelné `?base=EUR` vrátí ceny v jiné měně než CZK. |
|
||||||
|
| `GET /health` | Stav služby |
|
||||||
|
| `GET /docs` | Swagger UI |
|
||||||
|
| `GET /version` | Verze aplikace |
|
||||||
|
|
||||||
|
Veřejně se cesty volají s prefixem, například `https://services.csbot.cz/apps/exchange-rates/cnb`.
|
||||||
|
|
||||||
|
## Spuštění
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
pip install -r requirements.txt
|
||||||
|
uvicorn app.main:app --host 0.0.0.0 --port 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
Testy:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
pip install -r requirements-dev.txt
|
||||||
|
pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
## Proměnné prostředí
|
||||||
|
|
||||||
|
| Název | Výchozí hodnota | Popis |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `ROOT_PATH` | prázdná | Veřejný prefix za reverse proxy |
|
||||||
|
| `DATA_DIR` | `data` | Složka s JSON soubory kurzů |
|
||||||
|
| `REFRESH_INTERVAL_MINUTES` | `60` | Interval stahování v minutách |
|
||||||
|
| `APP_NAME` | `Exchange rates` | Název v dokumentaci API |
|
||||||
|
| `APP_VERSION` | `1.0.0` | Verze v dokumentaci API |
|
||||||
|
|
||||||
|
## Dokumentace
|
||||||
|
|
||||||
|
Je ve složce [documentation](documentation/stav.md).
|
||||||
|
|||||||
@@ -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
|
import asyncio
|
||||||
from fastapi import FastAPI
|
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(
|
app = FastAPI(
|
||||||
title=APP_NAME,
|
title=settings.app_name,
|
||||||
version=APP_VERSION,
|
version=settings.app_version,
|
||||||
root_path=ROOT_PATH
|
root_path=settings.root_path,
|
||||||
|
lifespan=lifespan,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health")
|
@app.get("/health")
|
||||||
def health():
|
def health() -> dict[str, str]:
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/version")
|
@app.get("/version")
|
||||||
def version():
|
def version() -> dict[str, str]:
|
||||||
return {
|
return {
|
||||||
"app": APP_NAME,
|
"app": settings.app_name,
|
||||||
"version": APP_VERSION,
|
"version": settings.app_version,
|
||||||
"language": "python",
|
"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())
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Mapa kódu
|
||||||
|
|
||||||
|
| Soubor | Účel |
|
||||||
|
| --- | --- |
|
||||||
|
| `app/main.py` | FastAPI aplikace, routy, spuštění stahování na pozadí |
|
||||||
|
| `app/config.py` | jediné místo, které čte proměnné prostředí |
|
||||||
|
| `app/models.py` | modely kurzů a odpovědi API |
|
||||||
|
| `app/conversion.py` | přepočet kurzů na jinou základní měnu |
|
||||||
|
| `app/refresh.py` | stažení, zpracování chyb, opakování |
|
||||||
|
| `app/storage.py` | atomický zápis a čtení JSON souborů |
|
||||||
|
| `app/sources/__init__.py` | registr zdrojů, klíč je veřejná cesta |
|
||||||
|
| `app/sources/base.py` | sdílený typ `Source` a pomocné funkce |
|
||||||
|
| `app/sources/<id>.py` | čistá funkce `parse` jednoho zdroje |
|
||||||
|
| `tests/` | testy parserů, API a úložiště |
|
||||||
|
|
||||||
|
## Přidání zdroje
|
||||||
|
|
||||||
|
Přidat `app/sources/<id>.py` s funkcí `parse`, zapsat zdroj do registru, přidat test a řádek do [zdroje.md](zdroje.md).
|
||||||
|
|
||||||
|
## Proč je to takhle
|
||||||
|
|
||||||
|
- Všechny zdroje vrací stejný tvar, aby aplikace při přechodu na jinou banku změnila jen cestu. Převod na tento tvar dělá `make_rate` v `app/sources/base.py`, popis je v [zdroje.md](zdroje.md).
|
||||||
|
- Parsery používají jen standardní knihovnu, stačí jim to a image zůstává malý.
|
||||||
|
- Prohlížeč (Playwright) se nepoužívá, zapojené zdroje ho nepotřebují.
|
||||||
|
- Stahování běží v procesu aplikace, proto musí běžet jedna instance s jedním workerem. Dockerfile to tak dnes spouští.
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Stav projektu
|
||||||
|
|
||||||
|
## Co projekt dělá
|
||||||
|
|
||||||
|
Po startu a pak jednou za `REFRESH_INTERVAL_MINUTES` stáhne kurzy ze všech zdrojů, uloží každý zdroj do `DATA_DIR/<id>.json` a vrací je na `GET /<id>`.
|
||||||
|
|
||||||
|
## Co je hotové a ověřené
|
||||||
|
|
||||||
|
- Zdroje `cnb`, `kb`, `csob`, `moneta`, `jt`, `mbank`, `ppf`, `trinity`, `fio`, `creditas` se stejným tvarem odpovědi, kontrakt a přehled jsou v [zdroje.md](zdroje.md).
|
||||||
|
- Parametr `?base` pro ceny v jiné měně a pole původu hodnot `buy_sell_origin` a `middle_origin`.
|
||||||
|
- Selhání zdroje nechá poslední platný soubor a zaloguje chybu. Ostatní zdroje běží dál.
|
||||||
|
- Příznak `stale` v odpovědi, když je poslední úspěšné stažení starší než tři intervaly.
|
||||||
|
- 31 testů prošlo.
|
||||||
|
- Celá aplikace běžela v testovacím klientovi proti živým zdrojům na Pythonu 3.13: 9 z 10 zdrojů vrátilo data, `/creditas` odmítl server (403).
|
||||||
|
- S `ROOT_PATH=/apps/exchange-rates` odpovídá `/docs` a OpenAPI má správný `servers`.
|
||||||
|
|
||||||
|
## Co není ověřené
|
||||||
|
|
||||||
|
- Docker image a běh na Pythonu 3.12.
|
||||||
|
- Kontroly z `AGENTS.md` na veřejné adrese, hlavně Swagger `Try it out`. Jdou udělat až po nasazení.
|
||||||
|
- Přijetí požadavků z IP adresy serveru. Banky mohou odpovídat jinak než při vývoji.
|
||||||
|
- Podmínky použití webů bank.
|
||||||
|
|
||||||
|
## Známé problémy a omezení
|
||||||
|
|
||||||
|
- Rozsah zatím nesplňuje "všechny banky". Chybějící banky a důvody jsou v [zdroje.md](zdroje.md).
|
||||||
|
- Creditas odpovídá nestabilně, po prvním úspěchu vrací 403.
|
||||||
|
- Disk containeru nemusí být trvalý. Po novém nasazení vrací zdroje 503, dokud neproběhne první stažení.
|
||||||
|
- Parsery závisí na struktuře stránek a nezveřejněných adresách. Změna se projeví chybou v logu a po třech intervalech příznakem `stale`.
|
||||||
|
- FastAPI hlásí parametr `root_path` jako zastaralý. Pořád funguje a verze je připnutá. Starlette také hlásí zastaralé použití `httpx` v testovacím klientovi.
|
||||||
|
|
||||||
|
## Odchylky od zásad
|
||||||
|
|
||||||
|
Projekt drží strukturu ze šablony AppFactory (`app/`, `requirements.txt`). Liší se tím, že nemá `pyproject.toml`, `uv.lock` ani src layout a tranzitivní závislosti nemají pevné verze. Lint a typová kontrola zatím nejsou nastavené.
|
||||||
|
|
||||||
|
## Další krok
|
||||||
|
|
||||||
|
1. Po nasazení kontroly z `AGENTS.md` na veřejné adrese.
|
||||||
|
2. Rozhodnout o Raiffeisenbank, UniCredit, Air Bank, České spořitelně a Revolutu.
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# Zdroje kurzů
|
||||||
|
|
||||||
|
Stav zjištěný 2026-11-04. Účel služby jsou hlavně e-shopy, proto se vrací bezhotovostní kurzy.
|
||||||
|
|
||||||
|
## Jednotný kontrakt
|
||||||
|
|
||||||
|
Všechny zdroje vrací stejný tvar, aplikace mění jen cestu (`/cnb` na `/kb`).
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"source": "kb",
|
||||||
|
"source_name": "Komerční banka",
|
||||||
|
"source_url": "https://www.kb.cz/cs/kurzovni-listek",
|
||||||
|
"valid_date": "2026-11-04",
|
||||||
|
"fetched_at": "2026-11-04T14:00:00Z",
|
||||||
|
"base": "CZK",
|
||||||
|
"stale": false,
|
||||||
|
"rates": [
|
||||||
|
{
|
||||||
|
"currency": "EUR",
|
||||||
|
"buy": 23.3892,
|
||||||
|
"sell": 25.2875,
|
||||||
|
"middle": 24.33835,
|
||||||
|
"buy_sell_origin": "fetched",
|
||||||
|
"middle_origin": "computed"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `buy`, `sell` a `middle` jsou vždy vyplněné, za 1 jednotku měny, v měně `base`. Měny kótované po 100 kusech se přepočítávají.
|
||||||
|
- `buy_sell_origin` a `middle_origin` říkají, jestli je hodnota stažená ze zdroje (`fetched`), nebo dopočítaná touto službou (`computed`). Převod na 1 jednotku se za dopočet nepovažuje.
|
||||||
|
- `rates` jsou seřazené podle kódu měny.
|
||||||
|
- Sada měn se mezi zdroji liší, protože každá instituce vyhlašuje jiné. Aplikace musí počítat s tím, že měna v seznamu nemusí být.
|
||||||
|
- Výchozí `base` je `CZK`, tak kurzy vyhlašují zdroje. `?base=EUR` vrátí kurzy v eurech a seznam pak obsahuje i `CZK`, ne samotné `EUR`. Když zdroj měnu nevyhlašuje, odpověď je 404.
|
||||||
|
- Jiná `base` je dopočet přes CZK, všechny hodnoty mají původ `computed`: `buy = X.buy / base.sell`, `sell = X.sell / base.buy`, `middle = X.middle / base.middle`. Skutečná konverze v bance se může lišit.
|
||||||
|
|
||||||
|
## Zapojené
|
||||||
|
|
||||||
|
| Id | Instituce | Měn | Formát | `buy` a `sell` | `middle` | Živá data |
|
||||||
|
| --- | --- | --- | --- | --- | --- | --- |
|
||||||
|
| `cnb` | Česká národní banka | 30 | oficiální TXT | dopočet, kurz ČNB bez rozpětí | stažený | ano |
|
||||||
|
| `kb` | Komerční banka | 16 | JSON ve stránce | stažené, bezhotovostní | dopočet | ano |
|
||||||
|
| `csob` | ČSOB | 15 | TXT export | stažené, devizy | stažený | ano |
|
||||||
|
| `moneta` | MONETA Money Bank | 12 | JSON endpoint jejich stránky, POST | stažené, bezhotovostní | dopočet | ano |
|
||||||
|
| `jt` | J&T Banka | 19 | JSON ve stránce | stažené, bezhotovostní | dopočet | ano |
|
||||||
|
| `mbank` | mBank | 12 | HTML tabulka | stažené, typ stránka neuvádí | stažený | ano |
|
||||||
|
| `ppf` | PPF banka | 18 | HTML tabulka | stažené, typ stránka neuvádí | stažený | ano |
|
||||||
|
| `trinity` | Trinity Bank | 4 | JSON ve stránce | stažené, bezhotovostní | stažený | ano |
|
||||||
|
| `fio` | Fio banka | 13 | HTML tabulka devizových konverzí | stažené, bezhotovostní | dopočet | ano |
|
||||||
|
| `creditas` | Banka CREDITAS | 13 | HTML tabulka | stažené, devizy, banka je označuje jako orientační | dopočet | ne |
|
||||||
|
|
||||||
|
Záměrně se nepoužívá:
|
||||||
|
|
||||||
|
- Fio sloupec `Kurz ČNB` a Moneta `rateAccounting`, protože nejsou středem cen dané banky.
|
||||||
|
- Moneta `multiplyFactor`. U JPY a HUF uvádí 100, ale ceny jsou už za 1 kus.
|
||||||
|
- Moneta řádky se starším `effectiveDate`, jde o vyřazené měny, například BGN.
|
||||||
|
|
||||||
|
**Creditas je nestabilní.** Stejný požadavek vrátil jednou 200 a potom opakovaně 403. Parser je ověřený jen na uložené kopii stránky z 2026-11-04. Když server odmítne, `/creditas` vrací 503, případně poslední uložená data. Blokace se neobchází.
|
||||||
|
|
||||||
|
## Nezapojené
|
||||||
|
|
||||||
|
| Instituce | Co se zjistilo | Možná cesta |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Revolut | stránka převodníku obsahuje jen jeden pár, `robots.txt` zakazuje `/api/`, nedokumentované API odmítá parametry | Business API `/rate` s tokenem |
|
||||||
|
| Česká spořitelna | kurzy jdou přes `/webapi`, který vyžaduje klíč | vlastní klíč z vývojářského portálu Erste, klíče vložené ve stránce se nepoužívají |
|
||||||
|
| Raiffeisenbank | `backend-data/currenciesAndFunds` vrací na běžný požadavek prázdný objekt | dozkoumat volání z jejich stránky |
|
||||||
|
| UniCredit | POST na `/cwa/getFXRates` vrací prázdnou odpověď nebo 500 podle formátu data | dozkoumat formát data |
|
||||||
|
| Air Bank | kurzy nejsou v HTML, endpoint nenalezen | dozkoumat jejich JavaScript |
|
||||||
|
| Partners Banka | stránka `/kurzy` popisuje kartové platby | žádný lístek nenalezen |
|
||||||
|
| Oberbank | zkoušená adresa vrací 404 | nezkoumáno dál |
|
||||||
|
|
||||||
|
Seznam není úplný výčet bank v ČR. Služba se představuje vlastním User-Agentem a ochrany proti botům neobchází. Moneta, ČSOB a Fio se čtou z adres, které používají jejich vlastní stránky, ale nejsou zveřejněné jako API, takže se mohou bez upozornění změnit. Podmínky použití webů nejsou zkontrolované.
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Záznam změn
|
||||||
|
|
||||||
|
## 2026-11-04
|
||||||
|
|
||||||
|
- Přidáno stahování kurzů a endpoint `GET /{source_id}` pro zdroje `cnb`, `kb`, `jt`, `mbank`, `ppf`, `trinity`, `fio`, `creditas`.
|
||||||
|
- Všechny zdroje vrací jednotný tvar: `buy`, `sell`, `middle` za 1 jednotku měny, vždy vyplněné. Kurzy jsou bezhotovostní.
|
||||||
|
- Přidáno ukládání do JSON, příznak `stale`, testy a dokumentace.
|
||||||
|
- Přidán parametr `?base` pro kurzy v jiné měně než CZK a pole `base` v odpovědi.
|
||||||
|
- Přidána pole `buy_sell_origin` a `middle_origin` s hodnotou `fetched` nebo `computed`.
|
||||||
|
- Přidány zdroje `csob` a `moneta`.
|
||||||
|
- Připnuté verze `fastapi` a `uvicorn` kvůli deterministickému buildu.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
[pytest]
|
||||||
|
testpaths = tests
|
||||||
|
pythonpath = .
|
||||||
|
addopts = --strict-markers
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
pytest==8.3.5
|
||||||
+4
-2
@@ -1,2 +1,4 @@
|
|||||||
fastapi
|
fastapi==0.162.0
|
||||||
uvicorn[standard]
|
uvicorn[standard]==0.54.0
|
||||||
|
httpx==0.28.1
|
||||||
|
tzdata==2025.2
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""TestClient is used without a context manager, so no background download runs."""
|
||||||
|
|
||||||
|
from dataclasses import replace
|
||||||
|
from datetime import UTC, date, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app import main
|
||||||
|
from app.models import Rate, RateSheet
|
||||||
|
from app.storage import read_sheet, write_sheet
|
||||||
|
|
||||||
|
|
||||||
|
def make_sheet(fetched_at: datetime) -> RateSheet:
|
||||||
|
return RateSheet(
|
||||||
|
source="cnb",
|
||||||
|
source_name="Česká národní banka",
|
||||||
|
source_url="https://example.test/rates",
|
||||||
|
fetched_at=fetched_at,
|
||||||
|
valid_date=date(2026, 11, 4),
|
||||||
|
rates=[
|
||||||
|
Rate(
|
||||||
|
currency="USD",
|
||||||
|
buy=21.57,
|
||||||
|
sell=21.57,
|
||||||
|
middle=21.57,
|
||||||
|
buy_sell_origin="computed",
|
||||||
|
middle_origin="fetched",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
|
||||||
|
monkeypatch.setattr(main, "settings", replace(main.settings, data_dir=tmp_path))
|
||||||
|
return TestClient(main.app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_health_answers_without_any_data(client: TestClient) -> None:
|
||||||
|
response = client.get("/health")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_source_is_not_found(client: TestClient) -> None:
|
||||||
|
assert client.get("/nonexistent").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_known_source_without_data_is_unavailable(client: TestClient) -> None:
|
||||||
|
assert client.get("/cnb").status_code == 503
|
||||||
|
|
||||||
|
|
||||||
|
def test_recent_data_is_returned_as_fresh(client: TestClient) -> None:
|
||||||
|
write_sheet(main.settings.data_dir, make_sheet(datetime.now(UTC)))
|
||||||
|
|
||||||
|
response = client.get("/cnb")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
body = response.json()
|
||||||
|
assert body["stale"] is False
|
||||||
|
assert body["rates"] == [
|
||||||
|
{
|
||||||
|
"currency": "USD",
|
||||||
|
"buy": 21.57,
|
||||||
|
"sell": 21.57,
|
||||||
|
"middle": 21.57,
|
||||||
|
"buy_sell_origin": "computed",
|
||||||
|
"middle_origin": "fetched",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
assert body["valid_date"] == "2026-11-04"
|
||||||
|
assert body["base"] == "CZK"
|
||||||
|
|
||||||
|
|
||||||
|
def test_base_parameter_converts_the_response(client: TestClient) -> None:
|
||||||
|
write_sheet(main.settings.data_dir, make_sheet(datetime.now(UTC)))
|
||||||
|
|
||||||
|
body = client.get("/cnb", params={"base": "USD"}).json()
|
||||||
|
|
||||||
|
assert body["base"] == "USD"
|
||||||
|
assert [rate["currency"] for rate in body["rates"]] == ["CZK"]
|
||||||
|
assert body["rates"][0]["middle_origin"] == "computed"
|
||||||
|
|
||||||
|
|
||||||
|
def test_base_currency_missing_in_source_is_not_found(client: TestClient) -> None:
|
||||||
|
write_sheet(main.settings.data_dir, make_sheet(datetime.now(UTC)))
|
||||||
|
|
||||||
|
assert client.get("/cnb", params={"base": "EUR"}).status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_old_data_is_returned_as_stale(client: TestClient) -> None:
|
||||||
|
age = timedelta(minutes=main.settings.refresh_interval_minutes * 3 + 1)
|
||||||
|
write_sheet(main.settings.data_dir, make_sheet(datetime.now(UTC) - age))
|
||||||
|
|
||||||
|
assert client.get("/cnb").json()["stale"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_storage_round_trip_leaves_no_temp_files(tmp_path: Path) -> None:
|
||||||
|
sheet = make_sheet(datetime.now(UTC))
|
||||||
|
|
||||||
|
write_sheet(tmp_path, sheet)
|
||||||
|
|
||||||
|
assert read_sheet(tmp_path, "cnb") == sheet
|
||||||
|
assert [path.name for path in tmp_path.iterdir()] == ["cnb.json"]
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.conversion import BaseCurrencyNotAvailable, rebase_rates
|
||||||
|
from app.models import Rate
|
||||||
|
|
||||||
|
EUR = Rate(
|
||||||
|
currency="EUR",
|
||||||
|
buy=24,
|
||||||
|
sell=25,
|
||||||
|
middle=24.5,
|
||||||
|
buy_sell_origin="fetched",
|
||||||
|
middle_origin="fetched",
|
||||||
|
)
|
||||||
|
USD = Rate(
|
||||||
|
currency="USD",
|
||||||
|
buy=20,
|
||||||
|
sell=22,
|
||||||
|
middle=21,
|
||||||
|
buy_sell_origin="fetched",
|
||||||
|
middle_origin="computed",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_czk_base_returns_published_rates_with_their_origin() -> None:
|
||||||
|
assert rebase_rates([EUR, USD], "CZK") == [EUR, USD]
|
||||||
|
|
||||||
|
|
||||||
|
def test_other_base_applies_spread_of_both_currencies_and_marks_all_as_computed() -> None:
|
||||||
|
assert rebase_rates([EUR, USD], "EUR") == [
|
||||||
|
Rate(
|
||||||
|
currency="CZK",
|
||||||
|
buy=0.04,
|
||||||
|
sell=0.0416666667,
|
||||||
|
middle=0.0408163265,
|
||||||
|
buy_sell_origin="computed",
|
||||||
|
middle_origin="computed",
|
||||||
|
),
|
||||||
|
Rate(
|
||||||
|
currency="USD",
|
||||||
|
buy=0.8,
|
||||||
|
sell=0.9166666667,
|
||||||
|
middle=0.8571428571,
|
||||||
|
buy_sell_origin="computed",
|
||||||
|
middle_origin="computed",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unpublished_base_is_an_error() -> None:
|
||||||
|
with pytest.raises(BaseCurrencyNotAvailable):
|
||||||
|
rebase_rates([USD], "EUR")
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
"""The samples are shortened copies of the real source documents from 2026-11-04."""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.models import Origin, Rate
|
||||||
|
from app.sources import cnb, creditas, csob, fio, jt, kb, mbank, moneta, ppf, trinity
|
||||||
|
|
||||||
|
|
||||||
|
def rate(
|
||||||
|
currency: str,
|
||||||
|
buy: float,
|
||||||
|
sell: float,
|
||||||
|
middle: float,
|
||||||
|
buy_sell_origin: Origin = "fetched",
|
||||||
|
middle_origin: Origin = "fetched",
|
||||||
|
) -> Rate:
|
||||||
|
return Rate(
|
||||||
|
currency=currency,
|
||||||
|
buy=buy,
|
||||||
|
sell=sell,
|
||||||
|
middle=middle,
|
||||||
|
buy_sell_origin=buy_sell_origin,
|
||||||
|
middle_origin=middle_origin,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
CSOB_SAMPLE = """2026-11-04 00:00:00
|
||||||
|
|
||||||
|
;;;;Devizy;;;Valuty
|
||||||
|
Země;Množství;Měna;Změna;Nákup;Prodej;Střed;Nákup;Prodej;Střed
|
||||||
|
EUR;1;EUR;0.1;23,713;24,988;24,351;23,713;24,988;24,351
|
||||||
|
Japonsko;100;JPY;-0.3;13,375;14,094;13,735;0,000;0,000;0,000
|
||||||
|
Nikde;1;XXX;0.0;0,000;0,000;0,000;1,000;2,000;1,500
|
||||||
|
"""
|
||||||
|
|
||||||
|
# effectiveDate 1793746800000 is 2026-11-03T23:00:00Z, 1767913200000 is in January 2026.
|
||||||
|
MONETA_SAMPLE = """{"responseObject":{"exchangeRates":[
|
||||||
|
{"effectiveDate":1793746800000,"multiplyFactor":1,"rateAccounting":24.34,
|
||||||
|
"rateCashBuy":23.49,"rateCashSell":25.2,"rateCashlessBuy":23.431,"rateCashlessSell":25.257,"symbol":"EUR"},
|
||||||
|
{"effectiveDate":1793746800000,"multiplyFactor":100,"rateAccounting":0.13755,
|
||||||
|
"rateCashBuy":0.0,"rateCashSell":0.0,"rateCashlessBuy":0.13245,"rateCashlessSell":0.14277,"symbol":"JPY"},
|
||||||
|
{"effectiveDate":1767913200000,"multiplyFactor":1,"rateAccounting":12.396,
|
||||||
|
"rateCashBuy":0.0,"rateCashSell":0.0,"rateCashlessBuy":11.942,"rateCashlessSell":12.872,"symbol":"BGN"}
|
||||||
|
]},"status":"OK"}"""
|
||||||
|
|
||||||
|
CNB_SAMPLE = """04.11.2026 #212
|
||||||
|
země|měna|množství|kód|kurz
|
||||||
|
Turecko|lira|100|TRY|43,120
|
||||||
|
USA|dolar|1|USD|21,570
|
||||||
|
"""
|
||||||
|
|
||||||
|
KB_SAMPLE = """<script>WIDGETS_CONFIG={"KBExchangeRatesList_526d":{
|
||||||
|
"api": "/api/exchangerate/list",
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"curencyIso": "EUR",
|
||||||
|
"currencyUnit": 1,
|
||||||
|
"cashSell": 25.433600,
|
||||||
|
"cashBuy": 23.243100,
|
||||||
|
"nonCashBuy": 23.389200,
|
||||||
|
"middleCNB": 24.340000,
|
||||||
|
"nonCashSell": 25.287500,
|
||||||
|
"validDate": "2026-11-04T07:00:00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"curencyIso": "JPY",
|
||||||
|
"currencyUnit": 100,
|
||||||
|
"cashSell": 0,
|
||||||
|
"cashBuy": 0,
|
||||||
|
"nonCashBuy": 13.5,
|
||||||
|
"nonCashSell": 14.5,
|
||||||
|
"validDate": "2026-11-04T07:00:00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"curencyIso": "RSD",
|
||||||
|
"currencyUnit": 100,
|
||||||
|
"cashSell": 20,
|
||||||
|
"cashBuy": 18,
|
||||||
|
"nonCashBuy": 0,
|
||||||
|
"nonCashSell": 0,
|
||||||
|
"validDate": "2026-11-04T07:00:00"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},"Other":{"items": []}};</script>"""
|
||||||
|
|
||||||
|
JT_ITEM = (
|
||||||
|
r'{\"currency\":\"EUR\",\"unitAmount\":1,\"nonCashBuy\":23.8218,\"nonCashSell\":24.7942,'
|
||||||
|
r'\"ecbDifference\":0.021411,\"cashBuy\":23.7003,\"cashSell\":24.9157,'
|
||||||
|
r'\"date\":\"2026-11-04T14:11:03+01:00\"}'
|
||||||
|
)
|
||||||
|
JT_SAMPLE = rf'<script>self.__next_f.push([1,"\"value\":[{JT_ITEM},{JT_ITEM}]"])</script>'
|
||||||
|
|
||||||
|
MBANK_SAMPLE = """<p class="title">
|
||||||
|
Kurzovní lístek platný k datu 04-11-2026 08:05:00</p>
|
||||||
|
<table><tr >
|
||||||
|
<td class="first">EURO</td>
|
||||||
|
<td class='unit'><div>EUR<span class="arrow up"></span></div></td>
|
||||||
|
<td>Eurozóna</td>
|
||||||
|
<td>1</td>
|
||||||
|
<td>23,6086</td>
|
||||||
|
<td>25,0690</td>
|
||||||
|
<td>24,3388</td>
|
||||||
|
<td class="last">1,4604 (6,2%)</td>
|
||||||
|
</tr></table>"""
|
||||||
|
|
||||||
|
PPF_SAMPLE = """<tr class="down" data-id="265877" data-seq="424"
|
||||||
|
data-released="2026-11-04 14:01:00">
|
||||||
|
<td class="currency"><span class="try">Turecko</span></td>
|
||||||
|
<td class="md-show" style="font-weight: 600;">
|
||||||
|
TRY
|
||||||
|
</td>
|
||||||
|
<td class="md-show" style="text-align: center;">
|
||||||
|
100
|
||||||
|
</td>
|
||||||
|
<td style="width: 15%; text-align: right;">
|
||||||
|
41.959
|
||||||
|
</td>
|
||||||
|
<td class="md-show" style="width: 15%; text-align: right;">
|
||||||
|
44.333
|
||||||
|
</td>
|
||||||
|
<td class="md-show" style="text-align: right; width: 15%;">
|
||||||
|
43.146
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table></div>
|
||||||
|
<div data-tab-content="t2" style="display: none;">
|
||||||
|
<tr class="down" data-id="1" data-seq="1"
|
||||||
|
data-released="2026-11-04 14:01:00">
|
||||||
|
<td class="md-show" style="font-weight: 600;">
|
||||||
|
USD
|
||||||
|
</td>
|
||||||
|
<td>1</td><td>1.1</td><td>1.2</td><td>1.3</td>
|
||||||
|
</tr>"""
|
||||||
|
|
||||||
|
|
||||||
|
TRINITY_SAMPLE = (
|
||||||
|
r'self.__next_f.push([1,"5:{\"rows\":[{\"Id\":\"4059fe86\",\"CurrencyCode\":\"EUR\",'
|
||||||
|
r'\"PaymentType\":\"CASHLESS\",\"CurrencyUnit\":\"1\",\"RateBuy\":23.61,\"RateSell\":25.07,'
|
||||||
|
r'\"RateAverage\":24.34,\"RateBuyEcbDiff\":null,\"RateSellEcbDiff\":null,'
|
||||||
|
r'\"ValidFrom\":\"$D2026-11-03T23:00:00.000Z\",\"ValidTo\":null}]}"])'
|
||||||
|
)
|
||||||
|
|
||||||
|
FIO_SAMPLE = """<input size="10" name="keDni_den" class="text datepicker" type="text" value="04.11.2026">
|
||||||
|
<tr class="even">
|
||||||
|
<td class="col1">EUR</td>
|
||||||
|
|
||||||
|
<td class="tleft">
|
||||||
|
EMU
|
||||||
|
</td>
|
||||||
|
|
||||||
|
<td class="tright">1</td>
|
||||||
|
<td class="tright">23,62148</td>
|
||||||
|
<td class="tright">25,05752</td>
|
||||||
|
<td class="tright">24,31000</td>
|
||||||
|
</tr>"""
|
||||||
|
|
||||||
|
CREDITAS_ROW = """<tr class="entry entry-row" data-entries = "entry">
|
||||||
|
<td><div class="entry-cell__value">
|
||||||
|
<a href = "https://www.creditas.cz/historie-kurzu?history={currency}">{currency}</a>
|
||||||
|
</div></td>
|
||||||
|
<td><div class="entry-cell__name">Jednotka</div>
|
||||||
|
<div class="entry-cell__value">
|
||||||
|
1
|
||||||
|
</div></td>
|
||||||
|
<td><div class="entry-cell__name">Nakupujeme v CZK</div>
|
||||||
|
<div class="entry-cell__value">
|
||||||
|
{buy}
|
||||||
|
</div></td>
|
||||||
|
<td><div class="entry-cell__name">Prodáváme v CZK</div>
|
||||||
|
<div class="entry-cell__value">
|
||||||
|
<span class="arrow arrow--up"></span>24,827 CZK
|
||||||
|
</div></td>
|
||||||
|
</tr>"""
|
||||||
|
CREDITAS_SAMPLE = (
|
||||||
|
"<p><strong>Kurzy platné k 4. 11. 2026</strong></p>"
|
||||||
|
+ CREDITAS_ROW.format(currency="EUR", buy='<span class="arrow arrow--up"></span>23,853 CZK')
|
||||||
|
+ CREDITAS_ROW.format(currency="USD", buy="-")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_trinity_converts_utc_validity_to_prague_date() -> None:
|
||||||
|
parsed = trinity.parse(TRINITY_SAMPLE)
|
||||||
|
|
||||||
|
assert parsed.valid_date == date(2026, 11, 4)
|
||||||
|
assert parsed.rates == [rate("EUR", 23.61, 25.07, 24.34)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_fio_computes_middle_instead_of_using_cnb_column() -> None:
|
||||||
|
parsed = fio.parse(FIO_SAMPLE)
|
||||||
|
|
||||||
|
assert parsed.valid_date == date(2026, 11, 4)
|
||||||
|
assert parsed.rates == [rate("EUR", 23.62148, 25.05752, 24.3395, middle_origin="computed")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_creditas_skips_row_without_price() -> None:
|
||||||
|
parsed = creditas.parse(CREDITAS_SAMPLE)
|
||||||
|
|
||||||
|
assert parsed.valid_date == date(2026, 11, 4)
|
||||||
|
assert parsed.rates == [rate("EUR", 23.853, 24.827, 24.34, middle_origin="computed")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_csob_uses_noncash_columns_and_converts_to_one_unit() -> None:
|
||||||
|
parsed = csob.parse(CSOB_SAMPLE)
|
||||||
|
|
||||||
|
assert parsed.valid_date == date(2026, 11, 4)
|
||||||
|
assert parsed.rates == [
|
||||||
|
rate("EUR", 23.713, 24.988, 24.351),
|
||||||
|
rate("JPY", 0.13375, 0.14094, 0.13735),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_moneta_ignores_multiply_factor_and_discontinued_currency() -> None:
|
||||||
|
parsed = moneta.parse(MONETA_SAMPLE)
|
||||||
|
|
||||||
|
assert parsed.valid_date == date(2026, 11, 4)
|
||||||
|
assert parsed.rates == [
|
||||||
|
rate("EUR", 23.431, 25.257, 24.344, middle_origin="computed"),
|
||||||
|
rate("JPY", 0.13245, 0.14277, 0.13761, middle_origin="computed"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_cnb_fills_all_prices_with_reference_rate_per_one_unit() -> None:
|
||||||
|
parsed = cnb.parse(CNB_SAMPLE)
|
||||||
|
|
||||||
|
assert parsed.valid_date == date(2026, 11, 4)
|
||||||
|
assert parsed.rates == [
|
||||||
|
rate("TRY", 0.4312, 0.4312, 0.4312, buy_sell_origin="computed"),
|
||||||
|
rate("USD", 21.57, 21.57, 21.57, buy_sell_origin="computed"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_kb_uses_noncash_rates_and_computes_middle() -> None:
|
||||||
|
parsed = kb.parse(KB_SAMPLE)
|
||||||
|
|
||||||
|
assert parsed.valid_date == date(2026, 11, 4)
|
||||||
|
assert parsed.rates == [
|
||||||
|
rate("EUR", 23.3892, 25.2875, 24.33835, middle_origin="computed"),
|
||||||
|
rate("JPY", 0.135, 0.145, 0.14, middle_origin="computed"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_jt_reads_escaped_json_without_duplicates() -> None:
|
||||||
|
parsed = jt.parse(JT_SAMPLE)
|
||||||
|
|
||||||
|
assert parsed.valid_date == date(2026, 11, 4)
|
||||||
|
assert parsed.rates == [rate("EUR", 23.8218, 24.7942, 24.308, middle_origin="computed")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_mbank_reads_published_middle() -> None:
|
||||||
|
parsed = mbank.parse(MBANK_SAMPLE)
|
||||||
|
|
||||||
|
assert parsed.valid_date == date(2026, 11, 4)
|
||||||
|
assert parsed.rates == [rate("EUR", 23.6086, 25.069, 24.3388)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_ppf_converts_to_one_unit_and_ignores_card_transaction_tab() -> None:
|
||||||
|
parsed = ppf.parse(PPF_SAMPLE)
|
||||||
|
|
||||||
|
assert parsed.valid_date == date(2026, 11, 4)
|
||||||
|
assert parsed.rates == [rate("TRY", 0.41959, 0.44333, 0.43146)]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"parser",
|
||||||
|
[
|
||||||
|
cnb.parse,
|
||||||
|
kb.parse,
|
||||||
|
jt.parse,
|
||||||
|
mbank.parse,
|
||||||
|
ppf.parse,
|
||||||
|
trinity.parse,
|
||||||
|
fio.parse,
|
||||||
|
creditas.parse,
|
||||||
|
csob.parse,
|
||||||
|
moneta.parse,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_changed_page_format_is_an_error(parser) -> None:
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
parser("<html>Stránka se změnila</html>")
|
||||||
Reference in New Issue
Block a user