KDA <- function(rets, leverageFactor)
{
# i never change these args
offset <- 0
momWeights <- c(12, 4, 2, 1)
ep <- xts::endpoints(rets) + offset
ep[ep < 1] <- 1
ep[ep > nrow(rets)] <- nrow(rets)
ep <- unique(ep)
epDiff <- diff(ep)
if(xts::last(epDiff)==1)
ep <- ep[-length(ep)]
emptyVec <- data.frame(t(rep(0, ncol(rets)-2)))
names(emptyVec) <- names(rets)[1:(ncol(rets)-2)]
allWts <- list()
for(i in 1:(length(ep)-12)) {
retSubset <- rets[c((ep[i]+1):ep[(i+12)]),]
epSub <- ep[i:(i+12)]
sixMonths <- rets[(epSub[7]+1):epSub[13],]
threeMonths <- rets[(epSub[10]+1):epSub[13],]
oneMonth <- rets[(epSub[12]+1):epSub[13],]
moms <- PerformanceAnalytics::Return.cumulative(oneMonth) * momWeights[1] +
PerformanceAnalytics::Return.cumulative(threeMonths) * momWeights[2] +
PerformanceAnalytics::Return.cumulative(sixMonths) * momWeights[3] +
PerformanceAnalytics::Return.cumulative(retSubset) * momWeights[4]
assetMoms <- moms[,1:(ncol(moms)-2),drop=FALSE]
cpMoms <- moms[,(ncol(moms)-1):ncol(moms)]
selectedAssets <- assetMoms > 0
investedAssets <- emptyVec
if (sum(selectedAssets)==0) {
investedAssets <- emptyVec
} else if (sum(selectedAssets)==1) {
investedAssets <- emptyVec + selectedAssets
} else {
idx <- which(selectedAssets)
cors <- (stats::cor(oneMonth[,idx]) * momWeights[1] +
stats::cor(threeMonths[,idx]) * momWeights[2] +
stats::cor(sixMonths[,idx]) * momWeights[3] +
stats::cor(retSubset[,idx]) * momWeights[4]) / sum(momWeights)
vols <- PerformanceAnalytics::StdDev(oneMonth[,idx])
covs <- t(vols) %*% vols * cors
minVolRets <- t(matrix(rep(1, sum(selectedAssets))))
minVolWt <- tseries::portfolio.optim(x=minVolRets, covmat = covs)$pw
names(minVolWt) <- colnames(covs)
investedAssets <- emptyVec
investedAssets[,selectedAssets] <- minVolWt
}
pctAggressive <- mean(cpMoms > 0)
investedAssets <- investedAssets * pctAggressive
if (pctAggressive == 1)
investedAssets = investedAssets * leverageFactor
wts <- xts::xts(investedAssets, order.by=xts::last(zoo::index(retSubset)))
allWts[[i]] <- wts
}
allWts <- do.call(rbind, allWts)
allWts$CASH <- 1-rowSums(allWts)
allWts
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.