Get more exchange rates
This commit is contained in:
parent
b0381db3b5
commit
66ca6c0744
49
agenda/fx.py
49
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"]
|
||||
}
|
||||
|
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
Loading…
Reference in a new issue