Hello Qiang,
Here is the script I have used in the leaderboard webinar. Please note that the “diversityScore” function is not shared with users as the aim is not to optimise this metric; you should aim to have exposure to all assets to increase your ranking.
We’ll publish the webinar replay on Monday 8 June.
Script:
## DIVERSIFICATION
## ===============
# Single asset portfolio
staticPayout = function(assetReturns, weights){
dates = index(assetReturns)
nbDate = nrow(assetReturns)
alloc = xts(matrix(rep(weights, nbDate),nrow=nbDate, byrow=TRUE), order.by=dates)
alloc = to.monthly(alloc, OHLC=FALSE, indexAt=‘endof’)
return(alloc)
}
# Check payout
rets = getStrategyReturns(list(‘TYa’, ‘USHYa’, ‘BNKa’))
print(head(staticPayout(rets, c(0.1,0.3,0.6))))
# Create portfolio with only one asset invested
portfolio(list(‘TYa’, ‘USHYa’, ‘BNKa’)) %>%
payout(staticPayout, weights = c(0.0, 1.0, 0.0)) %>%
evaluate() -> singleAssetPort
diversityScore(singleAssetPort)
# Create portfolio with only all assets invested
portfolio(list(‘TYa’, ‘USHYa’, ‘BNKa’)) %>%
payout(staticPayout, weights = c(0.3, 0.5, 0.2)) %>%
evaluate() -> singleAssetPort
diversityScore(singleAssetPort)
# Diversification score is higher => we improved our diversification
## ROBUSTNESS
## ==========
#1. Hard coding data calls
poorPayout = function(assetReturns){
# Call data here …
px = getAlphathonBBs(asPrice=TRUE)
# … the payout becomes specific: it becomes artificially linked to the
# behaviour of getAlphathonBBs.
…
}
robustPayout = function(assetReturns, px=getAlphathonBBs()){
…
}
#2. Use external variables
px = getAlphathonBBs(asPrice=TRUE)
poorPayout = function(assetReturns){
movingAverages = apply(px, 2, function(x){EMA(x, 50)})
print(tail(movingAverages))
}
robustPayout = function(assetReturns, px=getAlphathonBBs(asPrice=TRUE),
MAperiod = 100){
movingAverages = apply(px, 2, function(x){EMA(x, MAperiod)})
print(tail(movingAverages))
}
#3. Change in input structure
# What if input series gets discontinued?
# Test your payout with discontinued data to make sure it runs
returns = getStrategyReturns(list(‘TYa’, ‘USHYa’, ‘BNKa’))
print(dim(returns))
discData = returns[-seq(1000, 1500),]
plotAl(discData)
strat = staticPayout(discData, c(0.3, 0.5, 0.2))
# check the allocations have been able to handle discontinuity
plot(as.numeric(index(strat)), coredata(strat[,1]))
#4. Use external libraries
poorPayout = function(assetReturns){
dateMonths = month(index(assetReturns))
print(dateMonths[1:10])
}
robustPayout = function(assetRetuns){
dateMonths = lubridate::month(index(assetReturns))
print(dateMonths[1:10])
}