Files
@ 8dede9d1398c
Branch filter:
Location: NPO-Accounting/oxrlib/oxrlib/commands/historical.py
8dede9d1398c
7.9 KiB
text/x-python
historical: Swap Ledger and Beancount formatters in the class hierarchy.
This makes sense for a couple of reasons:
* The Beancount formatter has "less features" than the Ledger formatter, so
this is a more "logical" organization of the hierarchy anyway. Note how
this eliminates the need for the BeancountFormatter.__init__ override to
turn off Ledger features.
* Any future work will probably be focused on the Beancount formatter, so
this reduces the amount of code you have to understand and hold in your
head to do that.
This makes sense for a couple of reasons:
* The Beancount formatter has "less features" than the Ledger formatter, so
this is a more "logical" organization of the hierarchy anyway. Note how
this eliminates the need for the BeancountFormatter.__init__ override to
turn off Ledger features.
* Any future work will probably be focused on the Beancount formatter, so
this reduces the amount of code you have to understand and hold in your
head to do that.
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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | 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, cost_rates, price_rates=None,
signed_currencies=(), base_fmt='#,##0.###',
rate_precision=5, denomination=None):
self.cost_rates = cost_rates
self.price_rates = price_rates
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.cost_rates.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.cost_rates.convert(from_amt, from_curr, to_curr)
return "{} = {}".format(
self.format_currency(from_amt, from_curr),
self.format_currency(to_amt, to_curr),
)
class BeancountFormatter(Formatter):
COST_FMT = '{{{}}}'
PRICE_FMT = ' @ {}'
def price_rate(self, from_amt, from_curr, to_curr):
if self.price_rates is None:
return None
else:
return self.price_rates.convert(from_amt, from_curr, to_curr)
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 normalize_enough(self, rate, curr, from_amt, to_amt, prec=None):
if prec is None:
prec = self.rate_prec
# Starting from prec, find the least amount of precision to
# make sure from_amt converts exactly to to_amt.
for try_prec in itertools.count(prec):
try_rate = self.normalize_rate(rate, try_prec)
got_amt = self.currency_decimal(from_amt * try_rate, curr)
# If got_amt == to_amt, this is enough precision to do the
# conversion exactly, so we're done.
# If try_rate == rate, there's no more precision available, so stop.
if (got_amt == to_amt) or (try_rate == rate):
break
return try_rate
def _pretty_rate(self, fmt, rate, curr, from_amt=None, to_amt=None):
if to_amt is None:
rate = self.normalize_rate(rate)
else:
rate = self.normalize_enough(rate, curr, from_amt, to_amt)
return fmt.format(self.format_currency(rate, curr, currency_digits=False))
def format_rate_pair(self, from_curr, to_curr):
from_amt = 1
cost = self.cost_rates.convert(from_amt, from_curr, to_curr)
price = self.price_rate(from_amt, from_curr, to_curr)
if price is None:
price_s = ''
else:
price_s = self._pretty_rate(self.PRICE_FMT, price, to_curr)
return "{} {} {}{}".format(
from_amt,
from_curr,
self._pretty_rate(self.COST_FMT, cost, to_curr),
price_s,
)
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
cost = self.cost_rates.convert(1, currency, denomination)
price = self.price_rate(1, currency, denomination)
to_amt = self.currency_decimal(amount * cost, denomination)
if price is None:
price_s = ''
else:
price_s = self._pretty_rate(
self.PRICE_FMT, price, denomination, amount, to_amt,
)
return "{} {}{}".format(
amt_s,
self._pretty_rate(self.COST_FMT, cost, denomination, amount, to_amt),
price_s,
)
def format_conversion(self, from_amt, from_curr, to_curr):
to_amt = self.cost_rates.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 LedgerFormatter(BeancountFormatter):
COST_FMT = '{{={}}}'
def can_sign_currency(self, code):
return len(babel.numbers.get_currency_symbol(code)) == 1
def price_rate(self, from_amt, from_curr, to_curr):
if self.price_rates is None:
rates = self.cost_rates
else:
rates = self.price_rates
return rates.convert(from_amt, from_curr, to_curr)
class Formats(enum.Enum):
RAW = Formatter
LEDGER = LedgerFormatter
BEANCOUNT = BeancountFormatter
@classmethod
def from_arg(cls, s):
return cls[s.upper()]
def load_rates(config, loaders, date):
with loaders.historical(date, config.args.base) as rate_json:
rates = oxrrate.Rate.from_json_file(rate_json)
if loaders.should_cache():
config.cache.save_rate(rates)
return rates
def run(config, stdout, stderr):
loaders = config.get_loaders()
cost_rates = load_rates(config, loaders, config.args.date)
if config.args.from_date is None:
price_rates = None
else:
price_rates = load_rates(config, loaders, config.args.from_date)
formatter = config.args.output_format.value(
cost_rates,
price_rates,
config.args.signed_currencies,
denomination=config.args.denomination,
)
if not config.args.from_currency:
for from_curr in sorted(cost_rates.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)
|