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:
JiriUhlir
2026-11-04 15:09:24 +01:00
parent 4e1ac94210
commit 4c81c5bb34
32 changed files with 1446 additions and 16 deletions
+74
View File
@@ -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={},
),
)
}
+49
View File
@@ -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",
)
+43
View File
@@ -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)
+40
View File
@@ -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)
+33
View File
@@ -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)
+35
View File
@@ -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)
+37
View File
@@ -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)
+40
View File
@@ -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)
+36
View File
@@ -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)
+35
View File
@@ -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)
+40
View File
@@ -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)
+37
View File
@@ -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)