VBA UDF 根据每日股票价格计算协方差

VBA UDF to calculate Covariance from Daily Stock prices

结果截图:错误:

示例数据截图:

我是 VBA 的新手,现在我遇到了一个错误。我想通过将股票价格作为参数来计算协方差,其中 returns 一个 n*n 数组(n= 其参数的列数)。我无法找出我在以下代码中的错误:

Function covarmat(prices As Range) As Variant
    Dim i As Integer, j As Integer
    Dim n As Integer

    n = prices.Columns.Count

    Dim resultarray()

    ReDim resultarray(n, n)
    Dim f  'as a proxy for return variant
    Dim basicarray() 'to extract columns and calculate returns
    ReDim basicarray(prices.Rows.Count, prices.Columns.Count)                                               Tried this separately! Works perfect!

    For j = 1 To prices.Columns.Count
        For i = 1 To prices.Rows.Count
            basicarray(i, j) = prices(i + 1, j) / prices(i, j) - 1
        Next i
    Next j
    f = basicarray

    For i = 1 To n
        For j = 1 To n
            resultarray(i, j) = Application.Covariance_S(f.columns(i), f.Columns(j))
        Next j
    Next i

covarmat = resultarray
End Function

这将为您提供 covarinace_s 的数组。所以它是一个数组公式。 Select 范围等于 n*n 并输入公式 (Ctrl+Shift+Enter)。

Function covarmat(prices As Range) As Variant
    Dim i As Integer, j As Integer
    Dim n As Integer

    n = prices.Columns.Count

    Dim resultarray()
    ReDim resultarray(1 To n, 1 To n)

    Dim basicarray()
    ReDim basicarray(1 To prices.Rows.Count - 1, 1 To n)

    For j = 1 To n
        For i = 1 To prices.Rows.Count - 1
            basicarray(i, j) = prices(i + 1, j) / prices(i, j) - 1
        Next i
    Next j

    For i = 1 To n
        For j = 1 To n
            resultarray(i, j) = Application.Covariance_S _
            (Application.WorksheetFunction.Index(basicarray, 0, i), _
            Application.WorksheetFunction.Index(basicarray, 0, j))
        Next j
    Next i

covarmat = resultarray
End Function