vendredi 14 octobre 2016

R: Error in sample.int(): NMOF Package

I am trying to replicate the following code (based on Financial Optimization in R by @EnricoSchumann) but I got the following error. The code tries to solve Markowitz Model with cardinality constraint. Further, it also tries to constraint the value of minimum weight (winf) to be non-zero.

Error:

Error in sample.int(length(x), ...) : invalid first argument

Code

library(NMOF)
resample <- function(x,...) x[sample.int(length(x),...)]
data <- list(m = colMeans(fundData), ## expected returns
             Sigma = cov(fundData),  ## expected var of returns
             na = dim(fundData)[2L], ## number of assets
             eps = 0.2/100,          ## stepsize for LS
             winf = 0.03,               ## minimum weight
             wsup = 0.5,               ## maximum weight
             lambda = 1)
cat("The Portfolio will consist of at least ", ceiling(1/data$wsup), 
    " assets. \n", sep = "")

OF <- function(w, data){
  data$lambda * (w %*% data$Sigma %*% w) -
    (1 - data$lambda) * sum(w * data$m)
}

neighbour <- function(w, data){
  toSell <- which(w > data$winf)
  toBuy <- which(w < data$wsup)
  i <- toSell[sample.int(length(toSell), size = 1L)]
  j <- toBuy[sample.int(length(toBuy), size = 1L)]
  eps <- runif(1) * data$eps
  eps <- min(w[i] - data$winf, data$wsup - w[j], eps)
  w[i] <- w[i] - eps
  w[j] <- w[j] + eps
  w
}


#Initial Random Solution 
makex<-function(data){
  resample <- function(x,...)
    x[sample.int(length(x),...)]
  w0 <- numeric(data$na)
  nAssets <- resample(ceiling(1/data$wsup):data$na,1L)
  w0[sample(seq_len(data$na),nAssets)] <- runif(nAssets)
  w0/sum(w0)
}
w0 <- makex(data)
algo <- list(x0 = w0, neighbour = neighbour, nS = 5000L)
system.time(sol1 <- LSopt(OF, algo, data))

Suggestions welcome!




Aucun commentaire:

Enregistrer un commentaire