2020-11-06 17:23:14 +00:00
|
|
|
# piker: trading gear for hackers
|
|
|
|
# Copyright (C) 2018-present Tyler Goodlet (in stewardship of piker0)
|
|
|
|
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Affero General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Affero General Public License for more details.
|
|
|
|
|
|
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
|
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
|
2018-02-10 03:03:37 +00:00
|
|
|
"""
|
|
|
|
Handy financial calculations.
|
|
|
|
"""
|
|
|
|
import math
|
|
|
|
import itertools
|
|
|
|
|
|
|
|
|
2018-11-13 23:42:34 +00:00
|
|
|
def humanize(number, digits=1):
|
2018-02-10 03:03:37 +00:00
|
|
|
"""Convert large numbers to something with at most 3 digits and
|
|
|
|
a letter suffix (eg. k: thousand, M: million, B: billion).
|
|
|
|
"""
|
2018-02-14 17:06:29 +00:00
|
|
|
try:
|
|
|
|
float(number)
|
|
|
|
except ValueError:
|
|
|
|
return 0
|
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-11-13 23:42:34 +00:00
|
|
|
return "{:.{digits}f}{}".format(
|
|
|
|
number/10**maxmag, mag2suffix[maxmag], digits=digits)
|
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``.
|
|
|
|
"""
|
2018-05-08 19:47:48 +00:00
|
|
|
if not (init and new):
|
|
|
|
return 0
|
2018-02-11 00:54:09 +00:00
|
|
|
return (new - init) / init * 100.
|