#' ---1#' title: "Differential Evolution Optimization Demo"2#' date: "7/17/2014"3#' ---45#' This script demonstrates several optimization problems using Differential6#' Evolution as the optimization engine. This script is based heavily on7#' http://www.rinfinance.com/agenda/2012/workshop/Carl+Peterson.pdf.89#' The following optimization problems will be run10#' * mean-mETL: maximize mean-to-ETL (i.e. reward-to-risk)11#' * MinSD: minimize annualized standard deviation12#' * eqStdDev: equal risk (volatility)13#' * MeanRL: maximize mean with mETL risk limits1415#' Include optimizer and multi-core packages16library(PortfolioAnalytics)17require(DEoptim)18require(foreach)1920#' The multicore package, and therefore registerDoMC, should not be used in a21#' GUI environment, because multiple processes then share the same GUI. Only use22#' when running from the command line.23# require(doMC)24# registerDoMC(3)2526#' Load the data27data(edhec)28edhec.R <- edhec[,c("Convertible Arbitrage", "Equity Market Neutral",29"Fixed Income Arbitrage", "Event Driven", "CTA Global",30"Global Macro", "Long/Short Equity")]3132#' Define function to compute annualized standard deviation33pasd <- function(R, weights){34as.numeric(StdDev(R=R, weights=weights)*sqrt(12)) # hardcoded for monthly data35# as.numeric(StdDev(R=R, weights=weights)*sqrt(4)) # hardcoded for quarterly data36}3738#' Set some parameters39rebalance_period = 'quarters' # uses endpoints identifiers from xts40clean = "none" #"boudt"41permutations = 40004243#' Create initial portfolio object used to initialize ALL the bouy portfolios44init.portf <- portfolio.spec(assets=colnames(edhec.R),45weight_seq=generatesequence(by=0.005))46#' Add leverage constraint47init.portf <- add.constraint(portfolio=init.portf,48type="leverage",49min_sum=0.99,50max_sum=1.01)51#' Add box constraint52init.portf <- add.constraint(portfolio=init.portf,53type="box",54min=0.05,55max=0.3)5657#' Add measure 1, mean return58init.portf <- add.objective(portfolio=init.portf,59type="return", # the kind of objective this is60name="mean", # name of the function61enabled=TRUE, # enable or disable the objective62multiplier=0 # calculate it but don't use it in the objective63)6465#' Add measure 2, annualized standard deviation66init.portf <- add.objective(portfolio=init.portf,67type="risk", # the kind of objective this is68name="pasd", # to minimize from the sample69enabled=TRUE, # enable or disable the objective70multiplier=0 # calculate it but don't use it in the objective71)7273#' Add measure 3, ES with confidence level p=(1-1/12)74p <- 1-1/12 # for monthly7576init.portf <- add.objective(portfolio=init.portf,77type="risk", # the kind of objective this is78name="ES", # the function to minimize79enabled=FALSE, # enable or disable the objective80multiplier=0, # calculate it but don't use it in the objective81arguments=list(p=p)82)8384#' Set up portfolio for Mean-mETL85MeanmETL.portf <- init.portf86MeanmETL.portf$objectives[[1]]$multiplier=-1 # mean87MeanmETL.portf$objectives[[3]]$enabled=TRUE # mETL88MeanmETL.portf$objectives[[3]]$multiplier=1 # mETL8990#' Set up portfolio for min pasd91MinSD.portf <- init.portf92MinSD.portf$objectives[[2]]$multiplier=19394#' Set up portfolio for eqStdDev95EqSD.portf <- add.objective(portfolio=init.portf,96type="risk_budget",97name="StdDev",98min_concentration=TRUE,99arguments = list(p=(1-1/12)))100#' Without a sub-objective, we get a somewhat undefined result, since101#' there are (potentially) many Equal SD contribution portfolios.102EqSD.portf$objectives[[2]]$multiplier=1 # min pasd103104#' Set up portfolio to maximize mean with mETL risk limit105MeanRL.portf <- add.objective(portfolio=init.portf,106type='risk_budget',107name="ES",108min_prisk=-Inf,109max_prisk=0.4,110arguments=list(method="modified", p=p))111MeanRL.portf$objectives[[1]]$multiplier=-1 # mean112#' Change box constraints max to vector of 1s113MeanRL.portf$constraints[[2]]$max=rep(1, 7)114115#' Set the 'R' variable116R <- edhec.R117118#' Start the optimizations119start_time<-Sys.time()120print(paste('Starting optimization at',Sys.time()))121122#' Run the optimization123##### mean-mETL #####124MeanmETL.DE <- optimize.portfolio(R=R,125portfolio=MeanmETL.portf,126optimize_method="DEoptim",127trace=TRUE,128search_size=2000,129traceDE=5)130print(MeanmETL.DE)131print(MeanmETL.DE$elapsed_time)132chart.Weights(object=MeanmETL.DE, main="Mean-mETL Weights")133chart.RiskReward(object=MeanmETL.DE, return.col="mean", risk.col="ES")134# save(MeanmETL.DE, file=paste('MeanmETL',Sys.Date(),'rda',sep='.'))135136# Evaluate the objectives with DE through time137# MeanmETL.DE.t <- optimize.portfolio.rebalancing(R=R,138# portfolio=MeanSD.portf,139# optimize_method="random",140# trace=TRUE,141# search_size=2000,142# rebalance_on=rebalance_period,143# training_period=36)144# MeanmETL.w = extractWeights.rebal(MeanmETL.DE.t)145# MeanmETL=Return.rebalancing(edhec.R, MeanmETL)146# colnames(MeanmETL) = "MeanmETL"147# save(MeanmETL.DE, MeanmETL.DE.t, MeanmETL.w, MeanmETL, file=paste('MeanmETL',Sys.Date(),'rda',sep='.'))148149print(paste('Completed MeanmETL optimization at',Sys.time(),'moving on to MinSD'))150151#' Run the optimization152##### min pasd #####153MinSD.DE <- optimize.portfolio(R=R,154portfolio=MinSD.portf,155optimize_method="DEoptim",156trace=TRUE,157search_size=2000,158traceDE=5)159print(MinSD.DE)160print(MinSD.DE$elapsed_time)161chart.Weights(object=MinSD.DE, plot.type="barplot", legend.loc=NULL)162chart.RiskReward(object=MinSD.DE, return.col="mean", risk.col="pasd")163# save(MinSD.DE, file=paste('MinSD',Sys.Date(),'rda',sep='.'))164165print(paste('Completed MinSD optimization at',Sys.time(),'moving on to EqSD'))166167#' Run the optimization168##### EqSD #####169EqSD.DE <- optimize.portfolio(R=R,170portfolio=EqSD.portf,171optimize_method="DEoptim",172trace=TRUE,173search_size=2000,174traceDE=5)175print(EqSD.DE)176print(EqSD.DE$elapsed_time)177# save(EqSD.DE, file=paste('EqSD',Sys.Date(),'rda',sep='.'))178179chart.Weights(object=EqSD.DE)180chart.RiskReward(object=EqSD.DE, return.col="mean", risk.col="StdDev")181chart.RiskBudget(object=EqSD.DE, risk.type="absolute")182chart.RiskBudget(object=EqSD.DE, risk.type="pct_contrib")183184print(paste('Completed EqSD optimization at',Sys.time(),'moving on to MeanRL'))185186#' Run the optimization187##### MeanRL.DE #####188MeanRL.DE <- optimize.portfolio(R=R,189portfolio=MeanRL.portf,190optimize_method="DEoptim",191trace=TRUE,192search_size=2000,193traceDE=5)194print(MeanRL.DE)195print(MeanRL.DE$elapsed_time)196# save(MeanRL.DE, file=paste('MeanRL',Sys.Date(),'rda',sep='.'))197198chart.Weights(object=MeanRL.DE)199chart.RiskBudget(object=MeanRL.DE, risk.type="pct_contrib", neighbors=25)200201end_time<-Sys.time()202print("Optimization Complete")203print(end_time-start_time)204205206