This R session will introduce different solvers in R that can be used for portfolio optimization.

For an overwhelming amount of information on the many solvers for R, see the Task View on Optimization and Mathematical Programming.

John Nash, the author of many of the optimization packages (not to be confused with the main character of the movie A Beautiful Mind), has an interesting and insightful blog: https://nashjc.wordpress.com. In particular, the entry on choosing which method to use for “optimizing” functions is recommended as a guide on how to navigate the overwhelming amount of solvers in R.

General solvers

General solvers can deal with arbitrary nonlinear optimization problems, at the expense of perhaps slow convergence and risk of numerical issues.

Package stats

Package stats (base R package installed by default) offers several general purpose optimization routines.

  • optimize(): For one-dimensional unconstrained function optimization over an interval (for one-dimensional root finding use uniroot()).
f <- function(x) exp(-0.5*x) * sin(10*pi*x)
f(0.5)
#> [1] 4.768779e-16
result <- optimize(f, interval = c(0, 1), tol = 0.0001)
result
#> $minimum
#> [1] 0.3494978
#> 
#> $objective
#> [1] -0.8395633
str(result)
#> List of 2
#>  $ minimum  : num 0.349
#>  $ objective: num -0.84

# let's plot something
curve(f, 0, 1, n = 200, col=4); grid()
points(result$minimum, result$objective, pch = 20, col = "red", cex = 1.5)