Hello, I am new to VBA and I want to write a code that computes the semi-covariance matrix of my return data..
The semicovariance between two stocks (i and j) is calculated as below:
average of: (min(Ri - avg(Ri), 0) * (min(Rj - avg(Rj), 0)
where Ri and Rj are the return observations of stocks i and j respectively..
Using Excel functions, I have calculated the semicovariance between stocks i and j using the following formula:
=AVERAGE((IF(Ri-avg(Ri)<0;Ri-avg(Ri);0)*IF(Rj - avg(Rj)<0;Rj - avg(Rj);0))
Now I have 7 stocks and I would like to write a VBA code that calculates the semicovariance MATRIX between the 7 stocks. I know how to write the code for the regular covariance matrix, but that was easy because I can call the Excel function "Covar" directly...
This is my code for the regular covariance matrix:
---------------------------
Option Base 1
Function VarCovar(rng As Range) As Variant
Dim i As Integer
Dim j As Integer
Dim numCols As Integer
numCols = rng.Columns.Count
Dim matrix() As Double
ReDim matrix(numCols, numCols)
For i = 1 To numCols
For j = 1 To numCols
matrix(i, j) = Application.WorksheetFunction.Covar(rng.Columns(i), rng.Columns(j))
Next j
Next i
VarCovar = matrix
End Function
---------------------------
Can anyone help me with suggestions for a SEMIcovariance matrix VBA code??
Thank you in advance
The semicovariance between two stocks (i and j) is calculated as below:
average of: (min(Ri - avg(Ri), 0) * (min(Rj - avg(Rj), 0)
where Ri and Rj are the return observations of stocks i and j respectively..
Using Excel functions, I have calculated the semicovariance between stocks i and j using the following formula:
=AVERAGE((IF(Ri-avg(Ri)<0;Ri-avg(Ri);0)*IF(Rj - avg(Rj)<0;Rj - avg(Rj);0))
Now I have 7 stocks and I would like to write a VBA code that calculates the semicovariance MATRIX between the 7 stocks. I know how to write the code for the regular covariance matrix, but that was easy because I can call the Excel function "Covar" directly...
This is my code for the regular covariance matrix:
---------------------------
Option Base 1
Function VarCovar(rng As Range) As Variant
Dim i As Integer
Dim j As Integer
Dim numCols As Integer
numCols = rng.Columns.Count
Dim matrix() As Double
ReDim matrix(numCols, numCols)
For i = 1 To numCols
For j = 1 To numCols
matrix(i, j) = Application.WorksheetFunction.Covar(rng.Columns(i), rng.Columns(j))
Next j
Next i
VarCovar = matrix
End Function
---------------------------
Can anyone help me with suggestions for a SEMIcovariance matrix VBA code??
Thank you in advance