User Defined Function for stock variance

bilalalam

New Member
Joined
Apr 5, 2019
Messages
1
Hello,

I need help in creating a custom function that will calculate variance of a stock using its raw prices. This means that the returns calculation will take place within the function.

I have written the code, but its not giving the right answer, could anyone please guide me?
Thanks in Advance


Function portfolio_var(Asset2 As Range)


Dim LFirstRow2, LLastRow2 As Integer
Dim LCurrentRow2 As Integer
Dim LPrevPrice2 As Integer
Dim LTotal2 As Double
Dim LCount2 As Integer


'Determine first and last row to average
LFirstRow2 = Asset2.Row
LLastRow2 = LFirstRow2 + Asset2.Rows.Count - 2




'Determine previous price
LPrevPriceRowFirst2 = Asset2.Row + 1
LPrevPriceRowLast2 = LPrevPriceRowFirst2 + Asset2.Rows.Count - 2


'Initialize variables
LTotal2 = 0
LCount2 = 0
sumsqr = 0
avg = 0


'Move through each cells in the range and include in average calculation
For LCurrentRow2 = LFirstRow2 To LLastRow2
For LPrevPrice2 = LPrevPriceRowFirst2 To LPrevPriceRowLast2


LTotal2 = LTotal2 + WorksheetFunction.Ln(Cells(LCurrentRow2, 5) / Cells(LPrevPrice2, 5))
LCount2 = LCount2 + 1
Next
Next


avg = LTotal2 / LCount2


For LCurrentRow2 = LFirstRow2 To LLastRow2
For LPrevPrice2 = LPrevPriceRowFirst2 To LPrevPriceRowLast2


sumsqr = sumsqr + (WorksheetFunction.Ln(Cells(LCurrentRow2, 5) / Cells(LPrevPrice2, 5))) ^ 2


Next
Next


portfolio_var = (((LTotal2) ^ 2 / LCount2) - sumsqr) / (LCount2 - 1)

End Function
 

Excel Facts

Using Function Arguments with nested formulas
If writing INDEX in Func. Arguments, type MATCH(. Use the mouse to click inside MATCH in the formula bar. Dialog switches to MATCH.
Hello,

Take a look at Excel built-in functions ... with a wide choice Variance, Standard Deviation, Normal Distribution, etc ...
 
Upvote 0

Forum statistics

Threads
1,224,822
Messages
6,181,165
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top