Portfolio Optimisation under weight constraints
<p>With a lot of help from contributors to StackOverflow I have managed to put together a function to derive the weights of a 2-asset portfolio which maximises the Sharpe ratio. No short sales are allowed and the sum of weights add to 1. What I would like to do now is to constrain asset A to not being more or less than 10% from a user defined weight. As an example  I would like to constrain the weight of asset A to be no less than 54% or more than 66% (i.e 60% +/- 10%). So on the below example I would end up with weights of (0.54,0.66) instead of the unsconstrained (0.243,0.7570) .I assume this can be done by tweaking bVect but I am not so sure how to go about it. Any help would be appreciated.   </p>

<pre><code>asset_A &lt;- c(0.034320510,-0.001209628,0.031900161,0.023163947,-0.001872938,-0.010322489,0.006090395,-0.003270854,0.017778990,0.017204915) 

asset_B &lt;- c(0.047103261,0.055175057,0.021019816,0.020602347,0.007281368,-0.006547404,0.019155238,0.005494798,0.025429958,0.014929124)

     require(quadprog)

     HR_solve   &lt;- function(asset_A,asset_B) {
     vol_A    &lt;-  sd(asset_A)
     vol_B   &lt;-  sd(asset_B)
     cor_AB  &lt;-   cor(cbind(asset_A,asset_B),method="pearson")
     ret_A_B      &lt;- as.matrix(c(mean(asset_A),mean(asset_B)))

      vol_AB &lt;- c(vol_A,vol_B)
      covmat &lt;- diag(as.vector(vol_AB))%*%cor_AB%*%diag(as.vector(vol_AB))

      aMat &lt;- cbind(rep(1,nrow(covmat)),diag(1,nrow(covmat)))
      bVec  &lt;- c(1,0,0)
      zeros &lt;- array(0, dim = c(nrow(covmat),1))
      minw &lt;-  solve.QP(covmat, zeros, aMat, bVec, meq = 1 ,factorized = FALSE)$solution
      rp &lt;- as.numeric(t(minw) %*% ret_A_B)
      sp &lt;- sqrt(t(minw) %*% covmat %*% minw)
      wp &lt;- t(matrix(minw))

      sret &lt;- sort(seq(t(minw) %*% ret_A_B,max(ret_A_B),length.out=100))
      aMatt &lt;- cbind(ret_A_B,aMat)

      for (ri in sret[-1]){
      bVect  &lt;- c(ri,bVec)
      result &lt;-  tryCatch({solve.QP(covmat, zeros, aMatt, bVect, meq = 2,factorized = FALSE)},
                            warning = function(w){ return(NULL) } , error = function(w){ return(NULL)}, finally = {} )
     if (!is.null(result)){
     wp &lt;-  rbind(wp,as.vector(result$solution))
     rp &lt;-c(rp,t(as.vector(result$solution) %*% ret_A_B))
     sp &lt;- c(sp,sqrt(t(as.vector(result$solution)) %*% covmat %*% as.vector(result$solution))) }

     }

      HR_weights &lt;- wp[which.max(rp/sp),]
      as.matrix(HR_weights)
    }


HR_solve(asset_A,asset_B)


          [,1]
[1,] 0.2429662
[2,] 0.7570338
</code></pre>