Skip to content

Instantly share code, notes, and snippets.

@the023
Last active December 7, 2017 21:20
Show Gist options
  • Select an option

  • Save the023/a68a5619640c8a2f0cdfeb7c32c4b70b to your computer and use it in GitHub Desktop.

Select an option

Save the023/a68a5619640c8a2f0cdfeb7c32c4b70b to your computer and use it in GitHub Desktop.
chart %price and average volume for different cryptos
""" Get chart of multiple coins, in percent
use Cryptowatch API (watch for allowance and cost)
v.06 add switch to display volume. Add grid
v.05 fix date bug
v.04 adding volume + bar
see : https://screenshots.firefox.com/GJhtEVQxkRtJ47MW/null (wrong)
"""
import datetime
import requests
import json
import urllib
import time
import pandas as pd
import matplotlib.pyplot as plt
import sys
from time import sleep
class cw_ohcl_histo:
def __init__(self,
exchange='bitfinex',
pairs=['btcusd', 'ethbtc'],
after=int(time.time()) - 60 * 60,
before=int(time.time()),
periods='180',
displayvolume=False
):
self.exchange = exchange
self.pairs = pairs
self.after = int(after)
self.before = int(before)
self.periods = periods
self.displayvolume = displayvolume
self.baseurl = 'https://api.cryptowat.ch/'
self.dateformat = '%Y-%m-%d %H:%M:%S' #
self.lines = {
'close': {
'name': 'Close price',
'id': 4
}, 'volume': {
'id': 5,
'name': 'Volume'
}}
def run(self):
""" main method """
response = {}
for pair in self.pairs:
response[pair] = self.cw_getohlc(pair)
df_close = self.cw_format2df(response, column='close')
df_volume = self.cw_format2df(response, column='volume')
# divide all values by first one to get ratio
df_close = df_close / df_close.ix[0]
df_close = 100 * (df_close - 1)
df_volume = df_volume / df_volume.sum() # average
df_volume = 10 * df_close.values.max() * df_volume
# not sure those are the bests maths ...
# Strange way to normmalise data between close and price, todo : add new axis
# see : https://stackoverflow.com/questions/23482201/plot-pandas-dataframe-as-bar-and-line-on-the-same-one-chart
dfall = df_close.join((df_volume))
l = {}
for line in ['close', 'volume']:
l[line] = []
for name in self.pairs:
if str(name + line) in dfall:
l[line].append(name + line)
ax = dfall[l['close']].plot(linestyle='-')
if self.displayvolume:
dfall[l['volume']].plot(width=.9, kind='bar', alpha=.8, ax=ax)
title = '%Close' + (" and Avg Volume " if self.displayvolume else "")
plt.title('Change of %s on %s since %.1d min ' % (
title, self.exchange, (self.before - self.after) / 60))
plt.grid(True)
def cw_format2df(self, response, column):
""" put data in a dictionary """
columnid = self.lines[column]['id']
di = {}
for pair, datas in response.items():
if not 'allowance' in datas:
continue
di[pair + column] = {}
self.lines[column][pair] = datas['allowance']
for d in datas['result'][self.periods]:
thedate = datetime.datetime.fromtimestamp(d[0]).strftime(self.dateformat)
di[pair + column][thedate] = d[columnid]
df = pd.DataFrame.from_dict(di)
df = df.dropna()
return df
def cw_getohlc(self, pair):
""" get ohlc from exchange """
sleep(2)
url = self.baseurl + 'markets/' + self.exchange + '/' + pair + '/ohlc?'
payload = dict(
after=self.after,
before=self.before,
periods=self.periods
)
try:
# print(url + urllib.urlencode(payload))
jsonresp = requests.get(url, payload)
if (jsonresp.status_code != 200):
raise ValueError(' http problem with url: ', url + urllib.urlencode(payload))
except Exception as e:
print 'Error: fetching cryptowatch {}'.format(str(url))
print('Error: Exception' + repr(e))
return dict(error=repr(e))
return json.loads(jsonresp.text)
now = int(time.time())
# pairs=['btcusd', 'ethbtc', 'ltcbtc', 'bchbtc','neobtc'], # pairs=['btcusd', 'ethbtc', 'ltcbtc', 'bchbtc','neobtc'],
# pairs=['btcusd', 'ethbtc', 'ltcbtc', 'bchbtc','neobtc'],
cc = cw_ohcl_histo(
exchange='bitfinex', # check cryptowatch for the right names of exchange and pairs
pairs=['btcusd', 'ethusd', 'bchusd', 'dashusd', 'ltcusd'], # ,'dashbtc'
periods='180', # only 1 value: 60 180 300 900 3600
after=now - 60 * 60 * 6, # now - xxx seconds
before=now, # now in seconds,
displayvolume=False
)
cc.run()
cc2 = cw_ohcl_histo(
exchange='bitfinex', # check cryptowatch for the right names of exchange and pairs
pairs=['iotusd', 'xrpusd', 'xmrusd', 'neousd', 'eosusd'], # ,'dashbtc'
periods='180', # only 1 value: 60 180 300 900 3600
after=now - 60 * 60 * 6, # now - xxx seconds
before=now, # now in seconds,
displayvolume=False
)
cc2.run()
# ,'qtumusd','zecusd','btgusd',
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment