Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# R code re: post for replicating indexes in R
# "Replicating Indexes In R With Style Analysis: Part I"
# 10 Oct 2017
# By James Picerno
# (c) 2017 by Beta Publishing LLC
# load packages
# download price histories
Quandl.api_key("ABC123") # <-enter your Quandl API key here.
# Or use free price history at or
# to populate prices.1 file below
symbols <-c("XLF", "XLK", "XLI", "XLB", "XLY", "XLV", "XLU", "XLP", "XLE", "VOX", "VNQ", "SPY")
prices <- list()
for(i in 1:length(symbols)) {
price <- Quandl(paste0("EOD/", symbols[i]), start_date="2010-12-31", type = "xts")$Adj_Close
colnames(price) <- symbols[i]
prices[[i]] <- price
prices.1 <- na.omit(, prices))
dat1 <-ROC(prices.1,1,"discrete",na.pad=F)
# estimate weights <-dat1[,12] # returns of target fund to replicate
x.funds <-dat1[,1:11] # returns of funds to reweight to replicate target fund
rows <-nrow(x.funds)
cols <-ncol(x.funds)
Dmat <-cov(x.funds, use="pairwise.complete.obs")
dvec <-cov(, x.funds, use="pairwise.complete.obs")
a1 <-rep(1, cols)
a2 <-matrix(0, cols, cols)
diag(a2) <- 1
w.min <-rep(0, cols)
Amat <-t(rbind(a1, a2))
b0 <-c(1, w.min)
optimal <- solve.QP(Dmat, dvec, Amat, bvec = b0, meq = 1)
weights <-$solution)
rownames(weights) = names(x.funds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment