Files
@ fb2114896d9d
Branch filter:
Location: NPO-Accounting/oxrlib/oxrlib/commands/historical.py
fb2114896d9d
6.3 KiB
text/x-python
historical: Normalize class instantiation for formatters.
This will make them easier to extend with different price/cost rates,
and to add a Beancount formatter.
This will make them easier to extend with different price/cost rates,
and to add a Beancount formatter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | import decimal
import itertools
import operator
import babel.numbers
from .. import rate as oxrrate
try:
import enum
except ImportError:
import enum34 as enum
class Formatter:
def __init__(self, rate, signed_currencies=(), base_fmt='#,##0.###',
rate_precision=5, denomination=None):
self.rate = rate
self.base_fmt = base_fmt
self.base_fmt_noprec = base_fmt.rsplit('.', 1)[0]
self.signed_currencies = set(code for code in signed_currencies
if self.can_sign_currency(code))
self.rate_prec = rate_precision
self.denomination = denomination
def can_sign_currency(self, code):
return False
def format_currency(self, amount, code, currency_digits=True):
if currency_digits:
fmt = self.base_fmt
else:
fmt = '{}.{}'.format(self.base_fmt_noprec, '#' * -amount.as_tuple().exponent)
if code in self.signed_currencies:
fmt = '¤' + fmt
else:
fmt = fmt + ' ¤¤'
return babel.numbers.format_currency(amount, code, fmt, currency_digits=currency_digits)
def currency_decimal(self, amount, currency):
amt_s = babel.numbers.format_currency(amount, currency, '###0.###')
return decimal.Decimal(amt_s)
def normalize_rate(self, rate, prec=None):
return rate
def format_rate(self, rate):
return "{:g}".format(rate)
def format_rate_pair(self, from_curr, to_curr):
from_amt = 1
to_amt = self.rate.convert(from_amt, from_curr, to_curr)
return "{} {} = {} {}".format(
self.format_rate(from_amt), from_curr,
self.format_rate(to_amt), to_curr,
)
def format_rate_pair_bidir(self, from_curr, to_curr, sep='\n'):
return "{}{}{}".format(
self.format_rate_pair(from_curr, to_curr),
sep,
self.format_rate_pair(to_curr, from_curr),
)
def format_conversion(self, from_amt, from_curr, to_curr):
to_amt = self.rate.convert(from_amt, from_curr, to_curr)
return "{} = {}".format(
self.format_currency(from_amt, from_curr),
self.format_currency(to_amt, to_curr),
)
class LedgerFormatter(Formatter):
def can_sign_currency(self, code):
return len(babel.numbers.get_currency_symbol(code)) == 1
def normalize_rate(self, rate, prec=None):
if prec is None:
prec = self.rate_prec
_, digits, exponent = rate.normalize().as_tuple()
# Return ``prec`` nonzero digits of precision, if available.
prec -= min(0, exponent + len(digits))
quant_to = '1.{}'.format('0' * prec)
try:
qrate = rate.quantize(decimal.Decimal(quant_to))
except decimal.InvalidOperation:
# The original rate doesn't have that much precision, so use it raw.
qrate = rate
return qrate.normalize()
def format_rate(self, rate):
return str(self.normalize_rate(rate))
def format_ledger_rate_raw(self, rate, curr):
rate_s = self.format_currency(rate, curr, currency_digits=False)
return "{{={0}}} @ {0}".format(rate_s)
def format_ledger_rate(self, rate, curr):
return self.format_ledger_rate_raw(self.normalize_rate(rate), curr)
def format_rate_pair(self, from_curr, to_curr):
from_amt = 1
to_amt = self.rate.convert(from_amt, from_curr, to_curr)
return "{} {} {}".format(
from_amt, from_curr, self.format_ledger_rate(to_amt, to_curr))
def _denomination_for(self, currency, default):
if self.denomination is None:
return default
elif self.denomination == currency:
return None
else:
return self.denomination
def format_denominated_rate(self, amount, currency, default_denomination):
denomination = self._denomination_for(currency, default_denomination)
amt_s = self.format_currency(amount, currency)
if denomination is None:
return amt_s
full_rate = self.rate.convert(1, currency, denomination)
# Starting from self.rate_prec, find the least amount of precision to
# make sure the `from` amount converts exactly to the `to` amount.
to_amt = self.currency_decimal(amount * full_rate, denomination)
for prec in itertools.count(self.rate_prec):
rate = self.normalize_rate(full_rate, prec)
got_amt = self.currency_decimal(amount * rate, denomination)
# If got_amt == to_amt, this is enough precision to do the
# conversion exactly, so we're done.
# If rate == full_rate, there's no more precision available, so stop.
if (got_amt == to_amt) or (rate == full_rate):
break
return "{} {}".format(amt_s, self.format_ledger_rate_raw(rate, denomination))
def format_conversion(self, from_amt, from_curr, to_curr):
to_amt = self.rate.convert(from_amt, from_curr, to_curr)
return "{}\n{}".format(
self.format_denominated_rate(from_amt, from_curr, to_curr),
self.format_denominated_rate(to_amt, to_curr, None),
)
class Formats(enum.Enum):
RAW = Formatter
LEDGER = LedgerFormatter
@classmethod
def from_arg(cls, s):
return cls[s.upper()]
def run(config, stdout, stderr):
loaders = config.get_loaders()
with loaders.historical(config.args.date, config.args.base) as rate_json:
rate = oxrrate.Rate.from_json_file(rate_json)
if loaders.should_cache():
config.cache.save_rate(rate)
formatter = config.args.output_format.value(
rate,
config.args.signed_currencies,
denomination=config.args.denomination,
)
if not config.args.from_currency:
for from_curr in sorted(rate.rates):
print(formatter.format_rate_pair_bidir(from_curr, config.args.to_currency),
file=stdout)
elif config.args.amount is None:
print(formatter.format_rate_pair_bidir(config.args.from_currency, config.args.to_currency),
file=stdout)
else:
print(formatter.format_conversion(config.args.amount,
config.args.from_currency,
config.args.to_currency),
file=stdout)
|