R:将日收益转换为月收益 [英] R: Convert daily returns to monthly returns
问题描述
我有 xts 的每日回报,我想将其转换为每月回报.
I have an xts of daily returns and I'd like to convert it to monthly returns.
我可以找到大量线程来将每日价格转换为周期收益,但我需要转换每日收益.
I can find tonnes of threads to convert daily prices to period returns, but I need to convert daily returns.
遵循了this 线程,效果很好,我注意到回报不是几何的,而是算术的.
Having followed the advice in this thread, which works well, I noticed that the returns are not geometric, they're arithmetic.
因此,我需要类似 cumprod(x+1)^(365/12)-1 的东西.
Therefore, I need something like cumprod(x+1)^(365/12)-1.
但是,用它替换 sum(cx) 不起作用.
However, replacing sum(cx) with that doesn't work.
这是我的代码:
# Generate data like the type I'm working with
testdata <- cbind(rnorm(100,0.0001,0.01),rnorm(100,0.0001,0.01))
testdata <- as.xts(testdata, order.by = seq(Sys.Date()-99,Sys.Date(),1))
myFun <- function(x) {
# need coredata, so c.xts will not be dispatched
cx <- coredata(x)
Return = sum(cx)
}
MonthlyReturns <- NULL
for (i in 1:ncol(testdata)){
MonthlyReturns <- cbind(MonthlyReturns,period.apply(testdata[,i], endpoints(testdata[,i], "months"),
myFun))
}
感谢任何帮助!
编辑 - 输出应与输入格式相同 - 每月回报表而不是每日回报.xts 或数据帧/矩阵.
EDIT - The output should be the same format as the input - a table of monthly returns instead of daily. Either xts or dataframe / matrix.
编辑 - 对于那些对回报矩阵的起源感兴趣的人,我正在使用 Performance Analytics 包中的 Return.annualized
函数,如图 这里.(实际上,我已经通过使用 Return.cumulative
对其进行了修改,它的速度要快得多).所以是的,虽然我确实有一个价格矩阵并且可以很容易地从中计算出每月的回报,但我的每日回报矩阵中还有来自其他计算的额外列,因此我需要转换每日回报,而不是每日价格.
EDIT - For those interested in the origin of the returns matrix, I'm using the Return.annualized
function from the Performance Analytics package as shown here. (Actually, I've modified it by using Return.cumulative
, which is much faster). So yes, although I do have a price matrix and can easily calculate monthly returns from that, I have additional columns in my daily returns matrix from other calculations, hence I need to convert the daily returns, not the daily prices.
推荐答案
作为公认解决方案的替代方案,获得每月回报的更快方法(> 5 倍)是结合 aggregate
函数与 cumprod
.
As an alternative to the accepted solution a much faster way ( > 5 times faster ) to get monthly returns is to combine the aggregate
function with cumprod
.
system.time(aggregate(testdata,as.yearmon,function(x) tail(cumprod(1 + x) -1,1)))
user system elapsed
0.021 0.002 0.023
system.time(apply.monthly(testdata, Return.cumulative))
user system elapsed
0.116 0.002 0.118
数据:
testdata <- as.xts(cbind(rnorm(10000,0.0001,0.01),rnorm(100,0.0001,0.01)), order.by = seq(Sys.Date()-9999,Sys.Date(),1))
这篇关于R:将日收益转换为月收益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!