Get startedGet started for free

Solve a simple portfolio optimization problem

This first exercise will teach you how to solve a simple portfolio optimization problem using PortfolioAnalytics. You will learn how to create a portfolio specification object, add constraints and objectives, and solve the optimization problem. The portfolio problem is to form a minimum variance portfolio subject to full investment and long only constraints. The objective is to minimize portfolio variance. There are two constraints in this problem: the full investment constraint means that the weights must sum to 1, and the long only constraint means that all weights must be greater than or equal to 0 (i.e. no short positions are allowed).

This exercise is part of the course

Intermediate Portfolio Analysis in R

View Course

Exercise instructions

  • Create a portfolio specification object using asset names from the index_returns dataset and name the portfolio specification object port_spec.
  • Add a full investment constraint such that the weights sum to 1 to the port_spec object.
  • Add a long only constraint such that the weight of an asset is between 0 and 1 to the port_spec object.
  • Add an objective to minimize portfolio standard deviation to the port_spec object.
  • Solve the portfolio optimization problem using optimize_method = "ROI". Assign the results of the optimization to an object named opt.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Create the portfolio specification
port_spec <- portfolio.spec(colnames(___))

# Add a full investment constraint such that the weights sum to 1
port_spec <- add.constraint(portfolio = ___, type = "___")

# Add a long only constraint such that the weight of an asset is between 0 and 1
port_spec <- add.constraint(portfolio = ___, type = "___")

# Add an objective to minimize portfolio standard deviation
port_spec <- add.objective(portfolio = ___, type = "___", name = "___")

# Solve the optimization problem
opt <- optimize.portfolio(___, portfolio = ___, optimize_method = "___")
Edit and Run Code