def test_decimal_float(self): """Regression test for issue #3.""" result = mathfilters.mod(Decimal('7.8'), '2.2') self.assertTrue(1 < result < 2, repr(result))
def get_multi_order_details_resp(self, req, order_ids): multi_trades = self.resp(req) data = {} for order_id in order_ids: total_fiat = Money('0', self.currency) total_btc = Money('0', 'BTC') our_trades = [] if order_id in multi_trades: order = multi_trades[order_id] trade_ids = order.get('trades', []) if trade_ids: opentm = order['opentm'] # Partially-executed orders haven't "closed" yet so they don't # have a closetm. We only need the already executed trades, so we # end the interval at NOW(). if 'closetm' in order: closetm = order['closetm'] else: closetm = Decimal(Delorean().epoch) trades = self.get_trades_info_from_ledger( trade_ids, opentm, closetm, ) for t_id, t in trades.iteritems(): fiat = abs(t['fiat']) btc = abs(t['btc']) if t['btc_fee'] and t['fiat_fee']: raise exceptions.ExchangeAPIErrorException( self, '#%s charged fees in both fiat (%s) and BTC (%s)' % ( order_id, t['fiat_fee'], t['btc_fee'], )) elif t['btc_fee']: fee = t['btc_fee'] else: fee = t['fiat_fee'] total_fiat += fiat total_btc += btc our_trades.append({ 'time': int(t['time']), 'trade_id': unicode(t_id), 'fee': fee, 'btc': btc, 'fiat': fiat, }) data[order_id] = { 'time_created': int(order['opentm']), 'type': self._order_mode_to_const(order['descr']['type']), 'btc_total': total_btc, 'fiat_total': total_fiat, 'trades': our_trades, } return data
def test_sum(self): self.assertEqual(self.table.columns['one'].aggregate(Sum()), Decimal('6.5')) self.assertEqual(self.table.columns['two'].aggregate(Sum()), Decimal('13.13'))
from cdecimal import Decimal version = "0.0013" block_reward = 500 # Initial block reward miner_core_count = -1 # -1 evaluates to number of cores # Lower limits on what the "time" tag in a block can say. median_block_time_limit = 100 # Take the median of this many of the blocks. # How far back in history do we look when we use statistics to guess at # the current blocktime and difficulty. history_length = 110 # How far in history we look when we determine next block reward # This constant is selected such that the 50 most recent blocks count for 1/2 the # total weight. inflection = Decimal('0.98') # How often to generate a block in seconds blocktime = 60 halve_at = (365 * 24 * 60 * 60 / blocktime) # Approximately one year recalculate_target_at = (4 * 60 * 60 // blocktime) # It's every half day # Precalculate memoized_weights = [inflection**i for i in range(history_length)] first_target = '0' * 4 + 'f' * 60 def generate_default_config(): config = dict() config['DEBUG'] = False config['database'] = {"type": "sql", "location": "halocoin.db"}
def test_round_limits(self): self.assertEqual(round_limits(Decimal('-2.7'), Decimal('2.7')), (Decimal('-3'), Decimal('3'))) self.assertEqual(round_limits(Decimal('-2.2'), Decimal('2.2')), (Decimal('-3'), Decimal('3'))) self.assertEqual(round_limits(Decimal('-2.22'), Decimal('2.22')), (Decimal('-3'), Decimal('3'))) self.assertEqual(round_limits(Decimal('0'), Decimal('75')), (Decimal('0'), Decimal('80'))) self.assertEqual(round_limits(Decimal('45'), Decimal('300')), (Decimal('0'), Decimal('300'))) self.assertEqual(round_limits(Decimal('200.75'), Decimal('715.345')), (Decimal('200'), Decimal('800'))) self.assertEqual(round_limits(Decimal('0.75'), Decimal('0.800')), (Decimal('0'), Decimal('1'))) self.assertEqual(round_limits(Decimal('-0.505'), Decimal('0.47')), (Decimal('-0.6'), Decimal('0.5')))
def test_mad(self): with self.assertRaises(NullComputationError): self.table.columns['one'].mad() self.assertAlmostEqual(self.table.columns['two'].mad(), Decimal('0'))
# 19.999999999999996, 19.595917942265423, 0.0] # # the correct answer is (the order may vary) # # print (math.sqrt(1248.),20.,math.sqrt(384.),0.,0.) # # (35.327043465311391, 20.0, 19.595917942265423, 0.0, 0.0) # # transpose and matrix multiplication functions are also included # to facilitate the solution of linear systems. # # Version 1.0 2005 May 01 import copy from cdecimal import Decimal ten = Decimal('10') one = Decimal('1') zero = Decimal('0') half = Decimal('0.5') def sqrt(n): return n**half #return sqrt_h(n, decimal.Decimal(1)) def svd(a): '''Compute the singular value decomposition of array.''' # Golub and Reinsch state that eps should not be smaller than the # machine precision, ie the smallest number # for which 1+e>1. tol should be beta/e where beta is the smallest
def test_decimal_decimal(self): val1 = Decimal('9.9') val2 = Decimal('6.6') self.assertEqual(Decimal('3.3'), mathfilters.sub(val1, val2))
def test_decimal_int(self): val1 = Decimal('9.999') val2 = 9 self.assertEqual(Decimal('0.999'), mathfilters.sub(val1, val2))
def test_decimal(self): self.assertEqual(Decimal('2.3'), mathfilters.valid_numeric(Decimal('2.3'))) self.assertEqual(Decimal('-2.3'), mathfilters.valid_numeric(Decimal('-2.3')))
def test_decimal_decimal(self): a, b = mathfilters.handle_float_decimal_combinations( Decimal('2.0'), Decimal('1.0'), '+') self.assertTrue(isinstance(a, Decimal), 'Type is {0}'.format(type(a))) self.assertTrue(isinstance(b, Decimal), 'Type is {0}'.format(type(b)))
def test_float_decimal(self): result = mathfilters.addition('3.7', Decimal('11.1')) self.assertEqual(Decimal('14.8'), result)
def test_decimal_int(self): val1 = Decimal('1.9') val2 = 4 self.assertEqual(Decimal('5.9'), mathfilters.addition(val1, val2))
def test_decimal_decimal(self): val1 = Decimal('7.3') val2 = Decimal('2.7') self.assertEqual(Decimal('10'), mathfilters.addition(val1, val2))
def test_max(self): self.assertEqual(self.table.columns['one'].max(), Decimal('2.7')) self.assertEqual(self.table.columns['two'].max(), Decimal('4.1'))
def test_float_decimal(self): """Regression test for issue #3.""" result = mathfilters.sub('201.7', Decimal('3.1')) self.assertTrue(198 < result < 199, repr(result))
def test_mode(self): with self.assertRaises(NullComputationError): self.table.columns['one'].mode() self.assertEqual(self.table.columns['two'].mode(), Decimal('3.42'))
import warnings from babel.core import Locale import six from agate.data_types.base import DataType from agate.exceptions import CastError #: A list of currency symbols sourced from `Xe <http://www.xe.com/symbols.php>`_. DEFAULT_CURRENCY_SYMBOLS = [ u'؋', u'$', u'ƒ', u'៛', u'¥', u'₡', u'₱', u'£', u'€', u'¢', u'﷼', u'₪', u'₩', u'₭', u'₮', u'₦', u'฿', u'₤', u'₫' ] POSITIVE = Decimal('1') NEGATIVE = Decimal('-1') class Number(DataType): """ Data representing numbers. :param locale: A locale specification such as :code:`en_US` or :code:`de_DE` to use for parsing formatted numbers. :param group_symbol: A grouping symbol used in the numbers. Overrides the value provided by the specified :code:`locale`. :param decimal_symbol: A decimal separate symbol used in the numbers. Overrides the value
def test_number_cast(self): values = (2, 1, None, Decimal('2.7'), 'n/a') casted = tuple(NumberType().cast(v) for v in values) self.assertSequenceEqual( casted, (Decimal('2'), Decimal('1'), None, Decimal('2.7'), None))
def bins(self, column_name, count=10, start=None, end=None): """ Generates (approximately) evenly sized bins for the values in a column. Bins may not be perfectly even if the spread of the data does not divide evenly, but all values will always be included in some bin. The resulting table will have two columns. The first will have the same name as the specified column, but will be type :class:`.Text`. The second will be named :code:`count` and will be of type :class:`.Number`. :param column_name: The name of the column to bin. Must be of type :class:`.Number` :param count: The number of bins to create. If not specified then each value will be counted as its own bin. :param start: The minimum value to start the bins at. If not specified the minimum value in the column will be used. :param end: The maximum value to end the bins at. If not specified the maximum value in the column will be used. :returns: A new :class:`Table`. """ if start is None or end is None: start, end = utils.round_limits( Min(column_name).run(self), Max(column_name).run(self)) else: start = Decimal(start) end = Decimal(end) spread = abs(end - start) size = spread / count breaks = [start] for i in range(1, count + 1): top = start + (size * i) breaks.append(top) decimal_places = utils.max_precision(breaks) break_formatter = utils.make_number_formatter(decimal_places) def name_bin(i, j, first_exclusive=True, last_exclusive=False): inclusive = format_decimal(i, format=break_formatter) exclusive = format_decimal(j, format=break_formatter) output = u'[' if first_exclusive else u'(' output += u'%s - %s' % (inclusive, exclusive) output += u']' if last_exclusive else u')' return output bins = OrderedDict() for i in range(1, len(breaks)): last_exclusive = (i == len(breaks) - 1) name = name_bin(breaks[i - 1], breaks[i], last_exclusive=last_exclusive) bins[name] = Decimal('0') for row in self._rows: value = row[column_name] if value is None: try: bins[None] += 1 except KeyError: bins[None] = Decimal('1') continue # pragma: no cover i = 1 try: while value >= breaks[i]: i += 1 except IndexError: i -= 1 last_exclusive = (i == len(breaks) - 1) name = name_bin(breaks[i - 1], breaks[i], last_exclusive=last_exclusive) bins[name] += 1 column_names = [column_name, 'count'] column_types = [Text(), Number()] return Table(bins.items(), column_names, column_types, row_names=tuple(bins.keys()))
def jd_to_mjd(jd): return jd - Decimal(2400000.5)
def test_quartiles(self): """ CDF quartile tests from: http://www.amstat.org/publications/jse/v14n3/langford.html#Parzen1979 """ # N = 4 rows = [(n, ) for n in [1, 2, 3, 4]] table = Table(rows, (('ints', self.number_type), )) quartiles = table.columns['ints'].quartiles() for i, v in enumerate(['1', '1.5', '2.5', '3.5', '4']): self.assertEqual(quartiles[i], Decimal(v)) # N = 5 rows = [(n, ) for n in [1, 2, 3, 4, 5]] table = Table(rows, (('ints', self.number_type), )) quartiles = table.columns['ints'].quartiles() for i, v in enumerate(['1', '2', '3', '4', '5']): self.assertEqual(quartiles[i], Decimal(v)) # N = 6 rows = [(n, ) for n in [1, 2, 3, 4, 5, 6]] table = Table(rows, (('ints', self.number_type), )) quartiles = table.columns['ints'].quartiles() for i, v in enumerate(['1', '2', '3.5', '5', '6']): self.assertEqual(quartiles[i], Decimal(v)) # N = 7 rows = [(n, ) for n in [1, 2, 3, 4, 5, 6, 7]] table = Table(rows, (('ints', self.number_type), )) quartiles = table.columns['ints'].quartiles() for i, v in enumerate(['1', '2', '4', '6', '7']): self.assertEqual(quartiles[i], Decimal(v)) # N = 8 (doubled) rows = [(n, ) for n in [1, 1, 2, 2, 3, 3, 4, 4]] table = Table(rows, (('ints', self.number_type), )) quartiles = table.columns['ints'].quartiles() for i, v in enumerate(['1', '1.5', '2.5', '3.5', '4']): self.assertEqual(quartiles[i], Decimal(v)) # N = 10 (doubled) rows = [(n, ) for n in [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]] table = Table(rows, (('ints', self.number_type), )) quartiles = table.columns['ints'].quartiles() for i, v in enumerate(['1', '2', '3', '4', '5']): self.assertEqual(quartiles[i], Decimal(v)) # N = 12 (doubled) rows = [(n, ) for n in [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]] table = Table(rows, (('ints', self.number_type), )) quartiles = table.columns['ints'].quartiles() for i, v in enumerate(['1', '2', '3.5', '5', '6']): self.assertEqual(quartiles[i], Decimal(v)) # N = 14 (doubled) rows = [(n, ) for n in [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7]] table = Table(rows, (('ints', self.number_type), )) quartiles = table.columns['ints'].quartiles() for i, v in enumerate(['1', '2', '4', '6', '7']): self.assertEqual(quartiles[i], Decimal(v))
""" """ from cdecimal import Decimal BUILTIN_STRAT_CONFIGS = { 'manual': { 'display_name': 'Manual', 'strategy_actor': 'MULTI', 'price_currency': 'USD', 'volume_currency': 'BTC', 'base_point_radius': 10, 'graph_volume_threshold': Decimal('0.00001'), 'position_graph_max': Decimal('100'), 'position_graph_min': Decimal('-100'), }, 'multiexchange_linear': { 'display_name': 'Multiexchange Linear BTC', 'strategy_actor': 'MULTIEXCHANGE_LINEAR', 'price_currency': 'USD', 'volume_currency': 'BTC', 'base_point_radius': 10, 'graph_volume_threshold': Decimal('0.00001'), 'position_graph_max': Decimal('2'), 'position_graph_min': Decimal('-2'), }, 'simple_mm': { 'display_name': 'Simple Market Making', 'strategy_actor': 'SIMPLE_MM', 'price_currency': 'USD', 'volume_currency': 'BTC',
def test_configurable_value_number(self): value = '133120102' output = configuration.parse_configurable_value(value) output.should.equal(Decimal('133120102'))
def get_trades_info_from_ledger(self, trade_ids, order_open_timestamp, order_close_timestamp): """ Check the ledger entries to get accurate numbers for how much our balance was changed. The ledger is Kraken's only real source of truth, the trades/order endpoints lie to us. """ # We add a 0.1s buffer to make sure we get entries right on the boundary # timestamps. ledger_start = order_open_timestamp - Decimal('0.1') # We add a 1s buffer because it takes Kraken a bit of time to write to the # ledger. ledger_end = order_close_timestamp + Decimal('1') entries = self.get_ledger_entries( start=ledger_start, end=ledger_end, ) trades_info = {} for trade_id in trade_ids: trades_info[trade_id] = { 'btc': Money.loads('BTC 0'), 'btc_fee': Money.loads('BTC 0'), 'fiat': Money(0, self.currency), 'fiat_fee': Money(0, self.currency), } for ledger_id, entry in entries.iteritems(): trade_id = entry['refid'] if trade_id not in trade_ids: continue amount = Decimal(entry['amount']) if entry['type'] == 'credit': # Credit ledger entries show up when we dip into our line of credit. # They have opposite signs, and need to be included along side the # trade ledger entries to get accurate trade amounts. amount = -amount elif entry['type'] == 'trade': pass else: raise exceptions.ExchangeAPIErrorException( self, 'Unexpected ledger entry type "%s"' % entry['type'], ) currency = self.convert_from_kraken_currency(entry['asset']) if currency == 'BTC': trades_info[trade_id]['btc'] += Money(amount, 'BTC') trades_info[trade_id]['btc_fee'] += Money(entry['fee'], 'BTC') else: trades_info[trade_id]['fiat'] += Money(amount, currency) trades_info[trade_id]['fiat_fee'] += Money(entry['fee'], currency) # There are multiple ledger entries per trade, but they should all be going #through at the same time, so we can just take the timestamp of the last # one. trades_info[trade_id]['time'] = entry['time'] return trades_info
def test_configurable_value_number_2(self): value = '0' output = configuration.parse_configurable_value(value) output.should.equal(Decimal('0'))
def print_bars(table, label_column_name, value_column_name, domain=None, width=120, output=sys.stdout): """ Print a bar chart representation of two columns. """ y_label = label_column_name label_column = table.columns[label_column_name] # if not isinstance(label_column.data_type, Text): # raise ValueError('Only Text data is supported for bar chart labels.') x_label = value_column_name value_column = table.columns[value_column_name] if not isinstance(value_column.data_type, Number): raise DataTypeError( 'Only Number data is supported for bar chart values.') output = output width = width # Format numbers decimal_places = max_precision(value_column) value_formatter = make_number_formatter(decimal_places) formatted_labels = [] for label in label_column: formatted_labels.append(six.text_type(label)) formatted_values = [] for value in value_column: formatted_values.append(format_decimal(value, format=value_formatter)) max_label_width = max(max([len(l) for l in formatted_labels]), len(y_label)) max_value_width = max(max([len(v) for v in formatted_values]), len(x_label)) plot_width = width - (max_label_width + max_value_width + 2) min_value = Min(value_column_name).run(table) max_value = Max(value_column_name).run(table) # Calculate dimensions if domain: x_min = Decimal(domain[0]) x_max = Decimal(domain[1]) if min_value < x_min or max_value > x_max: raise ValueError('Column contains values outside specified domain') else: x_min, x_max = round_limits(min_value, max_value) # All positive if x_min >= 0: x_min = Decimal('0') plot_negative_width = 0 zero_line = 0 plot_positive_width = plot_width - 1 # All negative elif x_max <= 0: x_max = Decimal('0') plot_negative_width = plot_width - 1 zero_line = plot_width - 1 plot_positive_width = 0 # Mixed signs else: spread = x_max - x_min negative_portion = (x_min.copy_abs() / spread) # Subtract one for zero line plot_negative_width = int( ((plot_width - 1) * negative_portion).to_integral_value()) zero_line = plot_negative_width plot_positive_width = plot_width - (plot_negative_width + 1) def project(value): if value >= 0: return plot_negative_width + int( (plot_positive_width * (value / x_max)).to_integral_value()) else: return plot_negative_width - int( (plot_negative_width * (value / x_min)).to_integral_value()) # Calculate ticks ticks = OrderedDict() # First tick ticks[0] = x_min ticks[plot_width - 1] = x_max tick_fractions = [Decimal('0.25'), Decimal('0.5'), Decimal('0.75')] # All positive if x_min >= 0: for fraction in tick_fractions: value = x_max * fraction ticks[project(value)] = value # All negative elif x_max <= 0: for fraction in tick_fractions: value = x_min * fraction ticks[project(value)] = value # Mixed signs else: # Zero tick ticks[zero_line] = Decimal('0') # Halfway between min and 0 value = x_min * Decimal('0.5') ticks[project(value)] = value # Halfway between 0 and max value = x_max * Decimal('0.5') ticks[project(value)] = value decimal_places = max_precision(ticks.values()) tick_formatter = make_number_formatter(decimal_places) ticks_formatted = OrderedDict() for k, v in ticks.items(): ticks_formatted[k] = format_decimal(v, format=tick_formatter) def write(line): output.write(line + '\n') # Chart top top_line = u'%s %s' % (y_label.ljust(max_label_width), x_label.rjust(max_value_width)) write(top_line) # Bars for i, label in enumerate(formatted_labels): value = value_column[i] if value == 0: bar_width = 0 elif value > 0: bar_width = project(value) - plot_negative_width elif value < 0: bar_width = plot_negative_width - project(value) label_text = label.ljust(max_label_width) value_text = formatted_values[i].rjust(max_value_width) bar = BAR_MARK * bar_width if value >= 0: gap = (u' ' * plot_negative_width) # All positive if x_min <= 0: bar = gap + ZERO_MARK + bar else: bar = bar + gap + ZERO_MARK else: bar = u' ' * (plot_negative_width - bar_width) + bar # All negative or mixed signs if x_max > value: bar = bar + ZERO_MARK bar = bar.ljust(plot_width) write('%s %s %s' % (label_text, value_text, bar)) # Axis & ticks axis = HORIZONTAL_LINE * plot_width tick_text = u' ' * width for i, (tick, label) in enumerate(ticks_formatted.items()): # First tick if tick == 0: offset = 0 # Last tick elif tick == plot_width - 1: offset = -(len(label) - 1) else: offset = int(-(len(label) / 2)) pos = (width - plot_width) + tick + offset # Don't print intermediate ticks that would overlap if tick != 0 and tick != plot_width - 1: if tick_text[pos - 1:pos + len(label) + 1] != ' ' * (len(label) + 2): continue tick_text = tick_text[:pos] + label + tick_text[pos + len(label):] axis = axis[:tick] + TICK_MARK + axis[tick + 1:] write(axis.rjust(width)) write(tick_text)
def test_text_cast(self): values = ('a', 1, None, Decimal('2.7'), 'n/a') casted = tuple(TextType().cast(v) for v in values) self.assertSequenceEqual(casted, ('a', '1', None, '2.7', None))
def test_min(self): self.assertEqual(self.table.columns['one'].aggregate(Min()), Decimal('1.1')) self.assertEqual(self.table.columns['two'].aggregate(Min()), Decimal('2.19'))
def test_negative_decimal(self): self.assertEqual(Decimal('9.99'), mathfilters.absolute(Decimal('-9.99')))