Skip to content

Instantly share code, notes, and snippets.

@scubamut
Last active November 23, 2024 11:29
Show Gist options
  • Save scubamut/7919048e5a076aae5d14236c8513fbc1 to your computer and use it in GitHub Desktop.
Save scubamut/7919048e5a076aae5d14236c8513fbc1 to your computer and use it in GitHub Desktop.
pandas as pd
import numpy as np
# Assuming returns is your dataset with returns data
def calculate_correlations(returns, symbols, window=50):
"""
Calculate rolling correlations between ETFs
Parameters:
returns: numpy array or pandas DataFrame of returns
symbols: list of symbol names
window: correlation lookback period
"""
# Create DataFrame if not already
df = pd.DataFrame(returns, columns=symbols)
# Dictionary to store correlation pairs
corr_pairs = {}
# Calculate rolling correlation for each pair
for i in range(len(symbols)):
for j in range(i+1, len(symbols)):
pair_name = f'{symbols[i]}_{symbols[j]}'
corr_pairs[pair_name] = df[symbols[i]].rolling(window=window).corr(df[symbols[j]])
# Combine all correlations into one DataFrame
corr_df = pd.DataFrame(corr_pairs)
return corr_df
# Example usage:
# corr_df = calculate_correlations(returns, symbols)
# To get the most recent correlation matrix:
def get_current_corr_matrix(df, symbols):
"""Get the most recent correlation matrix between all symbols"""
return df[symbols].corr()
symbols = ['XLF','XLI','XLK', 'XLY']
prices = yf.download(symbols)['Adj Close'].dropna()
returns = prices.pct_change()
returns.head()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment