PortfolioAnalytics
PortfolioAnalytics copied to clipboard
add.constraint type = "position_limit" causes error when running random_portfolios_v2 with sample method
I am running various tests to be able to upgrade my PortfolioAnalytics simulations to r4.4 with the latest version of PortfolioAnalytics. I noticed that my current production version that runs on r4.3 with a previous version of PortfolioAnalytics does not show an error. However on r4.4 with the current GitHub development version of PortfolioAnalytics causes an error when implying a limit on the number of long positions.
I have created a minimal version of the problem using a reprex (shown below) to highlight the problem. The position limit is set a 70. 70 is much larger than 4 so the limit should not have any impact on the selection of random portfolio's.
library(PortfolioAnalytics)
#> Loading required package: zoo
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#> as.Date, as.Date.numeric
#> Loading required package: xts
#> Loading required package: foreach
#> Loading required package: PerformanceAnalytics
#>
#> Attaching package: 'PerformanceAnalytics'
#> The following object is masked from 'package:graphics':
#>
#> legend
#> Registered S3 method overwritten by 'PortfolioAnalytics':
#> method from
#> print.constraint ROI
Assets = c("stock1", "stock2", "stock3", "stock4")
Initportfolio <- portfolio.spec(assets=Assets)
# Add the full investment constraint that specifies the weights must sum to 1
Initportfolio <- add.constraint(portfolio=Initportfolio, type = "leverage", min_sum = 0.98, max_sum = 1.02)
if (length(Assets) > 10){
Initportfolio <- add.constraint(portfolio=Initportfolio, type = "box", min = 0, max = 0.2)
} else {
Initportfolio <- add.constraint(portfolio=Initportfolio, type = "box", min = 0, max = 1)
}
NoLimit <- random_portfolios_v2( portfolio = Initportfolio, permutations = 100, rp_method = "sample", eliminate = TRUE)
# Add position limit to portfolio
Initportfolio <- add.constraint(portfolio=Initportfolio, type = "position_limit", max_pos_long = 70)
PositionLimit <- random_portfolios_v2( portfolio = Initportfolio, permutations = 100, rp_method = "sample", eliminate = TRUE)
#> Error in sample.int(length(x), size, replace, prob): cannot take a sample larger than the population when 'replace = FALSE'`
#Created on 2024-07-18 with reprex v2.1.1