[R] portfolio optimization in R

Esra Ulasan esra_ulasan at icloud.com
Thu Nov 20 05:29:26 CET 2014

Dear Sir/Madam,

I am a PhD candidate and writing my dissertation about portfolio optimization in R. However, I have some problems with the codes. It always give the dimension error. Could you help me to fix it?

Yours sincerely,

Here are the codes:

optimization <- function(x) {
  mean <- colMeans(x)
  names(mean) <-assets.names
  p <- ncol(x)
  n <- nrow(x)
  M <- as.integer(p)
  S <- cov(x)
  invS<- solve(S)
  u <- rep(1,p)

#w <- matrix(rep(0,p), nrow=p)
#r <- seq(0,length=p); w <- cbind (diag(450));    #sum of 1 
#constraint <- cbind(diag(450), rep(0, 450));  #non-negativity constraint
  a <- matrix(rep(0,4), nrow=2)
  a[1,1] <- u%*%invS%*%u; 
  a[1,2] <- a[2,1] <- u%*%invS%*%mean
  a[2,2] <-mean%*%invS%*%mean 
  d <- a[1,1]*a[2,2]-a[1,2]*a[1,2] 
  f <- (invS%*%(a[2,2]*u-a[1,2]*mean))/d 
  g <- (invS%*%(-a[1,2]*u+a[1,1]*mean))/d
  rho <- 0.5
  r <- seq(0, rho,length= M)
  w <- matrix(rep(0, p*M), nrow=p)
  for(m in 1:M) w[,m] <- f+r[,m]*g
  #w <- f+(rho*g)
  w[,m] >=0
  s <- sqrt(a[1,1]*((r-a[1,2]/a[1,1])^2)/d+ 1/a[1,1]) 
  ss <- sqrt(diag(S))
  names(ss) <- assets.name
  minp <- c(sqrt(1/a[1,1]), a[1,2]/a[1,1])
  wmimp<- f+(a[1,2]/a[1,1])*g; 
  tanp <- c(sqrt(a[2,2])/a[1,2], a[2,2]/a[1,2]) 
  wtanp <- f+(a[2,2]/a[1,2])*g; 
  return(solve(s, r, ss, p, minp, tanp, wminp, wtanp))

More information about the R-help mailing list