Working with real data

It is useful to know that portfolio optimization is totally integrated in various R packages that we will discuss later. However, it's better to walk before we run; so let's start with a simple self-made R function that we would also itemize line by line as follows:

minvariance <- function(assets, mu = 0.005) {
    return  <- log(tail(assets, -1) / head(assets, -1))
    Q       <- rbind(cov(return), rep(1, ncol(assets)),
               colMeans(return))
    Q       <- cbind(Q, rbind(t(tail(Q, 2)), matrix(0, 2, 2)))
    b       <- c(rep(0, ncol(assets)), 1, mu)
    solve(Q, b)
}

This is a direct implementation of the algorithm that we discussed in the Theorem (Lagrange) section.

For demonstration purposes, we have fetched some IT stock prices from a Quandl superset (http://www.quandl.com/USER_1KR/1KT ...

Get Introduction to R for Quantitative Finance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.