Path: blob/master/inst/tests/test_roi_max_ret_milp.R
1433 views
1# maximum return with position limit constraints2library(testthat)3library(ROI)4library(ROI.plugin.glpk)5library(Rglpk)6library(PerformanceAnalytics)78data(edhec)9R <- edhec[, 1:5]10m <- ncol(R)1112constraints <- list()13constraints$min_sum <- 0.9914constraints$max_sum <- 1.0115constraints$min <- rep(0.2, m)16constraints$max <- rep(1, m)17constraints$max_pos <- 31819moments <- list()20moments$mu <- colMeans(R)21moments$mean <- colMeans(R)2223target <- NA2425max_pos <- constraints$max_pos26min_pos <- 22728# Number of assets29N <- ncol(R)3031# Upper and lower bounds on weights32LB <- as.numeric(constraints$min)33UB <- as.numeric(constraints$max)3435##### ROI #####3637# Check for target return38if(!is.na(target)){39# We have a target40targetcon <- rbind(c(moments$mean, rep(0, N)),41c(-moments$mean, rep(0, N)))42targetdir <- c("<=", "==")43targetrhs <- c(Inf, -target)44} else {45# No target specified, just maximize46targetcon <- NULL47targetdir <- NULL48targetrhs <- NULL49}5051# weight_sum constraint52Amat <- rbind(c(rep(1, N), rep(0, N)),53c(rep(1, N), rep(0, N)))5455# Target return constraint56Amat <- rbind(Amat, targetcon)5758# Bounds and position limit constraints59Amat <- rbind(Amat, cbind(-diag(N), diag(LB)))60Amat <- rbind(Amat, cbind(diag(N), -diag(UB)))61Amat <- rbind(Amat, c(rep(0, N), rep(-1, N)))62Amat <- rbind(Amat, c(rep(0, N), rep(1, N)))6364dir <- c("<=", ">=", targetdir, rep("<=", 2*N), "<=", "<=")65rhs <- c(1, 1, targetrhs, rep(0, 2*N), -min_pos, max_pos)6667# Only seems to work if I do not specify bounds68# bnds <- V_bound(li=seq.int(1L, 2*N), lb=c(as.numeric(constraints$min), rep(0, N)),69# ui=seq.int(1L, 2*N), ub=c(as.numeric(constraints$max), rep(Inf, N)))70bnds <- NULL7172# Set up the types vector with continuous and binary variables73types <- c(rep("C", N), rep("B", N))7475# Set up the linear objective to maximize mean return76ROI_objective <- L_objective(L=c(-moments$mean, rep(0, N)))7778# Set up the optimization problem and solve79opt.prob <- OP(objective=ROI_objective,80constraints=L_constraint(L=Amat, dir=dir, rhs=rhs),81bounds=bnds, types=types)82roi.result <- ROI_solve(x=opt.prob, solver="glpk")8384##### Rglpk #####8586objL <- c(-moments$mean, rep(0, N))8788result <- Rglpk_solve_LP(obj=objL, mat=Amat, dir=dir, rhs=rhs, bounds=bnds, types=types)8990context("Test Rglpk_solve_LP and ROI_solve for maximum return with cardinality constraints")9192test_that("Objective values are equal", {93expect_equal(roi.result$objval, result$optimum)94})9596test_that("Solutions (optimal weights) are equal", {97expect_equal(roi.result$solution[1:m], result$solution[1:m])98})99100