pandas - Rolling average pairwise correlation in Python -


i have daily returns 3 markets (gld, spy, , uso). goal calculate the average pairwise correlation correlation matrix on rolling basis of 130 days.

my starting point was:

import numpy np import pandas pd import os os import pandas.io.data web import datetime datetime pandas.io.data import datareader  stocks = ['spy', 'gld', 'uso'] start = datetime.datetime(2010,1,1) end = datetime.datetime(2016,1,1)  df = web.datareader(stocks, 'yahoo', start, end) adj_close_df = df['adj close']  returns = adj_close_df.pct_change(1).dropna() returns = returns.dropna()  rollingcor = returns.rolling(130).corr() 

this creates panel of correlation matrices. however, extracting lower(or upper) triangles, removing diagonals , calculating average each observation i've drawn blank. ideally output each date in series can index dates.

maybe i've started wrong place appreciated.

to average pairwise correlation, can find sum of correlation matrix, substract n (ones on diagonal), divide 2 (symmetry), , divide n (average). think should it:

>>> n = len(stocks) >>> ((rollingcor.sum(skipna=0).sum(skipna=0) - n) / 2) / n date 2010-01-05         nan 2010-01-06         nan 2010-01-07         nan                 ...    2015-12-29    0.164356 2015-12-30    0.168102 2015-12-31    0.166462 dtype: float64 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -