Excel VBA: User defined function for stock volatility

HockeyGuy4433

New Member
Joined
Jun 20, 2018
Messages
6
Hi everyone,

I'm trying to create a function in VBA to find the annual volatility of a specific stock price. I have all of the numbers on my worksheet titled "Historical Copper Prices", I'm just having a hard time defining my ranges and executing the function.

'N' is around 150 right now but I'd prefer to have it from i = 3 to LastRow (Column A)
PriceRange will be from i = 3 to LastRow (Column C)

I'm running Excel 2016 on a MacBook Pro (MacOS Sierra 10.12.16), I realize there are some limitations but I think this should be pretty straightforward.

Code:
Option Explicit


Function StockVol(N, PriceRange)


' Calculates annualized volatility from price data.
' N = Number of quarters of data to use
' PriceRange = range of prices


Dim i, QtrlyRet()
ReDim QtrlyRet(N - 1)


' Code to calculate quarterly returns


    For i = 4 To N - 1
        QtrlyRet(i) = Log(Sheets("HistoricalCopperPrices").Cells(i, 3).Value / Sheets("HistoricalCopperPrices").Cells(i + 1, 3).Value)


    Next
            
' Calculate and annualize standard deviation


StockVol = Application.StDev(QtrlyRet) * Sqrt(250)


End Function
 

Excel Facts

Quick Sum
Select a range of cells. The total appears in bottom right of Excel screen. Right-click total to add Max, Min, Count, Average.

Forum statistics

Threads
1,223,888
Messages
6,175,207
Members
452,618
Latest member
Tam84

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