Skip to content

Instantly share code, notes, and snippets.

@jpicerno1
Last active November 24, 2022 04:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jpicerno1/8c26e3c6b16364fac3d01149b5ba401d to your computer and use it in GitHub Desktop.
Save jpicerno1/8c26e3c6b16364fac3d01149b5ba401d to your computer and use it in GitHub Desktop.
# R code re: CapitalSpecator.com post for replicating indexes in R
# "Replicating Indexes In R With Style Analysis: Part I"
# http://www.capitalspectator.com/replicating-indexes-in-r-with-style-analysis-part-i/
# 10 Oct 2017
# By James Picerno
# http://www.capitalspectator.com/
# (c) 2017 by Beta Publishing LLC
# load packages
library(quadprog)
library(PerformanceAnalytics)
library(quantmod)
require(Quandl)
# download price histories
Quandl.api_key("ABC123") # <-enter your Quandl API key here.
# Or use free price history at Tiingo.com or alphavantage.co
# 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(do.call(cbind, prices))
dat1 <-ROC(prices.1,1,"discrete",na.pad=F)
# estimate weights
y.fund <-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(y.fund, 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 <- as.data.frame(optimal$solution)
rownames(weights) = names(x.funds)
weights
# END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment