Dalsi banky, prehled ve Swaggeru, /status a prazdne promenne

- zdroje rb, unicredit a air
- nahore ve Swaggeru prehled nabizenych a nenabizenych bank s duvody
- GET /status s prehledem vypadku stahovani u jednotlivych bank
- prazdna promenna prostredi znamena vychozi hodnotu
- popis stahovani v documentation/stahovani.md
This commit is contained in:
JiriUhlir
2026-11-04 15:33:21 +01:00
parent 4c81c5bb34
commit e39f52f027
21 changed files with 835 additions and 82 deletions
+113 -38
View File
@@ -1,8 +1,26 @@
"""Registry of the supported sources. The key is the public URL segment."""
"""Registry of the sources. The key of SOURCES is the public URL segment."""
from app.sources import cnb, creditas, csob, fio, jt, kb, mbank, moneta, ppf, trinity
from dataclasses import dataclass
from app.sources import (
air,
cnb,
creditas,
csob,
fio,
jt,
kb,
mbank,
moneta,
ppf,
rb,
trinity,
unicredit,
)
from app.sources.base import Source
UNSPECIFIED_RATE_NOTE = "Stránka banky neuvádí, jestli jde o bezhotovostní kurz."
SOURCES: dict[str, Source] = {
source.id: source
for source in (
@@ -14,6 +32,7 @@ SOURCES: dict[str, Source] = {
"kurzy-devizoveho-trhu/denni_kurz.txt"
),
parse=cnb.parse,
note="Vyhlašuje jeden kurz, takže buy, sell a middle jsou stejné.",
),
Source(
id="kb",
@@ -21,42 +40,6 @@ SOURCES: dict[str, Source] = {
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",
@@ -70,5 +53,97 @@ SOURCES: dict[str, Source] = {
parse=moneta.parse,
request_json={},
),
Source(
id="rb",
name="Raiffeisenbank",
url="https://www.rb.cz/frontend-controller/backend-data/currency/listActual",
parse=rb.parse,
),
Source(
id="unicredit",
name="UniCredit Bank",
url=unicredit.URL,
parse=unicredit.parse,
fetch=unicredit.fetch,
),
Source(
id="air",
name="Air Bank",
url="https://www.airbank.cz/graphql",
parse=air.parse,
request_json={"query": air.QUERY},
note="Datum platnosti je datum poslední revize lístku, může být z předchozího dne.",
),
Source(
id="fio",
name="Fio banka",
url="https://www.fio.cz/akcie-investice/dalsi-sluzby-fio/devizove-konverze",
parse=fio.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,
note=UNSPECIFIED_RATE_NOTE,
),
Source(
id="ppf",
name="PPF banka",
url="https://www.ppfbanka.cz/cs/kurzovni-listek",
parse=ppf.parse,
note=UNSPECIFIED_RATE_NOTE,
),
Source(
id="trinity",
name="Trinity Bank",
url="https://public.trinitybank.cz/cs/kurzovni-listek",
parse=trinity.parse,
),
Source(
id="creditas",
name="Banka CREDITAS",
url="https://www.creditas.cz/kurzovni-listek",
parse=creditas.parse,
note=(
"Nespolehlivé: server banky stahování často odmítá (403), odpověď pak může být 503. "
"Banka kurzy označuje jako orientační."
),
),
)
}
@dataclass(frozen=True)
class UnavailableSource:
name: str
reason: str
UNAVAILABLE_SOURCES: tuple[UnavailableSource, ...] = (
UnavailableSource(
name="Česká spořitelna",
reason="Kurzy jsou dostupné jen přes API s klíčem. Vlastní klíč zatím nemáme.",
),
UnavailableSource(
name="Revolut",
reason=(
"Nemá veřejný kurzovní lístek a web strojový přístup k API zakazuje. "
"Oficiální cesta je Business API s tokenem, který zatím nemáme."
),
),
UnavailableSource(
name="Partners Banka",
reason="Kurzovní lístek jsme nenašli, web popisuje jen kartové platby kurzem ECB.",
),
UnavailableSource(
name="Oberbank",
reason="Veřejný kurzovní lístek jsme na webu nenašli.",
),
)
+32
View File
@@ -0,0 +1,32 @@
"""Air Bank: the GraphQL endpoint used by the bank's own rate list page."""
import json
from datetime import date
from app.models import ParsedRates
from app.sources.base import make_rate
QUERY = "{ exchangeRates { rates { code buy sell quantity lastRevisionDate } } }"
ISO_DATE_LENGTH = 10
def parse(document: str) -> ParsedRates:
items = json.loads(document)["data"]["exchangeRates"]["rates"]
# The source has no validity date, only a revision date that some currencies leave empty.
# The list is valid since its latest revision, which can be the previous day.
revisions = [item["lastRevisionDate"] for item in items if item["lastRevisionDate"]]
if not revisions:
raise ValueError("Air Bank revision date not found")
rates = [
make_rate(
currency=item["code"],
amount=item["quantity"],
buy=item["buy"],
sell=item["sell"],
)
for item in items
if item["buy"] and item["sell"]
]
return ParsedRates(valid_date=date.fromisoformat(max(revisions)[:ISO_DATE_LENGTH]), rates=rates)
+7 -1
View File
@@ -1,10 +1,12 @@
"""Shared building blocks of the source parsers."""
from collections.abc import Callable
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any
from zoneinfo import ZoneInfo
import httpx
from app.models import Origin, ParsedRates, Rate
# Dividing by the quoted amount (for example 100 JPY) must not lose precision
@@ -23,6 +25,10 @@ class Source:
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
# When set, replaces the single request, for sources that need several of them.
fetch: Callable[[httpx.AsyncClient], Awaitable[str]] | None = None
# Shown in the API documentation when consumers should know something about the source.
note: str | None = None
def parse_comma_decimal(value: str) -> float:
+31
View File
@@ -0,0 +1,31 @@
"""Raiffeisenbank: 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
def parse(document: str) -> ParsedRates:
# The bank publishes several lists a day, only the last one is currently valid.
rate_lists = json.loads(document)["exchangeRateLists"]
current = next((item for item in rate_lists if item["lastRates"]), None)
if current is None:
raise ValueError("Raiffeisenbank current rate list not found")
# exchangeRateBuy and exchangeRateSell are non-cash, the cash rates have a Cash suffix.
rates = [
make_rate(
currency=item["currencyFrom"],
amount=item["unitsFrom"],
buy=item["exchangeRateBuy"],
sell=item["exchangeRateSell"],
middle=item["exchangeRateCenter"],
)
for item in current["exchangeRates"]
if item["exchangeRateBuy"] and item["exchangeRateSell"]
]
valid_from = datetime.fromisoformat(current["effectiveDateFrom"])
return ParsedRates(valid_date=valid_from.astimezone(PRAGUE_ZONE).date(), rates=rates)
+88
View File
@@ -0,0 +1,88 @@
"""UniCredit Bank: the JSON endpoint used by the bank's own page, one request per currency."""
import json
from datetime import datetime
import httpx
from app.models import ParsedRates
from app.sources.base import PRAGUE_ZONE, make_rate
URL = "https://www.unicreditbank.cz/cwa/GetExchangeRates"
# Headers and date format are what the bank's page sends, the endpoint rejects anything else.
REQUEST_HEADERS = {
"EntityCode": "CZ",
"UserID": "",
"Language": "CS",
"SourceSystem": "PWS",
"Product": "PWS",
}
REQUEST_DATE_FORMAT = "%Y%m%dT%H:%M:%S.000%z"
# Currencies listed on the bank's page with the units the prices refer to. The API does not
# return the units, its page keeps them in the jsonCurrencyAmounts variable.
CURRENCY_UNITS = {
"AUD": 1,
"BAM": 1,
"CAD": 1,
"CHF": 1,
"CNY": 1,
"DKK": 1,
"EUR": 1,
"GBP": 1,
"HKD": 1,
"HUF": 100,
"JPY": 100,
"NOK": 1,
"NZD": 1,
"PLN": 1,
"RON": 1,
"RSD": 100,
"SEK": 1,
"SGD": 1,
"TRY": 1,
"USD": 1,
}
async def fetch(client: httpx.AsyncClient) -> str:
"""Any failed currency fails the source, so a partial list never replaces a complete one."""
request_date = datetime.now(PRAGUE_ZONE).strftime(REQUEST_DATE_FORMAT)
items = []
for currency in CURRENCY_UNITS:
response = await client.post(
URL,
headers=REQUEST_HEADERS,
json={
"Currency": currency,
"DateFrom": request_date,
"DateTo": request_date,
"multiplier": "0",
},
)
response.raise_for_status()
items += response.json()
return json.dumps(items)
def parse(document: str) -> ParsedRates:
items = json.loads(document)
if not items:
raise ValueError("UniCredit rate list is empty")
# "Cards" is the non-cash rate, the page shows it in the Devizy tab. "Cash" is in Valuty.
# MiddleRate is the CNB rate, so the middle of the non-cash prices is used instead.
rates = [
make_rate(
currency=item["CurrencyCode"],
amount=CURRENCY_UNITS[item["CurrencyCode"]],
buy=item["CardsPurchaseRate"],
sell=item["CardsSaleRate"],
middle=item["CardsMiddleRate"],
)
for item in items
if item["CardsPurchaseRate"] and item["CardsSaleRate"]
]
latest_update = max(item["ExchangeRateUpdatedTimestamp"] for item in items)
valid_from = datetime.fromisoformat(latest_update)
return ParsedRates(valid_date=valid_from.astimezone(PRAGUE_ZONE).date(), rates=rates)