Sub readSecData()
Dim n As Integer, m As Integer, i As Integer, j As Integer
n = Range("B3").Value 'Number of Stock
m = Range("B4").Value 'Number of Probabilities
Dim stockReturn() As Double: ReDim stockReturn(1 To m, 1 To n)
Dim stockPababilities() As Double: ReDim stockPababilities(1 To m)
Dim expectedReturn() As Double: ReDim expectedReturn(1 To m)
Dim eVariance() As Double: ReDim eVariance(1 To n)
Dim eCovariance() As Double: ReDim eCovariance(1 To n, 1 To n)
For i = 1 To m
For j = 1 To n
stockReturn(i, j) = Range("B11").Offset(i, j)
Next j
Next i
For i = 1 To m
stockPababilities(i) = Range("B11").Offset(i, 0)
Next i
Call calReturnandVariance(stockReturn, stockPababilities, n, m, expectedReturn, eVariance)
Call calCovariance(stockReturn, stockPababilities, n, m, expectedReturn, eVariance, eCovariance)
'Output Data
Range("A12").Offset(m, 0) = "各证券的期望收益率"
Range("A12").Offset(m + 1, 0) = "各证券的标准差"
Range("A12").Offset(m + 3, 0) = "各证券间的协方差"
For i = 1 To n
Range("B12").Offset(m + 4, i) = "证券" & i
Range("B12").Offset(m + 4, i).HorizontalAlignment = xlCenter
Next i
For i = 1 To n
Range("B12").Offset(m + 4 + i, 0) = "证券" & i
Cells(11, i + 2).HorizontalAlignment = xlCenter
Next i
For i = 1 To n
Range("B12").Offset(m, i) = expectedReturn(i)
Range("B12").Offset(m + 1, i) = eVariance(i)
Next i
For i = 1 To n
For j = 1 To n
Range("B12").Offset(m + 4 + i, j) = eCovariance(i, j)
Next j
Next i
End Sub
Sub calReturnandVariance(stockReturn() As Double, stockPababilities() As Double, n As Integer, m As Integer, _
expectedReturn() As Double, eVariance() As Double)
Dim i As Integer, j As Integer
For i = 1 To n 'Number of Stock
expectedReturn(i) = 0
For j = 1 To m 'Number of Probabilities
expectedReturn(i) = expectedReturn(i) + stockPababilities(j) * stockReturn(j, i)
Next j
Next i
For i = 1 To n 'Number of Stock
eVariance(i) = 0
For j = 1 To m 'Number of Probabilities
eVariance(i) = eVariance(i) + stockPababilities(j) * (stockReturn(j, i) - expectedReturn(i)) ^ 2
Next j
eVariance(i) = eVariance(i) ^ 0.5
Next i
End Sub
Sub calCovariance(stockReturn() As Double, stockPababilities() As Double, n As Integer, m As Integer, _
expectedReturn() As Double, eVariance() As Double, eCovariance() As Double)
Dim i As Integer, j As Integer, t As Integer
For i = 1 To n
For j = 1 To n