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
我编写了一个代码来最小化我拥有的总金额,但是我也希望能够为股票分配权重并使它们的份额为整数。
我怎么能那样做?