Add constraints
Constraints are added to the portfolio specification object with the add.constraint()
function. Each constraint added is a separate object and stored in the constraints
slot in the portfolio object. In this way, the constraints are modular and one can easily add, remove, or modify the constraints in the portfolio object. The required arguments for add.constraint()
are the portfolio
the constraint is added to, the constraint type
, and named arguments passed via ...
to the constructor of the constraint type.
Basic constraint types:
- Specify the constraint on the sum of the weights
weight_sum
,weight
,leverage
full_investment
is a special case that setsmin_sum = max_sum = 1
dollar_neutral
is a special case that setsmin_sum = max_sum = 0
- Specify constraints for the individual asset weights
box
long_only
is a special case that setsmin = 0
andmax = 1
- Specify the constraint for the sum of weights of assets by group (sector, region, asset class, etc.)
group
- Specify a constraint on the target mean return
return
In this exercise, you will add a few of the more common constraint types. In addition to the basic constraint types listed above, PortfolioAnalytics
also supports position limit, turnover, diversification, factor exposure, and leverage exposure constraint types. If you are interested in the other constraint types, look at the help files for the constraint constructors. The help files include a description of the constraint type as well as example code.
This exercise is part of the course
Intermediate Portfolio Analysis in R
Exercise instructions
- Add a
weight_sum
constraint such that the minimum sum of weights is 1 and the maximum sum of weights is 1. - Add a
box
constraint such that the first five assets have a minimum weight of 10% and the remaining assets have a minimum weight of 5%. All assets have a maximum weight of 40% - Add a
group
constraint such that assets 1, 5, 7, 9, 10, and 11 are the first group and assets 2, 3, 4, 6, 8, and 12 are the second group. Set the minimum weight to 40% and maximum weight to 60% for each group.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add the weight sum constraint
port_spec <- add.constraint(portfolio = ___, type = ___, min_sum = ___, max_sum = ___)
# Add the box constraint
port_spec <- add.constraint(portfolio = ___, type = ___, min = c(___), max = ___)
# Add the group constraint
port_spec <- add.constraint(portfolio = ___, type = ___, groups = list(c(___), c(___)), group_min = ___, group_max = ___)
# Print the portfolio specification object