2018-02-10 03:03:37 +00:00
|
|
|
"""
|
|
|
|
Handy financial calculations.
|
|
|
|
"""
|
|
|
|
import math
|
|
|
|
import itertools
|
|
|
|
|
|
|
|
|
|
|
|
def humanize(number):
|
|
|
|
"""Convert large numbers to something with at most 3 digits and
|
|
|
|
a letter suffix (eg. k: thousand, M: million, B: billion).
|
|
|
|
"""
|
2018-02-13 15:35:11 +00:00
|
|
|
if not number or number <= 0:
|
2018-02-11 00:54:09 +00:00
|
|
|
return number
|
2018-02-10 03:03:37 +00:00
|
|
|
mag2suffix = {3: 'k', 6: 'M', 9: 'B'}
|
|
|
|
mag = math.floor(math.log(number, 10))
|
2018-02-13 15:35:11 +00:00
|
|
|
if mag < 3:
|
|
|
|
return number
|
2018-02-10 03:03:37 +00:00
|
|
|
maxmag = max(itertools.takewhile(lambda key: mag >= key, mag2suffix))
|
2018-02-14 07:43:55 +00:00
|
|
|
return "{:.2f}{}".format(number/10**maxmag, mag2suffix[maxmag])
|
2018-02-11 00:54:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
def percent_change(init, new):
|
|
|
|
"""Calcuate the percentage change of some ``new`` value
|
|
|
|
from some initial value, ``init``.
|
|
|
|
"""
|
|
|
|
return (new - init) / init * 100.
|