Blogs

Calculating Correlations of Coins

Try this to visualize coin correlations with a heatmap and print high/low correled coins listed in Binance. 

import requests
import json
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

data = json.loads(requests.get(
    'https://api.binance.com/api/v3/ticker/24hr').text)
all_symbols = pd.DataFrame([_['symbol'] for _ in data],columns=['symbol'])

pattern = '.*USDT'
coin_symbols = all_symbols[all_symbols['symbol'].
                           str.contains(pattern)].reset_index(drop=True)


all_coins, interval, limit = [], '1d', 90
for symbol in coin_symbols.iloc[:10,0]: # select 10 coins to call from API
    coin = json.loads(requests.get('https://api.binance.com/api/v3/klines?'+
                                   f'symbol={symbol}&interval={interval}&limit={limit}').text)
    all_coins.append([float(_[4]) for _ in coin])

coins = pd.DataFrame(all_coins).T
coins.columns = coin_symbols.iloc[:10,0].values
coins = coins.pct_change().dropna()
coins_corr = coins.corr()


mask = np.zeros_like(coins_corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
    f, ax = plt.subplots(figsize=(12, 9))
    ax = sns.heatmap(coins_corr,
                     annot=True,
                     linewidths=.5,
                     cmap="YlGnBu",
                     mask=mask,
                     square=True)

print(coins_corr[(coins_corr<0.3) | (coins_corr > 0.6)]['BTCUSDT'].
      dropna().sort_values(ascending=False))

90 day correlation results of BTCUSDT:

BTCUSDT     1.000000
ETHUSDT     0.897821
BNBUSDT     0.866627
EOSUSDT     0.841162
LTCUSDT     0.831265
XRPUSDT     0.822991
QTUMUSDT    0.808420
NEOUSDT     0.801963
ADAUSDT     0.798002
BCCUSDT     0.057136