while (i <= n1){
return_expect <- colMeans(return_daily[(i-60):(i-1), 1:n2], na.rm=TRUE)
# 60 days of observation for expected returns, fixed in my project, can change if you desire different estimator
Dmat <- cov(return_daily[(i-60):(i-1), 1:n2], use = "complete.obs")
# Sample Covariance with 60 days of observation for returns, change to m: 120; l: 200
Amat <- cbind(1, return_expect, diag(1,n2), diag(-1,n2))
target <- 0.15 / 250
# target yearly return 15%, fixed in my project, can change if you desire different constrain
bvec <- c(1, target, -2+rep(0,n2), -2+rep(0,n2))
dvec <- rep(0,n2)
opt_sol <- solve.QP(Dmat,dvec,Amat,bvec, meq=2, factorized=FALSE)$solution
# solve the optimization problem
weight[i+0:min(4,n1-i), ] <- matrix(rep(opt_sol, min(5,n1-i+1)), ncol=n2, byrow=T)
# record weight for each asset
return_daily[i+0:min(4,n1-i), n2+1] <- return_daily[i+0:min(4,n1-i), 1:n2] %*% opt_sol
# record new daily return for each asset and portfolio overall
i = i + 5
# weekly rebalance portfolio, adjust weight per 5 trading day
# fixed in my project, can change if you desire different condition
}