简体   繁体   中英

How do I compute the returns of a portfolio over a sequence of weights?

I am trying to create a bivariate portfolio and determine its returns. I want R to cycle through a sequence of weights ie from 0 to 1, increasing by 0.01.

The package I am using, PerformanceAnalytics, to compute the returns is only limited to assigning one set of weights. In this case, I would have to repeat the function 99 times to get what I want.

#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)

Instead I get this error

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

Which is to be expected given the package's limitations. Is there a function I could hopefully implement to solve this or package?

You can iterate over w1 using lapply() :

library(PerformaneAnalytics)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM