Skip to content

Instantly share code, notes, and snippets.

@gaugau3000
Created April 28, 2024 19:52
Show Gist options
  • Save gaugau3000/cbd745ce840eabcac4a8a48f6b6a0a73 to your computer and use it in GitHub Desktop.
Save gaugau3000/cbd745ce840eabcac4a8a48f6b6a0a73 to your computer and use it in GitHub Desktop.
rolling betas
import ccxt
import pandas as pd
import matplotlib.pyplot as plt
# Initialize exchange
exchange = ccxt.binance({
'enableRateLimit': True,
'options': {
'defaultType': 'future'
}
})
# Fetch daily candles for BTC/USDT and UNI/USDT
btc_data = exchange.fetch_ohlcv("BTC/USDT", timeframe='1h', limit=1000)
uni_data = exchange.fetch_ohlcv("UNI/USDT", timeframe='1h', limit=1000)
# Convert data to DataFrame
btc_df = pd.DataFrame(btc_data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
uni_df = pd.DataFrame(uni_data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
# Convert timestamp to readable dates
btc_df['timestamp'] = pd.to_datetime(btc_df['timestamp'], unit='ms')
uni_df['timestamp'] = pd.to_datetime(uni_df['timestamp'], unit='ms')
# Set the timestamp as the index
btc_df.set_index('timestamp', inplace=True)
uni_df.set_index('timestamp', inplace=True)
# Compute daily returns
btc_df['returns'] = btc_df['close'].pct_change()
uni_df['returns'] = uni_df['close'].pct_change()
# Compute rolling beta of UNI to BTC
rolling_covariance = uni_df['returns'].rolling(window=40).cov(btc_df['returns'])
rolling_variance = btc_df['returns'].rolling(window=40).var()
rolling_beta = rolling_covariance / rolling_variance
# Compute rolling correlation of UNI to BTC
rolling_correlation = uni_df['returns'].rolling(window=40).corr(btc_df['returns'])
# Plotting the prices, rolling beta, and rolling correlation
fig, ax = plt.subplots(3, 1, figsize=(12, 15))
# Prices plot with different scales
ax0 = ax[0]
ax0.plot(btc_df['close'], label='BTC/USDT', color='blue')
ax0.set_ylabel('BTC/USDT Price', color='blue')
ax0.tick_params(axis='y', labelcolor='blue')
ax0.legend(loc='upper left')
# Create a second y-axis for the UNI/USDT prices
ax1 = ax0.twinx()
ax1.plot(uni_df['close'], label='UNI/USDT', color='red')
ax1.set_ylabel('UNI/USDT Price', color='red')
ax1.tick_params(axis='y', labelcolor='red')
ax1.legend(loc='upper right')
ax[0].set_title('BTC/USDT and UNI/USDT Prices on Different Scales')
# Rolling beta plot
ax[1].plot(rolling_beta, color='green', label='Rolling Beta UNI/BTC')
ax[1].set_title('Rolling Beta of UNI to BTC on 40 periods')
ax[1].legend()
# Rolling correlation plot
ax[2].plot(rolling_correlation, color='purple', label='Rolling Correlation UNI/BTC')
ax[2].set_title('Rolling Correlation of UNI to BTC on 40 periods')
ax[2].legend()
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment