piker/piker/calc.py

104 lines
2.3 KiB
Python
Raw Normal View History

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/>.
"""
Handy financial calculations.
"""
import math
import itertools
2021-09-16 15:48:31 +00:00
from bidict import bidict
_mag2suffix = bidict({3: 'k', 6: 'M', 9: 'B'})
2021-08-27 20:37:08 +00:00
def humanize(
number: float,
digits: int = 1
2021-09-16 15:48:31 +00:00
2021-08-27 20:37:08 +00:00
) -> str:
'''
Convert large numbers to something with at most ``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:
return str(round(number, ndigits=digits))
2021-11-04 12:31:48 +00:00
mag = round(math.log(number, 10))
2018-02-13 15:35:11 +00:00
if mag < 3:
return str(round(number, ndigits=digits))
2021-11-04 12:31:48 +00:00
maxmag = max(
itertools.takewhile(
lambda key: mag >= key, _mag2suffix
)
)
return "{value}{suffix}".format(
value=round(number/10**maxmag, ndigits=digits),
2021-09-16 15:48:31 +00:00
suffix=_mag2suffix[maxmag],
)
2021-09-16 15:48:31 +00:00
def puterize(
text: str,
digits: int = 1,
) -> float:
'''Inverse of ``humanize()`` above.
'''
try:
suffix = str(text)[-1]
mult = _mag2suffix.inverse[suffix]
value = text.rstrip(suffix)
return round(float(value) * 10**mult, ndigits=digits)
except KeyError:
# no matching suffix try just the value
return float(text)
def pnl(
2021-08-27 20:37:08 +00:00
init: float,
new: float,
) -> float:
'''Calcuate the percentage change of some ``new`` value
from some initial value, ``init``.
2021-08-27 20:37:08 +00:00
'''
2018-05-08 19:47:48 +00:00
if not (init and new):
return 0
2021-08-27 20:37:08 +00:00
return (new - init) / init
def percent_change(
init: float,
new: float,
) -> float:
return pnl(init, new) * 100.