[Returnanalytics-commits] r3352 - in pkg/PortfolioAnalytics/sandbox/RFinance2014: . data optimization_figures optimization_results

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Tue Apr 8 07:39:48 CEST 2014


Author: rossbennett34
Date: 2014-04-08 07:39:47 +0200 (Tue, 08 Apr 2014)
New Revision: 3352

Added:
   pkg/PortfolioAnalytics/sandbox/RFinance2014/data/crsp_weekly.rda
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/crra_ES.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/crra_RR.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/crra_minES.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/eqrb_minES.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/opt_dn.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/opt_minES.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/rb_minES.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/ret_crra.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/ret_minES.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/ret_minVar.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/weights_minVarLW.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/weights_minVarSample.png
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/bt.opt.crra.rda
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/bt.opt.minES.rda
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.crra.rda
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.dn.rda
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minES.rda
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minVarLW.rda
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minVarSample.rda
Modified:
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R
   pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd
   pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.html
   pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.md
Log:
Updates to RFinance 2014 presentation

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/data/crsp_weekly.rda
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/data/crsp_weekly.rda
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/crra_ES.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/crra_ES.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/crra_RR.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/crra_RR.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/crra_minES.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/crra_minES.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/eqrb_minES.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/eqrb_minES.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/opt_dn.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/opt_dn.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/opt_minES.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/opt_minES.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/rb_minES.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/rb_minES.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/ret_crra.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/ret_crra.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/ret_minES.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/ret_minES.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/ret_minVar.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/ret_minVar.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/weights_minVarLW.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/weights_minVarLW.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/weights_minVarSample.png
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/weights_minVarSample.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/bt.opt.crra.rda
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/bt.opt.crra.rda
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/bt.opt.minES.rda
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/bt.opt.minES.rda
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.crra.rda
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.crra.rda
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.dn.rda
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.dn.rda
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minES.rda
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minES.rda
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minVarLW.rda
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minVarLW.rda
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minVarSample.rda
===================================================================
(Binary files differ)


Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minVarSample.rda
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Modified: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R	2014-04-07 23:47:06 UTC (rev 3351)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R	2014-04-08 05:39:47 UTC (rev 3352)
@@ -35,13 +35,18 @@
 # expected utility function. Demonstrate a custom moment function and
 # a custom objective function.
 
+# Set the directory to save the optimization results
+results.dir <- "optimization_results"
+
 # Load the packages
 library(PortfolioAnalytics)
 library(foreach)
 library(ROI)
 library(ROI.plugin.quadprog)
-library(ROI.plugin.glpk)
 
+# for running via Rscript
+library(methods)
+
 # Source in the lwShrink function
 source("R/lwShrink.R")
 
@@ -56,18 +61,17 @@
 
 # Prep data for Examples 1 and 2
 # use the first 10 stocks in largecap_weekly, midcap_weekly, and smallcap_weekly
-N <- 10
-equity.data <- cbind(largecap_weekly[,1:N], 
-                     midcap_weekly[,1:N], 
-                     smallcap_weekly[,1:N])
+equity.data <- cbind(largecap_weekly[,1:10], 
+                     midcap_weekly[,1:10], 
+                     smallcap_weekly[,1:10])
 market <- largecap_weekly[,21]
 Rf <- largecap_weekly[,22]
 stocks <- colnames(equity.data)
 
-# Specify an initial portfolio
-portf.init <- portfolio.spec(stocks)
 
 ##### Example 1 #####
+# Specify an initial portfolio
+portf.init <- portfolio.spec(stocks)
 # Add constraints
 # weights sum to 1
 portf.minvar <- add.constraint(portf.init, type="full_investment")
@@ -78,7 +82,7 @@
 # objective to minimize portfolio variance
 portf.minvar <- add.objective(portf.minvar, type="risk", name="var")
 
-# Rebalancing parameters
+# Backtesting parameters
 # Set rebalancing frequency
 rebal.freq <- "quarters"
 # Training Period
@@ -92,11 +96,19 @@
 # By default, momentFUN uses set.portfolio.moments which computes the sample
 # moment estimates
 
-opt.minVarSample <- optimize.portfolio.rebalancing(equity.data, portf.minvar, 
-                                                   optimize_method="ROI", 
-                                                   rebalance_on=rebal.freq, 
-                                                   training_period=training, 
-                                                   trailing_periods=trailing)
+cat("Example 1: running minimum variance with sample covariance matrix 
+    estimate backtest\n")
+if(file.exists(paste(results.dir, "opt.minVarSample.rda", sep="/"))){
+  cat("file already exists\n")
+} else {
+  opt.minVarSample <- optimize.portfolio.rebalancing(equity.data, portf.minvar, 
+                                                     optimize_method="ROI", 
+                                                     rebalance_on=rebal.freq, 
+                                                     training_period=training, 
+                                                     trailing_periods=trailing)
+  cat("opt.minVarSample complete. Saving results to ", results.dir, "\n") 
+  save(opt.minVarSample, file=paste(results.dir, "opt.minVarSample.rda", sep="/"))
+}
 
 # Custom moment function to use Ledoit-Wolf shinkage covariance matrix estimate
 lw.sigma <- function(R, ...){
@@ -110,28 +122,24 @@
   return(out)
 }
 
-# Using Ledoit-Wolf Shrinkage Covariance Matrix Estimate
-opt.minVarLW <- optimize.portfolio.rebalancing(equity.data, portf.minvar, 
-                                               optimize_method="ROI", 
-                                               momentFUN=lw.sigma,
-                                               rebalance_on=rebal.freq, 
-                                               training_period=training, 
-                                               trailing_periods=trailing)
+cat("Example 1: running minimum variance with Ledoit-Wolf shrinkage covariance 
+    matrix estimate backtest\n")
+if(file.exists(paste(results.dir, "opt.minVarLW.rda", sep="/"))){
+  cat("file already exists\n")
+} else{
+  # Using Ledoit-Wolf Shrinkage Covariance Matrix Estimate
+  opt.minVarLW <- optimize.portfolio.rebalancing(equity.data, portf.minvar, 
+                                                 optimize_method="ROI", 
+                                                 momentFUN=lw.sigma,
+                                                 rebalance_on=rebal.freq, 
+                                                 training_period=training, 
+                                                 trailing_periods=trailing)
+  cat("opt.minVarLW complete. Saving results to ", results.dir, "\n") 
+  save(opt.minVarLW, file=paste(results.dir, "opt.minVarLW.rda", sep="/"))
+}
 
-# Chart the weights through time
-chart.Weights(opt.minVarSample, main="minVarSample Weights")
-chart.Weights(opt.minVarLW, main="minVarLW Weights")
-
-# Compute and chart the performance summary
-ret.minVarSample <- summary(opt.minVarSample)$portfolio_returns
-ret.minVarRobust <- summary(opt.minVarLW)$portfolio_returns
-ret.minVar <- cbind(ret.minVarSample, ret.minVarRobust)
-colnames(ret.minVar) <- c("Sample", "LW")
-charts.PerformanceSummary(ret.minVar)
-
 ##### Example 2 #####
-portf.init <- portfolio.spec(stocks, 
-                             weight_seq=generatesequence(min=-0.2, max=0.2, by=0.001))
+portf.init <- portfolio.spec(stocks)
 
 # weights sum to 0
 portf.dn <- add.constraint(portf.init, type="weight_sum", 
@@ -153,44 +161,48 @@
                            lower=-0.5, upper=0.5)
 # portf.dn <- add.constraint(portf.dn, type="leverage_exposure", leverage=2)
 
-rp <- random_portfolios(portf.dn, 10000, eliminate=TRUE)
-dim(rp)
+# generate random portfolios
+if(file.exists(paste(results.dir, "rp.rda", sep="/"))){
+  cat("random portfolios already generated\n")
+} else {
+  cat("generating random portfolios\n")
+  rp <- random_portfolios(portf.dn, 10000, eliminate=TRUE)
+  cat("random portfolios generated. Saving rp to ", results.dir, "\n") 
+  save(rp, file=paste(results.dir, "rp.rda", sep="/"))
+}
 
-# Add objective to target return of 0.001
-portf.dn.StdDev <- add.objective(portf.dn, type="return", name="mean", 
-                                 target=0.001)
-# Add objective to minimize portfolio variance
-portf.dn.StdDev <- add.objective(portf.dn.StdDev, type="risk", name="StdDev")
+# Add objective to maximize return
+portf.dn.StdDev <- add.objective(portf.dn, type="return", name="mean")
+# Add objective to target a portfolio standard deviation of 2%
+portf.dn.StdDev <- add.objective(portf.dn.StdDev, type="risk", name="StdDev",
+                                 target=0.02)
 
-# Run optimization
-opt <- optimize.portfolio(equity.data, portf.dn.StdDev, 
-                          optimize_method="random", rp=rp,
-                          trace=TRUE)
+cat("Example 2: running dollar neutral optimization\n")
+if(file.exists(paste(results.dir, "opt.dn.rda", sep="/"))){
+  cat("file already exists\n")
+} else {
+  # Run optimization
+  opt.dn <- optimize.portfolio(equity.data, portf.dn.StdDev, 
+                               optimize_method="random", rp=rp,
+                               trace=TRUE)
+  cat("opt.dn complete. Saving results to ", results.dir, "\n") 
+  save(opt.dn, file=paste(results.dir, "opt.dn.rda", sep="/"))
+}
 
-plot(opt, risk.col="StdDev", neighbors=10)
-
-# chart.RiskReward(opt, risk.col="StdDev", neighbors=25)
-# chart.Weights(opt, plot.type="bar", legend.loc=NULL)
-# wts <- extractWeights(opt)
-# t(wts) %*% betas
-# sum(abs(wts))
-# sum(wts[wts > 0])
-# sum(wts[wts < 0])
-# sum(wts != 0)
-
 # Prep data for Examples 3 and 4
 # For now, use the first 8 
 R <- edhec[,1:8]
 # Abreviate column names for convenience and plotting
 colnames(R) <- c("CA", "CTAG", "DS", "EM", "EQN", "ED", "FA", "GM")
-funds <- colnames(R)
 
+
 ##### Example 3 #####
 # Example 3 will consider three portfolios
 # - minES
-# - minES with 30% component contribution limit
+# - minES with component contribution limit
 # - minES with equal risk contribution
 
+funds <- colnames(R)
 portf.init <- portfolio.spec(funds)
 portf.init <- add.constraint(portf.init, type="weight_sum", 
                              min_sum=0.99, max_sum=1.01)
@@ -230,58 +242,20 @@
                                  minES.RB=portf.minES.RB, 
                                  minES.EqRB=portf.minES.EqRB))
 
-# Run the optimization
-opt.minES <- optimize.portfolio(R, portf, optimize_method="DEoptim", 
-                                search_size=2000, trace=TRUE, traceDE=0,
-                                message=TRUE)
+cat("Example 3: running minimum ES optimizations\n")
+if(file.exists(paste(results.dir, "opt.minES.rda", sep="/"))){
+  cat("file already exists\n")
+} else {
+  # Run the optimization
+  opt.minES <- optimize.portfolio(R, portf, optimize_method="DEoptim", 
+                                  search_size=2000, trace=TRUE, traceDE=0,
+                                  message=TRUE)
+  cat("opt.minES complete. Saving results to ", results.dir, "\n")
+  save(opt.minES, file=paste(results.dir, "opt.minES.rda", sep="/"))
+}
 
-# ES(R, portfolio_method="component", weights=extractWeights(opt.minES[[1]]))
-# extractObjectiveMeasures(opt.minES)
+# Now we want to evaluate the optimization through time
 
-# extract objective measures, out, and weights 
-xtract <- extractStats(opt.minES)
-
-# get the 'mean' and 'ES' columns from each element of the list
-xtract.mean <- unlist(lapply(xtract, function(x) x[,"mean"]))
-xtract.ES <- unlist(lapply(xtract, function(x) x[,"ES"]))
-
-# plot the feasible space
-par(mar=c(7,4,4,1)+0.1)
-plot(xtract.ES, xtract.mean, col="gray", 
-     xlab="ES", ylab="Mean",
-     xlim=c(0, max(xtract.ES)))
-
-# min ES
-points(x=opt.minES[[1]]$objective_measures$ES,
-       y=opt.minES[[1]]$objective_measures$mean,
-       pch=15, col="purple")
-text(x=opt.minES[[1]]$objective_measures$ES,
-     y=opt.minES[[1]]$objective_measures$mean,
-     labels="Min ES", pos=4, col="purple", cex=0.8)
-
-# min ES with risk budget upper limit on component contribution to risk
-points(x=opt.minES[[2]]$objective_measures$ES$MES,
-       y=opt.minES[[2]]$objective_measures$mean,
-       pch=15, col="black")
-text(x=opt.minES[[2]]$objective_measures$ES$MES,
-     y=opt.minES[[2]]$objective_measures$mean,
-     labels="Min ES RB", pos=4, col="black", cex=0.8)
-
-# min ES with equal (i.e. min concentration) component contribution to risk
-points(x=opt.minES[[3]]$objective_measures$ES$MES,
-       y=opt.minES[[3]]$objective_measures$mean,
-       pch=15, col="darkgreen")
-text(x=opt.minES[[3]]$objective_measures$ES$MES,
-     y=opt.minES[[3]]$objective_measures$mean,
-     labels="Min ES EqRB", pos=4, col="darkgreen", cex=0.8)
-
-# Chart the risk contribution
-chart.RiskBudget(opt.minES[[1]], risk.type="percentage", neighbors=10)
-chart.RiskBudget(opt.minES[[2]], risk.type="percentage", neighbors=10)
-chart.RiskBudget(opt.minES[[3]], risk.type="percentage", neighbors=10)
-
-# Now we want to evaluate portfolio through time
-
 # Add risk budget objective to minES portfolio with multiplier=0 so that it
 # is calculated, but does not affect optimization
 portf.minES <- add.objective(portf.minES, type="risk_budget", 
@@ -295,30 +269,25 @@
 # Trailing Period
 trailing <- 72
 
-# Backtest
-bt.opt.minES <- optimize.portfolio.rebalancing(R, portf,
-                                               optimize_method="DEoptim", 
-                                               rebalance_on=rebal.freq, 
-                                               training_period=training, 
-                                               trailing_periods=trailing,
-                                               traceDE=0, message=TRUE)
+cat("Example 3: running minimum ES backtests\n")
+if(file.exists(paste(results.dir, "bt.opt.minES.rda", sep="/"))){
+  cat("file already exists\n")
+} else {
+  # Backtest
+  bt.opt.minES <- optimize.portfolio.rebalancing(R, portf,
+                                                 optimize_method="DEoptim", 
+                                                 rebalance_on=rebal.freq, 
+                                                 training_period=training, 
+                                                 trailing_periods=trailing,
+                                                 traceDE=0, message=TRUE)
+  cat("bt.opt.minES complete. Saving results to ", results.dir, "\n")
+  save(bt.opt.minES, file=paste(results.dir, "bt.opt.minES.rda", sep="/"))
+}
 
-# Plot the risk contribution through time
-chart.RiskBudget(bt.opt.minES[[1]], risk.type="percentage")
-chart.RiskBudget(bt.opt.minES[[2]], risk.type="percentage")
-chart.RiskBudget(bt.opt.minES[[3]], risk.type="percentage")
-
-# Extract the returns from each element and chart the performance summary
-ret.bt.opt <- do.call(cbind, lapply(bt.opt.minES, function(x) summary(x)$portfolio_returns))
-colnames(ret.bt.opt) <- c("min ES", "min ES RB", "min ES Eq RB")
-head(ret.bt.opt)
-charts.PerformanceSummary(ret.bt.opt)
-
 ##### Example 4 #####
 
-
 # Simple function to compute the moments used in CRRA
-custom.moments <- function(R, ...){
+crra.moments <- function(R, ...){
   out <- list()
   out$mu <- colMeans(R)
   out$sigma <- cov(R)
@@ -342,46 +311,51 @@
 }
 
 # test the CRRA function
-portf.tmp <- portfolio.spec(funds)
-portf.tmp <- add.constraint(portf.tmp, type="weight_sum", 
+portf.crra <- portfolio.spec(funds)
+portf.crra <- add.constraint(portf.crra, type="weight_sum", 
                              min_sum=0.99, max_sum=1.01)
 
-portf.tmp <- add.constraint(portf.tmp, type="box", 
+portf.crra <- add.constraint(portf.crra, type="box", 
                              min=0.05, max=0.4)
 
-portf.tmp <- add.objective(portf.tmp, type="return", 
+portf.crra <- add.objective(portf.crra, type="return", 
                             name="CRRA", arguments=list(lambda=5))
 
 # I just want these for plotting
 # Set multiplier=0 so that it is calculated, but does not affect the optimization
-portf.tmp <- add.objective(portf.tmp, type="return", name="mean", multiplier=0)
-portf.tmp <- add.objective(portf.tmp, type="risk", name="ES", multiplier=0)
-portf.tmp <- add.objective(portf.tmp, type="risk", name="StdDev", multiplier=0)
+portf.crra <- add.objective(portf.crra, type="return", name="mean", multiplier=0)
+portf.crra <- add.objective(portf.crra, type="risk", name="ES", multiplier=0)
+portf.crra <- add.objective(portf.crra, type="risk", name="StdDev", multiplier=0)
 
-# Run the optimization
-opt.crra <- optimize.portfolio(R, portf.tmp, optimize_method="DEoptim", 
-                               search_size=5000, trace=TRUE, 
-                               momentFUN="custom.moments")
+cat("Example 4: running maximum CRRA optimization\n")
+if(file.exists(paste(results.dir, "opt.crra.rda", sep="/"))){
+  cat("file already exists\n")
+} else {
+  # Run the optimization
+  opt.crra <- optimize.portfolio(R, portf.crra, optimize_method="DEoptim", 
+                                 search_size=5000, trace=TRUE, traceDE=0,
+                                 momentFUN="crra.moments")
+  cat("opt.crra complete. Saving results to ", results.dir, "\n") 
+  save(opt.crra, file=paste(results.dir, "opt.crra.rda", sep="/"))
+}
 
-opt.crra
-chart.RiskReward(opt.crra, risk.col="ES")
-chart.RiskReward(opt.crra, risk.col="StdDev")
+cat("Example 4: running maximum CRRA backtest\n")
+if(file.exists(paste(results.dir, "bt.opt.crra.rda", sep="/"))){
+  cat("file already exists\n")
+} else {
+  # Run the optimization with rebalancing
+  bt.opt.crra <- optimize.portfolio.rebalancing(R, portf.crra, 
+                                                optimize_method="DEoptim",
+                                                search_size=5000, trace=TRUE,
+                                                traceDE=0,
+                                                momentFUN="crra.moments",
+                                                rebalance_on=rebal.freq, 
+                                                training_period=training, 
+                                                trailing_periods=trailing)
+  cat("bt.opt.crra complete. Saving results to ", results.dir, "\n")
+  save(bt.opt.crra, file=paste(results.dir, "bt.opt.crra.rda", sep="/"))
+}
 
-# Run the optimization with rebalancing
-bt.opt.crra <- optimize.portfolio.rebalancing(R, portf.tmp, 
-                                              optimize_method="DEoptim",
-                                              search_size=5000, trace=TRUE,
-                                              momentFUN="custom.moments",
-                                              rebalance_on=rebal.freq, 
-                                              training_period=training, 
-                                              trailing_periods=trailing)
-# Compute the portfolio returns with rebalancing
-ret.crra <- summary(bt.opt.crra)$portfolio_returns
-colnames(ret.crra) <- "CRRA"
-
-# Plot the performance summary of the returns from example 3 and CRRA
-charts.PerformanceSummary(cbind(ret.bt.opt, ret.crra))
-
 # # Calculate the turnover per period
 # turnover.rebalancing <- function(object){
 #   weights <- extractWeights(object)

Modified: pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd	2014-04-07 23:47:06 UTC (rev 3351)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd	2014-04-08 05:39:47 UTC (rev 3352)
@@ -49,7 +49,7 @@
 
 ## Overview
 
-PortfolioAnalytics is an R package designed to provide numerical solutions and visualizations for portfolio problems with complex constraints and objectives.
+PortfolioAnalytics is an R package designed to provide numerical solutions and visualizations for portfolio optimization problems with complex constraints and objectives.
 
 ## Key Features
 
@@ -86,6 +86,12 @@
 * Particle Swarm Optimization (pso)
 * Generalized Simulated Annealing (GenSA)
 
+## Random Portfolios
+TODO: Add graphic comparing the three methods
+
+## Random Portfolios: Simplex Method
+TODO: Add graphic with different fev biasing values
+
 ## Workflow
 TODO: Add a nice graphic here (Guy might have one)
 
@@ -136,30 +142,316 @@
 # dev.off()
 ```
 
+
 # Example 1
 
 ## Minimum Variance Portfolio
-Consider a portfolio of stocks. Full investment and long only (or box) constraints. Objective to minimize portfolio variance. Demonstrate a custom moments function to compare a sample covariance matrix estimate and a Ledoit-Wolf shrinkage covariance matrix estimate. An alternative is a robust (MCD, MVE, etc.) estimate, DCC GARCH model, factor model, etc.
+Consider a portfolio of stocks. Our objective to minimize portfolio variance subect to full investment and box constraints. We will use out of sample backtesting to compare the sample covariance matrix estimate and a Ledoit-Wolf shinkage estimate. 
 
-Use the crsp_weekly data set
+<!---
+Demonstrate a custom moments function to compare a sample covariance matrix estimate and a Ledoit-Wolf shrinkage covariance matrix estimate. An alternative is a robust (MCD, MVE, etc.) estimate, DCC GARCH model, factor model, etc.
+-->
 
+## Data
+```{r, eval=FALSE}
+load("data/crsp_weekly.rda")
+equity.data <- cbind(largecap_weekly[,1:10], 
+                     midcap_weekly[,1:10], 
+                     smallcap_weekly[,1:10])
+```
+
+## Specify Portfolio
+```{r,eval=FALSE}
+stocks <- colnames(equity.data)
+portf.init <- portfolio.spec(stocks)
+portf.minvar <- add.constraint(portf.init, type="full_investment")
+portf.minvar <- add.constraint(portf.minvar, type="box", min=0.01, max=0.2)
+portf.minvar <- add.objective(portf.minvar, type="risk", name="var")
+```
+
+<!---
+Talk a little about adding constraints and objectives
+-->
+
+## Ledoit-Wolf Shrinkage Estimate
+The default function for `momentFUN` is `set.portfolio.moments`. We need to write our own function to estimate the covariance matrix.
+```{r, eval=FALSE}
+lw.sigma <- function(R, ...){
+  out <- list()
+  # estimate covariance matrix via ledoit-wolf shrinkage
+  out$sigma <- lwShrink(R)$cov
+  return(out)
+}
+```
+
+## Backtesting Parameters
+```{r, eval=FALSE}
+# Set rebalancing frequency
+rebal.freq <- "quarters"
+# Training Period
+training <- 400
+# Trailing Period
+trailing <- 250
+```
+
+
+## Run Optimization
+```{r, eval=FALSE}
+opt.minVarSample <- optimize.portfolio.rebalancing(equity.data, portf.minvar, 
+                                                   optimize_method="ROI", 
+                                                   rebalance_on=rebal.freq, 
+                                                   training_period=training, 
+                                                   trailing_periods=trailing)
+opt.minVarLW <- optimize.portfolio.rebalancing(equity.data, portf.minvar, 
+                                               optimize_method="ROI", 
+                                               momentFUN=lw.sigma,
+                                               rebalance_on=rebal.freq, 
+                                               training_period=training, 
+                                               trailing_periods=trailing)
+```
+
+## Chart Weights
+```{r, eval=FALSE}
+chart.Weights(opt.minVarSample, main="minVarSample Weights", legend.loc=NULL)
+chart.Weights(opt.minVarLW, main="minVarLW Weights", legend.loc=NULL)
+```
+
+## Sample Estimate
+![alt text](optimization_figures/weights_minVarSample.png)
+
+## Ledoit-Wolf Shrinkage Estimate
+![alt text](optimization_figures/weights_minVarLW.png)
+
+## Returns
+Compute the rebalancing returns and chart the performance summary
+```{r, eval=FALSE}
+ret.minVarSample <- summary(opt.minVarSample)$portfolio_returns
+ret.minVarRobust <- summary(opt.minVarLW)$portfolio_returns
+ret.minVar <- cbind(ret.minVarSample, ret.minVarRobust)
+colnames(ret.minVar) <- c("Sample", "LW")
+charts.PerformanceSummary(ret.minVar)
+```
+
+## Performance Summary
+![alt text](optimization_figures/ret_minVar.png)
+
 # Example 2
 
 ## Market Neutral Portfolio
-Consider a portfolio of stocks. Dollar neutral, beta neutral, box, and position limit constraints. Objective to minimize portfolio StdDev. This will demonstrate some of the more advanced constraint types.
+Consider a portfolio of stocks. Our objective to maximize portfolio return and minimize portfolio StdDev with a target of 0.02 subject to Dollar neutral, beta neutral, box, and position limit constraints. We will use the same data considered in example 1.
 
-Use the crsp_weekly data set
+## Specify Portfolio: Contraints
+```{r, eval=FALSE, tidy=FALSE}
+portf.init <- portfolio.spec(stocks)
+portf.dn <- add.constraint(portf.init, type="weight_sum", 
+                                  min_sum=-0.01, max_sum=0.01)
+portf.dn <- add.constraint(portf.dn, type="box", min=-0.2, max=0.2)
+portf.dn <- add.constraint(portf.dn, type="position_limit", max_pos=20)
+betas <- t(CAPM.beta(equity.data, market, Rf))
+portf.dn <- add.constraint(portf.dn, type="factor_exposure", B=betas, 
+                           lower=-0.5, upper=0.5)
+```
 
+## Specify Portfolio: Objectives
+```{r,eval=FALSE, tidy=FALSE}
+portf.dn.StdDev <- add.objective(portf.dn, type="return", name="mean")
+portf.dn.StdDev <- add.objective(portf.dn.StdDev, type="risk", name="StdDev",
+                                 target=0.02)
+```
+
+## Run Optimization
+```{r, eval=FALSE, tidy=FALSE}
+rp <- random_portfolios(portf.dn, 10000, "sample", eliminate=TRUE)
+
+opt.dn <- optimize.portfolio(equity.data, portf.dn.StdDev, 
+                               optimize_method="random", rp=rp,
+                               trace=TRUE)
+```
+
+## Plot Results
+```{r, eval=FALSE, tidy=FALSE}
+plot(opt.dn, main="Dollar Neutral Portfolio", risk.col="StdDev", neighbors=10)
+```
+![alt text](optimization_figures/opt_dn.png)
+
+
 # Example 3
 
 ## Minimum Expected Shortfall
 Consider an allocation to hedge funds using the EDHEC-Risk Alternative Index as a proxy. This will be an extended example starting with an objective to minimize portfolio expected shortfall, then risk budget percent contribution limit, then equal risk contribution limit.
+* Minimize Expected Shortfall
+* Minimize Expected Shortfall with Risk Budget Limit
+* Minimize Expected Shortfall with Equal Risk Contribution
 
+Add risk budget objective to minimize concentration of percentage component contribution to risk. Concentration is defined as the Herfindahl-Hirschman Index (HHI). $\sum_{i=1}^n x_i^2$
+
+## Data
+```{r, eval=FALSE}
+R <- edhec[,1:8]
+# Abreviate column names for convenience and plotting
+colnames(R) <- c("CA", "CTAG", "DS", "EM", "EQN", "ED", "FA", "GM")
+```
+
+## Specify Initial Portfolio
+```{r, eval=FALSE, tidy=FALSE}
+funds <- colnames(R)
+portf.init <- portfolio.spec(funds)
+portf.init <- add.constraint(portf.init, type="weight_sum", 
+                             min_sum=0.99, max_sum=1.01)
+portf.init <- add.constraint(portf.init, type="box", 
+                             min=0.05, max=0.4)
+portf.init <- add.objective(portf.init, type="return", 
+                            name="mean", multiplier=0)
+```
+
+## Add Objectives
+```{r, eval=FALSE, tidy=FALSE}
+portf.minES <- add.objective(portf.init, type="risk", name="ES")
+
+portf.minES.RB <- add.objective(portf.minES, type="risk_budget", 
+                                name="ES", max_prisk=0.2)
+portf.minES.RB$constraints[[2]]$max <- rep(1,ncol(R))
+
+portf.minES.EqRB <- add.objective(portf.minES, type="risk_budget", 
[TRUNCATED]

To get the complete diff run:
    svnlook diff /svnroot/returnanalytics -r 3352


More information about the Returnanalytics-commits mailing list