I am trying to calculate the rolling average pairwise correlation between a number of assets in excel.
I have created a custom function, and tried using the correlation matrix, but neither are satisfactory.
- The assets are located in columns
- Correlation must be over the defined time period/lookback
- But if data is missing in part of the look back, that asset is ignored (until it has sufficient data)
So far, the function works but I cannot force it to ignore incomplete ranges (it replaces blank with 0):
Function avgRho(DataRange As Range)
'
Dim nRow As Long, nCol As Long
Dim i As Long, j As Long, j1 As Long, j2 As Long
Dim RtnData() As Double
Dim v1
Dim counts As Double, sum_correl As Double
Dim rtn1() As Double, rtn2() As Double
'
avgRho = 0
'
nRow = DataRange.Rows.Count
nCol = DataRange.Columns.Count
If nRow <= 2 Or nCol <= 1 Then Exit Function
'
ReDim RtnData(1 To nRow, 1 To nCol)
ReDim rtn1(1 To nRow)
ReDim rtn2(1 To nRow)
'
For i = 1 To nRow
For j = 1 To nCol
v1 = DataRange(i, j).Value
RtnData(i, j) = v1
Next j
Next i
'
counts = 0
sum_correl = 0
For j1 = 1 To nCol
'
For i = 1 To nRow
rtn1(i) = RtnData(i, j1)
Next i
'
For j2 = j1 + 1 To nCol
For i = 1 To nRow
rtn2(i) = RtnData(i, j2)
Next i
'
counts = counts + 1
sum_correl = sum_correl + WorksheetFunction.Correl(rtn1, rtn2)
'
Next j2
'
Next j1
'
If sum_correl > 0 Then avgRho = sum_correl / counts
'
End Function