Path: blob/master/sandbox/symposium2013/optimize.HFindexes.R
1433 views
### For Presentation at FactSet's 2013 US Investment Process Symposium1# November 10 - 12 , 20132# Peter Carl34### Load the necessary packages5# Include optimizer packages6require(PortfolioAnalytics)7require(quantmod)8library(DEoptim)9library(ROI)10require(ROI.plugin.quadprog)11require(ROI.plugin.glpk)12# ... and multi-core packages13require(foreach)14require(doMC)15registerDoMC(6)1617# Available on r-forge18# require(FactorAnalytics) # development version > build1920### Set script constants21runname='historical.moments'22rebalance_period = 'years' #'quarters' # uses endpoints identifiers from xts; how to do semi-annual?23clean = "boudt" # "none"24permutations = 200025p=1-1/12 # set confidence for VaR/mETL for monthly data2627### Description2829# Seven assets, in this case hedge fund indexes representing different styles and two 'types':30# Convertible Arbitrage | Non-directional31# Equity Market Neutral | Non-directional32# Fixed Income Arbitrage | Non-directional33# Event Driven | Non-directional34# CTA Global | Directional35# Global Macro | Directional36# Long/Short Equity | Directional3738# see analyze.HFindexes.R for more detail3940# Set up seven objectives as buoy portfolios:41# - Equal contribution to...42# 1 Weight43# 2 Variance44# 3 Risk (mETL)45# - Reward to Risk ratio of...46# 4 Mean-Variance47# 5 Mean-mETL48# - Minimum...49# 6 Variance50# 7 Risk (mETL)5152# Add constraints53# - Box constraints - 5% to 30%54# - Group constraints - Non-directional constrained to 20-70%; Directional between 10-50%55# - Rebalancing period - quarterly56# - Turnover constraints - TBD5758#------------------------------------------------------------------------59# Set up an initial portfolio object with constraints and objectives using60# v2 specification6162# Create initial portfolio object used to initialize ALL the bouy portfolios63init.portf <- portfolio.spec(assets=colnames(R),64weight_seq=generatesequence(by=0.005)65)66# Add leverage constraint67init.portf <- add.constraint(portfolio=init.portf,68type="leverage"69)70# Add box constraint71init.portf <- add.constraint(portfolio=init.portf,72type="box",73min=0.05,74max=0.375)76# Add group constraint77init.portf <- add.constraint(portfolio=init.portf, type="group",78groups=list(c(1:4),79c(5:7)),80group_min=c(0.25,.05),81group_max=c(0.85,0.75)82)8384# print(init.portf)85# summary(init.portf)8687#------------------------------------------------------------------------88### Construct BUOY 1: Constrained Mean-StdDev Portfolio - using ROI89# Add the return and sd objectives to the constraints created above90MeanSD.portf <- add.objective(portfolio=init.portf,91type="return", # the kind of objective this is92name="mean" # name of the function93)94MeanSD.portf <- add.objective(portfolio=MeanSD.portf,95type="risk", # the kind of objective this is96name="var", # name of the function97arguments=list(clean=clean)98)99100### Construct BUOY 2: Constrained Mean-mETL Portfolio - using ROI101#@ Cannot maximize mean return per unit ETL with ROI, consider using102#@ random portfolios or DEoptim. - RB103# Add the return and mETL objectives104MeanmETL.portf <- add.objective(portfolio=init.portf,105type="return", # the kind of objective this is106name="mean" # name of the function107, multiplier=-12108)109MeanmETL.portf <- add.objective(portfolio=MeanmETL.portf,110type="risk", # the kind of objective this is111name="ES", # the function to minimize112arguments=list(p=p, clean=clean)113)114115### Construct BUOY 3: Constrained Minimum Variance Portfolio - using ROI116# Add the variance objective117MinSD.portf <- add.objective(portfolio=init.portf,118type="risk", # the kind of objective this is119name="var", # name of the function120arguments=list(p=p, clean=clean)121)122123### Construct BUOY 4: Constrained Minimum mETL Portfolio - using ROI124# Add the mETL objective125MinmETL.portf <- add.objective(portfolio=init.portf,126type="risk", # the kind of objective this is127name="ES", # the function to minimize128arguments=list(p=p, clean=clean)129)130131### Construct BUOY 5: Constrained Equal Variance Contribution Portfolio - using RP132#@ - Add the sub-objectives first. Adding these 3 objectives means that we are133#@ maximizing mean per unit StdDev with equal volatility contribution portfolios. - RB134# Without a sub-objective, we get a somewhat undefined result, since there are (potentially) many Equal SD contribution portfolios.135# MRCSD.portf <- add.objective(portfolio=init.portf,136# type="risk",137# name="StdDev"138# ) # OR139# MRCSD.portf <- add.objective(portfolio=init.portf,140# type="return",141# name="mean"142# )143MRCSD.portf <- add.objective(portfolio=init.portf,144type="risk_budget",145name="StdDev",146min_concentration=TRUE,147arguments = list(clean=clean)148)149150# MRCSD.portf$constraints[[1]]$min_sum = 0.99 # set to speed up RP151# MRCSD.portf$constraints[[1]]$max_sum = 1.01152153### Construct BUOY 6: Constrained Equal mETL Contribution Portfolio - using RP154#@ Add the sub-objectives first. These should be added to the MRCmETL portfolio.155#@ All objectives below mean that we are maximizing mean return per unit ES with156#@ equal ES contribution. - RB157# Without a sub-objective, we get a somewhat undefined result, since there are (potentially) many Equal SD contribution portfolios.158# MRCmETL.portf <- add.objective(portfolio=init.portf,159# type="risk",160# name="ES"161# ) # OR162MRCmETL.portf <- add.objective(portfolio=init.portf,163type="return",164name="mean"165)166MRCmETL.portf <- add.objective(MRCmETL.portf,167type="risk_budget",168name="ES",169min_concentration=TRUE,170arguments = list(p=p, clean=clean)171)172# Calculate portfolio variance, but don't use it in the objective; used only for plots173MRCmETL.portf <- add.objective(portfolio=MRCmETL.portf,174type="risk", # the kind of objective this is175name="StdDev", # the function to minimize176enabled=TRUE, # enable or disable the objective177multiplier=0, # calculate it but don't use it in the objective178arguments=list(clean=clean)179)180# MRCmETL.portf$constraints[[1]]$min_sum = 0.99 # set to speed up RP181# MRCmETL.portf$constraints[[1]]$max_sum = 1.01182183### Construct BUOY 7: Equal Weight Portfolio184# There's only one, so create a portfolio object with all the objectives we want calculated.185EqWgt.portf <- portfolio.spec(assets=colnames(R))186EqWgt.portf <- add.constraint(portfolio=EqWgt.portf, type="leverage", min_sum=1, max_sum=1)187EqWgt.portf <- add.objective(portfolio=EqWgt.portf, type="return", name="mean")188EqWgt.portf <- add.objective(portfolio=EqWgt.portf, type="risk_budget", name="ES", arguments=list(p=p, clean=clean))189EqWgt.portf <- add.objective(portfolio=EqWgt.portf, type="risk_budget", name="StdDev", arguments=list(clean=clean))190191### Construct BUOY 8: Inverse Volatility Portfolio192# There's only one, so create a portfolio object with all the objectives we want calculated.193VolWgt.portf <- portfolio.spec(assets=colnames(R))194VolWgt.portf <- add.constraint(portfolio=VolWgt.portf, type="leverage", min_sum=0.99, max_sum=1.01)195VolWgt.portf <- add.objective(portfolio=VolWgt.portf, type="return", name="mean")196VolWgt.portf <- add.objective(portfolio=VolWgt.portf, type="risk_budget", name="ES", arguments=list(p=p, clean=clean))197VolWgt.portf <- add.objective(portfolio=VolWgt.portf, type="risk_budget", name="StdDev", arguments=list(clean=clean))198199# REMOVED - to much to show already200# ### Construct RISK BUDGET Portfolio201# ConstrConcmETL.portf <- portfolio.spec(assets=colnames(R),202# weight_seq=generatesequence(by=0.005)203# )204# # Add leverage constraint205# ConstrConcmETL.portf <- add.constraint(portfolio=RiskBudget.portf,206# type="leverage",207# min_sum=0.99, # set to speed up RP, DE208# max_sum=1.01209# )210# # Establish position bounds211# ConstrConcmETL.portf <- add.constraint(portfolio=ConstrConcmETL.portf,212# type="box",213# min=0.01, # leave relatively unconstrained214# max=1.0215# )216# # Maximize mean return217# ConstrConcmETL.portf <- add.objective(portfolio=ConstrConcmETL.portf,218# type="return", # maximize return219# name="mean",220# multiplier=12221# )222# # Add a risk measure223# # Use ES to be consistent with risk measures in other BUOY portfolios224# ConstrConcmETL.portf <- add.objective(portfolio=ConstrConcmETL.portf,225# type="risk",226# name="ETL", # using a different name to avoid clobbering slot below, workaround for bug227# multiplier=1,228# arguments = list(p=p, clean=clean)229# )230#231# # Set contribution limits232# ConstrConcmETL.portf <- add.objective(portfolio=ConstrConcmETL.portf,233# type="risk_budget",234# name="ES",235# max_prisk=0.3, # Sets the maximum percentage contribution to risk236# arguments = list(p=p, clean=clean)237# )238# Calculate portfolio variance, but don't use it in the objective; used only for plots239# ConstrConcmETL.portf <- add.objective(portfolio=ConstrConcmETL.portf,240# type="risk", # the kind of objective this is241# name="StdDev", # the function to minimize242# enabled=TRUE, # enable or disable the objective243# multiplier=0, # calculate it but don't use it in the objective244# arguments=list(clean=clean)245# )246247#------------------------------------------------------------------------248### Evaluate portfolio objective objects249#------------------------------------------------------------------------250# Generate a single set of random portfolios to evaluate against all RP constraint sets251print(paste('constructing random portfolios at',Sys.time()))252253# Modify the init.portf specification to get RP running254rp.portf <- init.portf255# rp.portf$constraints[[1]]$min_sum = 0.99 # set to speed up RP256# rp.portf$constraints[[1]]$max_sum = 1.01257rp.portf$constraints[[1]]$min_sum = 1.00 # for more accuracy258rp.portf$constraints[[1]]$max_sum = 1.00259# rp = random_portfolios(portfolio=rp.portf, permutations=30000, max_permutations=400) # will get fewer with less accuracy260load(file=paste(resultsdir,'random-portfolios-2013-10-05.historical.moments.rda'))261rp.mean = apply(rp, 1, function(w) mean(R %*% w))262rp.sd = apply(rp, 1, function(x) StdDev(R=R, weights=x, p=p, clean=clean))263plot(rp.sd, rp.mean, col="darkgray", cex=0.5)264265# REMOVED: This was fruitless266# rp1 = random_portfolios(portfolio=rp.portf, permutations=10000, max_permutations=400, rp_method="sample")267# rp1.mean = apply(rp1, 1, function(w) mean(R %*% w))268# rp1.sd = apply(rp1, 1, function(x) StdDev(R=R, weights=x, p=p))269# rp1.etl=NULL; for(i in 1:NROW(rp1)) {rp1.etl[i]=ETL(R=R, weights=as.vector(rp1[i,]), p=p, portfolio_method="component")[[1]]}270# plot(rp1.sd, rp1.mean, col="gray", cex=0.5)271#272# rp2 = random_portfolios(portfolio=rp.portf, permutations=10000, max_permutations=400, rp_method="simplex", fev=2)273# rp2.mean = apply(rp2, 1, function(w) mean(R %*% w))274# rp2.sd = apply(rp2, 1, function(x) StdDev(R=R, weights=x, p=p))275# points(rp2.sd,rp2.mean, col="blue", cex=0.5)276#277# rp3 = random_portfolios(portfolio=rp.portf, permutations=10000, max_permutations=400, rp_method="grid")278# rp3.mean = apply(rp3, 1, function(w) mean(R %*% w))279# rp3.sd = apply(rp3, 1, function(x) StdDev(R=R, weights=x, p=p))280# points(rp3.sd,rp3.mean, col="green", cex=0.5)281282# print(paste('done constructing random portfolios at',Sys.time()))283# save(rp,file=paste(resultsdir, 'random-portfolios-', Sys.Date(), '-', runname, '.rda',sep=''))284285286start_time<-Sys.time()287print(paste('Starting optimization at',Sys.time()))288289### Evaluate BUOY 1: Constrained Mean-StdDev Portfolio - with ROI290MeanSD.ROI<-optimize.portfolio(R=R,291portfolio=MeanSD.portf,292optimize_method='ROI',293trace=TRUE294)295plot(MeanSD.ROI, risk.col="StdDev", return.col="mean", rp=permutations, chart.assets=TRUE, main="Mean-Volatility Portfolio")296save(MeanSD.ROI,file=paste(resultsdir, 'MeanSD-', Sys.Date(), '-', runname, '.rda',sep='')) # Save the results297print(paste('Completed meanSD optimization at',Sys.time(),'moving on to meanmETL'))298299### Evaluate BUOY 2: Constrained Mean-mETL Portfolio - with DE or RND300# Not possible with ROI - RB301# MeanmETL.ROI<-optimize.portfolio(R=R,302# portfolio=MeanmETL.portf,303# optimize_method='ROI',304# trace=TRUE, verbose=TRUE305# )306#307308# So use random portfolios instead309MeanmETL.RND<-optimize.portfolio(R=R,310portfolio=MeanmETL.portf,311optimize_method='random',312rp=rp,313trace=TRUE314)315plot(MeanmETL.RND, risk.col="StdDev", return.col="mean", rp=permutations, chart.assets=TRUE, main="Mean-mETL Portfolio")316plot(MeanmETL.RND, risk.col="ES", return.col="mean", rp=permutations, chart.assets=TRUE, main="Mean-mETL Portfolio")317save(MeanmETL.RND,file=paste(resultsdir, 'MeanETL-RP-', Sys.Date(), '-', runname, '.rda',sep=''))318chart.EfficientFrontier(MeanmETL.RND)319320# OR with DE optim321MeanmETL.DE<-optimize.portfolio(R=R,322portfolio=MeanmETL.portf,323optimize_method='DEoptim',324search_size=20000,325initialpop=rp[1:50,] # seed with a starting population that we know fits the constraint space326)327plot(MeanmETL.DE, risk.col="StdDev", return.col="mean", chart.assets=TRUE, main="Mean-mETL Portfolio")328plot(MeanmETL.DE, risk.col="ES", return.col="mean", chart.assets=TRUE, main="Mean-mETL Portfolio")329save(MeanmETL.DE,file=paste(resultsdir, 'MeanETL-DE-', Sys.Date(), '-', runname, '.rda',sep=''))330print(paste('Completed meanmETL optimization at',Sys.time(),'moving on to MinSD'))331332333### Evaluate BUOY 3: Constrained Minimum Variance Portfolio - with ROI334MinSD.ROI<-optimize.portfolio(R=R,335portfolio=MinSD.portf,336optimize_method='ROI',337trace=TRUE338) #339plot(MinSD.ROI, risk.col="StdDev", return.col="mean", rp=permutations, chart.assets=TRUE, main="Minimum Volatility Portfolio with ROI")340save(MinSD.ROI,file=paste(resultsdir, 'MinSD-', Sys.Date(), '-', runname, '.rda',sep=''))341print(paste('Completed MinSD optimization at',Sys.time(),'moving on to MinmETL'))342# OR with random portfolios343# MinSD.RND<-optimize.portfolio(R=R,344# portfolio=MinSD.portf,345# optimize_method='random',346# rp=rp,347# trace=TRUE, verbose=TRUE348# ) #349# plot(MinSD.RND, risk.col="StdDev", return.col="mean", chart.assets=TRUE, main="Minimum Volatility Portfolio with RP")350351### Evaluate BUOY 4: Constrained Minimum mETL Portfolio - with ROI352MinmETL.ROI<-optimize.portfolio(R=R,353portfolio=MinmETL.portf,354optimize_method='ROI',355trace=TRUE, verbose=TRUE356)357plot(MinmETL.ROI, risk.col="StdDev", return.col="mean", rp=permutations, chart.assets=TRUE, main="Minimum mETL Portfolio")358plot(MinmETL.ROI, risk.col="ES", return.col="mean", rp=permutations, chart.assets=TRUE, main="Minimum mETL Portfolio")359save(MinmETL.ROI,file=paste(resultsdir, 'MinmETL-', Sys.Date(), '-', runname, '.rda',sep=''))360print(paste('Completed MinmETL optimization at',Sys.time(),'moving on to MRCSD'))361362### Evaluate BUOY 5: Constrained Equal Variance Contribution Portfolio - with RP363# MRCSD.RND<-optimize.portfolio(R=R,364# portfolio=MRCSD.portf,365# optimize_method='random',366# rp=rp,367# trace=TRUE368# )369# plot(MRCSD.RND, risk.col="StdDev", return.col="mean", chart.assets=TRUE, main="Equal Volatility Contribution Portfolio")370# chart.RiskBudget(MRCSD.RND, risk.type="percentage", neighbors=25)371# save(MRCSD.RND,file=paste(resultsdir, 'MRCSD.RND-', Sys.Date(), '-', runname, '.rda',sep=''))372# ... not a very satisfying solution373374# OR DE optim - this gets very close (a nice, straight line), so use it375MRCSD.DE<-optimize.portfolio(R=R,376portfolio=MRCSD.portf,377optimize_method='DEoptim',378search_size=20000,379itermax=400,380initialpop=rp[1:50,], # seed with a starting population that we know fits the constraint space381trace=FALSE382)383plot(MRCSD.DE, risk.col="StdDev", return.col="mean", chart.assets=TRUE, main="Equal Volatility Contribution Portfolio")384chart.RiskBudget(MRCSD.DE, risk.type="percentage", neighbors=25)385save(MRCSD.DE,file=paste(resultsdir, 'MRCSD.DE-', Sys.Date(), '-', runname, '.rda',sep=''))386387print(paste('Completed MRCSD optimization at',Sys.time(),'moving on to MRCmETL'))388389### Evaluate BUOY 6: Constrained Equal mETL Contribution Portfolio - with RP390MRCmETL.RND<-optimize.portfolio(R=R,391portfolio=MRCmETL.portf,392optimize_method='random',393rp=rp,394trace=TRUE395) #396plot(MRCmETL.RND, risk.col="StdDev", return.col="mean", chart.assets=TRUE, main="Equal mETL Contribution Portfolio")397plot(MRCmETL.RND, risk.col="ES", return.col="mean", chart.assets=TRUE, main="Equal mETL Contribution Portfolio")398chart.RiskBudget(MRCmETL.RND, neighbors=25)399save(MRCmETL.RND,file=paste(resultsdir, 'MRCmETL-', Sys.Date(), '-', runname, '.rda',sep=''))400401# OR DE optim -402MRCmETL.DE<-optimize.portfolio(R=R,403portfolio=MRCmETL.portf,404optimize_method='DEoptim',405search_size=20000,406NP=200,407initialpop=rp[1:50,], # seed with a starting population that we know fits the constraint space408trace=FALSE409)410plot(MRCmETL.DE, risk.col="StdDev", return.col="mean", chart.assets=TRUE, main="Equal Volatility Contribution Portfolio")411chart.RiskBudget(MRCmETL.DE, risk.type="percentage", neighbors=25)412save(MRCmETL.DE,file=paste(resultsdir, 'MRCmETL.DE-', Sys.Date(), '-', runname, '.rda',sep=''))413414# # test it unconstrained:415# unconstr.portf <- portfolio.spec(assets=colnames(R),416# weight_seq=generatesequence(by=0.005)417# )418# unconstr.portf <- add.constraint(portfolio=unconstr.portf,419# type="leverage",420# min_sum=0.99, # set to speed up RP421# max_sum=1.01422# )423# # Establish position bounds424# unconstr.portf <- add.constraint(portfolio=unconstr.portf,425# type="box",426# min=0.01,427# max=1.0428# )429# MRCmETLun.portf <- add.objective(portfolio=unconstr.portf,430# type="return",431# name="mean"432# )433# MRCmETLun.portf <- add.objective(MRCmETL.portf,434# type="risk_budget",435# name="ES",436# min_concentration=TRUE,437# arguments = list(p=p, clean=clean)438# )439#440# # ...in DE optim -441# MRCmETLun.DE<-optimize.portfolio(R=R,442# portfolio=MRCmETLun.portf,443# optimize_method='DEoptim',444# search_size=20000,445# NP=200,446# initialpop=rp[1:50,], # seed with a starting population that we know fits the constraint space447# trace=FALSE448# )449450print(paste('Completed MRCmETL optimization at',Sys.time(),'moving on to RiskBudget'))451452### Evaluate BUOY 7: Equal Weight Portfolio453# Calculate the objective measures for the equal weight portfolio454EqWgt.opt <- equal.weight(R=R, portfolio=EqWgt.portf)455456### Evaluate BUOY 8: Inverse Volatility Portfolio457volatility.weight <- function (R, portfolio, ...)458{459if (!is.portfolio(portfolio))460stop("portfolio object passed in must be of class 'portfolio'")461assets <- portfolio$assets462nassets <- length(assets)463weights <- as.vector((1/StdDev(R))/sum(1/StdDev(R)))464names(weights) <- names(assets)465if (ncol(R) != nassets) {466if (ncol(R) > nassets) {467R <- R[, 1:nassets]468warning("number of assets is less than number of columns in returns object, subsetting returns object.")469}470else {471stop("number of assets is greater than number of columns in returns object")472}473}474out <- constrained_objective(w = weights, R = R, portfolio = portfolio,475trace = TRUE, ...)$objective_measures476return(structure(list(R = R, weights = weights, objective_measures = out,477call = match.call(), portfolio = portfolio), class = c("optimize.portfolio.invol",478"optimize.portfolio")))479}480# Calculate the objective measures for the vol weight portfolio481VolWgt.opt <- volatility.weight(R=R, portfolio=VolWgt.portf)482483484# REMOVED485# ### Evaluate Constrained Concentration to mETL Portfolio - with DE486# # registerDoSEQ() # turn off parallelization to keep the trace data487# ConstrConcmETL.DE<-optimize.portfolio(R=R,488# portfolio=ConstrConcmETL.portf,489# optimize_method='DEoptim',490# search_size=40000,491# NP=4000,492# itermax=400,493# trace=FALSE494# )495# # list(c=0.25, # speed of crossover adaption (0,1]496# # CR=0.75) # crossover probability [0,1]497# plot(ConstrConcmETL.DE, risk.col="StdDev", return.col="mean")498# plot(ConstrConcmETL.DE, risk.col="ES", return.col="mean") # several outlier portfolios499# chart.RiskBudget(ConstrConcmETL.DE)500# chart.RiskBudget(ConstrConcmETL.DE, risk.type="percentage")501#502# save(ConstrConcmETL.DE,file=paste(resultsdir, 'ConstrConcmETL-', Sys.Date(), '-', runname, '.rda',sep=''))503# print(ConstrConcmETL.DE$elapsed_time)504print('Done with optimizations.')505506#------------------------------------------------------------------------507### Extract data from optimizations for analysis508#------------------------------------------------------------------------509# Combine optimization objects510buoys <- combine.optimizations(list(MeanSD=MeanSD.ROI, MeanmETL=MeanmETL.RND, MinSD=MinSD.ROI, MinmETL=MinmETL.ROI, MRCSD=MRCSD.DE, MRCmETL=MRCmETL.DE, VolWgt=VolWgt.opt, EqWgt=EqWgt.opt))511# chart.Weights(buoys, plot.type="bar", ylim=c(0,1))512#513# #@ Chart the portfolios that have mean and ES as objective measures. - RB514# chart.RiskReward(buoys, risk.col="ES")515# #@ Chart the portfolios that have mean and StdDev as objective measures. - RB516# chart.RiskReward(buoys, risk.col="StdDev")517#518# #@ The MRCmETL and RB optimizations would be good to compare because they are519# #@ similar in that they both include component ES as an objective. - RB520# buoyETL <- combine.optimizations(list(MRCmETL=MRCmETL.RND, RB=RiskBudget.DE, EqWgt=EqWgt.opt))521# chart.RiskBudget(buoyETL, match.col="ES", risk.type="percentage", legend.loc="topright")522#523# #@ Compare the equal weight portfolio and the equal SD contribution portfolio. - RB524# buoyStdDev <- combine.optimizations(list(MRCSD=MRCSD.RND, EqWgt=EqWgt.opt))525# chart.RiskBudget(buoyStdDev, match.col="StdDev", risk.type="absolute", legend.loc="topleft")526527Wgts = extractWeights(buoys)528529### Extract portfolio measures from each objective530# We can't just extract them, because they aren't all calculated531# so fill them in...532buoys.portfmeas = buoys.contrib.sd = buoys.contrib.es = buoys.perc.sd = buoys.perc.es = NULL533for(i in 1:NROW(Wgts)){534mean = sum(colMeans(R)*Wgts[i,])535sd = StdDev(R, weights=Wgts[i,], portfolio_method="component", clean=clean)536es = ES(R, weights=Wgts[i,], method="modified", portfolio_method="component", p=p, clean=clean)537buoys.portfmeas=rbind(buoys.portfmeas, c(mean, sd[[1]][1], es[[1]][1]))538buoys.contrib.sd= rbind(buoys.contrib.sd,sd[[2]])539buoys.contrib.es= rbind(buoys.contrib.es,es[[2]])540buoys.perc.sd = rbind(buoys.perc.sd,sd[[3]])541buoys.perc.es = rbind(buoys.perc.es,es[[3]])542}543colnames(buoys.portfmeas)=c("Mean", "StdDev", "mETL")544rownames(buoys.portfmeas)=545rownames(buoys.contrib.sd)=546rownames(buoys.contrib.es)=547rownames(buoys.perc.sd) =548rownames(buoys.perc.es) = rownames(Wgts)549colnames(buoys.contrib.sd)=550colnames(buoys.contrib.es)=551colnames(buoys.perc.sd) =552colnames(buoys.perc.es) = colnames(Wgts)553554# get the RP portfolios with risk and return pre-calculated555xtract = extractStats(MRCmETL.RND)556save(xtract,file=paste(resultsdir, 'xtract-RPs-', Sys.Date(), '-', runname, '.rda',sep=''))557# columnnames = colnames(xtract)558results.names=rownames(buoys.portfmeas)559560# by Asset metrics561assets.portfmeas=as.matrix(scatterFUN(R, FUN="mean"))562assets.portfmeas=cbind(assets.portfmeas, scatterFUN(R, FUN="StdDev", clean=clean))563assets.portfmeas=cbind(assets.portfmeas, scatterFUN(R, FUN="ES", clean=clean))564colnames(assets.portfmeas)=c("Mean", "StdDev", "mETL")565rownames(assets.portfmeas)=colnames(Wgts)566567568569#------------------------------------------------------------------------570# Run select buoy optimizations through time571#------------------------------------------------------------------------572#573574# Equal Weight575dates=index(R[endpoints(R, on=rebalance_period)])576EqWgt.w = xts(matrix(rep(1/NCOL(R),length(dates)*NCOL(R)), ncol=NCOL(R)), order.by=dates)577colnames(EqWgt.w)= colnames(R)578EqWgt.R=Return.rebalancing(R, EqWgt.w)579chart.StackedBar(EqWgt.w, colorset=wb13color, gap=0)580581VolWgt.w = NULL582for(i in 3:length(dates)){583x = volatility.weight(R=R[paste0("::",dates[i]),], portfolio=VolWgt.portf)584VolWgt.w = rbind(VolWgt.w, x$weights)585}586VolWgt.w = as.xts(VolWgt.w, order.by=dates[-1:-2])587VolWgt.R=Return.rebalancing(R, VolWgt.w)588589# Equal SD590MRCSD.DE.t = optimize.portfolio.rebalancing(R=R,591portfolio=MRCSD.portf,592optimize_method='DEoptim',593search_size=2000,594NP=200,595initialpop=rp[1:50,], # seed with a starting population that we know fits the constraint space596trace=FALSE,597rebalance_on=rebalance_period, # uses xts 'endpoints'598trailing_periods=NULL, # calculates from inception599training_period=36) # starts 3 years in to the data history600MRCSD.w = extractWeights(MRCSD.DE.t)601MRCSD.gw = extractGroups(MRCSD.DE.t)602save(MRCSD.DE.t,file=paste(resultsdir, 'MRCSD.DE.t-', Sys.Date(), '-', runname, '.rda',sep=''))603chart.UnStackedBar(MRCSD.w, rotate="horizontal", colorset=wb13color, space=0, las=2)604MRCSD.R=Return.rebalancing(edhec.R, MRCSD.w)605colnames(MRCSD) = "MRCSD"606607# Extract perc contrib of mES from results object608x=NULL609for(i in 1:length(names(MRCSD.DE.t))) {610x = rbind(x,MRCSD.DE.t[[i]][["objective_measures"]]$StdDev$pct_contrib_StdDev)611}612MRCSD.DE.pct_contrib_StdDev.t = as.xts(x, order.by=as.POSIXct(names(MRCSD.DE.t)))613chart.UnStackedBar(x.xts, rotate="horizontal", colorset=wb13color, space=0, las=2)614615616# MRC mETL617MRCmETL.DE.t = optimize.portfolio.rebalancing(R=R,618portfolio=MRCmETL.portf,619optimize_method='DEoptim',620search_size=20000,621NP=200,622initialpop=rp[1:50,], # seed with a starting population that we know fits the constraint space623trace=FALSE,624rebalance_on=rebalance_period, # uses xts 'endpoints'625trailing_periods=NULL, # calculates from inception626training_period=36) # starts 3 years in to the data history627MRCmETL.w = extractWeights(MRCmETL.DE.t)628MRCmETL.gw = extractGroups(MRCmETL.DE.t)629save(MRCmETL.DE.t,file=paste(resultsdir, 'MRCmETL.DE.t-', Sys.Date(), '-', runname, '.rda',sep=''))630chart.UnStackedBar(MRCmETL.w, rotate="horizontal", colorset=wb13color, space=0, las=2)631MRCmETL=Return.rebalancing(edhec.R, MRCmETL.w)632colnames(MRCmETL) = "MRCmETL"633634MRCmETL.RND.t = optimize.portfolio.rebalancing(R=R,635portfolio=MRCmETL.portf,636optimize_method='random',637rp=rp,638trace=TRUE,639rebalance_on=rebalance_period, # uses xts 'endpoints'640trailing_periods=NULL, # calculates from inception641training_period=36) # starts 3 years in to the data history642MRCmETL.RND.w = extractWeights(MRCmETL.RND.t)643MRCmETL.gw = extractGroups(MRCmETL.RND.t)644save(MRCmETL.DE.t,file=paste(resultsdir, 'MRCmETL.DE.t-', Sys.Date(), '-', runname, '.rda',sep=''))645chart.UnStackedBar(MRCmETL.w, rotate="horizontal", colorset=wb13color, space=0, las=2)646MRCmETL=Return.rebalancing(edhec.R, MRCmETL.w)647colnames(MRCmETL) = "MRCmETL"648end_time<-Sys.time()649end_time-start_time650651652#########################################################################653# Optimization ends here654#########################################################################655656657658659