def arbitrage1(): if True: capital = 10 import pdb; pdb.set_trace() trade1 = capital / float(finalask2['ask']) currentask1 = float(finalask2['ask']) currentvoluem1 = float(finalask2['total']) #DOGE --> BTC i.e. selling DOGE trade2 = trade1 * float(finalbid3['bid']) currentbid2 = float(finalbid3['bid']) currentvoluem2 = float(finalbid3['total']) #BTC --> LTC i.e. buying LTC trade3 = trade2 / float(finalask1['ask']) currentask3 = float(finalask1['ask']) currentvoluem3 = float(finalask1['total']) PNL = trade3 - capital pnlp = decimal(PNL*100/capital) if PNL > 0: print "LTC/BTC undervalued: --> LTC to DOGE --> DOGE to BTC --> BTC to LTC" print "DOGE/LTC | ASK:",decimal(currentask1),"|Volume:", decimal(currentvoluem1),"LTC" print "DOGE/BTC | BID:",decimal(currentbid2),"| Volume:", decimal(currentvoluem2),"BTC" print "LTC/BTC | ASK:",decimal(currentask3),"| Volume:", decimal(currentvoluem3),"BTC" print "PNL absolut:", decimal(PNL), "PNL in %", pnlp vol1ltc = decimal(currentvoluem1) vol2ltc = currentvoluem2 / float(finalbid1['BID']) vol3ltc = currentvoluem3 / float(finalbid1['BID']) amount = min(vol1ltc, vol2ltc, vol3ltc) decamount = decimal(amount) print "Sell" ,decamount, "LTC"
def test(): print("Introduce x") x = input('x = ') # raw_input devuelve un string print(raizcuadrada(decimal(x)))
def compute_amount_in(moorecoind, txinfo): result = decimal("0.0") for vin in txinfo['vin']: in_info = moorecoind.getrawtransaction(vin['txid'], 1) vout = in_info['vout'][vin['vout']] result = result + vout['value'] return result
def main(): a, b, x = map(int, input().split()) if Decimal(a) * Decimal(b) / Decimal(2) >= Decimal(x) / Decimal(a): else: c = Decimal(b) * Decimal(b) * Decimal(a) ans = math.degrees(math.atan(Decimal(c)/decimal(x))) print(90 - ans)
def main(): import optparse parser = optparse.optionparser(usage="%prog [options]") parser.add_option("--from", dest="fromaddresses", default=none, help="addresses to get moorecoins from") parser.add_option("--to", dest="to", default=none, help="address to get send moorecoins to") parser.add_option("--amount", dest="amount", default=none, help="amount to send") parser.add_option("--fee", dest="fee", default="0.0", help="fee to include") parser.add_option("--datadir", dest="datadir", default=determine_db_dir(), help="location of moorecoin.conf file with rpc username/password (default: %default)") parser.add_option("--testnet", dest="testnet", default=false, action="store_true", help="use the test network") parser.add_option("--dry_run", dest="dry_run", default=false, action="store_true", help="don't broadcast the transaction, just create and print the transaction data") (options, args) = parser.parse_args() check_json_precision() config = read_moorecoin_config(options.datadir) if options.testnet: config['testnet'] = true moorecoind = connect_json(config) if options.amount is none: address_summary = list_available(moorecoind) for address,info in address_summary.iteritems(): n_transactions = len(info['outputs']) if n_transactions > 1: print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions)) else: print("%s %.8f %s"%(address, info['total'], info['account'])) else: fee = decimal(options.fee) amount = decimal(options.amount) while unlock_wallet(moorecoind) == false: pass # keep asking for passphrase until they get it right txdata = create_tx(moorecoind, options.fromaddresses.split(","), options.to, amount, fee) sanity_test_fee(moorecoind, txdata, amount*decimal("0.01")) if options.dry_run: print(txdata) else: txid = moorecoind.sendrawtransaction(txdata) print(txid)
def getStockCurrentDay(code, Market): ''' 获取股票当日数据 腾讯API API地址:http://qt.gtimg.cn/q=sh600383 sh:上海 sz:深圳 返回当天成交数据 code:股票代码 market:股票市场 数据返回@return dict ''' if code and Market: url = 'http://qt.gtimg.cn/q=%s%s' % (Market, code) headers = {'Content-type': 'application/x-javascript; charset=GBK'} result = httpGetContent(url=url, headers=headers, charset='gbk') if result: stocklist = _get_content(result) if stocklist: stockdict = {} stockdict['code'] = code # 股票代码 stockdict['name'] = unicode(stocklist[1], 'utf8') # 股票名称 stockdict['last_closing'] = float(stocklist[4]) # 昨日收盘价格 stockdict['start'] = float(stocklist[5]) # 开盘价格 stockdict['end'] = float(stocklist[3]) # 当前收盘价格(可以是当前价格) stockdict['high'] = float(stocklist[33]) # 最高价格 stockdict['low'] = float(stocklist[34]) # 最低价格 stockdict['buyvol'] = int(stocklist[7]) # 外盘 todo 数据对不上 stockdict["sellvol"] = int(stocklist[8]) # 内盘 todo 数据对不上 stockdict['range_price'] = float(stocklist[31]) # 涨跌价格 stockdict['range_percent'] = float(stocklist[32]) # 涨跌比% stockdict['volume'] = int(stocklist[6]) # 成交量(手) stockdict['total_price'] = int(stocklist[37]) # 成交额(万元) stockdict['change_rate'] = decimal(stocklist[38]) # 换手率 stockdict['pe'] = decimal(stocklist[39]) # 市盈率 stockdict['swing'] = float(stocklist[43]) # 振幅 stockdict['pb'] = float(stocklist[46]) # 股票市净率 stockdict['date'] = stocklist[30][:8] # 时间 stockdict[ "block"] = False if stockdict["start"] else True #股票是否停牌 return stockdict
def select_coins(needed, inputs): # feel free to improve this, this is good enough for my simple needs: outputs = [] have = decimal("0.0") n = 0 while have < needed and n < len(inputs): outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]}) have += inputs[n]["amount"] n += 1 return (outputs, have-needed)
def __init__(self, fields): self.tx_date = fields[0] self.value_date = fields[1] self.currency = fields[2] self.description = fields[3].strip() self.merchant_type = fields[4].strip() self.city = fields[5] self.country = fields[6] self.delta = decimal(fields[7]) self.tx_amount = fields[8]
def __init__(self, fields): self.posting_date = fields[0] self.value_date = fields[1] if len(fields) == 6: self.tx_date = fields[2] ndi = 3 else: self.tx_date = '' ndi = 2 self.description = fields[ndi + 0].strip() self.tx_amount = fields[ndi + 1] self.delta = decimal(fields[ndi + 2])
def typeconvert(item): if item[0] == '/': return item elif item[0] == '[': temp = item temp = temp.replace(' ', ',') return ast.literal_eval(temp) elif item[0].isalpha(): return item else: for c in item: if c == '.': return decimal(item) if c == '-': return int(item) #implies item is a negative integer if not isinstance(int(c), int): return item return int(item)
def figureJsonVal(ctx) -> object: '''grammar:<pre>value : STRING | NUMBER | obj // all array's obj value can't parsed as Anson, taken as HashMap | envelope | array | 'true' | 'false' | 'None' ;</pre> Parameters: ----------- ctx: ValueContext Returns ------- java simple value (STRING, NUMBER, 'true', 'false', None) java equivalent: private static Object figureJsonVal(ValueContext ctx ''' txt = ctx.getText() if (txt == None): return None elif (ctx.NUMBER() != None): try: return int(txt) except Exception as e: # @UnusedVariable try: return float(txt) except Exception as e1: # @UnusedVariable return decimal(txt) elif (ctx.STRING() != None): return AnsonListener.getStringVal(ctx.STRING(), txt) elif (txt != None and txt.toLowerCase().equals("true")): return True elif (txt != None and txt.toLowerCase().equals("flase")): return False return None
def create_tx(moorecoind, fromaddresses, toaddress, amount, fee): all_coins = list_available(moorecoind) total_available = decimal("0.0") needed = amount+fee potential_inputs = [] for addr in fromaddresses: if addr not in all_coins: continue potential_inputs.extend(all_coins[addr]["outputs"]) total_available += all_coins[addr]["total"] if total_available < needed: sys.stderr.write("error, only %f btc available, need %f\n"%(total_available, needed)); sys.exit(1) # # note: # python's json/jsonrpc modules have inconsistent support for decimal numbers. # instead of wrestling with getting json.dumps() (used by jsonrpc) to encode # decimals, i'm casting amounts to float before sending them to moorecoind. # outputs = { toaddress : float(amount) } (inputs, change_amount) = select_coins(needed, potential_inputs) if change_amount > base_fee: # don't bother with zero or tiny change change_address = fromaddresses[-1] if change_address in outputs: outputs[change_address] += float(change_amount) else: outputs[change_address] = float(change_amount) rawtx = moorecoind.createrawtransaction(inputs, outputs) signed_rawtx = moorecoind.signrawtransaction(rawtx) if not signed_rawtx["complete"]: sys.stderr.write("signrawtransaction failed\n") sys.exit(1) txdata = signed_rawtx["hex"] return txdata
def typeconvert(item): if item[0] == '/': #any item in the form '/word' return item elif item[0] == '[': #any array with items inside temp = item temp = temp.replace(' ', ',') return ast.literal_eval(temp) elif item[0].isalpha(): #any PS operator return item else: #covers any integers/decimal values for c in item: if c == '.': return decimal(item) #presence of decimal -> return decimal value if c == '-': return int(item) #implies item is a negative integer if not isinstance(int(c), int): return item #implies that item is an operator (not an integer) return int(item)
def munge(self, infile): '''DOCSTRING''' rtnum = 2 if not check_filename(infile, rtnum): print("Error: invalid input %s" % os.path.basename(infile)) sys.exit(1) else: dat = file(infile, 'r') recordset = [] for line in dat: # TODO think about a field name to character range mapping for # this. RT = field(line[0]) VERSION = field(line[1:5]) TLID = field(line[5:15]) RTSQ = field(line[15:18]) LONG1 = decimal(field(line[18:28])) LAT1 = decimal(field(line[28:37])) LONG2 = decimal(field(line[37:47])) LAT2 = decimal(field(line[47:56])) LONG3 = decimal(field(line[56:66])) LAT3 = decimal(field(line[66:75])) LONG4 = decimal(field(line[75:85])) LAT4 = decimal(field(line[85:94])) LONG5 = decimal(field(line[94:104])) LAT5 = decimal(field(line[104:113])) LONG6 = decimal(field(line[113:123])) LAT6 = decimal(field(line[123:132])) LONG7 = decimal(field(line[132:142])) LAT7 = decimal(field(line[142:151])) LONG8 = decimal(field(line[151:161])) LAT8 = decimal(field(line[161:170])) LONG9 = decimal(field(line[170:180])) LAT9 = decimal(field(line[180:189])) LONG10 = decimal(field(line[189:199])) LAT10 = decimal(field(line[199:208])) # It is an error if any of RT, VERSION, TLID, RTSQ, LONG1 or LAT1 # are not present. # if not check_required((RT, VERSION, TLID, RTSQ, LONG1, LAT1)): print("One of the required fields is missing!") sys.exit(1) # TODO Ask the user what field separator they want (one space, # vtab, comma), but default to comma. Keep in sync with the other # munge tool. #fieldsep='\t' fieldsep = ',' recordset.append( fieldsep.join( (RT, VERSION, TLID, RTSQ, str(LONG1), str(LAT1), str(LONG2), str(LAT2), str(LONG3), str(LAT3), str(LONG4), str(LAT4), str(LONG5), str(LAT5), str(LONG6), str(LAT6), str(LONG7), str(LAT7), str(LONG8), str(LAT8), str(LONG9), str(LAT9), str(LONG10), str(LAT10)))) dat.close() return recordset
# -*- coding: utf-8 -*- """ Created on Thu Oct 30 16:15:53 2014 @author: nscheidler """ from decimal import * for i in range(2,1000): if(len(str(decimal(1)/decimal(i)))) > 15: print i, 1.0/i def cycleLength(fraction): curCycle = [] for i in range(2,len(str(fraction))): print i
x = '3334.321' import decimal i = int(decimal(x)) print i type(i)
import decimal print(decimal('0.70'))
import math import decimal if __name__ == '__main__': STR = str(input().split()) v = decimal(STR[0]) t = decimal(STR[1]) print(v * t)
t = Template('${village}folk send $$10 to $cause.') t.substitute(village='Nottingham', cause='the ditch fund') import time, os.path photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg'] class BatchRename(Template): delimiter = '%' fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ') fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ') class BatchRename(Template): delimiter = '%' fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ') class BatchRename(Template): delimiter = '%' fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ') from decimal import * round(decimal('0.70') * decimal('1.05'), 2) from decimal import * round(Decimal('0.70') * Decimal('1.05'), 2) round(.70 * 1.05, 2) from decimal import * round(Decimal('0.70') * Decimal('1.05'), 2) from decimal import * round(Decimal ('0.70') * Decimal ('1.05'), 2) round(0.70 * 1.05, 2) round(Decimal ('0.70') * Decimal ('1.05'), 2) round(Decimal('0.70') * Decimal('1.05'), 2) Decimal('1.00') % Decimal('.10') 1.00 % 0.10 sum([Decimal('0.1')]*10) == Decimal('1.0') sum([0.1]*10) == 1.0 sum([0.1]*10) == 1
def compute_amount_out(txinfo): result = decimal("0.0") for vout in txinfo['vout']: result = result + vout['value'] return result
# on localhost. # # depends on jsonrpc # from decimal import * import getpass import math import os import os.path import platform import sys import time from jsonrpc import serviceproxy, json base_fee=decimal("0.001") def check_json_precision(): """make sure json library being used does not lose precision converting btc values""" n = decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise runtimeerror("json encode/decode loses precision") def determine_db_dir(): """return the default location of the moorecoin data directory""" if platform.system() == "darwin": return os.path.expanduser("~/library/application support/moorecoin/") elif platform.system() == "windows": return os.path.join(os.environ['appdata'], "moorecoin") return os.path.expanduser("~/.moorecoin")
def Output(language, inspection, sessionCount): #If the file is empty, we will create a file with headers included. #If not, we will append only values to the end of the file. #User can specify if headers always get added no matter what. global addHeaders try: if (os.stat(outputfile).st_size == 0): file = open(outputfile, 'w') else: if horizontal == True: file = open(outputfile, 'w') else: file = open(outputfile, 'a') except IOError: print( "ERROR: Unable to access file. Is it currently open or owned by a different user?" ) return except OSError: addHeaders = True file = open(outputfile, 'w') #Let's create a dictionary for easy search sessionCountDict = {} decimal.getcontext().rounding = decimal.ROUND_DOWN decimal.getcontext().prec = 2 for item in inspection: keyName = item[0] countForKey = item[1] sessionCountDict[keyName] = countForKey #Horizontal print - this includes the individual numbers as well as the percentage. if horizontal == True: printString = "CURRENT SESSION NUMBER," + sessionCount print(printString) file.write(printString + "\n") printString = "KEY NAME,SESSION COUNT,VALUE MAX,PERCENT USED" print(printString) file.write(printString + "\n") for item in language: if item[0] in sessionCountDict: percentUsed = 0.0 #Divde by value count / valueMax to get percent used of the last slice it exists in. try: percentUsed = float( float(sessionCountDict[item[0]]) / float(item[4]) * 100.0) percentUsed = decimal(percentUsed) except ZeroDivisionError: percentUsed = 0.0 #Truncate to 2 decimal places printString = item[0] + "," + sessionCountDict[ item[0]] + "," + item[4] + "," + str(percentUsed) + "%" print(printString) file.write(printString + "\n") else: percentUsed = 0.0 printString = item[0] + ",0," + item[4] + "," + str( percentUsed) + "%" print(printString) file.write(printString + "\n") #Vertical Printing else: #Create top row with names length = len(language) #Add headers if new file or they want them if (addHeaders == True): printString = "SESSION NUMBER," counter = 0 for item in language: printString = printString + item[0] #Add commas except at last item if (counter < length - 1): printString = printString + "," counter = counter + 1 print(printString) file.write(printString + "\n") #Now, create row of data starting with sessionCount followed by the right percentages printString = sessionCount + "," counter = 0 for item in language: if item[0] in sessionCountDict: try: percentUsed = float( float(sessionCountDict[item[0]]) / float(item[4]) * 100.0) percentUsed = round(percentUsed, 1) except ZeroDivisionError: percentUsed = 0.0 else: percentUsed = 0.0 printString = printString + str(percentUsed) + "%" if (counter < length - 1): printString = printString + "," counter = counter + 1 print(printString) file.write(printString + "\n")
import decimal from Decimal product_cost = decimal(88.40) commission_rate = decimal(0.08) qty = 450 product_cost += (commission_rate * product_cost) print(product_cost * qty)
def integer(): c = 7 d = 3 sum1 = c + d #can be +,-,/,// print(f'Integer fn result is {sum1}') print(type(sum1)) boolean(False) floating() def floating(): e = .1 f = .3 sum2 = e + e - f #can be any arithmetic operator print(f'Floating fn result is {sum2}') print(type(sum2)) boolean(True) def boolean(g): if g: print('Boolean call is from Floating fn') print(type(g)) else: print('Boolean call is from Integer fn') print(type(g)) decimal()
if timezone.is_aware(value): raise ValueError("Django does not support timezone-aware times.") <<<<<<< HEAD return six.text_type(value) def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None): """ Transforms a decimal.Decimal value to an object compatible with what is ======= return str(value) def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None): """ Transform a decimal.Decimal value to an object compatible with what is >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 expected by the backend driver for decimal (numeric) columns. """ return utils.format_number(value, max_digits, decimal_places) def adapt_ipaddressfield_value(self, value): """ <<<<<<< HEAD Transforms a string representation of an IP address into the expected ======= Transform a string representation of an IP address into the expected >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 type for the backend driver. """ return value or None def year_lookup_bounds_for_date_field(self, value):
def check_json_precision(): """make sure json library being used does not lose precision converting btc values""" n = decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise runtimeerror("json encode/decode loses precision")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: 王辉 @email: [email protected] @time: 2018/10/16 14:20 """ import decimal import json dic = {'a': decimal(2.03)} print(json.dumps(dic))
def __eq__(self, other): first = decimal(self.numerator / self.denominator) second = decimal(other.numerator / other.denominator) return first == second
def __init__(self, x=0, y=0): self.x = decimal(x) self.y = decimal(y)
1/3 1 // 3 / a a = 2 a.bit_length() a = 1.24 a = 1024 a.bit_length() a = 3 a.bit_length() a = 4 a.bit_length() help("bit_length") import decimal decimal("0.2") from decimal import Decimal Decimal("0.23") Decimal("0.23") + Decimal("0.232") 0.23+0.232 from fractions import Fraction s = set() s s = set([23,234234,45,88,9]) 2 in s 23 in s s2 = set([23,23]) len(s2) s s2 s | s2
import decimal c = decimal.getcontext().copy() c.prec = 3 pi = c.create - decimal('3.1415') print('PI:', pi) print('RESTULT:', decimal.Decimal('2.01') * pi)
def temp_kelvin_to_celsius(temp_in_kelvin): return decimal(temp_in_kelvin) - decimal(273.15)