user1494429
user1494429

Reputation: 21

how to calculate rolling volatility

I am trying to design a function that will calculate 30 day rolling volatility. I have a file with 3 columns: date, and daily returns for 2 stocks.

How can I do this? I have a problem in summing the first 30 entries to get my vol.

Edit:

So it will read an excel file, with 3 columns: a date, and daily returns.

daily.ret = read.csv("abc.csv")

e.g. date stock1 stock2 01/01/2000 0.01 0.02

etc etc, with years of data. I want to calculate rolling 30 day annualised vol. This is my function:

calc_30day_vol = function()
{
stock1 = abc$stock1^2
stock2 = abc$stock1^2
j = 30
approx_days_in_year = length(abc$stock1)/10
vol_1 = 1: length(a1) 
vol_2 = 1: length(a2)

for (i in 1 : length(a1))
{
vol_1[j] = sqrt( (approx_days_in_year / 30 ) * rowSums(a1[i:j])

vol_2[j] = sqrt( (approx_days_in_year / 30 ) * rowSums(a2[i:j])


j = j + 1
}

}

So stock1, and stock 2 are the squared daily returns from the excel file, needed to calculate vol. Entries 1-30 for vol_1 and vol_2 are empty since we are calculating 30 day vol. I am trying to use the rowSums function to sum the squared daily returns for the first 30 entries, and then move down the index for each iteration. So from day 1-30, day 2-31, day 3-32, etc, hence why I have defined "j".

I'm new at R, so apologies if this sounds rather silly.

Upvotes: 1

Views: 5633

Answers (1)

GSee
GSee

Reputation: 49820

This should get you started.

First I have to create some data that look like you describe

library(quantmod)
getSymbols(c("SPY", "DIA"), src='yahoo')
m <- merge(ROC(Ad(SPY)), ROC(Ad(DIA)), all=FALSE)[-1, ]
dat <- data.frame(date=format(index(m), "%m/%d/%Y"), coredata(m))
tmpfile <- tempfile()
write.csv(dat, file=tmpfile, row.names=FALSE)

Now I have a csv with data in your very specific format. Use read.zoo to read csv and then convert to an xts object (there are lots of ways to read data into R. See R Data Import/Export)

r <- as.xts(read.zoo(tmpfile, sep=",", header=TRUE, format="%m/%d/%Y"))
# each column of r has daily log returns for a stock price series
# use `apply` to apply a function to each column.
vols.mat <- apply(r, 2, function(x) {
    #use rolling 30 day window to calculate standard deviation.
    #annualize by multiplying by square root of time
    runSD(x, n=30) * sqrt(252)
})
#`apply` returns a `matrix`; `reclass` to `xts`
vols.xts <- reclass(vols.mat, r) #class as `xts` using attributes of `r`
tail(vols.xts)
#           SPY.Adjusted DIA.Adjusted
#2012-06-22    0.1775730    0.1608266
#2012-06-25    0.1832145    0.1640912
#2012-06-26    0.1813581    0.1621459
#2012-06-27    0.1825636    0.1629997
#2012-06-28    0.1824120    0.1630481
#2012-06-29    0.1898351    0.1689990

#Clean-up
unlink(tmpfile)

Upvotes: 5

Related Questions