Source code for mlthon.basics.qty

from decimal import Decimal, Context, Inexact


[docs]class Qty(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(Qty._DECIMAL, context=Context(traps=[Inexact]))
[docs] @staticmethod def from_str(s: str): return Qty(Decimal(s))
[docs] @staticmethod def from_int(i: int): return Qty(Decimal(i))
[docs] @staticmethod def from_json(value): if isinstance(value, Decimal): return Qty(value) elif isinstance(value, str): return Qty.from_str(value) elif isinstance(value, int): return Qty.from_int(value) else: raise NotImplementedError
[docs] @staticmethod def zero(): return Qty(Decimal(0))
[docs] @staticmethod def null(): """ Note that a null Qty cannot be used to perform arithmetic comparisons with other Qty objects. """ return Qty(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 "{Qty: " + self.raw_value_.to_eng_string() + ", implieds: " + str(Qty._IMPLIED_DECIMALS) + "}" def __str__(self): return self.raw_value_.to_eng_string() # Arithmetic operation def __add__(self, other): return Qty(self.raw_value_ + other.raw_value_) def __sub__(self, other): return Qty(self.raw_value_ - other.raw_value_) def __mul__(self, other): return Qty(self.raw_value_ * other.raw_value_) def __truediv__(self, other): return Qty(self.raw_value_ / other.raw_value_) def __neg__(self): return Qty(-self.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_ def __abs__(self): return Qty(abs(self.raw_value_))