R语言 如何计算一系列权重下的投资组合收益?

lsmd5eda  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(206)

我试图创建一个双变量投资组合并确定其收益。我希望R在一系列权重中循环,即从0到1,增加0.01。
我使用的计算回报的软件包PerformanceAnalytics仅限于分配一组权重。在这种情况下,我必须重复该函数99次才能得到我想要的结果。

#This is what is typically done 
# Create the weights
myweights <- c(0.5, 0.5)

#Calculate returns

returns <- Return.calculate(prices data)

# Create a portfolio using buy and hold
pf_bh <- Return.portfolio(returns, weights = myweights)

#Instead of the above I would like:
w1 <- seq(from = 0, to = 1, by = 0.01)

#Creating the weights
weights <- c(w1, 1-w1)

#Portfolio returns
pf_bh <- Return.portfolio(returns, weights = myweights)

但我却收到此错误

Error in `dimnames<-.xts`(`*tmp*`, value = dn) : 
  length of 'dimnames' [2] not equal to array extent

考虑到这个包的限制,这是可以预料到的。有没有一个函数我可以有希望地实现来解决这个或包?

8i9zcol2

8i9zcol21#

可以使用lapply()迭代w1

library(PerformaneAnalytics)

pf_bh <- lapply(
  w1,
  \(w) Return.portfolio(returns, weights = c(w, 1 - w))
)

相关问题