1

我正在尝试设计一个计算 30 天滚动波动率的函数。我有一个包含 3 列的文件:日期和 2 只股票的每日回报。

我怎样才能做到这一点?我在总结前 30 个条目以获得我的 vol 时遇到问题。

编辑:

因此它将读取一个包含 3 列的 excel 文件:日期和每日收益。

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

例如日期 stock1 stock2 01/01/2000 0.01 0.02

等等等等,有多年的数据。我想计算滚动 30 天的年化成交量。这是我的功能:

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
}

}

所以 stock1 和 stock 2 是来自 excel 文件的每日收益的平方,需要计算 vol。vol_1 和 vol_2 的条目 1-30 为空,因为我们正在计算 30 天的 vol。我正在尝试使用 rowSums 函数对前 30 个条目的每日收益平方求和,然后在每次迭代中向下移动索引。所以从第 1-30 天、第 2-31 天、第 3-32 天等开始,这就是我定义“j”的原因。

我是 R 的新手,如果这听起来很愚蠢,我深表歉意。

4

1 回答 1

5

这应该让你开始。

首先,我必须创建一些看起来像您描述的数据

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)

现在我有一个 csv,其中包含您非常特定格式的数据。用于read.zoo读取 csv 然后转换为 xts 对象(有很多方法可以将数据读入 R。请参阅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)
于 2012-07-01T19:22:54.767 回答