我正在尝试计算excel中多个资产之间的滚动平均成对相关性。
我创建了一个自定义函数,并尝试使用相关矩阵,但两者都不令人满意。
到目前为止,该函数有效但我无法强制它忽略不完整的范围(它将空格替换为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
答案 0 :(得分:0)
通过类似于建议解决,感谢Peekay,在添加到数据矩阵RtnData时过滤掉空白单元格 还改变了计数过程:
Function avgRho(DataRange As Range)
'
Dim nRow As Long, nCol As Long
Dim i As Integer, j As Integer, j1 As Integer, j2 As Integer
Dim RtnData() As Double
Dim v1
Dim counts As Double, sum_correl As Double
Dim rtn1() As Double, rtn2() As Double
Dim MatColCount As Integer
'
avgRho = 0
MatColCount = 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
MatColCount = 0
For j = 1 To nCol
If DataRange(1, j).Value <> "" And DataRange(nRow, j) <> "" Then
v1 = DataRange(i, j).Value
MatColCount = MatColCount + 1
RtnData(i, MatColCount) = v1
End If
Next j
Next i
'
counts = 0
sum_correl = 0
If MatColCount <= 1 Then Exit Function
'
For j1 = 1 To MatColCount
For i = 1 To nRow
rtn1(i) = RtnData(i, j1)
Next i
'
For j2 = j1 + 1 To MatColCount
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 counts > 0 Then avgRho = sum_correl / counts
'
End Function