# basic finance
library(xts) # to manipulate time series of stock data
library(portfolioBacktest) # to conduct backtests
library(pob) # book package with financial data
library(quantmod) # to download market data from the Internet
# plotting
library(ggplot2) # for nice plots
library(RcppRoll) # fast rolling means (roll_meanr)
# optimization
library(quadprog)
library(CVXR)
library(sparseIndexTracking) # to design index tracking portfolios
library(TRexSelector) # T-Rex method for sparse regression with FDR control
Portfolio Optimization
Chapter 13: Index Tracking Portfolios
R code
R code examples for Chapter 13 of the book:
Daniel P. Palomar (2024). Portfolio Optimization: Theory and Application. Cambridge University Press.
Loading packages
First load the packages used in the examples:
What is index tracking?
Tracking of the S&P 500 index by the SPDR S&P 500 ETF:
# get data from Yahoo!Finance
library(quantmod)
<- Ad(getSymbols("^GSPC", from = "2007-01-01", auto.assign = FALSE))
SP500_prices <- Ad(getSymbols("SPY", from = "2007-01-01", auto.assign = FALSE))
SPY_prices <- cbind(SP500_prices, SPY_prices)
SP500_SPY_prices colnames(SP500_SPY_prices) <- c("S&P 500", "SPY")
ggplot(fortify(SP500_SPY_prices, melt = TRUE), aes(x = Index, y = Value, color = Series)) +
geom_line(linewidth = 1.0) +
scale_y_log10() +
scale_x_date(date_breaks = "1 year", date_labels = "%Y", date_minor_breaks = "1 month") +
theme(legend.title = element_blank()) +
labs(title = "Tracking of S&P 500 index", x= NULL, y = "dollars")