Python decimal.Decimal() Examples

The following are 30 code examples of decimal.Decimal(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module decimal , or try the search function .
Example #1
Source File: cons.py    From xalpha with MIT License 6 votes vote down vote up
def myround(num, label=1):
    """
    correct implementation of round with round half up, round to 2 decimals

    :param num: the floating number, to be rounded
    :param label: integer 1 or 2, 1 for round half up while 2 for always round down
    :returns: the float number after rounding, with two decimals
    """
    if label == 1:
        res = float(
            Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_HALF_UP")
        )
    elif (
        label == 2
    ):  # for jingshunchangcheng... who just omit the overflow share behind 2 decimal
        res = float(Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_DOWN"))
    return res 
Example #2
Source File: product.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_margin(price=0.0):
    """
    Returns the proper margin % for this price
    """
    price  = Decimal(price)
    margin = defaults.margin()

    try:
        return Decimal(margin)
    except Exception:
        ranges = margin.split(';')
        for r in ranges:
            m = re.search(r'(\d+)\-(\d+)=(\d+)', r)
            p_min, p_max, margin = m.groups()
            if Decimal(p_min) <= price <= Decimal(p_max):
                return Decimal(margin)

    return Decimal(margin) 
Example #3
Source File: product.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calculate_price(self, price, shipping=0.0):
        """
        Calculates price and returns it w/ and w/o tax
        """
        conf = Configuration.conf()
        shipping = shipping or 0.0

        if not isinstance(shipping, Decimal):
            shipping = Decimal(shipping)

        margin = get_margin(price)
        vat = Decimal(conf.get("pct_vat", 0.0))

        # TWOPLACES = Decimal(10) ** -2  # same as Decimal('0.01')
        # @TODO: make rounding configurable!
        wo_tax = ((price*100)/(100-margin)+shipping).to_integral_exact(rounding=ROUND_CEILING)
        with_tax = (wo_tax*(vat+100)/100).to_integral_exact(rounding=ROUND_CEILING)

        return wo_tax, with_tax 
Example #4
Source File: classified.py    From django-classified with MIT License 6 votes vote down vote up
def currency(value, currency=None):
    """
    Format decimal value as currency
    """
    try:
        value = D(value)
    except (TypeError, InvalidOperation):
        return ""

    # Using Babel's currency formatting
    # http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency

    kwargs = {
        'currency': currency or CURRENCY,
        'locale': to_locale(get_language() or settings.LANGUAGE_CODE)
    }

    return format_currency(value, **kwargs) 
Example #5
Source File: order_book.py    From TradzQAI with Apache License 2.0 6 votes vote down vote up
def add(self, order):
        order = {
            'id': order.get('order_id') or order['id'],
            'side': order['side'],
            'price': Decimal(order['price']),
            'size': Decimal(order.get('size') or order['remaining_size'])
        }
        if order['side'] == 'buy':
            bids = self.get_bids(order['price'])
            if bids is None:
                bids = [order]
            else:
                bids.append(order)
            self.set_bids(order['price'], bids)
        else:
            asks = self.get_asks(order['price'])
            if asks is None:
                asks = [order]
            else:
                asks.append(order)
            self.set_asks(order['price'], asks) 
Example #6
Source File: order_book.py    From TradzQAI with Apache License 2.0 6 votes vote down vote up
def reset_book(self):
        self._asks = SortedDict()
        self._bids = SortedDict()
        res = self._client.get_product_order_book(product_id=self.product_id, level=3)
        for bid in res['bids']:
            self.add({
                'id': bid[2],
                'side': 'buy',
                'price': Decimal(bid[0]),
                'size': Decimal(bid[1])
            })
        for ask in res['asks']:
            self.add({
                'id': ask[2],
                'side': 'sell',
                'price': Decimal(ask[0]),
                'size': Decimal(ask[1])
            })
        self._sequence = res['sequence'] 
Example #7
Source File: order_book.py    From TradzQAI with Apache License 2.0 6 votes vote down vote up
def remove(self, order):
        price = Decimal(order['price'])
        if order['side'] == 'buy':
            bids = self.get_bids(price)
            if bids is not None:
                bids = [o for o in bids if o['id'] != order['order_id']]
                if len(bids) > 0:
                    self.set_bids(price, bids)
                else:
                    self.remove_bids(price)
        else:
            asks = self.get_asks(price)
            if asks is not None:
                asks = [o for o in asks if o['id'] != order['order_id']]
                if len(asks) > 0:
                    self.set_asks(price, asks)
                else:
                    self.remove_asks(price) 
Example #8
Source File: order_book.py    From TradzQAI with Apache License 2.0 6 votes vote down vote up
def match(self, order):
        size = Decimal(order['size'])
        price = Decimal(order['price'])

        if order['side'] == 'buy':
            bids = self.get_bids(price)
            if not bids:
                return
            assert bids[0]['id'] == order['maker_order_id']
            if bids[0]['size'] == size:
                self.set_bids(price, bids[1:])
            else:
                bids[0]['size'] -= size
                self.set_bids(price, bids)
        else:
            asks = self.get_asks(price)
            if not asks:
                return
            assert asks[0]['id'] == order['maker_order_id']
            if asks[0]['size'] == size:
                self.set_asks(price, asks[1:])
            else:
                asks[0]['size'] -= size
                self.set_asks(price, asks) 
Example #9
Source File: fields.py    From django-places with MIT License 6 votes vote down vote up
def to_python(self, value):
        if not value or value == 'None':
            return None
        if isinstance(value, Places):
            return value
        if isinstance(value, list):
            return Places(value[0], value[1], value[2])

        value_parts = [Decimal(val) for val in value.split(',')[-2:]]

        try:
            latitude = value_parts[0]
        except IndexError:
            latitude = '0.0'

        try:
            longitude = value_parts[1]
        except IndexError:
            longitude = '0.0'
        try:
            place = ','.join(value.split(',')[:-2])
        except:
            pass

        return Places(place, latitude, longitude) 
Example #10
Source File: context.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_pi(from_scratch: bool = False) -> "Decimal":
    """Get pi to 36 digits (or more with mpmath).

    Parameters
    ----------
    from_scratch : bool, optional
        If True, recomputes Pi from mpmath.

    Returns
    -------
    Decimal
        A representation of Pi
    """

    if from_scratch:  # pragma: no cover
        from mpmath import mp

        mp.dps = 36
        return mp.pi
    else:
        return Decimal("3.14159265358979323846264338327950288") 
Example #11
Source File: utils.py    From MPContribs with MIT License 6 votes vote down vote up
def clean_value(value, unit="", convert_to_percent=False, max_dgts=3):
    """return clean value with maximum digits and optional unit and percent"""
    dgts = max_dgts
    value = str(value) if not isinstance(value, six.string_types) else value
    try:
        value = Decimal(value)
        dgts = len(value.as_tuple().digits)
        dgts = max_dgts if dgts > max_dgts else dgts
    except DecimalException:
        return value
    if convert_to_percent:
        value = Decimal(value) * Decimal("100")
        unit = "%"
    val = "{{:.{}g}}".format(dgts).format(value)
    if unit:
        val += " {}".format(unit)
    return val 
Example #12
Source File: test_serializers.py    From figures with MIT License 6 votes vote down vote up
def test_has_fields(self):
        '''
        Initially, doing a limited test of fields as figure out how mamu of the
        CourseEnrollment model fields and relationships we need to capture.
        '''
        data = self.serializer.data

        assert data['course_id'] == str(self.model_obj.course_id)
        # assert data['course']['id'] == str(self.model_obj.course.id)
        # assert data['course']['display_name'] == self.model_obj.course.display_name
        # assert data['course']['org'] == self.model_obj.course.org

        assert dateutil_parse(data['created']) == self.model_obj.created
        assert data['user']['fullname'] == self.model_obj.user.profile.name

        for field_name in (self.expected_results_keys - self.special_fields):
            db_field = getattr(self.model_obj, field_name)
            if type(db_field) in (float, Decimal, ):
                assert float(data[field_name]) == pytest.approx(db_field)
            else:
                assert data[field_name] == db_field 
Example #13
Source File: test_serializers.py    From figures with MIT License 6 votes vote down vote up
def test_has_fields(self):
        '''Verify the serialized data has the same keys and values as the model

        Django 2.0 has a convenient method, 'Cast' that will simplify converting
        values:
        https://docs.djangoproject.com/en/2.0/ref/models/database-functions/#cast

        This means that we can retrieve the model instance values as a dict
        and do a simple ``assert self.serializer.data == queryset.values(...)``
        '''

        data = self.serializer.data

        # Hack: Check date and datetime values explicitly
        assert data['date_for'] == str(self.metrics.date_for)
        assert dateutil_parse(data['created']) == self.metrics.created
        assert dateutil_parse(data['modified']) == self.metrics.modified
        check_fields = self.expected_results_keys - self.date_fields - set(['site'])
        for field_name in check_fields:
            db_field = getattr(self.metrics, field_name)
            if type(db_field) in (float, Decimal, ):
                assert float(data[field_name]) == pytest.approx(db_field)
            else:
                assert data[field_name] == db_field 
Example #14
Source File: collect_data.py    From harmony-ops with MIT License 6 votes vote down vote up
def collect_data(address_list, round, output_dir = None):
    results = []
    for a in address_list:
        req = json.dumps(common.current_balance_request(a.address))
        result = common.request(common.api_base % int(a.shard), req)
        new_entry = {"address": a.address, "shard": a.shard, "index": round}
        if result == None:
            new_entry["balance"] = dec.Decimal('NAN')
        else:
            new_entry["balance"] = common.format_balance(result["result"])
        results.append(new_entry)

    if output_dir:
        output_path = os.path.join(output_dir, timestamp.strftime("%b%d%Y_%H%M"))
        write_output(pd.DataFrame(results), output_path)
    else:
        return pd.DataFrame(results) 
Example #15
Source File: quantity.py    From tensortrade with Apache License 2.0 6 votes vote down vote up
def contain(self, exchange_pair: 'ExchangePair'):
        options = exchange_pair.exchange.options
        price = exchange_pair.price

        if exchange_pair.pair.base == self.instrument:
            size = self.size
            return Quantity(self.instrument, min(size, options.max_trade_size), self.path_id)

        size = self.size * price
        if size < options.max_trade_size:
            return Quantity(self.instrument, self.size, self.path_id)

        max_trade_size = Decimal(options.max_trade_size)
        contained_size = max_trade_size / price
        contained_size = contained_size.quantize(Decimal(10)**-self.instrument.precision, rounding=ROUND_DOWN)
        return Quantity(self.instrument, contained_size, self.path_id) 
Example #16
Source File: test_order_spec.py    From tensortrade with Apache License 2.0 6 votes vote down vote up
def test_str(mock_exchange_class):

    exchange = mock_exchange_class.return_value
    exchange.options = ExchangeOptions()
    exchange.id = "fake_exchange_id"
    exchange.name = "coinbase"
    exchange.clock = mock.Mock()
    exchange.clock.step = 0
    exchange.quote_price = mock.Mock(return_value=Decimal(7000.00))

    order_spec = OrderSpec(
        side=TradeSide.BUY,
        trade_type=TradeType.MARKET,
        exchange_pair=ExchangePair(exchange, USD / BTC)
    )

    pattern = re.compile("<[A-Z][a-zA-Z]*:\\s(\\w+=.*,\\s)*(\\w+=.*)>")

    string = str(order_spec)
    assert string

    assert string == pattern.fullmatch(string).string 
Example #17
Source File: vanderwaals_radii.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, context: str = "MANTINA2009"):
        self.vdwr: Dict[str, Datum] = collections.OrderedDict()

        from .data import mantina_2009_vanderwaals_radii

        if context == "MANTINA2009":
            self.doi = mantina_2009_vanderwaals_radii["doi"]
            self.native_units = mantina_2009_vanderwaals_radii["units"]

            # TypedDict wont be in until 3.8, have to ignore heterogeneous dicts for now
            for vdwr in mantina_2009_vanderwaals_radii["vanderwaals_radii"]:  # type: ignore
                self.vdwr[vdwr[0]] = Datum(vdwr[0], self.native_units, Decimal(vdwr[1]), doi=self.doi)
        else:
            raise KeyError("Context set as '{}', only contexts {'MANTINA2009', } are currently supported")

        self.name = context
        self.year = int(mantina_2009_vanderwaals_radii["date"][:4])  # type: ignore 
Example #18
Source File: test_order.py    From tensortrade with Apache License 2.0 6 votes vote down vote up
def test_is_complete(mock_exchange_class):

    exchange = mock_exchange_class.return_value
    exchange.options = ExchangeOptions()
    exchange.id = "fake_exchange_id"
    exchange.name = "coinbase"
    exchange.clock = mock.Mock()
    exchange.clock.step = 0

    wallets = [Wallet(exchange, 10000 * USD), Wallet(exchange, 0 * BTC)]
    portfolio = Portfolio(USD, wallets)

    # Market order
    order = Order(step=0,
                  exchange_pair=ExchangePair(exchange, USD / BTC),
                  side=TradeSide.BUY,
                  trade_type=TradeType.MARKET,
                  quantity=5000.00 * USD,
                  portfolio=portfolio,
                  price=Decimal(7000.00))

    assert not order.is_complete()

    order.remaining = 0 * USD
    assert order.is_complete() 
Example #19
Source File: exchange_pair.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def price(self) -> Decimal:
        return self.exchange.quote_price(self.pair) 
Example #20
Source File: sqlalchemy_types.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def _decimal_to_dt(dec):
        """Return a datetime from Decimal unixtime format."""
        if dec is None:
            return None

        integer = int(dec)
        micro = (dec - decimal.Decimal(integer)) * decimal.Decimal(1000000)
        daittyme = datetime.datetime.utcfromtimestamp(integer)
        return daittyme.replace(microsecond=int(round(micro))) 
Example #21
Source File: test_order.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def test_to_json(mock_exchange_class):

    exchange = mock_exchange_class.return_value
    exchange.options = ExchangeOptions()
    exchange.id = "fake_exchange_id"
    exchange.name = "coinbase"
    exchange.clock = mock.Mock()
    exchange.clock.step = 0
    exchange.quote_price = mock.Mock(return_value=Decimal(7000.00))

    wallets = [Wallet(exchange, 10000 * USD), Wallet(exchange, 0 * BTC)]
    portfolio = Portfolio(USD, wallets)

    order = Order(step=0,
                  exchange_pair=ExchangePair(exchange, USD / BTC),
                  side=TradeSide.BUY,
                  trade_type=TradeType.MARKET,
                  quantity=5200.00 * USD,
                  portfolio=portfolio,
                  price=Decimal(7000.00))

    d = {
        "id": str(order.id),
        "step": int(order.step),
        "exchange_pair": str(order.exchange_pair),
        "status": str(order.status),
        "type": str(order.type),
        "side": str(order.side),
        "base_symbol": str(order.pair.base.symbol),
        "quote_symbol": str(order.pair.quote.symbol),
        "quantity": str(order.quantity),
        "size": float(order.size),
        "remaining": str(order.remaining),
        "price": float(order.price),
        "criteria": str(order.criteria),
        "path_id": str(order.path_id),
        "created_at": str(order.created_at)
    }

    assert order.to_json() == d 
Example #22
Source File: quantity.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def quantize(self):
        return Quantity(self.instrument,
                        self.size.quantize(Decimal(10)**-self.instrument.precision),
                        self.path_id) 
Example #23
Source File: quantity.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def size(self) -> Decimal:
        return self._size 
Example #24
Source File: test_order.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def test_str(mock_exchange_class):

    exchange = mock_exchange_class.return_value
    exchange.options = ExchangeOptions()
    exchange.id = "fake_exchange_id"
    exchange.name = "coinbase"
    exchange.clock = mock.Mock()
    exchange.clock.step = 0
    exchange.quote_price = mock.Mock(return_value=Decimal(7000.00))

    wallets = [Wallet(exchange, 10000 * USD), Wallet(exchange, 0 * BTC)]
    portfolio = Portfolio(USD, wallets)

    order = Order(step=0,
                  exchange_pair=ExchangePair(exchange, USD / BTC),
                  side=TradeSide.BUY,
                  trade_type=TradeType.MARKET,
                  quantity=5200.00 * USD,
                  portfolio=portfolio,
                  price=Decimal(7000.00))

    pattern = re.compile("<[A-Z][a-zA-Z]*:\\s(\\w+=.*,\\s)*(\\w+=.*)>")

    string = str(order)
    assert string

    assert string == pattern.fullmatch(string).string 
Example #25
Source File: test_serializers.py    From figures with MIT License 5 votes vote down vote up
def test_average_progress_valid(self, average_progress):
        obj = CourseDailyMetricsFactory(average_progress=average_progress)
        serializer = CourseDailyMetricsSerializer(instance=obj)
        check_val = Decimal(average_progress).quantize(Decimal('.00'))
        data = serializer.data
        assert data['average_progress'] == unicode(check_val) 
Example #26
Source File: test_course_daily_metrics_view.py    From figures with MIT License 5 votes vote down vote up
def assert_response_equal(self, response_data, obj):
        '''Convenience method to compare serialized data to model object
        '''
        # Hack: Check date and datetime values explicitly
        assert response_data['date_for'] == str(obj.date_for)
        assert parse(response_data['created']) == obj.created
        assert parse(response_data['modified']) == obj.modified
        check_fields = self.expected_results_keys - self.date_fields - set(['site'])
        for field_name in check_fields:
            obj_field = getattr(obj, field_name)
            if (type(response_data) in (float, Decimal,) or 
                type(obj_field) in (float, Decimal,)):
                assert float(response_data[field_name]) == pytest.approx(obj_field)
            else:
                assert response_data[field_name] == obj_field 
Example #27
Source File: test_broker.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def test_on_fill(mock_trade_class,
                 mock_exchange_class):

    exchange = mock_exchange_class.return_value
    exchange.options.max_trade_size = 1e6
    exchange.id = "fake_exchange_id"
    exchange.name = "coinbase"
    exchange.quote_price = lambda pair: Decimal(7000.00)

    broker = Broker()
    broker.exchanges = [exchange]

    wallets = [Wallet(exchange, 10000 * USD), Wallet(exchange, 0 * BTC)]
    portfolio = Portfolio(USD, wallets)

    order = Order(step=0,
                  exchange_pair=ExchangePair(exchange, USD / BTC),
                  side=TradeSide.BUY,
                  trade_type=TradeType.MARKET,
                  quantity=5200.00 * USD,
                  portfolio=portfolio,
                  price=7000.00)

    order.attach(broker)

    order.execute()

    broker._executed[order.id] = order

    trade = mock_trade_class.return_value
    trade.quantity = 5197.00 * USD
    trade.commission = 3.00 * USD
    trade.order_id = order.id

    assert order.status == OrderStatus.OPEN
    order.fill(trade)
    assert order.status == OrderStatus.FILLED

    assert order.remaining == 0

    assert trade in broker.trades[order.id] 
Example #28
Source File: quantity.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def __init__(self, instrument: 'Instrument', size: Union[float, Decimal] = 0, path_id: str = None):
        if size < 0:
            raise InvalidNegativeQuantity(size)

        self._instrument = instrument
        self._size = size if isinstance(size, Decimal) else Decimal(size)
        self._path_id = path_id 
Example #29
Source File: metrics.py    From figures with MIT License 5 votes vote down vote up
def get_course_average_progress_for_time_period(site, start_date, end_date, course_id):
    filter_args = dict(
        site=site,
        date_for__gt=prev_day(start_date),
        date_for__lt=next_day(end_date),
        course_id=course_id
    )

    qs = CourseDailyMetrics.objects.filter(**filter_args)
    if qs:
        value = qs.aggregate(average=Avg('average_progress'))['average']
        return float(Decimal(value).quantize(Decimal('.00')))
    else:
        return 0.0 
Example #30
Source File: course_daily_metrics.py    From figures with MIT License 5 votes vote down vote up
def get_average_progress_deprecated(course_id, date_for, course_enrollments):
    """Collects and aggregates raw course grades data
    """
    progress = []
    for ce in course_enrollments:
        try:
            course_progress = figures.metrics.LearnerCourseGrades.course_progress(ce)
            figures.pipeline.loaders.save_learner_course_grades(
                site=figures.sites.get_site_for_course(course_id),
                date_for=date_for,
                course_enrollment=ce,
                course_progress_details=course_progress['course_progress_details'])
        # TODO: Use more specific database-related exception
        except Exception as e:  # pylint: disable=broad-except
            error_data = dict(
                msg='Unable to get course blocks',
                username=ce.user.username,
                course_id=str(ce.course_id),
                exception=str(e),
                )
            log_error(
                error_data=error_data,
                error_type=PipelineError.GRADES_DATA,
                user=ce.user,
                course_id=ce.course_id,
                )
            course_progress = dict(
                progress_percent=0.0,
                course_progress_details=None)
        if course_progress:
            progress.append(course_progress)

    if progress:
        progress_percent = [rec['progress_percent'] for rec in progress]
        average_progress = float(sum(progress_percent)) / float(len(progress_percent))
        average_progress = float(Decimal(average_progress).quantize(Decimal('.00')))
    else:
        average_progress = 0.0

    return average_progress