Blogs

Rolling Correlation Calculation on Metal Futures

Import the libraries:

import pandas as pd
from yahoo_fin.stock_info import get_data
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

Get multiple data form Yahoo Finance and combine into a single dataframe:

start_date = "01/01/2010"
end_date = "30/06/2022"
interval = '1d'
tickers = ['GC=F','SI=F','PA=F','PL=F']

metals_dict = {}
for ticker in tickers:
    data = get_data(ticker,start_date, end_date, index_as_date=True, interval=interval)
    metals_dict[ticker] = data['adjclose']


metals = pd.concat(metals_dict,axis=1)
metals.columns = ['gold_usd', 'silver_usd', 'palad_usd','plat_usd']
metals.dropna(inplace=True)

Calculate Rolling Correlations:

window = 90

palad_plat = metals['palad_usd'].rolling(window).corr(metals['plat_usd'])
silver_plat = metals['silver_usd'].rolling(window).corr(metals['plat_usd'])
gold_plat = metals['gold_usd'].rolling(window).corr(metals['plat_usd'])
palad_silver = metals['palad_usd'].rolling(window).corr(metals['silver_usd'])
palad_gold = metals['palad_usd'].rolling(window).corr(metals['gold_usd'])
gold_silver = metals['gold_usd'].rolling(window).corr(metals['silver_usd'])

Plot into a single figure for easy overview:

fig, axs = plt.subplots(2, 3, figsize=(25,12))
fig.suptitle(f'Metals Correlations | {window} Day Rolling')
x = metals.index
axs[0, 0].plot(x, palad_plat)
axs[0, 0].set_title('palad_plat')
axs[0, 1].plot(x, silver_plat)
axs[0, 1].set_title('silver_plat')
axs[0, 2].plot(x, gold_plat)
axs[0, 2].set_title('gold_plat')
axs[1, 0].plot(x, palad_silver)
axs[1, 0].set_title('palad_silver')
axs[1, 1].plot(x, palad_gold)
axs[1, 1].set_title('palad_gold')
axs[1, 2].plot(x, gold_silver)
axs[1, 2].set_title('gold_silver')

Here's the result: