From 66ca6c0744cae6af0f3a3a39e199bb0e874a1e06 Mon Sep 17 00:00:00 2001 From: Edward Betts Date: Thu, 18 Apr 2024 22:26:04 +0100 Subject: [PATCH] Get more exchange rates --- agenda/fx.py | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ update.py | 5 ++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/agenda/fx.py b/agenda/fx.py index 1d48e49..b96d0c3 100644 --- a/agenda/fx.py +++ b/agenda/fx.py @@ -42,3 +42,52 @@ async def get_gbpusd(config: flask.config.Config) -> Decimal: data = json.loads(r.text, parse_float=Decimal) return typing.cast(Decimal, 1 / data["quotes"]["USDGBP"]) + + +def get_exchange_rates(config) -> dict[str, Decimal]: + """Get current values of exchange rates for a list of currencies against GBP.""" + currencies = config.CURRENCIES + access_key = config.EXCHANGERATE_ACCESS_KEY + data_dir = config.DATA_DIR + + now = datetime.now() + now_str = now.strftime("%Y-%m-%d_%H:%M") + fx_dir = os.path.join(data_dir, "fx") + os.makedirs(fx_dir, exist_ok=True) # Ensure the directory exists + + currency_string = ",".join(sorted(currencies)) + file_suffix = f"{currency_string}_to_GBP.json" + existing_data = os.listdir(fx_dir) + existing_files = [f for f in existing_data if f.endswith(file_suffix)] + + if existing_files: + recent_filename = max(existing_files) + recent = datetime.strptime(recent_filename[:16], "%Y-%m-%d_%H:%M") + delta = now - recent + + if delta < timedelta(hours=6): + full_path = os.path.join(fx_dir, recent_filename) + with open(full_path) as file: + data = json.load(file, parse_float=Decimal) + return { + cur: Decimal(data["quotes"][f"GBP{cur}"]) + for cur in currencies + if f"GBP{cur}" in data["quotes"] + } + + url = "http://api.exchangerate.host/live" + params = {"currencies": currency_string, "source": "GBP", "access_key": access_key} + + filename = f"{now_str}_{file_suffix}" + with httpx.Client() as client: + response = client.get(url, params=params) + + with open(os.path.join(fx_dir, filename), "w") as file: + file.write(response.text) + + data = json.loads(response.text, parse_float=Decimal) + return { + cur: Decimal(data["quotes"][f"GBP{cur}"]) + for cur in currencies + if f"GBP{cur}" in data["quotes"] + } diff --git a/update.py b/update.py index 24c0976..c322387 100755 --- a/update.py +++ b/update.py @@ -12,13 +12,13 @@ from time import time import requests +import agenda.fx import agenda.thespacedevs import agenda.types import agenda.uk_holiday import agenda.waste_schedule from agenda import gwr - config = __import__("config.default", fromlist=[""]) @@ -133,6 +133,9 @@ def main() -> None: update_gwr_advance_ticket_date() update_gandi() + if hour % 12 == 0: + agenda.fx.get_exchange_rates(config) + update_thespacedevs()