Exemplo n.º 1
0
    def imprint(self, start_expr=True, variant='latex'):
        extra_sign = ''
        if not start_expr and self >= 0:
            extra_sign = '+'
        if variant == 'latex':
            self_str = locale.format(
                '%.{}f'.format(
                    self.fracdigits_nb(ignore_trailing_zeros=False)),
                Decimal(self))

        elif variant == 'user_input':
            self_str = Decimal.__str__(self)
        else:
            raise ValueError(
                'variant must belong to [\'latex\', '
                '\'user_input\']; got \'{}\' instead.'.format(variant))
        if self.unit is None:
            return extra_sign + self_str
        else:
            if variant == 'latex':
                required.package['siunitx'] = True
                if self.unit.content in ['€', r'\officialeuro']:
                    required.package['eurosym'] = True
                if physical_quantity(self.unit) == 'angle':
                    return extra_sign + r'\ang{' + self_str + '}'
                else:
                    return extra_sign + r'\SI{' + self_str \
                        + '}{' + self.unit.imprint(standalone=False) + '}'
            else:  # 'user_input'
                return extra_sign + self_str + ' ' + self.unit.uiprinted
Exemplo n.º 2
0
def getDatos(datos_xml):
    datos_factura = datos_xml.getElementsByTagName('cfdi:Comprobante')
    total = datos_factura[0].attributes['Total'].value
    total = Decimal(total)
    numero = datos_factura[0].attributes['Folio'].value
    fecha = datos_factura[0].attributes['Fecha'].value
    fecha = fecha.split('T', 1)[0]
    fecha = datetime.datetime.strptime(fecha, "%Y-%m-%d").date()
    datos_emisor = datos_xml.getElementsByTagName('cfdi:Emisor')
    datos_proveedor = resolverEmisor(datos_emisor[0])
    estado = resolverEstado()
    nomenclador_moneda = datos_factura[0].attributes['Moneda'].value
    moneda = resolverMoneda(nomenclador_moneda)
    datos_conceptos = datos_xml.getElementsByTagName('cfdi:Concepto')
    conceptos = resolverConceptos(datos_conceptos)
    return {
        'msg': 'ok',
        'rc': 0,
        'data': {
            'numero': numero,
            'monto': total.__str__(),
            'fecha_emision': fecha.isoformat(),
            'monto_pagado': 0,
            'proveedor': datos_proveedor,
            'estado': estado.id,
            'moneda': moneda,
            'conceptos': conceptos
        }
    }
Exemplo n.º 3
0
 def __repr__(self):
     basic_repr = repr(Decimal(Decimal.__str__(self))).replace(
         'Decimal', 'Number')
     if self.unit is None:
         return basic_repr
     else:
         return basic_repr.replace("')",
                                   " {}')".format(self.unit.uiprinted))
Exemplo n.º 4
0
 def __float__(self):
     """Float representation."""
     if self.is_nan():
         if self.is_snan():
             raise ValueError("Cannot convert signaling NaN to float")
         s = '-nan' if self.is_signed() else 'nan'
     else:
         s = Decimal.__str__(self)
     return float(s)
Exemplo n.º 5
0
 def __float__(self):
     """Float representation."""
     if self.is_nan():
         if self.is_snan():
             raise ValueError("Cannot convert signaling NaN to float")
         s = '-nan' if self.is_signed() else 'nan'
     else:
         s = Decimal.__str__(self)
     return float(s)
Exemplo n.º 6
0
 def get_bills(self, type):
     bills = []
     billsets = self.billset_set.all()
     for billset in billsets:
         bill_type = billset.bill_set.filter(type=type)
         sum = Decimal(0.0)
         for bill in bill_type:
             sum += bill.amount
         bills.append(sum.__str__())
     return bills
Exemplo n.º 7
0
    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()

        if isinstance(self.default, Money):
            kwargs['default'] = Decimal.__str__(self.default)
        if self.default_currency is not None:
            kwargs['default_currency'] = str(self.default_currency)
        if self.currency_choices is not None:
            kwargs['currency_choices'] = self.currency_choices

        return name, path, args, kwargs
Exemplo n.º 8
0
 def __str__(self):
     """
     Renders the price localized and formatted in its current currency.
     """
     vals = dict(code=self._currency_code, symbol=self._currency[2], currency=self._currency[3])
     if self.is_nan():
         return self.MONEY_FORMAT.format(amount='–', **vals)
     try:
         vals.update(amount=Decimal.__str__(self.quantize(self._cents)))
     except InvalidOperation:
         raise ValueError("Can not represent {} as Money type.".format(self.__repr__()))
     return self.MONEY_FORMAT.format(**vals)
Exemplo n.º 9
0
 def __str__(self):
     """
     Renders the price localized and formatted in its current currency.
     """
     vals = dict(code=self._currency_code, symbol=self._currency[2], currency=self._currency[3])
     if self.is_nan():
         return self.MONEY_FORMAT.format(amount='–', **vals)
     try:
         vals.update(amount=Decimal.__str__(self.quantize(self._cents)))
     except InvalidOperation:
         raise ValueError("Can not represent {} as Money type.".format(self.__repr__()))
     return self.MONEY_FORMAT.format(**vals)
Exemplo n.º 10
0
 def __str__(self):
     """
     Renders the price localized and formatted in its current currency.
     """
     vals = self._get_format_values()
     if self.is_nan():
         return self.MONEY_FORMAT.format(amount='–', **vals)
     try:
         vals.update(
             amount=Decimal.__str__(Decimal.quantize(self, self._cents)))
     except InvalidOperation:
         raise ValueError("Can not represent {} as Money type.".format(
             self.__repr__()))
     return '{:f}'.format(self)
Exemplo n.º 11
0
 def __str__(self):
     """
     Renders the price localized and formatted in its current currency.
     """
     vals = self._get_format_values()
     if self.is_nan():
         return self.MONEY_FORMAT.format(amount='–', **vals)
     try:
         vals.update(amount=Decimal.__str__(self.quantize(self._cents)))
     except InvalidOperation:
         raise ValueError("Can not represent {} as Money type.".format(self.__repr__()))
     if six.PY2:
         return u'{:f}'.format(self)
     return '{:f}'.format(self)
Exemplo n.º 12
0
 def __repr__(self):
     value = Decimal.__str__(self)
     return "{}('{}')".format(self.__class__.__name__, value)
Exemplo n.º 13
0
 def __str__(self):
     basic_str = Decimal.__str__(self)
     if self.unit is None:
         return basic_str
     else:
         return basic_str + ' ' + str(self.unit)
Exemplo n.º 14
0
 def deconstruct(self):
     return [
         '{}.{}'.format(self.__module__, self.__class__.__name__),
         [Decimal.__str__(self)], {}]
Exemplo n.º 15
0
 def __reduce__(self):
     return (self.__class__, (Decimal.__str__(self),))
Exemplo n.º 16
0
 def __repr__(self):
     return '{}({})'.format(self.__class__.__name__, Decimal.__str__(self))
Exemplo n.º 17
0
 def deconstruct(self):
     return (
         '{}.{}'.format(self.__module__, self.__class__.__name__),
         [Decimal.__str__(self)],
         {},
     )
 def __repr__(self):
     return "Nbr('%s')" % _Decimal.__str__(self)
Exemplo n.º 19
0
 def __reduce__(self):
     """Required for pickling MoneyInCUR type"""
     return _make_money, (self._currency_code, Decimal.__str__(self))
Exemplo n.º 20
0
 def __repr__(self):
     return '{}({})'.format(self.__class__.__name__, Decimal.__str__(self))
Exemplo n.º 21
0
 def __repr__(self):
     value = Decimal.__str__(self)
     return "{}('{}')".format(self.__class__.__name__, value)
Exemplo n.º 22
0
 def __reduce__(self):
     return self.__class__, (Decimal.__str__(self), self._currency)
Exemplo n.º 23
0
class Price(object):
    def __init__(
        self, price_value,
        precision=Decimal(".111111111111111")):  # precision defaults to 15
        if isinstance(price_value, Decimal):
            self.__value = price_value
        elif isinstance(price_value, float):
            self.__value = Decimal(price_value).quantize(
                precision, rounding=decimal.ROUND_HALF_UP)
        else:
            self.__value = Decimal(price_value)
        self.__hash = self.__value.__hash__()
        self.__float_value = float(self.__value)
        self.__precision = precision

    def better_than(self, other_price, side):
        """
        Determines if this price is better than the passed in price. Returns True if it is and False if it isn't.
        The determination is made using the passed in side:
           *if side is bid then better than means a higher price
           *if side is ask then better than means a lower price
           *if side is other then there is no such thing as a better price so the return is False
        
        :param other_price: Price. the price you are comparing to
        :param side: Side. the side used for the comparison
        :return: boolean
        """
        assert isinstance(side, Side), "side should be MarketObjects.Side.Side"
        # if this price is a bid it is better than otherPrice if greater than

        if side.is_bid():
            return self > other_price
        # otherwise price is an ask and it is better than otherPrice if less than
        else:
            return self < other_price

    def better_or_same_as(self, other_price, side):
        """
        Determines if this price is better than or same as the passed in price.
        Returns True if it is and False if it isn't.
        The determination is made using the passed in side:
           *if side is bid then better than means a higher price
           *if side is ask then better than means a lower price
           *if side is other then there is no such thing as a better price so the return is False
        
        :param other_price: Price. the price you are comparing to
        :param side: Side. the side used for the comparison
        :return: boolean
        """
        return True if other_price == self else self.better_than(
            other_price, side)

    def worse_than(self, other_price, side):
        """
        Determines if this price is worse than the passed in price.
        Returns True if it is and False if it isn't.
        The determination is made using the passed in side:
           *if side is bid then worse than means a lower price
           *if side is ask then worse than means a higher price
           *if side is other then there is no such thing as a worse price so the return is False
        
        :param other_price: Price. the price you are comparing to
        :param side: Side. the side used for the comparison
        :return: boolean
        """
        assert isinstance(
            other_price,
            Price), "other_price should be MarketObjects.Price.Price"
        assert isinstance(side, Side), "side should be MarketObjects.Side.Side"
        # if this price is a bid it is worse than otherPrice if less than
        if side.is_bid():
            return self < other_price
        # otherwise price is an ask and it is worse than otherPrice if greater than
        else:
            return self > other_price

    def worse_or_same_as(self, other_price, side):
        """
        Determines if this price is worse than or same as the passed in price.
        Returns True if it is and False if it isn't.
        The determination is made using the passed in side:
           *if side is bid then worse than means a lower price
           *if side is ask then worse than means a higher price
           *if side is other then there is no such thing as a worse price so the return is False

        :param other_price: Price. the price you are comparing to
        :param side: Side. the side used for the comparison
        :return: boolean
        """
        return True if other_price == self else self.worse_than(
            other_price, side)

    def ticks_behind(self, other_price, side, market):
        """
        For bids it subtracts its own price from the other price and divides by mpi
  
        For asks it subtracts the other price from its own price and divides by mpi.
  
        The result is if the other price is a better price then we get a positive
         number and if the other price is a worse price, we get a negative number.
  
        If otherprice is none it returns None
        :param other_price: MarketObjects.Price.Price the price you are comparing too
        :param side: MMarketObjects.Side.Side side of the market the comparison is happening on
        :param market: MarketObjects.Market.Market
        :return: float Can be None
        """
        if other_price is None:
            return None

        if side.is_bid():
            ticks_behind = (other_price - self) / market.mpi()
        else:
            ticks_behind = (self - other_price) / market.mpi()
        return float(ticks_behind)

    def __hash__(self):
        return self.__hash

    def __repr__(self):
        return self.__value.__repr__()

    def __str__(self):
        return self.__value.__str__()

    def __lt__(self, other):
        if not isinstance(other, Price):
            raise TypeError(other, '< requires another Price object')
        else:
            return self.__value < other.__value

    def __le__(self, other):
        if not isinstance(other, Price):
            raise TypeError(other, '<= requires another Price object')
        else:
            return self.__value <= other.__value

    def __eq__(self, other):
        if other is None:
            return False
        elif isinstance(other, Price):
            return self.__value == other.__value
        else:
            return self.__value == Price(other).__value

    def __ne__(self, other):
        return not self == other

    def __gt__(self, other):
        if not isinstance(other, Price):
            raise TypeError(other, '> requires another Price object')
        else:
            return self.__value > other.__value

    def __ge__(self, other):
        if not isinstance(other, Price):
            raise TypeError(other, '>= requires another Price object')
        else:
            return self.__value >= other.__value

    def __bool__(self):
        return bool(self.__value)

    def __add__(self, other):
        if isinstance(other, float):
            value = self.__float_value + other
        else:
            if isinstance(other, Price):
                other = other.__value
            value = self.__value + other
        return self.__class__(value, precision=self.__precision)

    def __radd__(self, other):
        return self.__add__(other)

    def __sub__(self, other):
        if isinstance(other, float):
            value = self.__float_value - other
        else:
            if isinstance(other, Price):
                other = other.__value
            value = self.__value - other
        return self.__class__(value, precision=self.__precision)

    def __rsub__(self, other):
        return (-self).__add__(other)

    def __mul__(self, other):
        if isinstance(other, float):
            value = self.__float_value * other
        else:
            if isinstance(other, Price):
                raise TypeError(
                    "Two prices cannot be multiplied"
                )  # just doesn't make sense. Why would someone do this?
            value = self.__value * other
        return self.__class__(value, precision=self.__precision)

    def __rmul__(self, other):
        return self.__mul__(other)

    def __div__(self, other):
        return self.__truediv__(other)

    def __truediv__(self, other):
        if isinstance(other, Price):
            # not really sure why someone would want to divide a price by another price
            raise TypeError("Two prices cannot be divided")
        else:
            if other == 0:
                raise ZeroDivisionError()
            if isinstance(other, float):
                value = self.__float_value / other
            else:
                value = self.__value / other
        return self.__class__(value, precision=self.__precision)

    def __floordiv__(self, other):
        if isinstance(other, Price):
            # not really sure why someone would want to divide a price by another price
            raise TypeError("Two prices cannot be divided")
        else:
            if other == 0:
                raise ZeroDivisionError()
            if isinstance(other, float):
                value = self.__float_value // other
            else:
                value = self.__value // other
        return self.__class__(value, precision=self.__precision)

    def __mod__(self, other):
        if isinstance(other, Price):
            # not really sure why someone would want to modulo a price by another price
            raise TypeError("modulo of two prices is not supported")
        if other == 0:
            raise ZeroDivisionError()
        if isinstance(other, float):
            value = self.__float_value % other
        else:
            value = self.__value % other
        return self.__class__(value, precision=self.__precision)

    def __divmod__(self, other):
        raise TypeError("divmod of a price is not supported")

    def __pow__(self, other):
        raise TypeError("pow of a price is not supported")

    def __neg__(self):
        return self.__class__(-self.__value)

    def __pos__(self):
        return self.__class__(+self.__value)

    def __abs__(self):
        return self.__class__(abs(self.__value))

    def __int__(self):
        return int(self.__value)

    def __float__(self):
        return self.__float_value
Exemplo n.º 24
0
 def __reduce__(self):
     """Required for pickling MoneyInCUR type"""
     return _make_money, (self._currency_code, Decimal.__str__(self))
Exemplo n.º 25
0
 def __reduce__(self):
     return (self.__class__, (Decimal.__str__(self), ))
Exemplo n.º 26
0
class ContractingDecimal:
    def _get_other(self, other):
        if type(other) == ContractingDecimal:
            return other._d
        elif type(other) == float or type(other) == int:
            return Decimal(str(other))
        return other

    def __init__(self, a):
        if type(a) == float or type(a) == int:
            a = str(a)

        self._d = Decimal(a)

    def __bool__(self):
        return self._d > 0

    def __eq__(self, other):
        return self._d.__eq__(self._get_other(other))

    def __lt__(self, other):
        return self._d.__lt__(self._get_other(other))

    def __le__(self, other):
        return self._d.__le__(self._get_other(other))

    def __gt__(self, other):
        return self._d.__gt__(self._get_other(other))

    def __ge__(self, other):
        return self._d.__ge__(self._get_other(other))

    def __str__(self):
        return self._d.__str__()

    def __neg__(self):
        return self._d.__neg__()

    def __pos__(self):
        return self._d.__pos__()

    def __abs__(self):
        return self._d.__abs__()

    def __add__(self, other):
        x = self._d.__add__(self._get_other(other))
        return fix_precision(x)

    def __radd__(self, other):
        return fix_precision(self._d.__radd__(self._get_other(other)))

    def __sub__(self, other):
        return fix_precision(self._d.__sub__(self._get_other(other)))

    def __rsub__(self, other):
        return fix_precision(self._d.__rsub__(self._get_other(other)))

    def __mul__(self, other):
        return fix_precision(self._d.__mul__(self._get_other(other)))

    def __rmul__(self, other):
        return fix_precision(self._d.__rmul__(self._get_other(other)))

    def __truediv__(self, other):
        return fix_precision(self._d.__truediv__(self._get_other(other)))

    def __rtruediv__(self, other):
        return fix_precision(self._d.__rtruediv__(self._get_other(other)))

    def __divmod__(self, other):
        return fix_precision(self._d.__divmod__(self._get_other(other)))

    def __rdivmod__(self, other):
        return fix_precision(self._d.__divmod__(self._get_other(other)))

    def __mod__(self, other):
        return fix_precision(self._d.__mod__(self._get_other(other)))

    def __rmod__(self, other):
        return fix_precision(self._d.__rmod__(self._get_other(other)))

    def __floordiv__(self, other):
        return fix_precision(self._d.__floordiv__(self._get_other(other)))

    def __rfloordiv__(self, other):
        return fix_precision(self._d.__rfloordiv__(self._get_other(other)))

    def __pow__(self, other):
        return fix_precision(self._d.__pow__(self._get_other(other)))

    def __rpow__(self, other):
        return fix_precision(self._d.__rpow__(self._get_other(other)))

    def __int__(self):
        return self._d.__int__()

    def __float__(self):
        raise Exception('Cannot cast Decimal to float.')

    def __repr__(self):
        return self._d.__repr__()
Exemplo n.º 27
0
class ContractingDecimal:
    def _get_other(self, other):
        if type(other) == ContractingDecimal:
            return other._d
        elif type(other) == float or type(other) == int:
            o = str(other)
            return Decimal(neg_sci_not(o))
        return other

    def __init__(self, a):
        if type(a) == float or type(a) == int:
            o = str(a)
            self._d = Decimal(neg_sci_not(o))
        elif type(a) == Decimal:
            self._d = a
        elif type(a) == str:
            self._d = Decimal(neg_sci_not(a))
        else:
            self._d = Decimal(a)

    def __bool__(self):
        return self._d > 0

    def __eq__(self, other):
        return self._d.__eq__(self._get_other(other))

    def __lt__(self, other):
        return self._d.__lt__(self._get_other(other))

    def __le__(self, other):
        return self._d.__le__(self._get_other(other))

    def __gt__(self, other):
        return self._d.__gt__(self._get_other(other))

    def __ge__(self, other):
        return self._d.__ge__(self._get_other(other))

    def __str__(self):
        return self._d.__str__()

    def __neg__(self):
        return self._d.__neg__()

    def __pos__(self):
        return self._d.__pos__()

    def __abs__(self):
        return self._d.__abs__()

    def __add__(self, other):
        x = self._d.__add__(self._get_other(other))
        return fix_precision(x)

    def __radd__(self, other):
        return fix_precision(self._d.__radd__(self._get_other(other)))

    def __sub__(self, other):
        return fix_precision(self._d.__sub__(self._get_other(other)))

    def __rsub__(self, other):
        return fix_precision(self._d.__rsub__(self._get_other(other)))

    def __mul__(self, other):
        return fix_precision(self._d.__mul__(self._get_other(other)))

    def __rmul__(self, other):
        return fix_precision(self._d.__rmul__(self._get_other(other)))

    def __truediv__(self, other):
        return fix_precision(self._d.__truediv__(self._get_other(other)))

    def __rtruediv__(self, other):
        return fix_precision(self._d.__rtruediv__(self._get_other(other)))

    def __divmod__(self, other):
        return fix_precision(self._d.__divmod__(self._get_other(other)))

    def __rdivmod__(self, other):
        return fix_precision(self._d.__divmod__(self._get_other(other)))

    def __mod__(self, other):
        return fix_precision(self._d.__mod__(self._get_other(other)))

    def __rmod__(self, other):
        return fix_precision(self._d.__rmod__(self._get_other(other)))

    def __floordiv__(self, other):
        return fix_precision(self._d.__floordiv__(self._get_other(other)))

    def __rfloordiv__(self, other):
        return fix_precision(self._d.__rfloordiv__(self._get_other(other)))

    def __pow__(self, other):
        return fix_precision(self._d.__pow__(self._get_other(other)))

    def __rpow__(self, other):
        return fix_precision(self._d.__rpow__(self._get_other(other)))

    def __int__(self):
        return self._d.__int__()

    def __float__(self):
        return float(self._d)

    def __round__(self, n=None):
        return self._d.__round__(n)