通过VBA的协方差矩阵问题

时间:2019-07-09 13:00:52

标签: excel vba

我正在尝试编写一个返回数组协方差的函数。给我5个股票的股票价格从2nd February 2017降到8th July 2019。我首先找到了他们的算术收益。但是在编写代码之后,按 Ctrl + Shift + Enter 会给我#VALUE

Function VarCovArr(RNG As Range)
    Dim Arr()
    Dim OutputArr()
    Dim i As Long
    Dim j As Long
    Dim k As Long
    Dim ReturnArr()
    Dim WF As Object
    Dim TempArr()
    Dim TempArr2()

    Set WF = Application.WorksheetFunction
    Arr = RNG

   'Build Return Array
   '(1) Size of Array

    ReDim ReturnArr(LBound(Arr, 1) To UBound(Arr, 1) - 1, LBound(Arr, 2) To UBound(Arr, 2))

    For i = LBound(ReturnArr, 1) To UBound(ReturnArr, 1)
        For j = LBound(ReturnArr, 2) To UBound(ReturnArr, 2)
            ReturnArr = Arr(i + 1, j) / Arr(i, j) - 1
        Next j
    Next i

    ReDim OutputArr(1 To UBound(Arr, 2), 1 To UBound(Arr, 2))
    ReDim TempArr(1 To UBound(ReturnArr, 1), 1 To UBound(ReturnArr, 1))
    ReDim TempArr2(1 To UBound(ReturnArr, 1), 1 To UBound(ReturnArr, 1))

    For i = LBound(OutputArr, 1) To UBound(OutputArr, 1)
        For j = LBound(OutputArr, 2) To UBound(OutputArr, 2)
            For k = LBound(ReturnArr, 1) To UBound(ReturnArr, 2)
                TempArr(k) = ReturnArr(k, i)
                TempArr2(k) = ReturnArr(k, j)

                '(2) Store Covariance matrix
                OutputArr(i, j) = Application.WorksheetFunction.Covariance_S(TempArr, TempArr2)
            Next k
        Next j
    Next i

    VarCovArr = OutputArr
End Function

0 个答案:

没有答案