Path: blob/master/inst/tests/test_rp_sample.R
1433 views
1require(testthat)2require(PortfolioAnalytics)34context("random portfolios sample method")56data(edhec)7ret <- edhec[, 1:4]8funds <- colnames(ret)910init.portf <- portfolio.spec(assets=funds)11init.portf <- add.constraint(init.portf, type="weight_sum",12min_sum=0.99, max_sum=1.01)13init.portf <- add.constraint(init.portf, type="box",14min=-0.3, max=0.65)1516# generate portfolios to satisfy weight_sum and box constraints17rp1 <- random_portfolios(init.portf, 1000, eliminate=FALSE)18test_that("we have created at least 1 feasible portfolio to satisfy weight_sum and box constraints", {19expect_that(any(apply(rp1, 1, PortfolioAnalytics:::check_constraints, portfolio=group.portf)), is_true())20})2122# portfolio with group constraints23group.portf <- add.constraint(init.portf, type="group",24groups=list(1:2,3:4),25group_min=c(0.08, 0.05),26group_max=c(0.55, 0.85),27group_pos=c(2,2))2829# generate portfolios to satisfy weight_sum, box, and group constraints30rp2 <- random_portfolios(group.portf, 1000, eliminate=FALSE)31test_that("we have created at least 1 feasible portfolio to satisfy weight_sum, box, and group constraints", {32expect_that(any(apply(rp2, 1, PortfolioAnalytics:::check_constraints, portfolio=group.portf)), is_true())33})3435# add leverage exposure constraint36lev.portf <- add.constraint(init.portf, type="leverage_exposure",37leverage=1.6)3839# generate portfolios to satisfy weight_sum, box, and leverage constraints40rp3 <- random_portfolios(lev.portf, 1000, eliminate=FALSE)41test_that("we have created at least 1 feasible portfolio to satisfy weight_sum, box, and leverage constraints", {42expect_that(any(apply(rp3, 1, PortfolioAnalytics:::check_constraints, portfolio=group.portf)), is_true())43})4445# add position limit constraint46pos1.portf <- add.constraint(init.portf, type="position_limit",47max_pos=3)4849# generate portfolios to satisfy weight_sum, box, and position limit constraints50rp4 <- random_portfolios(pos1.portf, 1000, eliminate=FALSE)51test_that("we have created at least 1 feasible portfolio to satisfy weight_sum, box, and position limit constraints", {52expect_that(any(apply(rp4, 1, PortfolioAnalytics:::check_constraints, portfolio=group.portf)), is_true())53})5455# add position limit constraint with long and short position limits56pos2.portf <- add.constraint(init.portf, type="position_limit",57max_pos_long=3, max_pos_short=1)5859# generate portfolios to satisfy weight_sum, box, and position limit constraints60rp5 <- random_portfolios(pos2.portf, 1000, eliminate=FALSE)61test_that("we have created at least 1 feasible portfolio to satisfy weight_sum, box, and long/short position limit constraints", {62expect_that(any(apply(rp5, 1, PortfolioAnalytics:::check_constraints, portfolio=group.portf)), is_true())63})64656667