data-xexe/xexe/rate_writing.py
2024-06-11 23:07:15 +02:00

38 lines
1.2 KiB
Python

import csv
import datetime
import pathlib
from abc import ABC, abstractmethod
from xexe.exchange_rates import ExchangeRates
class RateWriter(ABC):
@abstractmethod
def write_rates(self, rates: ExchangeRates) -> None:
pass
class CSVRateWriter(RateWriter):
def __init__(self, output_file_path: pathlib.Path) -> None:
super().__init__()
self.output_file_path = output_file_path
def write_rates(self, rates: ExchangeRates) -> None:
with open(self.output_file_path, mode="w") as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(
["from_currency", "to_currency", "rate", "rate_date", "exported_at"]
)
exported_at = datetime.datetime.now()
for rate in rates._rate_index.values():
csv_writer.writerow(
[
rate.from_currency.value,
rate.to_currency.value,
rate.rate.amount,
rate.rate_date.strftime("%Y-%m-%d"),
exported_at.isoformat(timespec="seconds"),
]
)