Esempio n. 1
0
def test_array():
    v = mpd.MoneyArray([1, 2, 3], 'GBP')
    result = np.array(v)
    expected = np.array([
        money.XMoney(1, 'GBP'),
        money.XMoney(2, 'GBP'),
        money.XMoney(3, 'GBP'),
    ])
    tm.assert_numpy_array_equal(result, expected)
Esempio n. 2
0
def test_to_pymoney():
    v = mpd.MoneyArray([1, 2, 3], 'USD')
    result = v.to_pymoney()
    expected = [
        money.XMoney(1, 'USD'),
        money.XMoney(2, 'USD'),
        money.XMoney(3, 'USD'),
    ]
    assert result == expected
Esempio n. 3
0
def test_iter_works():
    x = mpd.MoneyArray([0, 1, 2], 'GBP')
    result = list(x)
    expected = [
        money.XMoney(0, 'GBP'),
        money.XMoney(1, 'GBP'),
        money.XMoney(2, 'GBP'),
    ]
    assert result == expected
Esempio n. 4
0
    def __ge__(self, other):
        if not isinstance(other, MoneyArray):
            return NotImplemented
        mask = self.isna() | other.isna()
        same = (self.data['cu'] == other.data['cu']) | mask
        result = (self.data['va'] >= other.data['va'])
        for i, ceq in enumerate(same):
            if not ceq:
                result[i] = money.XMoney(*self.data[i]) < money.XMoney(
                    *self.other[i])

        result[mask] = False
        return result
Esempio n. 5
0
    def to_currency(self, money_code, shallow=True, in_place=False):
        if shallow:
            if in_place:
                copy = self
            else:
                copy = self.copy()
            copy.default_money_code = money_code
        else:
            mask = self.isna()
            same = (self.data['cu'] == money_code) | mask
            decimalize = np.vectorize(decimal.Decimal)

            result = self.data
            if not in_place:
                result = result.copy()

            for i, ceq in enumerate(same):
                if not ceq:
                    va = money.XMoney(self.data[i]['va'], self.data[i]['cu']) \
                           .to(money_code).amount
                    result[i] = (va, money_code)

            if in_place:
                self.data = result
            copy = self.__class__(result,
                                  default_money_code=money_code,
                                  dtype=self.dtype)

        return copy
Esempio n. 6
0
    def _reduce(self, name, skipna=True, **kwargs):
        """ _reduce is called when min, sum or max is called via the pandas series (column). 
        It's stored as an array of floats & the _reduce operation is performed on that.
        """
        currencies = [cu for cu in np.unique(self.data['cu']) if cu]
        totals = {}

        if name == 'mean':
            meth = getattr(self, '_sum', None)
        else:
            meth = getattr(self, '_' + name, None)

        if meth:
            if len(currencies) > 1:
                money_code = self.default_money_code if self.default_money_code else currencies[
                    0]
                for i, currency in enumerate(currencies):
                    totals[currency] = money.XMoney(
                        meth(self.data['va'][self.data['cu'] == currency],
                             skipna=skipna,
                             **kwargs), currency)
                total = meth(np.array([
                    subtotal.to(money_code).amount
                    for subtotal in totals.values()
                ]),
                             skipna=skipna,
                             **kwargs)
                if name == 'mean':
                    total = total / len(self.data)
                total = money.XMoney(amount=total, currency=money_code)
            else:
                money_code = currencies[
                    0] if currencies else self.default_money_code
                total = money.XMoney(
                    meth(self.data['va'], skipna=skipna, **kwargs), money_code)

            return total
        else:
            msg = "'{}' does not implement reduction '{}'"
            raise TypeError(msg.format(type(self).__name__, name))
Esempio n. 7
0
    def to_decimals(self, money_code=None):
        r"""Create a list of decimals from an ISO4712 code, attempting conversion with XMoney where necessary.

        Parameters
        ----------
        money_code : ISO4712 3-letter currency code

        Returns
        -------
        list of decimals

        Examples
        --------
        >>> arr = MoneyArray([10, 20], 'GBP')
        >>> values = arr.to_decimals('GBP')
        >>> values
        [10, 20]

        See Also
        --------
        to_bytes
        """

        if not money_code:
            money_code = self.default_money_code
            if not money_code:
                codes = {c['cu'] for c in self.data if c['cu']}
                if len(codes) != 1:
                    raise TypeError(
                        "Cannot output mixed-currency monies as decimal "
                        "without either a target or default currency")
                money_code = codes[0]

        mask = self.isna()
        same = (self.data['cu'] == money_code) | mask
        decimalize = np.vectorize(decimal.Decimal)
        result = decimalize(self.data['va'])
        for i, ceq in enumerate(same):
            if not ceq:
                result[i] = money.XMoney(*self.data[i]).to(money_code).amount

        return result
Esempio n. 8
0
    def to_pymoney(self):
        """Convert the array to a list of scalar Money objects.

        Returns
        -------
        addresses : List
            Each element of the list will be a :class:`money.XMoney` or np.nan

        See Also
        --------

        Examples
        ---------
        >>> MoneyArray(['120 EUR', '127 USD']).to_pymoney()
        [XMoney('120', 'EUR'), XMoney('127', 'USD')]
        """
        return [
            money.XMoney(x['va'], x['cu']) if x['cu'] else np.nan
            for x in self.data
        ]
Esempio n. 9
0
 def _box_scalar(scalar):
     if scalar == (0, ''):
         return np.nan
     elif type(scalar) is tuple:
         return money.XMoney(scalar[0], scalar[1])
     return money.XMoney(scalar['va'], scalar['cu'])
Esempio n. 10
0
from moneypandas import parser, MoneyArray


@pytest.mark.parametrize(
    'values',
    [[u'123 EUR', u'234 EUR']
     # TODO: reinstate byte tests
     # [b'\xc0\xa8\x01\x01',
     # b' \x01\r\xb8\x85\xa3\x00\x00\x00\x00\x8a.\x03ps4'],
     ])
def test_to_money(values):
    result = parser.to_money(values)
    expected = MoneyArray([123, 234], 'EUR')
    assert result.equals(expected)


@pytest.mark.parametrize(
    'val, expected, money_code',
    [(u'123 EUR', money.XMoney(123, 'EUR'), None),
     (123, money.XMoney(123, 'EUR'), 'EUR'),
     (money.XMoney(100, 'GBP'), money.XMoney(100, 'GBP'), None)])
def test_as_money_object(val, expected, money_code):
    result = parser._as_money_object(val, money_code)
    assert result == (expected.amount, expected.currency)


@pytest.mark.parametrize("val", [u"129", -1])
def test_as_money_object_raises(val):
    with pytest.raises(ValueError):
        parser._as_money_object(val)
Esempio n. 11
0
def test_getitem_scalar():
    ser = mpd.MoneyArray([0, 1, 2], 'USD')
    result = ser[1]
    assert result == money.XMoney(1, 'USD')
Esempio n. 12
0
    ser = mpd.MoneyArray([0, 1, 2], 'USD')
    result = ser[1]
    assert result == money.XMoney(1, 'USD')


def test_getitem_slice():
    ser = mpd.MoneyArray([0, 1, 2], 'USD')
    result = ser[1:]
    expected = mpd.MoneyArray([1, 2], 'USD')
    assert result.equals(expected)


@pytest.mark.parametrize('value', [
    u'123 USD',
    123,
    money.XMoney(123, 'USD'),
])
def test_setitem_scalar(value):
    ser = mpd.MoneyArray([0, 1, 2], 'USD')
    ser[1] = value
    expected = mpd.MoneyArray([0, 123, 2], 'USD')
    assert ser.equals(expected)


def test_setitem_array():
    ser = mpd.MoneyArray([0, 1, 2], 'USD')
    ser[[1, 2]] = ['10 USD', '20 USD']
    expected = mpd.MoneyArray([0, 10, 20], 'USD')
    assert ser.equals(expected)

Esempio n. 13
0
def test_setitem_scalar():
    ser = pd.Series(mpd.MoneyArray([0, 1, 2], 'EUR'))
    ser[1] = money.XMoney(10, 'EUR')
    expected = pd.Series(mpd.MoneyArray([0, 10, 2], 'EUR'))
    tm.assert_series_equal(ser, expected)
Esempio n. 14
0
def test_getitem_scalar():
    ser = pd.Series(mpd.MoneyArray([None, 1, 2], 'USD'))
    result = ser[1]
    assert result == money.XMoney(1, 'USD')