Source code for mlthon.basics.price
from decimal import Decimal, Context, Inexact
[docs]class Price(object):
_IMPLIED_DECIMALS = 10 # Number of implied decimals
_EXPONENT = Decimal(10) ** _IMPLIED_DECIMALS # 10000000000
_DECIMAL = Decimal(10) ** -_IMPLIED_DECIMALS # 0.0000000001
def __init__(self, raw_val: Decimal):
self.raw_value_ = raw_val.quantize(Price._DECIMAL, context=Context(traps=[Inexact]))
[docs] @staticmethod
def from_str(s):
return Price(Decimal(s))
[docs] @staticmethod
def from_int(i: int):
return Price(Decimal(i))
[docs] @staticmethod
def zero():
return Price(Decimal(0))
[docs] @staticmethod
def null():
""" Note that a null Price cannot be used to perform arithmetic comparisons with other Price objects. """
return Price(Decimal('Nan'))
[docs] def is_null(self):
return self.raw_value_.is_nan()
[docs] def to_float(self):
return float(self.raw_value_)
[docs] def to_str(self, num_decimal=_IMPLIED_DECIMALS):
decimal = Decimal(10) ** -num_decimal
return self.raw_value_.quantize(decimal, context=Context(traps=[Inexact])).to_eng_string()
def __repr__(self):
return "{Price: " + self.raw_value_.to_eng_string() + ", implieds: " + str(Price._IMPLIED_DECIMALS) + "}"
def __str__(self):
return self.raw_value_.to_eng_string()
# Arithmetic operation
def __add__(self, other):
return Price(self.raw_value_ + other.raw_value_)
def __sub__(self, other):
return Price(self.raw_value_ - other.raw_value_)
def __mul__(self, other):
return Price(self.raw_value_ * other.raw_value_)
def __truediv__(self, other):
return Price(self.raw_value_ / other.raw_value_)
# Comparison
def __eq__(self, other):
return self.raw_value_ == other.raw_value_
def __lt__(self, other):
return self.raw_value_ < other.raw_value_
def __le__(self, other):
return self.raw_value_ <= other.raw_value_
def __ge__(self, other):
return self.raw_value_ >= other.raw_value_
def __gt__(self, other):
return self.raw_value_ > other.raw_value_