random

- collection of un-sorted bollocks
git clone git://git.acid.vegas/random.git
Log | Files | Refs | Archive

stdcap.py (3144B)

      1 #!/usr/bin/env python
      2 # CoinMarketCap Standard Deviation - Developed by acidvegas in Python (https://acid.vegas/random)
      3 
      4 '''
      5 The script will calculate the mean, median, mode, high, low & std for the entire cryptocurrency market over the last 7 days.
      6 
      7 API Documentation:
      8 	https://coinmarketcap.com/api/
      9 '''
     10 
     11 import datetime
     12 import http.client
     13 import json
     14 import math
     15 import time
     16 import statistics
     17 
     18 class CoinMarketCap(object):
     19 	def __init__(self):
     20 		self.cache = {'ticker':{'BTC':{'last_updated':0}}}
     21 
     22 	def _ticker(self):
     23 		conn = http.client.HTTPSConnection('api.coinmarketcap.com')
     24 		conn.request('GET', '/v1/ticker/?limit=0')
     25 		data = json.loads(conn.getresponse().read().replace(b': null', b': "0"'))
     26 		conn.close()
     27 		return data
     28 
     29 	def _markets():
     30 		conn = http.client.HTTPSConnection('s2.coinmarketcap.com')
     31 		conn.request('GET', '/generated/search/quick_search.json')
     32 		data = json.loads(conn.getresponse().read())
     33 		conn.close()
     34 		results = dict()
     35 		for item in data:
     36 			results[item['id']] = item['name']
     37 		return results
     38 
     39 	def _graph(self, name, start_time, end_time):
     40 		conn = http.client.HTTPSConnection('graphs2.coinmarketcap.com', timeout=60)
     41 		conn.request('GET', f'/currencies/{name}/{start_time}/{end_time}/')
     42 		return json.loads(conn.getresponse().read())
     43 
     44 def generate_table(data):
     45 	matrix = dict()
     46 	keys = data[0].keys()
     47 	for item in keys:
     48 		matrix[item] = list()
     49 	del keys
     50 	for item in data:
     51 		for subitem in item:
     52 			matrix[subitem].append(item[subitem])
     53 	for item in matrix:
     54 		matrix[item] = len(max(matrix[item], key=len))
     55 	columns = [item.ljust(matrix[item]) for item in matrix.keys()]
     56 	print('   '.join(columns))
     57 	del columns
     58 	for item in data:
     59 		row_columns = [item[subitem].ljust(matrix[subitem]) for subitem in item]
     60 		print(' | '.join(row_columns))
     61 
     62 def stddev(data):
     63 	n = len(data)
     64 	if n <= 1:
     65 		return 0.0
     66 	mean = avg_calc(data)
     67 	sd = 0.0
     68 	for el in data:
     69 		sd += (float(el)-mean)**2
     70 	sd = math.sqrt(sd/float(n-1))
     71 	return sd
     72 
     73 def avg_calc(ls):
     74 	n = len(ls)
     75 	mean = 0.0
     76 	if n <= 1:
     77 		return ls[0]
     78 	for el in ls:
     79 		mean = mean+float(el)
     80 	mean = mean/float(n)
     81 	return mean
     82 
     83 def get_data(coin, start_time, end_time):
     84 	try:
     85 		time.sleep(4)
     86 		data = [item[1] for item in CMC._graph(coin, start_time, end_time)['price_usd']]
     87 		return {'name':coin,'mean':f'{sum(data)/len(data):.2f}','median':f'{statistics.median(data):.2f}','mode':f'{max(set(data),key=data.count):.2f}','high':f'{max(data):.2f}','low':f'{min(data):.2f}','std':f'{stddev(data):.2f}'}
     88 	except:
     89 		return {'name':'none','mean':'none','median':'none','mode':'none','high':'none','low':'none','std':'0'}
     90 
     91 CMC         = CoinMarketCap()
     92 ticker_data = CMC._ticker()
     93 start_time  = int((datetime.datetime.now()-datetime.timedelta(days=180)).timestamp()*1000)
     94 end_time    = int(datetime.datetime.now().timestamp()*1000)
     95 coins       = [item['id'] for item in ticker_data][:10]
     96 data        = [get_data(coin, start_time, end_time) for coin in coins]
     97 data        = sorted(data, key=lambda k: float(k['std']), reverse=True)
     98 generate_table(data)
     99 size=len(CMC._graph('bitcoin', start_time, end_time)['price_usd'])
    100 print('Spread acrosss 7 days - ' + str(size) + ' points')