Forked from mostlyinteresting/btc_gold_correlation.py
Created
January 22, 2020 13:25
-
-
Save snapo/0a6043457df16f7ca3c195ad2b277bb9 to your computer and use it in GitHub Desktop.
Rolling 30 day correlation of BTC with gold
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import pandas as pd | |
import datetime as dt | |
import seaborn as sns | |
import matplotlib.pyplot as plt | |
import ccxt | |
sns.set(style = 'ticks', context = 'talk') | |
plt.style.use("dark_background") | |
pd.options.mode.chained_assignment = None | |
#Millisecond UTC timestamp to datetime | |
def ms2dt(x): | |
return dt.datetime.utcfromtimestamp(x//1000).replace(microsecond=x%1000*1000) | |
#Datetime to millisecond | |
def dt2ms(x): | |
return int(float(pd.to_datetime(x).to_datetime64()) / 1e6) | |
if __name__ == '__main__': | |
symbol = 'BTC/USDT' | |
btcStr = 'Bitcoin' | |
goldStr = 'Gold' | |
startDate = dt.datetime(year = 2010, month = 1, day = 1) | |
today = dt.datetime.now() | |
today = dt.datetime(year = today.year, month = today.month, day = today.day) | |
lastYr = today - pd.Timedelta(days = 365) | |
startDate = startDate.strftime('%Y-%m-%d') | |
endDate = today.strftime('%Y-%m-%d') | |
polo = ccxt.poloniex() | |
startDate = dt.datetime(year = 2010, month = 1, day = 3) | |
startDateMS = dt2ms(startDate) | |
btc = polo.fetch_ohlcv(symbol, timeframe = '1d', since = startDateMS) | |
btc = pd.DataFrame(btc, columns = ['Date','Open','High','Low','Close','Volume']) | |
btc['Date'] = btc['Date'].apply( lambda x: ms2dt(x)) | |
btc.set_index('Date', inplace = True) | |
btc = btc[ btc.index < today ] | |
btc = btc[['Close']] | |
btc.rename( columns = {'Close':btcStr}, inplace = True) | |
#load gold data | |
gold = pd.read_csv('gold.csv') | |
gold.rename( columns = {'Close':goldStr}, inplace = True) #spot price | |
gold['Date'] = pd.to_datetime(gold['Date'], errors = 'coerce') | |
gold.set_index('Date', inplace = True) | |
prices = btc.join(gold, how = 'left') | |
prices.dropna(how = 'any', axis = 'rows', inplace = True) | |
returns = prices.pct_change() | |
returns.dropna(how = 'any', axis = 'rows', inplace = True) | |
rollingCorr = returns.rolling(30).corr().reset_index() | |
rollingCorr = rollingCorr[['Date',btcStr]][ rollingCorr['level_1'] == goldStr ] | |
rollingCorr.rename( columns = {btcStr:'Correlation'}, inplace = True) #spot price | |
rollingCorr = rollingCorr[ rollingCorr['Date'] >= lastYr ] | |
g = sns.lineplot(x = 'Date', y = 'Correlation', data = rollingCorr) | |
plt.xticks(rotation=45) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment