Skip to content

Commit

Permalink
Merge pull request #44 from macxred/feat/implement-price-price-history
Browse files Browse the repository at this point in the history
Feat: create get_exchange_rate() method and tests for it
  • Loading branch information
lasuk authored Sep 6, 2024
2 parents 15fc100 + 54fd0cd commit 5088892
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
26 changes: 26 additions & 0 deletions cashctrl_api/client.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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()
21 changes: 21 additions & 0 deletions tests/test_currencies.py
Original file line number Diff line number Diff line change
@@ -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."

0 comments on commit 5088892

Please sign in to comment.