Calculating Beta vs Bitcoin

A few days ago a few friends asked me to calculate beta for several coins versus Bitcoin. Below is a 60 day beta calculation of a few alt coins against BTC. Now it probably makes sense to use a different proxy for the market instead of Bitcoin. A better solution would be to put together a weighted basket of currencies or using the CoinMarketCap total market instead. Feel free to use the code below. I use Plotly for my charting. I’ve never calculated before so I may be wrong in my approach. If you have feedback please let me know on Twitter or via email (contact@quantalys.us).

If you have other ideas for analytics please let me know.

bitcoin_beta

In [1]:
import numpy as np
import matplotlib.pyplot as plt
from __future__ import division
import pandas as pd
import datetime
import os
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
In [2]:
import coinmarketcap_usd_history
In [3]:
from pandas_datareader import data as pdr

/take in date until today

In [164]:
def beta(coin1, coin2, start, end):
    x=coinmarketcap_usd_history.main([coin1,start,end,'--dataframe'])
    y=coinmarketcap_usd_history.main([coin2,start,end,'--dataframe'])
    
    z=[x,y]
    for z in z:
        z['Change']=0.000000
        for index, row in z.iterrows():
            if index>0:
                z['Change'][index]=(z['Close'][index]/z['Close'][index-1])-1.000    
    return [x, y]
In [5]:
coin1, coin2, coin3, coin4, coin5 ='bitcoin','ethereum','neo','qtum','bitcoin-cash'
coin_names=[coin1,coin2,coin3,coin4,coin5]
In [6]:
import datetime
In [17]:
t=datetime.datetime.today().strftime("%Y-%m-%d")
In [166]:
btc=beta(coin1,coin1,'2016-01-01',t)
In [19]:
coin1_list=beta(coin1,coin2,'2016-01-01',t)
In [20]:
coin3_list=beta(coin1,coin3,'2016-11-01',t)
In [21]:
coin4_list=beta(coin1,coin4,'2017-07-15',t)
In [22]:
coin5_list=beta(coin1,coin5,'2017-08-15',t)
In [176]:
roll_period=60
In [154]:
coins=[coin1_list, coin3_list, coin4_list, coin5_list]
In [198]:
k=0
col_names=[]
df=pd.DataFrame()

for j in coins[0:4]:
    z=[]      
    for i in range(0, j[0].count().max()-1):
        y=j[0][i:i+roll_period-1]['Change'].cov(j[1][i:i+roll_period-1]['Change'])/j[0][i:i+roll_period-1]['Change'].var(axis=0)
        x=(j[0]['Date'][i], 
           j[0]['Close'][i], #coin 1 close
           j[0]['Change'][i], #coin 1 change
           j[1]['Close'][i], #coin 2 close
           j[1]['Change'][i], #coin 2 change
           y)
        z.append(x)
    df_temp=pd.DataFrame(z, 
                         columns=['Date',
                         coin_names[0] + ' Close', 
                         coin_names[k+1] + ' Close', 
                         coin_names[0] + ' chg', 
                         coin_names[k+1] + ' chg', 
                         'Beta '+ coin_names[k+1]])
    if k==0:
        df=df_temp         
    if k>0:
        df=pd.merge(df[['Date'] + col_names], df_temp[['Date','Beta ' + coin_names[k+1]]], how='left').fillna("")
    col_names.append('Beta ' + coin_names[k+1])
    k+=1
In [172]:
#use for singular beta
z=[]      
for i in range(1, btc[0].count().max()-1):
    y=btc[0][i:i+roll_period]['Change'].cov(btc[1][i:i+roll_period]['Change'])/btc[0][i:i+roll_period]['Change'].var(axis=0)
    x=(btc[0]['Date'][i], 
       btc[0]['Close'][i], #coin 1 close
       btc[0]['Change'][i], #coin 1 change
       btc[1]['Close'][i], #coin 2 close
       btc[1]['Change'][i], #coin 2 change
       y)
    z.append(x)
df_temp=pd.DataFrame(z)
if k==0:
    btc=df_temp         
In [157]:
import plotly
In [137]:
api_key='xxxxxxxxx'
user_name='username'
In [138]:
plotly.tools.set_credentials_file(username=user_name, api_key=api_key)
In [187]:
df.dtypes
Out[187]:
Date                 datetime64[ns]
Beta ethereum               float64
Beta neo                     object
Beta qtum                    object
Beta bitcoin-cash            object
dtype: object
In [212]:
import plotly.plotly as py
from plotly.graph_objs import *

low_bound=365
high_bound=roll_period

b_eth = Scatter(
    x=df[(df['Date']>datetime.datetime.today()+datetime.timedelta(days=-low_bound)) &
         (df['Date']<datetime.datetime.today()+datetime.timedelta(days=-high_bound)) 
        ]['Date'],
    y=df[(df['Date']>datetime.datetime.today()+datetime.timedelta(days=-low_bound)) &
         (df['Date']<datetime.datetime.today()+datetime.timedelta(days=-high_bound)) 
        ]['Beta ethereum'],
    name='b_eth'
)

b_neo = Scatter(
    x=df[(df['Date']>datetime.datetime.today()+datetime.timedelta(days=-low_bound)) &
         (df['Date']<datetime.datetime.today()+datetime.timedelta(days=-high_bound)) 
        ]['Date'],
    y=df[(df['Date']>datetime.datetime.today()+datetime.timedelta(days=-low_bound)) &
         (df['Date']<datetime.datetime.today()+datetime.timedelta(days=-high_bound)) 
        ]['Beta neo'],
    name='b_neo'
)

b_qtum = Scatter(
    x=df[(df['Date']>datetime.datetime.today()+datetime.timedelta(days=-low_bound)) &
         (df['Date']<datetime.datetime.today()+datetime.timedelta(days=-high_bound)) 
        ]['Date'],
    y=df[(df['Date']>datetime.datetime.today()+datetime.timedelta(days=-low_bound)) &
         (df['Date']<datetime.datetime.today()+datetime.timedelta(days=-high_bound)) 
        ]['Beta qtum'],
    name='b_qtum'
)

b_bch = Scatter(
    x=df[(df['Date']>datetime.datetime.today()+datetime.timedelta(days=-low_bound)) &
         (df['Date']<datetime.datetime.today()+datetime.timedelta(days=-high_bound)) 
        ]['Date'],
    y=df[(df['Date']>datetime.datetime.today()+datetime.timedelta(days=-low_bound)) &
         (df['Date']<datetime.datetime.today()+datetime.timedelta(days=-high_bound)) 
        ]['Beta bitcoin-cash'],
    name='b_bch'
)

data = Data([b_eth, b_neo, b_qtum, b_bch])

py.plot(data, filename = 'basic-line', title='Rolling ' + str(roll_period) + ' day beta')
High five! You successfully sent some data to your account on plotly. View your plot in your browser at https://plot.ly/~quantalysus/0 or inside your plot.ly account where it is named 'basic-line'
Out[212]:
u'https://plot.ly/~quantalysus/0'
In [202]:
coin1_list[0].to_csv('bitcoin.csv')
coin1_list[1].to_csv('ethereum.csv')

Roadmap
1) Add rolling 90 days
2) Find solution for minimum date bounds for alternative coins
3) Put charts on Plotly
4) Publish chart on Quantalysus
5) Publish Google Doc data

 

Leave a Reply