# portfolio optimization with a loop

I am attempting to minimize the variance of a 3 stock portfolio using optimization within a loop. What I have done is calculated the stock returns and cov matrix from dates 1980-01-01 to 1989-12-31 and optimized for the minvar portfolio using solve.QP. From here, I would like to calculate the minvar portfolio for every year leading up to date 2010-12-31 and store the weights and optimal value in a vector. My code is as follows:

    library(quantmod)
library(FRAPO)
port=cbind(F$F.Adjusted,AA$AA.Adjusted,IBM$IBM.Adjusted) portret=returnseries(port,"discrete",trim=TRUE) portret=data.frame(date=index(portret),coredata=portret) colnames(portret)=c("time","F","AA","IBM") #to determine where to end portA which(portret=="1989-12-29",arr.ind=TRUE) #row number 2527 references date 1989-12-29 portA=subset(portret,select=c("F","AA","IBM"),subset=portret[,1]<portret[2527,1]) portAcov=cov(portA) Dmat=portAcov dvec=c(0,0,0) A=c(1,1,1) B=diag(3) portAmeans=colMeans(portA) Amat=cbind(A,portAmeans,B) bvec=c(1,0,0,0,0) sol=solve.QP(Dmat,dvec,Amat,bvec,meq=1) #this gives me my minvar port weights for up to year 1990 portB=subset(portret,select=c("F","AA","IBM"),subset=portret[,1]>=portret[2527,1]) w=matrix(0,nrow(portret),3) w[1,1:3]=sol$solution
v[1]=sol$value for(i in (which(portret=="1990-01-02",arr.ind=TRUE)[1]: which(portret=="2010-12-31",arr.ind=TRUE)[1])){ Dmat=cov(subset(portret[,2:4],select=c("F","AA","IBM"),subset=portret[,1] <portret[i,1])) sol2=solve.QP(Dmat,dvec,Amat,bvec,meq=1) w[i,1:3]=sol2$solution