From 74895720d6cb59394012978c1dda9ee7c36ba954 Mon Sep 17 00:00:00 2001 From: Jon Michael Aanes Date: Sun, 1 Sep 2024 17:39:04 +0200 Subject: [PATCH] Amount prefix --- fin_defs/__init__.py | 16 +++++++++++++++- test/test_asset_amount.py | 8 ++++++++ test/test_data.py | 4 +--- test/test_ids.py | 3 --- 4 files changed, 24 insertions(+), 7 deletions(-) create mode 100644 test/test_asset_amount.py diff --git a/fin_defs/__init__.py b/fin_defs/__init__.py index 8321282..b57ed23 100644 --- a/fin_defs/__init__.py +++ b/fin_defs/__init__.py @@ -258,6 +258,7 @@ Commodity.COFFEE = Commodity('COFFEE') DKK = FiatCurrency('DKK') USD = FiatCurrency('USD') EUR = FiatCurrency('EUR') +GBP = FiatCurrency('GBP') BTC = CryptoCurrency('BTC', coingecko_id='bitcoin') MPC = CryptoCurrency('MPC', coingecko_id='partisia-blockchain') SPX = Index('SPX') @@ -316,6 +317,13 @@ WELL_KNOWN_SYMBOLS = ( | {'SPX500': SPX, 'SP500': SPX, 'Nasdaq 100': NDX} ) +ASSET_PREFIX: dict[Asset, str] = { + USD: '$', + EUR: '€', + GBP: '£', + BTC: '₿', +} + NYSE = StockExchange( name='New York Stock Exchange', mic='XNYS', @@ -430,8 +438,14 @@ class AssetAmount: amount: Decimal def __str__(self): + return self.human_readable_str() + + def human_readable_str(self): specificity = '2' if self.amount >= 0.10 else '3' - return ('{:.' + specificity + 'f} {}').format(self.amount, self.asset) + prefix = ASSET_PREFIX.get(self.asset, '') + return ('{}{:.' + specificity + 'f} {}').format( + prefix, self.amount, self.asset.raw_short_name() + ) def __mul__(self, other: Decimal): if not isinstance(other, Decimal): diff --git a/test/test_asset_amount.py b/test/test_asset_amount.py new file mode 100644 index 0000000..28109f8 --- /dev/null +++ b/test/test_asset_amount.py @@ -0,0 +1,8 @@ +from decimal import Decimal + +import fin_defs + + +def test_str(): + amount = fin_defs.AssetAmount(fin_defs.USD, Decimal(10)) + assert str(amount) == '$10.00 USD' diff --git a/test/test_data.py b/test/test_data.py index 055c933..7545960 100644 --- a/test/test_data.py +++ b/test/test_data.py @@ -7,10 +7,8 @@ BAD_TICKERS = ['TEST123', '123', 'TEST.EUR', 'TEST:EUR', 'EUR:TEST'] @pytest.mark.parametrize('ticker', BAD_TICKERS) def test_bad_tickers(ticker): - try: + with pytest.raises(Exception) as e: fin_defs.Stock(ticker) - except Exception as e: - assert e @pytest.mark.parametrize('ticker', BAD_TICKERS) diff --git a/test/test_ids.py b/test/test_ids.py index a71c807..f28ca12 100644 --- a/test/test_ids.py +++ b/test/test_ids.py @@ -8,9 +8,6 @@ def test_to_from_string_id(asset: fin_defs.Asset): assert fin_defs.Asset.from_string_id(asset.to_string_id()) == asset -import fin_defs - - @pytest.mark.parametrize('asset', fin_defs.WELL_KNOWN_SYMBOLS.values()) def test_to_from_polygon_id(asset: fin_defs.Asset): assert fin_defs.Asset.from_polygon_id(asset.to_polygon_id()) == asset