In R, I have an xts object with monthly returns, which I am looking to calculate an overall time-weighted return for each asset individually. Here is a sample of the data:
在R中,我有一个带月回报的xts对象,我希望单独计算每个资产的总时间加权回报。以下是数据示例:
SPY EFA
2005-02-28 0.0206 0.0371
2005-03-31 -0.0184 -0.0265
2005-04-29 -0.0189 -0.0163
For example, I'm looking to calculate the time-weighted returns for SPY from 2/28/05 through 4/29/05. Manually, I would calculate as [(1 + .0206)*(1 + -.0184) * (1 + .0189) - 1] * 100. I have 100 vectors of assets. How would I accomplish this in R? Thank you.
例如,我打算从2005年2月28日到2005年4月29日计算SPY的时间加权回报。手动,我会计算为[(1 + .0206)*(1 + -.0184)*(1 + .0189) - 1] * 100.我有100个资产向量。我将如何在R中实现这一目标?谢谢。
1 个解决方案
#1
0
You can choose sapply and prod with anonymous function to calculate it, like below:
您可以选择sapply和prod with anonymous function来计算它,如下所示:
df <- data.frame( spy = c(.0206,-0.0184,0.0189 ), efa = c(0.0371,-0.0265,-0.01631))
sapply(df,function(x)(prod(x+1)-1)*100)
Output:
> sapply(df,function(x)(prod(x+1)-1)*100)
spy efa
2.0755376 -0.6850001
Manually multiplying your expression gives:
手动乘以你的表达式给出:
((1 + .0206)*(1 + -.0184) * (1 + .0189) - 1) * 100 = 2.075538 (approx)
which is same as sapply result for spy
这与间谍的结果相同
#1
0
You can choose sapply and prod with anonymous function to calculate it, like below:
您可以选择sapply和prod with anonymous function来计算它,如下所示:
df <- data.frame( spy = c(.0206,-0.0184,0.0189 ), efa = c(0.0371,-0.0265,-0.01631))
sapply(df,function(x)(prod(x+1)-1)*100)
Output:
> sapply(df,function(x)(prod(x+1)-1)*100)
spy efa
2.0755376 -0.6850001
Manually multiplying your expression gives:
手动乘以你的表达式给出:
((1 + .0206)*(1 + -.0184) * (1 + .0189) - 1) * 100 = 2.075538 (approx)
which is same as sapply result for spy
这与间谍的结果相同