From 54fd0cd97c855b212a52857c878f3a6d4c3d052b Mon Sep 17 00:00:00 2001 From: Alex the wizard Date: Tue, 13 Aug 2024 16:12:40 +0300 Subject: [PATCH] feat: create get_exchange_rate() method and tests for it --- cashctrl_api/client.py | 26 ++++++++++++++++++++++++++ tests/test_currencies.py | 21 +++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 tests/test_currencies.py diff --git a/cashctrl_api/client.py b/cashctrl_api/client.py index 11cf4a8..dd9e8b6 100644 --- a/cashctrl_api/client.py +++ b/cashctrl_api/client.py @@ -1,5 +1,6 @@ """Module to interact with the REST API of the CashCtrl accounting service.""" +from datetime import datetime import json from mimetypes import guess_type import os @@ -557,3 +558,28 @@ def list_journal_entries(self) -> pd.DataFrame: journal_entries = pd.DataFrame(response["data"]) df = enforce_dtypes(journal_entries, JOURNAL_ENTRIES) return df.sort_values("dateAdded") + + # ---------------------------------------------------------------------- + # Price + + def get_exchange_rate( + self, + from_currency: str, + to_currency: str, + date: datetime.date = None + ) -> float: + """ + Retrieves the exchange rate for a given currency pair on a specific date. + + Args: + from_currency (str): The currency code to convert from. + to_currency (str): The currency code to convert to. + date (datetime.date, optional): The date for which the exchange rate + is requested. Defaults to None, which retrieves the latest rate. + + Returns: + float: The exchange rate for the given currency pair. + """ + params = {"from": from_currency, "to": to_currency, "date": date} + response = self.request("GET", "currency/exchangerate", params=params) + return response.json() diff --git a/tests/test_currencies.py b/tests/test_currencies.py new file mode 100644 index 0000000..dc999e6 --- /dev/null +++ b/tests/test_currencies.py @@ -0,0 +1,21 @@ +"""Unit tests for currencies.""" + +from cashctrl_api import CashCtrlClient +import pytest + + +def test_exchange_rate(): + cc_client = CashCtrlClient() + + exchange_rate = cc_client.get_exchange_rate("USD", "CHF") + assert isinstance(exchange_rate, float), "`exchange_rate` is not a Float." + + # Exchange rate for invalid currency should raise an error + with pytest.raises(Exception): + cc_client.get_exchange_rate("USD", "INVALID") + + exchange_rate = cc_client.get_exchange_rate("USD", "USD") + assert exchange_rate == 1, "Exchange rate for the same currency should be 1." + + exchange_rate = cc_client.get_exchange_rate("USD", "CHF", '2020-01-15') + assert exchange_rate == 0.967145, "Exchange rate for USD-CHF on 2020-01-15 should be 0.967145."