from dataclasses import dataclass import datetime import json import os from typing import Dict import requests class PriceException(Exception): pass url_energy = "https://www.ote-cr.cz/cs/kratkodobe-trhy/elektrina/denni-trh/@@chart-data?report_date={}" url_currency = "https://data.kurzy.cz/json/meny/b[1].json" url_currency2 = "https://www.cnb.cz/cs/financni-trhy/devizovy-trh/kurzy-devizoveho-trhu/kurzy-devizoveho-trhu/denni_kurz.txt?date={day}.{month}.{year}" CACHE_PATH = "./cache" def get_energy_prices(d: datetime.date=datetime.date.today(), no_cache:bool=False) -> Dict[str, float]: """ """ date_str = d.strftime("%Y-%m-%d") hours = {} cache_file = os.path.join(CACHE_PATH, "hours-{}.json".format(date_str)) if os.path.isfile(cache_file) and not no_cache: with open(cache_file, "r") as f: hours = json.load(f) if not hours or no_cache: r = requests.get(url_energy.format(date_str)) for raw in r.json()["data"]["dataLine"][1]["point"]: hours[str(int(raw["x"])-1)] = raw["y"] with open(cache_file, "w") as f: f.write(json.dumps(hours)) return hours #def get_currency_ratio(currency): # r = requests.get(url_currency) # return r.json()["kurzy"][currency]["dev_stred"] def get_eur_czk_ratio(d: datetime.date=datetime.date.today(), no_cache:bool=False) -> float: ratio = 0 cache_file = os.path.join(CACHE_PATH, "eur-czk-{}.json".format(d.strftime("%Y-%m-%d"))) if os.path.isfile(cache_file): with open(cache_file, "r") as f: ratio = float(f.read()) if not ratio or no_cache: url = url_currency2.format(day=d.day,month=d.month,year=d.year) r = requests.get(url) for row in [x.split("|") for x in r.text.split("\n") if x and "|" in x]: if row[3] == "EUR": ratio = float(row[4].replace(",", ".")) break if not ratio: raise PriceException("EUR not found") with open(cache_file, "w") as f: f.write(str(ratio)) return ratio