<jupyter_start><jupyter_text>Exponentially weighted moving covariance<jupyter_code>import os, sys
sys.path.append(os.path.abspath('../src'))
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import xpca
first_year = 2008; last_year = 2020
df = pd.read_parquet('../data/equity_indices.parquet')
df = df[str(first_year):str(last_year)]
df.head()
df.tail()
ewmcov = xpca.EWMCov(alpha=.9305)
xs = df.values
n = np.shape(xs)[0]
means = []
covs = []
for i in range(n):
    ewmcov.add(xs[i,:])
    means.append(ewmcov.mean)
    covs.append(ewmcov.cov)
idx_1 = 0; idx_2 = 1
fig = plt.figure(figsize=(12, 3))
ax = fig.add_subplot(131)
ax.plot(df.index, [c[idx_1,idx_1] for c in covs], linewidth=.5)
ax.set_title(f'Variance of {df.columns[idx_1]}')
ax = fig.add_subplot(132)
ax.plot(df.index, [c[idx_2,idx_2] for c in covs], linewidth=.5)
ax.set_title(f'Variance of {df.columns[idx_2]}')
ax = fig.add_subplot(133)
ax.plot(df.index, [c[idx_1,idx_2] / np.sqrt(c[idx_1,idx_1] * c[idx_2,idx_2]) for c in covs], linewidth=.5)
ax.set_title(f'Correlation of {df.columns[idx_1]} and {df.columns[idx_2]}')
fig.tight_layout();
sample_cov = np.cov(xs, rowvar=False)
fig = plt.figure(figsize=(12, 3))
ax = fig.add_subplot(131)
sns.heatmap(sample_cov, center=0., cmap='RdBu')
ax.set_xticklabels(df.columns)
ax.set_yticklabels(df.columns)
ax.set_title('Sample covariance matrix')
ax = fig.add_subplot(132)
sns.heatmap(np.mean(np.stack(covs), axis=0), center=0., cmap='RdBu')
ax.set_xticklabels(df.columns)
ax.set_yticklabels(df.columns)
ax.set_title('Mean EWM covariance matrix')
ax = fig.add_subplot(133)
sns.heatmap(covs[-1], center=0., cmap='RdBu')
ax.set_xticklabels(df.columns)
ax.set_yticklabels(df.columns)
ax.set_title('Last EWM covariance matrix')
fig.tight_layout();<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1715068493150685, 'fraction_numerical': 0.03452054794520548, 'mean_word_length': 6.246031746031746, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '620851', 'license': 'Apache-2.0', 'n_tokens_mistral': 829, 'n_tokens_neox': 780, 'n_words': 138, 'path': 'notebooks/ewmcov.ipynb', 'repo_name': 'sydx/xpca', 'size': '1825'}