Search code examples
rfor-loopr-portfolioanalytics

How to for loop using different columns of data frame?


Basically I was working on a portfolio return problem. The stock return is like:

AMZN <- c(0.1, 0.3, 0.4, 0.2)
BBY <- c(0.2, 0.4, 0.5, 0.3)
TGT <- c(-0.1, -0.3, -0.2,-0.5)
df1 <- data.frame(AMZN, BBY, TGT)
date <- c("2000-01-01","2000-02-01", "2000-03-01", "2000-04-01")
date <-  as.Date(date, "%Y-%m-%d") 
df1 <- cbind(date, df1)
xts <- xts(df1[,-1], order.by=df1[,1])

I want to use Return.portfolio(xts, weight) to calculate portfolio return. So The weight is like

w1 <- c(0.2, 0.3, 0.1, 0.4)
w2 <- c(0.5, 0.1, 0.1, 0.3)
w3 <- c(0.1, 0.1, 0.4, 0.4)
Weights <- data.frame(w1, w2, w3)

Since there are several groups of weights assigned, I need to get multiple portfolio return. The code I tried is

for (i in colnames(Weights)){
     Return.portfolio(xts, (Weights[[i]]))
 }

Although R does not report any error, the only thing I got is a value which i is "w3".


Solution

  • I think you may need to initialize a NULL object first. Maybe something like this

    Return<-NULL
    for (i in 1:ncol(Weights)){
     Return<- cbind(Return, Return.portfolio(xts, (Weights[[i]])))
    }