total_amount <- 1000000 df <- data.frame("price"= c(226,186,456,615,549), "firms"= c("VRSN","TXN","DPZ","IDXX","ORLY")) FUN <- function(q, price=df$price){ total <- sum(price * q) errs <- c( (total-total_amount)^2, ( ( q[1]*price)/sum(q[1]*price+q[2]*price+q[3]*price+q[4]*price+q[5]*price) + q[2]*price/sum(q[1]*price+q[2]*price+q[3]*price+q[4]*price+q[5]*price) + q[3]*price/sum(q[1]*price+q[2]*price+q[3]*price+q[4]*price+q[5]*price) + q[4]*price/sum(q[1]*price+q[2]*price+q[3]*price+q[4]*price+q[5]*price) + q[5]*price/sum(q[1]*price+q[2]*price+q[3]*price+q[4]*price+q[5]*price) )) sum(errs) } init_q <- rep(1,nrow(df)) res <- optim(init_q, FUN, lower=rep(0,nrow(df)), method="L-BFGS-B") res res$par round(res$par) sum(round(res$par)*df$price) - total_amount dt <- df$firms %>% as.data.frame() dt$lot <- round(res$par,0) dt$price <- df$price dt$dnm <- dt$lot*dt$price/sum(dt$lot*dt$price) dt I wrote a code that minimize the total amount of money that I had, however I also want to be able to assign weights to stocks and make them have shares as integer.
How could I do that ?