[R] non negativity constraints if else function

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Sun Dec 21 09:26:07 CET 2014


Please keep the conversation on the list, Esra... I don't do personal 
tutoring online, and others may answer your questions sooner and better 
than I can.

Some comments below:

On Sat, 20 Dec 2014, Esra Ulasan wrote:

> Hello,
> Thank you very much for your concern. I have these codes for portfolio optimization solved by Lagrange function.
> I want to put a non-negativity constraint on weights. If the element of weight vector is negative remove it from the vector and recalculate the other elements of weight vector again after removing negative ones. It is going to be a non-negativity constraint on weights. I am trying to do it but I could not solve it.
> Thank you very much.
> Esra
>
> optimization<-function(returns) {

# what is "x"? From context, perhaps a matrix?
# also, you are abusing positional parameters by not putting x first.. 
# read ?colMeans
# also, "mean" is the name of a VERY common R function... using it as a 
# variable name is very confusing at best

>  mean <- colMeans(na.rm=FALSE,x)

# what is "asset.names"?

>  names(mean) <-assets.names

# 100L is a simpler way to write an integer, though it does not look 
# to me like M really needs to be an integer so much

>  M <- as.integer(100)    #nuber of ports on the eff.front.
>  S <- cov(x)
>  Rmax<- 0.01282409    #max monthly return value
>  Thetah <- solve(S)

# what is p?

>  u <- rep(1,p)
>  a<- matrix(rep(0,4), nrow=2)
>  a[1,1] <- t(u)%*%Thetah%*%u
>  a[1,2] <- t(mean)%*%Thetah%*%u
>  a[2,1] <- a[1,2]
>  a[2,2] <- t(mean)%*%Thetah%*%mean

# you might be interested in the ?det function

>  d <- a[1,1]*a[2,2]-a[1,2]*a[1,2]
>  f <- (Thetah%*%(a[2,2]*u-a[1,2]*mean))/d
>  g <- (Thetah%*%(-a[1,2]*u+a[1,1]*mean))/d
>  r <- seq(0, Rmax, length=M)
>  w <- matrix((rep(0, p*M)), nrow=p)
>
>  for(i in 1:M) { w[,i] = f+r[i]*g                    #portfolio weights
>      if (w[,i] <0) {w[,i]=0} else {w[,i]=w[,i]}
>    }
>  rownames(w)=assets.names

# I think the following two lines can entirely replace the for loop 
#above

w <- f + r * g
>  w=ifelse(w<0, 0, w)
>

# I am not familiar with this type of modification of matrices

>  #removing zero rows from weight matrix
>  row_sub = apply(w, 1, function(row) all(row !=0 ))
>  w2=w[row_sub,]
>
>  s <- sqrt( a[1,1]*((r - a[1,2]/a[1,1])^2)/d + 1/a[1,1] ) # variance of the frontier
>  ss <- sqrt(diag(S))
>  names(ss) <- assets.names
>  minp <- c(sqrt(1/a[1,1]), a[1,2]/a[1,1])            # risk-return values of MVP
>  wminp <- f + (a[1,2]/a[1,1])*g                      #weights(allocation of assets) of MVP
>  names(wminp) <- assets.names
>  sharpe <- c((sqrt(1/a[1,1])) / a[1,2]/a[1,1])      #maximum sharpe ratio
>  tanp <- c(sqrt(a[2,2])/a[1,2], a[2,2]/a[1,2])      #risk-return values of tangency portfolio
>  wtanp <- f+(a[2,2]/a[1,2])*g                       #weight (allocation of assets) of tangency portfolio
>

# Not sure what you are hoping to achieve by concatenating some scalars 
# and vectors together for return from the function.

> return(c(s, r, ss, mean, minp, tanp, wminp, wtanp, w))
>

# seem to be missing a brace "}"

Have you read the help file for the "optim" function? It includes some 
options for constrained optimization that might help you.

(no more comments)

>
> 20 Ara 2014 tarihinde 20:41 saatinde, Jeff Newmiller <jdnewmil at dcn.davis.CA.us> ?unlar? yazd?:
>
>> "if weight element is negative set it to zero, else recalculate the weights again"... this seems like the only way out of this loop is to calculate negative weights... and since you set them to zero at that point they will all be zero when you are done. Somehow I doubt that is what you intended to say.
>>
>> On the other hand, if you had provided us with example input data and result data then we would not have to guess what you want.
>>
>> I suspect that loops are not really what you want at all... but I could be wrong.
>>
>> ---------------------------------------------------------------------------
>> Jeff Newmiller                        The     .....       .....  Go Live...
>> DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
>>                                      Live:   OO#.. Dead: OO#..  Playing
>> Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
>> /Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
>> ---------------------------------------------------------------------------
>> Sent from my phone. Please excuse my brevity.
>>
>> On December 19, 2014 8:26:55 PM PST, Esra Ulasan <esra_ulasan at icloud.com> wrote:
>>> Hello,
>>>
>>> I have tried the solve the non-negativity constraint "if else function"
>>> in R. But I have done something wrong because it still gives the same
>>> solution. I want that, if weight element is negative set it to zero,
>>> else recalculate the weights again. These are the codes:
>>>
>>> for(i in 1:M){ w[,i] = f+r[i]*g              #portfolio weights
>>>   for(i in 1:M){
>>>     if (w <0){w=0}else{w=w}
>>>   }
>>> }
>>> If you help me I would be happy
>>> Thank you
>>> 	[[alternative HTML version deleted]]
>>>
>>> ______________________________________________
>>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>>> https://stat.ethz.ch/mailman/listinfo/r-help
>>> PLEASE do read the posting guide
>>> http://www.R-project.org/posting-guide.html
>>> and provide commented, minimal, self-contained, reproducible code.
>>
>

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k



More information about the R-help mailing list