[Returnanalytics-commits] r3472 - pkg/PortfolioAnalytics/demo

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Fri Jul 18 03:35:17 CEST 2014


Author: rossbennett34
Date: 2014-07-18 03:35:16 +0200 (Fri, 18 Jul 2014)
New Revision: 3472

Modified:
   pkg/PortfolioAnalytics/demo/backwards_compat.R
   pkg/PortfolioAnalytics/demo/chart_concentration.R
   pkg/PortfolioAnalytics/demo/constrained_optim.R
   pkg/PortfolioAnalytics/demo/demo_DEoptim.R
   pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R
   pkg/PortfolioAnalytics/demo/demo_factor_exposure.R
   pkg/PortfolioAnalytics/demo/demo_group_constraints.R
   pkg/PortfolioAnalytics/demo/demo_leverage_exposure_constraint.R
   pkg/PortfolioAnalytics/demo/demo_max_STARR.R
   pkg/PortfolioAnalytics/demo/demo_max_Sharpe.R
   pkg/PortfolioAnalytics/demo/demo_max_quadratic_utility.R
   pkg/PortfolioAnalytics/demo/demo_max_return.R
   pkg/PortfolioAnalytics/demo/demo_min_StdDev.R
   pkg/PortfolioAnalytics/demo/demo_min_expected_shortfall.R
   pkg/PortfolioAnalytics/demo/demo_opt_combine.R
   pkg/PortfolioAnalytics/demo/demo_proportional_cost.R
   pkg/PortfolioAnalytics/demo/demo_return_target.R
   pkg/PortfolioAnalytics/demo/demo_risk_budgets.R
   pkg/PortfolioAnalytics/demo/demo_roi_solvers.R
   pkg/PortfolioAnalytics/demo/demo_weight_concentration.R
   pkg/PortfolioAnalytics/demo/higher_moments_boudt.R
   pkg/PortfolioAnalytics/demo/meucci_ffv.R
   pkg/PortfolioAnalytics/demo/multi_layer_optimization.R
   pkg/PortfolioAnalytics/demo/regime_switching.R
   pkg/PortfolioAnalytics/demo/relative_ranking.R
   pkg/PortfolioAnalytics/demo/sortino.R
   pkg/PortfolioAnalytics/demo/testing_GenSA.R
   pkg/PortfolioAnalytics/demo/testing_ROI.R
   pkg/PortfolioAnalytics/demo/testing_pso.R
Log:
Editing demos so they compile to Rstudio notebooks

Modified: pkg/PortfolioAnalytics/demo/backwards_compat.R
===================================================================
--- pkg/PortfolioAnalytics/demo/backwards_compat.R	2014-07-15 01:00:58 UTC (rev 3471)
+++ pkg/PortfolioAnalytics/demo/backwards_compat.R	2014-07-18 01:35:16 UTC (rev 3472)
@@ -1,3 +1,14 @@
+#' ---
+#' title: "Backwards Compatibility Demo"
+#' author: "Ross Bennett"
+#' date: "7/17/2014"
+#' ---
+
+#' This script demonstrates how to solve optimization problems using what is
+#' referred to as the v1 specification. The v1 specification was used in
+#' before PortfolioAnalytics version 0.8.3 to define the optimization problem
+#' with constraints and objectives.
+
 library(PortfolioAnalytics)
 library(DEoptim)
 library(ROI)
@@ -7,28 +18,28 @@
 ret <- edhec[, 1:4]
 funds <- colnames(ret)
 
-# Set up constraint object using v1 specification
+#' Set up constraint object using v1 specification
 gen.constr <- constraint(assets=funds, min=0, max=0.55, min_sum=0.99, max_sum=1.01, 
                          weight_seq=generatesequence(min=0, max=0.55, by=0.002))
 class(gen.constr)
 
-# Add an objective to the gen.constr object
+#' Add an objective to the gen.constr object
 gen.constr <- add.objective(constraints=gen.constr, type="return", name="mean", enabled=TRUE)
 
-# Run the optimization
-# optimize.portfolio will detect that a v1_constraint object has been passed in
-# and will update to the v2 specification using a portfolio object with 
-# constraints and objectives from the v1_constraint object.
+#' Here we run the optimization. Note that optimize.portfolio will detect 
+#' that a v1_constraint object has been passed in and will update to the 
+#' v2 specification using a portfolio object with constraints and objectives 
+#' from the v1_constraint object.
 
-# Random Portfolios
+#' Solve the problem using the random portfolios optimization engine
 optrpv1 <- optimize.portfolio(R=ret, constraints=gen.constr, optimize_method="random", search_size=2000)
 optrpv1
 
-# DEoptim
+#' Solve the problem using the DEoption (Differential Evolution) optimization engine
 optdev1 <- optimize.portfolio(R=ret, constraints=gen.constr, optimize_method="DEoptim", search_size=2000)
 optdev1
 
-# ROI
+#' Solve the problem using the ROI (R Optimization Infrastructure) optimization engine
 optroiv1 <- optimize.portfolio(R=ret, constraints=gen.constr, optimize_method="ROI")
 optroiv1
 

Modified: pkg/PortfolioAnalytics/demo/chart_concentration.R
===================================================================
--- pkg/PortfolioAnalytics/demo/chart_concentration.R	2014-07-15 01:00:58 UTC (rev 3471)
+++ pkg/PortfolioAnalytics/demo/chart_concentration.R	2014-07-18 01:35:16 UTC (rev 3472)
@@ -1,11 +1,20 @@
+#' ---
+#' title: "chart.Concentration Demo"
+#' author: "Ross Bennett"
+#' date: "7/17/2014"
+#' ---
 
+#' This script demonstrates how to use chart.Concentration to visualize
+#' the concentration of the portfolio.
+
+
 library(PortfolioAnalytics)
 
 data(edhec)
 R <- edhec[, 1:8]
 funds <- colnames(R)
 
-# Construct initial portfolio
+#' Construct initial portfolio
 init.portf <- portfolio.spec(assets=funds)
 init.portf <- add.constraint(portfolio=init.portf, 
                              type="leverage", 
@@ -26,13 +35,14 @@
                             type="risk", 
                             name="ES")
 
+#' Construct a risk budget portfolio.
 rb.portf <- add.objective(portfolio=init.portf, 
                           type="risk_budget", 
                           name="ES",
                           max_prisk=0.4, 
                           arguments=list(p=0.92))
 
-# Use DEoptim for optimization
+#' Use random portfolios for optimization.
 opt <- optimize.portfolio(R=R, 
                           portfolio=init.portf, 
                           optimize_method="random", 
@@ -45,19 +55,19 @@
                              search_size=2000, 
                              trace=TRUE)
 
-# This won't work because opt is not a risk budget optimization
-# This should result in an error and not plot anything
-chart.Concentration(opt, conc.type="pct_contrib")
+#' This won't work because opt is not a risk budget optimization.
+#' This should result in an error and not plot anything.
+#chart.Concentration(opt, conc.type="pct_contrib")
 
-# opt is minimum ES optimization so we can still chart it using weights as
-# the measure of concentration
+#' `opt` is minimum ES optimization so we can still chart it using weights as
+#' the measure of concentration.
 chart.Concentration(opt, conc.type="weights", chart.assets=TRUE, col=heat.colors(10))
 chart.Concentration(opt, conc.type="weights", chart.assets=TRUE, col=bluemono)
 
-# The concentration is based on the HHI of the percentage component 
-# contribution to risk
+#' Here we plot the concentration based on the HHI of the percentage component 
+#' contribution to risk.
 chart.Concentration(opt_rb, conc.type="pct_contrib")
 
-# The concentration is based on the HHI of the weights
+#' Here we plot the concentration is based on the HHI of the weights.
 chart.Concentration(opt_rb, conc.type="weights")
 

Modified: pkg/PortfolioAnalytics/demo/constrained_optim.R
===================================================================
--- pkg/PortfolioAnalytics/demo/constrained_optim.R	2014-07-15 01:00:58 UTC (rev 3471)
+++ pkg/PortfolioAnalytics/demo/constrained_optim.R	2014-07-18 01:35:16 UTC (rev 3472)
@@ -1,11 +1,17 @@
+#' ---
+#' title: "Constrained Optimization Demo"
+#' ---
 
+#' This script demonstrates how to set up and solve constrained optimization
+#' problems. Note that this script using the pre version 0.8.3 syntax.
+
 library(PortfolioAnalytics)
 require(DEoptim)
 
-# Load the data
+#' Load the data
 data(edhec)
 
-#constraints
+#' Set up the constraints and objectives to define the optimization problem
 constraints <- constraint(assets = colnames(edhec[, 1:10]), min = 0.01, 
                           max = 0.4, min_sum=0.99, max_sum=1.01, 
                           weight_seq = generatesequence())
@@ -21,12 +27,12 @@
                              max_prisk=.15,
                              target=0.05)
 
-print("We'll use a search_size parameter of 1000 for this demo, but realistic 
-      portfolios will likely require search_size parameters much larger, the 
-      default is 20000 which is almost always large enough for any realistic 
-      portfolio and constraints, but will take substantially longer to run.")
+#' We'll use a search_size parameter of 1000 for this demo, but realistic 
+#' portfolios will likely require search_size parameters much larger, the 
+#' default is 20000 which is almost always large enough for any realistic 
+#' portfolio and constraints, but will take substantially longer to run.
 
-# look for a solution using both DEoptim and random portfolios
+#' Look for a solution using both DEoptim and random portfolios
 opt_out <- optimize.portfolio(R=edhec[,1:10], 
                               constraints=constraints, 
                               optimize_method="DEoptim", 
@@ -39,7 +45,7 @@
                                      search_size=1000, 
                                      trace=TRUE)
 
-# Optimize a portfolio that rebalances quarterly
+#' Optimize a portfolio that rebalances quarterly
 opt_out_rebalancing <- optimize.portfolio.rebalancing(R=edhec[,1:10], 
                                                       constraints=constraints, 
                                                       optimize_method="random", 
@@ -47,11 +53,12 @@
                                                       trace=FALSE, 
                                                       rebalance_on='quarters')
 
+#' Extract the optimal weights at each rebalance date and compute the returns
 rebalancing_weights <- extractWeights(opt_out_rebalancing)
 rebalancing_returns <- Return.rebalancing(R=edhec,weights=rebalancing_weights)
 charts.PerformanceSummary(rebalancing_returns)
 
-# Optimize a portfolio that rebalances quarterly with 48 mo trailing
+#' Optimize a portfolio that rebalances quarterly with 48 month trailing
 opt_out_trailing <- optimize.portfolio.rebalancing(R=edhec[,1:10], 
                                                  constraints=constraints, 
                                                    optimize_method="random", 

Modified: pkg/PortfolioAnalytics/demo/demo_DEoptim.R
===================================================================
--- pkg/PortfolioAnalytics/demo/demo_DEoptim.R	2014-07-15 01:00:58 UTC (rev 3471)
+++ pkg/PortfolioAnalytics/demo/demo_DEoptim.R	2014-07-18 01:35:16 UTC (rev 3472)
@@ -1,59 +1,61 @@
+#' ---
+#' title: "Differential Evolution Optimization Demo"
+#' date: "7/17/2014"
+#' ---
 
-# The following optimization problems will be run
-# mean-mETL
-# - maximize mean-to-ETL (i.e. reward-to-risk)
-# MinSD
-# - minimize annualized standard deviation
-# eqStdDev
-# - equal risk (volatility)
-# MeanRL
-# - maximize mean with mETL risk limits
+#' This script demonstrates several optimization problems using Differential
+#' Evolution as the optimization engine. This script is based heavily on
+#' http://www.rinfinance.com/agenda/2012/workshop/Carl+Peterson.pdf.
 
-# Include optimizer and multi-core packages
+#' The following optimization problems will be run
+#' * mean-mETL: maximize mean-to-ETL (i.e. reward-to-risk)
+#' * MinSD: minimize annualized standard deviation
+#' * eqStdDev: equal risk (volatility)
+#' * MeanRL: maximize mean with mETL risk limits
+
+#' Include optimizer and multi-core packages
 library(PortfolioAnalytics)
-require(quantmod)
 require(DEoptim)
 require(foreach)
 
-# The multicore package, and therefore registerDoMC, should not be used in a
-# GUI environment, because multiple processes then share the same GUI. Only use
-# when running from the command line.
+#' The multicore package, and therefore registerDoMC, should not be used in a
+#' GUI environment, because multiple processes then share the same GUI. Only use
+#' when running from the command line.
 # require(doMC)
 # registerDoMC(3)
 
+#' Load the data
 data(edhec)
-
-# Drop some indexes and reorder
 edhec.R <- edhec[,c("Convertible Arbitrage", "Equity Market Neutral", 
                     "Fixed Income Arbitrage", "Event Driven", "CTA Global", 
                     "Global Macro", "Long/Short Equity")]
 
-# Annualized standard deviation
+#' Define function to compute annualized standard deviation
 pasd <- function(R, weights){
   as.numeric(StdDev(R=R, weights=weights)*sqrt(12)) # hardcoded for monthly data
   # as.numeric(StdDev(R=R, weights=weights)*sqrt(4)) # hardcoded for quarterly data
 }
 
-# Set some parameters
+#' Set some parameters
 rebalance_period = 'quarters' # uses endpoints identifiers from xts
 clean = "none" #"boudt"
 permutations = 4000
 
-# Create initial portfolio object used to initialize ALL the bouy portfolios
+#' Create initial portfolio object used to initialize ALL the bouy portfolios
 init.portf <- portfolio.spec(assets=colnames(edhec.R), 
                              weight_seq=generatesequence(by=0.005))
-# Add leverage constraint
+#' Add leverage constraint
 init.portf <- add.constraint(portfolio=init.portf, 
                              type="leverage", 
                              min_sum=0.99, 
                              max_sum=1.01)
-# Add box constraint
+#' Add box constraint
 init.portf <- add.constraint(portfolio=init.portf, 
                              type="box", 
                              min=0.05, 
                              max=0.3)
 
-#Add measure 1, mean return
+#' Add measure 1, mean return
 init.portf <- add.objective(portfolio=init.portf,
                             type="return", # the kind of objective this is
                             name="mean", # name of the function
@@ -61,7 +63,7 @@
                             multiplier=0 # calculate it but don't use it in the objective
 )
 
-# Add measure 2, annualized standard deviation
+#' Add measure 2, annualized standard deviation
 init.portf <- add.objective(portfolio=init.portf,
                             type="risk", # the kind of objective this is
                             name="pasd", # to minimize from the sample
@@ -69,8 +71,7 @@
                             multiplier=0 # calculate it but don't use it in the objective
 )
 
-# Add measure 3, ES with p=(1-1/12)
-# set confidence for ES
+#' Add measure 3, ES with confidence level p=(1-1/12)
 p <- 1-1/12 # for monthly
 
 init.portf <- add.objective(portfolio=init.portf,
@@ -81,26 +82,27 @@
                             arguments=list(p=p)
 )
 
-# Set up portfolio for Mean-mETL
+#' Set up portfolio for Mean-mETL
 MeanmETL.portf <- init.portf
 MeanmETL.portf$objectives[[1]]$multiplier=-1 # mean
 MeanmETL.portf$objectives[[3]]$enabled=TRUE # mETL
 MeanmETL.portf$objectives[[3]]$multiplier=1 # mETL
 
-# Set up portfolio for min pasd
+#' Set up portfolio for min pasd
 MinSD.portf <- init.portf
 MinSD.portf$objectives[[2]]$multiplier=1
 
-# Set up portfolio for eqStdDev
+#' Set up portfolio for eqStdDev
 EqSD.portf <- add.objective(portfolio=init.portf,
                                 type="risk_budget",
                                 name="StdDev",
                                 min_concentration=TRUE,
                                 arguments = list(p=(1-1/12)))
-# Without a sub-objective, we get a somewhat undefined result, since there are (potentially) many Equal SD contribution portfolios.
+#' Without a sub-objective, we get a somewhat undefined result, since 
+#' there are (potentially) many Equal SD contribution portfolios.
 EqSD.portf$objectives[[2]]$multiplier=1 # min pasd
 
-# Set up portfolio to maximize mean with mETL risk limit
+#' Set up portfolio to maximize mean with mETL risk limit
 MeanRL.portf <- add.objective(portfolio=init.portf, 
                               type='risk_budget', 
                               name="ES", 
@@ -108,15 +110,17 @@
                               max_prisk=0.4, 
                               arguments=list(method="modified", p=p))
 MeanRL.portf$objectives[[1]]$multiplier=-1 # mean
-# Change box constraints max to vector of 1s
+#' Change box constraints max to vector of 1s
 MeanRL.portf$constraints[[2]]$max=rep(1, 7)
 
-# Set the 'R' variable
+#' Set the 'R' variable
 R <- edhec.R
 
+#' Start the optimizations
 start_time<-Sys.time()
 print(paste('Starting optimization at',Sys.time()))
 
+#' Run the optimization
 ##### mean-mETL #####
 MeanmETL.DE <- optimize.portfolio(R=R,
                                   portfolio=MeanmETL.portf,
@@ -145,7 +149,7 @@
 
 print(paste('Completed MeanmETL optimization at',Sys.time(),'moving on to MinSD'))
 
-
+#' Run the optimization
 ##### min pasd #####
 MinSD.DE <- optimize.portfolio(R=R,
                                portfolio=MinSD.portf,
@@ -161,6 +165,7 @@
 
 print(paste('Completed MinSD optimization at',Sys.time(),'moving on to EqSD'))
 
+#' Run the optimization
 ##### EqSD #####
 EqSD.DE <- optimize.portfolio(R=R,
                               portfolio=EqSD.portf,
@@ -179,6 +184,7 @@
 
 print(paste('Completed EqSD optimization at',Sys.time(),'moving on to MeanRL'))
 
+#' Run the optimization
 ##### MeanRL.DE #####
 MeanRL.DE <- optimize.portfolio(R=R,
                               portfolio=MeanRL.portf,

Modified: pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R
===================================================================
--- pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R	2014-07-15 01:00:58 UTC (rev 3471)
+++ pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R	2014-07-18 01:35:16 UTC (rev 3472)
@@ -1,24 +1,30 @@
-# Script to test efficient frontiers
+#' ---
+#' title: "Efficient Frontier Demo"
+#' date: "7/17/2014"
+#' ---
 
-# Efficient frontiers can be plotted two ways
-# 1. Run optimize.portfolio with trace=TRUE and then chart that object
-# 2. create an efficient frontier and then chart that object
+#' This script demonstrates how to compute and plot the efficient frontier
+#' given different constraints and objectives.
 
+#' Efficient frontiers can be plotted two ways
+#' 1. Run optimize.portfolio with trace=TRUE and then chart that object.
+#' 2. create an efficient frontier and then chart that object.
+
+#' Load required packages
 library(PortfolioAnalytics)
 library(DEoptim)
 library(ROI)
 require(ROI.plugin.quadprog)
 require(ROI.plugin.glpk)
 
+#' Load the data and change the column names for better legends in plotting.
 data(edhec)
 R <- edhec[, 1:5]
-# change the column names for better legends in plotting
 colnames(R) <- c("CA", "CTAG", "DS", "EM", "EQM")
 funds <- colnames(R)
 
-# initial portfolio object
+#' Set up the initial portfolio object with some basic constraints.
 init <- portfolio.spec(assets=funds)
-# initial constraints
 init <- add.constraint(portfolio=init, type="full_investment")
 init <- add.constraint(portfolio=init, type="box", min=0.15, max=0.45)
 init <- add.constraint(portfolio=init, type="group",
@@ -27,101 +33,105 @@
                        group_min=0.05,
                        group_max=0.7)
 
-# create mean-etl portfolio
+#' Add objectives for mean-ES (Expected Shortfall) portfolio.
 meanetl.portf <- add.objective(portfolio=init, type="risk", name="ES")
 meanetl.portf <- add.objective(portfolio=meanetl.portf, type="return", name="mean")
 
-# create mean-var portfolio
+#' Add objectives for mean-variance portfolio.
 meanvar.portf <- add.objective(portfolio=init, type="risk", name="var", risk_aversion=10)
 meanvar.portf <- add.objective(portfolio=meanvar.portf, type="return", name="mean")
 
-# create efficient frontiers
-
-# mean-var efficient frontier
+#' Compute the mean-variance efficient frontier.
 meanvar.ef <- create.EfficientFrontier(R=R, portfolio=init, type="mean-StdDev")
 meanvar.ef
 summary(meanvar.ef, digits=2)
 meanvar.ef$frontier
 
-# The RAR.text argument can be used for the risk-adjusted-return name on the legend,
-# by default it is 'Modified Sharpe Ratio'
-chart.EfficientFrontier(meanvar.ef, match.col="StdDev", type="l", RAR.text="Sharpe Ratio", pch=4)
+#' The RAR.text argument can be used for the risk-adjusted-return name on the 
+#' legend, by default it is 'Modified Sharpe Ratio'.
+chart.EfficientFrontier(meanvar.ef, match.col="StdDev", type="l", 
+                        RAR.text="Sharpe Ratio", pch=4)
 
-# The tangency portfolio and line are plotted by default, these can be ommitted
-# by setting rf=NULL
+#' The tangency portfolio and line are plotted by default, these can be 
+#' ommitted by setting rf=NULL.
 chart.EfficientFrontier(meanvar.ef, match.col="StdDev", type="b", rf=NULL)
 
-# The tangency line can be omitted with tangent.line=FALSE. The tangent portfolio,
-# risk-free rate and Sharpe Ratio are still included in the plot
+#' The tangency line can be omitted with tangent.line=FALSE. The tangent 
+#' portfolio, risk-free rate and Sharpe Ratio are still included in the plot.
 chart.EfficientFrontier(meanvar.ef, match.col="StdDev", type="l", tangent.line=FALSE)
 
-# The assets can be omitted with chart.assets=FALSE
+#' The assets can be omitted with chart.assets=FALSE.
 chart.EfficientFrontier(meanvar.ef, match.col="StdDev", type="l", 
                         tangent.line=FALSE, chart.assets=FALSE)
 
-# Just the names of the assets can be omitted with labels.assets=FALSE and the 
-# plotting character can be changed with pch.assets
+#' Just the names of the assets can be omitted with labels.assets=FALSE and the 
+#' plotting character can be changed with pch.assets.
 chart.EfficientFrontier(meanvar.ef, match.col="StdDev", type="l", 
                         tangent.line=FALSE, labels.assets=FALSE, pch.assets=1)
 
-# Chart the asset weights along the efficient frontier
+#' Chart the asset weights along the efficient frontier.
 chart.Weights.EF(meanvar.ef, colorset=bluemono, match.col="StdDev")
 
-# Chart the group weights along the efficient frontier
+#' Chart the group weights along the efficient frontier.
 chart.Weights.EF(meanvar.ef, colorset=bluemono, by.groups=TRUE, match.col="StdDev")
 
-# The labels for Mean, Weight, and StdDev can be increased or decreased with
-# the cex.lab argument. The default is cex.lab=0.8
+#' The labels for Mean, Weight, and StdDev can be increased or decreased with
+#' the cex.lab argument. The default is cex.lab=0.8.
 chart.Weights.EF(meanvar.ef, colorset=bluemono, match.col="StdDev", main="", cex.lab=1)
 
-# If you have a lot of assets and they don't fit with the default legend, you
-# can set legend.loc=NULL and customize the plot.
+#' If you have a lot of assets and they don't fit with the default legend, you
+#' can set legend.loc=NULL and customize the plot.
 par(mar=c(8, 4, 4, 2)+0.1, xpd=TRUE)
 chart.Weights.EF(meanvar.ef, colorset=bluemono, match.col="StdDev", legend.loc=NULL)
 legend("bottom", legend=colnames(R), inset=-1, fill=bluemono, bty="n", ncol=3, cex=0.8)
 par(mar=c(5, 4, 4, 2)+0.1, xpd=FALSE)
 
-# run optimize.portfolio and chart the efficient frontier for that object
-opt_meanvar <- optimize.portfolio(R=R, portfolio=meanvar.portf, optimize_method="ROI", trace=TRUE)
+#' Run optimize.portfolio and chart the efficient frontier of the optimal
+#' portfolio object.
+opt_meanvar <- optimize.portfolio(R=R, portfolio=meanvar.portf, 
+                                  optimize_method="ROI", trace=TRUE)
 
-# The efficient frontier is created from the 'opt_meanvar' object by getting
-# The portfolio and returns objects and then passing those to create.EfficientFrontier
+#' The efficient frontier is created from the 'opt_meanvar' object by getting.
+#' The portfolio and returns objects and then passing those to create.EfficientFrontier.
 chart.EfficientFrontier(opt_meanvar, match.col="StdDev", n.portfolios=25, type="l")
 
-# Rerun the optimization with a new risk aversion parameter to change where the
-# portfolio is along the efficient frontier. The 'optimal' portfolio plotted on
-# the efficient frontier is the optimal portfolio returned by optimize.portfolio.
+#' Rerun the optimization with a new risk aversion parameter to change where 
+#' the portfolio is along the efficient frontier. The 'optimal' portfolio 
+#' plotted on the efficient frontier is the optimal portfolio returned by 
+#' optimize.portfolio.
 meanvar.portf$objectives[[2]]$risk_aversion=0.25
 opt_meanvar <- optimize.portfolio(R=R, portfolio=meanvar.portf, optimize_method="ROI", trace=TRUE)
 chart.EfficientFrontier(opt_meanvar, match.col="StdDev", n.portfolios=25, type="l")
 
-# The weights along the efficient frontier can be plotted by passing in the
-# optimize.portfolio output object
+#' The weights along the efficient frontier can be plotted by passing in the
+#' optimize.portfolio output object.
 chart.Weights.EF(opt_meanvar, match.col="StdDev")
 
 chart.Weights.EF(opt_meanvar, match.col="StdDev", by.groups=TRUE)
 
-# Extract the efficient frontier and then plot it
-# Note that if you want to do multiple charts of the efficient frontier from
-# the optimize.portfolio object, it is best to extractEfficientFrontier as shown
-# below
+#' Extract the efficient frontier and then plot it.
+#' Note that if you want to do multiple charts of the efficient frontier from
+#' the optimize.portfolio object, it is best to extractEfficientFrontier as 
+#' shown below.
 ef <- extractEfficientFrontier(object=opt_meanvar, match.col="StdDev", n.portfolios=15)
 ef
 summary(ef, digits=5)
 chart.Weights.EF(ef, match.col="StdDev", colorset=bluemono)
 chart.Weights.EF(ef, match.col="StdDev", colorset=bluemono, by.groups=TRUE)
 
-# mean-etl efficient frontier
+#' Compute the mean-ES efficient frontier.
 meanetl.ef <- create.EfficientFrontier(R=R, portfolio=init, type="mean-ES")
 meanetl.ef
 summary(meanetl.ef)
 meanetl.ef$frontier
 
+#' Chart the mean-ES efficient frontier.
 chart.EfficientFrontier(meanetl.ef, match.col="ES", main="mean-ETL Efficient Frontier", type="l", col="blue", RAR.text="STARR")
 chart.Weights.EF(meanetl.ef, colorset=bluemono, match.col="ES")
 chart.Weights.EF(meanetl.ef, by.groups=TRUE, colorset=bluemono, match.col="ES")
 
-# mean-etl efficient frontier using random portfolios
+#' Compute the mean-ES efficient frontier using random portfolios to solve
+#' the optimization problem.
 meanetl.rp.ef <- create.EfficientFrontier(R=R, portfolio=meanetl.portf, type="random", match.col="ES")
 chart.EfficientFrontier(meanetl.rp.ef, match.col="ES", main="mean-ETL RP Efficient Frontier", type="l", col="blue", rf=0)
 chart.Weights.EF(meanetl.rp.ef, colorset=bluemono, match.col="ES")
@@ -130,36 +140,39 @@
 opt_meanetl <- optimize.portfolio(R=R, portfolio=meanetl.portf, optimize_method="random", search_size=2000, trace=TRUE)
 chart.EfficientFrontier(meanetl.rp.ef, match.col="ES", main="mean-ETL RP Efficient Frontier", type="l", col="blue", rf=0, RAR.text="STARR")
 
-##### overlay efficient frontiers of multiple portfolios #####
-# Create a mean-var efficient frontier for multiple portfolios and overlay the efficient frontier lines
-# set up an initial portfolio with the full investment constraint and mean and var objectives
+#' Create a mean-var efficient frontier for multiple portfolios and overlay 
+#' the efficient frontier lines. Set up an initial portfolio with the full 
+#' investment constraint and mean and var objectives.
 init.portf <- portfolio.spec(assets=funds)
 init.portf <- add.constraint(portfolio=init.portf, type="full_investment")
 
-# long only constraints
+#' Portfolio with long only constraints.
 lo.portf <- add.constraint(portfolio=init.portf, type="long_only")
 
-# box constraints
+#' Portfolio with box constraints.
 box.portf <- add.constraint(portfolio=init.portf, type="box", min=0.05, max=0.65)
 
-# group constraints (also add long only constraints to the group portfolio)
+#' Portfolio with group constraints (also add long only constraints to the 
+#' group portfolio).
 group.portf <- add.constraint(portfolio=init.portf, type="group", 
                               groups=list(groupA=c(1, 3),
                                           groupB=c(2, 4, 5)),
                               group_min=c(0.25, 0.15), 
                               group_max=c(0.75, 0.55))
 group.portf <- add.constraint(portfolio=group.portf, type="long_only")
-# optimize.portfolio(R=R, portfolio=group.portf, optimize_method="ROI")
 
+#' Combine the portfolios into a list.
 portf.list <- combine.portfolios(list(lo.portf, box.portf, group.portf))
+
+#' Plot the efficient frontier overlay of the portfolios with varying constraints.
 legend.labels <- c("Long Only", "Box", "Group + Long Only")
 chart.EfficientFrontierOverlay(R=R, portfolio_list=portf.list, type="mean-StdDev", 
                                match.col="StdDev", legend.loc="topleft", 
                                legend.labels=legend.labels, cex.legend=0.6,
                                labels.assets=FALSE, pch.assets=18)
 
-# Efficient frontier in mean-ES space with varying confidence leves for
-# ES calculation
+#' Efficient frontier in mean-ES space with varying confidence leves for
+#' ES calculation.
 ES90 <- add.objective(portfolio=lo.portf, type="risk", name="ES", 
                           arguments=list(p=0.9))
 
@@ -169,7 +182,11 @@
 ES95 <- add.objective(portfolio=lo.portf, type="risk", name="ES", 
                       arguments=list(p=0.95))
 
+#' Combine the portfolios into a list.
 portf.list <- combine.portfolios(list(ES.90=ES90, ES.92=ES92, ES.95=ES95))
+
+#' Plot the efficient frontier overlay of the portfolios with varying 
+#' confidence levels fot he ES calculation.
 legend.labels <- c("ES (p=0.9)", "ES (p=0.92)", "ES (p=0.95)")
 chart.EfficientFrontierOverlay(R=R, portfolio_list=portf.list, type="mean-ES", 
                                match.col="ES", legend.loc="topleft", 

Modified: pkg/PortfolioAnalytics/demo/demo_factor_exposure.R
===================================================================
--- pkg/PortfolioAnalytics/demo/demo_factor_exposure.R	2014-07-15 01:00:58 UTC (rev 3471)
+++ pkg/PortfolioAnalytics/demo/demo_factor_exposure.R	2014-07-18 01:35:16 UTC (rev 3472)
@@ -1,3 +1,13 @@
+#' ---
+#' title: "Factor Exposure Demo"
+#' author: Ross Bennett
+#' date: "7/17/2014"
+#' ---
+
+#' This script demonstrates how to solve a portfolio optimization problem with
+#' factor exposure constraints.
+
+#' Load the required packages
 library(PortfolioAnalytics)
 library(ROI)
 require(ROI.plugin.quadprog)
@@ -5,91 +15,114 @@
 library(Rglpk)
 library(DEoptim)
 
+#' Load the data
 data(edhec)
 ret <- edhec[, 1:4]
 
-# Create portfolio object
+#' Create portfolio object
 pspec <- portfolio.spec(assets=colnames(ret))
-# Leverage constraint
+
+#' Here we define individual constraint objects.
+#' Leverage constraint.
 lev_constr <- weight_sum_constraint(min_sum=1, max_sum=1)
-# box constraint
+
+#' Box constraint
 lo_constr <- box_constraint(assets=pspec$assets, min=c(0.01, 0.02, 0.03, 0.04), max=0.65)
-# group constraint
+
+#' Group constraint'
 grp_constr <- group_constraint(assets=pspec$assets, groups=list(1:2, 3, 4), group_min=0.1, group_max=0.4)
-# position limit constraint
+
+#' Position limit constraint
 pl_constr <- position_limit_constraint(assets=pspec$assets, max_pos=4)
 
-# Make up a B matrix for an industry factor model
-# dummyA, dummyB, and dummyC could be industries, sectors, etc.
+#' Make up a B matrix for an industry factor model.
+#' dummyA, dummyB, and dummyC could be industries, sectors, etc.
 B <- cbind(c(1, 1, 0, 0),
            c(0, 0, 1, 0),
            c(0, 0, 0, 1))
 rownames(B) <- colnames(ret)
 colnames(B) <- c("dummyA", "dummyB", "dummyC")
-print(B)
 lower <- c(0.1, 0.1, 0.1)
 upper <- c(0.4, 0.4, 0.4)
 
-# Industry exposure constraint
-# The exposure constraint and group constraint are equivalent to test that they
-# result in the same solution
+#' Industry exposure constraint.
+#' The exposure constraint and group constraint are equivalent to test that 
+#' they result in the same solution.
 exp_constr <- factor_exposure_constraint(assets=pspec$assets, B=B, lower=lower, upper=upper)
 
-# objective to minimize variance 
+#' Here we define objectives.
+#' 
+#' Objective to minimize variance.
 var_obj <- portfolio_risk_objective(name="var")
-# objective to maximize return
+
+#' Objective to maximize return.
 ret_obj <- return_objective(name="mean")
-# objective to minimize ETL
+
+#' Objective to minimize ETL.
 etl_obj <- portfolio_risk_objective(name="ETL")
 
-# group constraint and exposure constraint should result in same solution
-
-##### minimize var objective #####
+#' Run optimization on minimum variance portfolio with leverage, long only,
+#' and group constraints.
 opta <- optimize.portfolio(R=ret, portfolio=pspec, 
                           constraints=list(lev_constr, lo_constr, grp_constr), 
                           objectives=list(var_obj), 
                           optimize_method="ROI")
 opta
 
+#' Run optimization on minimum variance portfolio with leverage, long only,
+#' and factor exposure constraints.
 optb <- optimize.portfolio(R=ret, portfolio=pspec, 
                           constraints=list(lev_constr, lo_constr, exp_constr), 
                           objectives=list(var_obj), 
                           optimize_method="ROI")
 optb
 
+#' Note that the portfolio with the group constraint and exposure constraint 
+#' should result in same solution.
 all.equal(opta$weights, optb$weights)
 
-##### maximize return objective #####
+#' Run optimization on maximum return portfolio with leverage, long only,
+#' and group constraints.
 optc <- optimize.portfolio(R=ret, portfolio=pspec, 
                           constraints=list(lev_constr, lo_constr, grp_constr), 
                           objectives=list(ret_obj), 
                           optimize_method="ROI")
 optc
 
+#' Run optimization on maximum return portfolio with leverage, long only,
+#' and factor exposure constraints.
 optd <- optimize.portfolio(R=ret, portfolio=pspec, 
                            constraints=list(lev_constr, lo_constr, exp_constr), 
                            objectives=list(ret_obj), 
                            optimize_method="ROI")
 optd
 
+#' Note that the portfolio with the group constraint and exposure constraint 
+#' should result in same solution.
 all.equal(optc$weights, optd$weights)
 
-##### minimize ETL objective #####
+#' Run optimization on minimum expected tail loss portfolio with leverage, 
+#' long only, and group constraints.
 opte <- optimize.portfolio(R=ret, portfolio=pspec, 
                           constraints=list(lev_constr, lo_constr, grp_constr), 
                           objectives=list(etl_obj), 
                           optimize_method="ROI")
 opte
 
+#' Run optimization on minimum expected tail loss portfolio with leverage, 
+#' long only, and factor exposure constraints.
 optf <- optimize.portfolio(R=ret, portfolio=pspec, 
                           constraints=list(lev_constr, lo_constr, exp_constr), 
                           objectives=list(etl_obj), 
                           optimize_method="ROI")
 optf
 
+#' Note that the portfolio with the group constraint and exposure constraint 
+#' should result in same solution.
 all.equal(opte$weights, optf$weights)
 
-##### maximize return objective with DEoptim #####
+#' Run optimization on maximum return portfolio with leverage, long only,
+#' and group constraints using DEoptim as the optimization engine.
 set.seed(123)
[TRUNCATED]

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


More information about the Returnanalytics-commits mailing list