[Returnanalytics-commits] r3037 - in pkg/PortfolioAnalytics: demo sandbox
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Mon Sep 9 23:27:22 CEST 2013
Author: rossbennett34
Date: 2013-09-09 23:27:22 +0200 (Mon, 09 Sep 2013)
New Revision: 3037
Added:
pkg/PortfolioAnalytics/demo/backwards_compat.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_ROI.R
pkg/PortfolioAnalytics/demo/demo_maxret_ROI.R
pkg/PortfolioAnalytics/demo/demo_opt_combine.R
pkg/PortfolioAnalytics/demo/demo_random_portfolios.R
pkg/PortfolioAnalytics/demo/demo_return_target.R
pkg/PortfolioAnalytics/demo/demo_weight_concentration.R
Removed:
pkg/PortfolioAnalytics/sandbox/testing_DE_opt_script.R
pkg/PortfolioAnalytics/sandbox/testing_back_compat.R
pkg/PortfolioAnalytics/sandbox/testing_constraint_fn_map.R
pkg/PortfolioAnalytics/sandbox/testing_diversification.R
pkg/PortfolioAnalytics/sandbox/testing_efficient_frontier.R
pkg/PortfolioAnalytics/sandbox/testing_factor_exposure.R
pkg/PortfolioAnalytics/sandbox/testing_group_multlevels.R
pkg/PortfolioAnalytics/sandbox/testing_maxret_ROI.R
pkg/PortfolioAnalytics/sandbox/testing_mult_opt_weights.R
pkg/PortfolioAnalytics/sandbox/testing_return_target.R
Modified:
pkg/PortfolioAnalytics/demo/00Index
pkg/PortfolioAnalytics/sandbox/testing_weight_conc.R
Log:
Moving several of the testing scripts from the sandbox folder to the demo folder. Updating the index file in the demo folder with added demos.
Modified: pkg/PortfolioAnalytics/demo/00Index
===================================================================
--- pkg/PortfolioAnalytics/demo/00Index 2013-09-09 20:23:12 UTC (rev 3036)
+++ pkg/PortfolioAnalytics/demo/00Index 2013-09-09 21:27:22 UTC (rev 3037)
@@ -2,6 +2,15 @@
sortino Maximize the Sortino Ratio of the portfolio
testing_ROI Demonstrate creating constraint object and solve five basic convex portfolio optimization problems with ROI using the 'edhec' dataset.
testing_pso Demonstrate creating constraint object and solve portfolio optimization problems with pso using the 'edhec' dataset. These sample problems are similar to those used in testing_ROI, so that one can compare solutions easily.
-testing_GenSA Demonstrate the creating constraint object and solve portfolio optimization problems with GenSA using the 'edhec' datset. These sample problems are similar to those used in testing_ROI, so that one can compare solutions easily.
-demo_ROI Demonstrate constraints and objectives that can be solved with ROI
+testing_GenSA Demonstrate creating the constraint object and solve portfolio optimization problems with GenSA using the 'edhec' datset. These sample problems are similar to those used in testing_ROI, so that one can compare solutions easily.
+demo_ROI Demonstrate constraints and objectives that can be solved with ROI.
+demo_DEoptim Demonstrate solving portfolio optimization problems using DEoptim as the solver. The demo solvers 4 problems: 1) Maximize mean return per unit mETL 2) Minimize annualized standard deviation 3) Minimize annualized standard deviation with equal contribution to risk using standard deviation as the risk measure 4) Maximize mean return with equal contribution to risk using modified ETL as the risk measure.
+demo_efficient_frontier Demonstrate how to create and chart efficient frontiers.
+demo_factor_exposure Demonstrate how to use the factor_exposure constraint.
+demo_group_ROI Demonstrate how to use group constraints using the ROI solver.
+demo_maxret_ROI Demonstrate maximizing return using the ROI solver.
+demo_opt_combine Demonstrate how to combine and chart the optimal weights for multiple optimizations.
+demo_weight_concentration Demonstrate how to use the weight concentration objective.
+backwards_compat Demonstrate how to solve optimization problems using v1 specification with a v1_constraint object.
+demo_random_portfolios Demonstrate examples from script.workshop2012.R using random portfolios
Copied: pkg/PortfolioAnalytics/demo/backwards_compat.R (from rev 3022, pkg/PortfolioAnalytics/sandbox/testing_back_compat.R)
===================================================================
--- pkg/PortfolioAnalytics/demo/backwards_compat.R (rev 0)
+++ pkg/PortfolioAnalytics/demo/backwards_compat.R 2013-09-09 21:27:22 UTC (rev 3037)
@@ -0,0 +1,35 @@
+library(PortfolioAnalytics)
+library(DEoptim)
+library(ROI)
+require(ROI.plugin.glpk)
+
+data(edhec)
+ret <- edhec[, 1:4]
+funds <- colnames(ret)
+
+# Set up constraint object using v1 specification
+gen.constr <- constraint(assets=funds, min=0, max=0.55, min_sum=0.99, max_sum=1, weight_seq=generatesequence(min=0, max=0.55, by=0.002))
+class(gen.constr)
+
+# 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.
+
+# Random
+optrpv1 <- optimize.portfolio(R=ret, constraints=gen.constr, optimize_method="random", search_size=2000)
+print(optrpv1$portfolio)
+print(optrpv1)
+
+# DEoptim
+optdev1 <- optimize.portfolio(R=ret, constraints=gen.constr, optimize_method="DEoptim", search_size=2000)
+print(optdev1)
+
+# ROI
+optroiv1 <- optimize.portfolio(R=ret, constraints=gen.constr, optimize_method="ROI")
+print(optroiv1)
+
+
Copied: pkg/PortfolioAnalytics/demo/demo_DEoptim.R (from rev 3022, pkg/PortfolioAnalytics/sandbox/testing_DE_opt_script.R)
===================================================================
--- pkg/PortfolioAnalytics/demo/demo_DEoptim.R (rev 0)
+++ pkg/PortfolioAnalytics/demo/demo_DEoptim.R 2013-09-09 21:27:22 UTC (rev 3037)
@@ -0,0 +1,198 @@
+
+# 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.
+# require(doMC)
+# registerDoMC(3)
+
+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
+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
+rebalance_period = 'quarters' # uses endpoints identifiers from xts
+clean = "none" #"boudt"
+permutations = 4000
+
+# 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
+init.portf <- add.constraint(portfolio=init.portf,
+ type="leverage",
+ min_sum=0.99,
+ max_sum=1.01)
+# Add box constraint
+init.portf <- add.constraint(portfolio=init.portf,
+ type="box",
+ min=0.05,
+ max=0.3)
+
+#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
+ enabled=TRUE, # enable or disable the objective
+ multiplier=0 # calculate it but don't use it in the objective
+)
+
+# 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
+ enabled=TRUE, # enable or disable the objective
+ 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
+p <- 1-1/12 # for monthly
+
+init.portf <- add.objective(portfolio=init.portf,
+ type="risk", # the kind of objective this is
+ name="ES", # the function to minimize
+ enabled=FALSE, # enable or disable the objective
+ multiplier=0, # calculate it but don't use it in the objective
+ arguments=list(p=p)
+)
+
+# 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
+MinSD.portf <- init.portf
+MinSD.portf$objectives[[2]]$multiplier=1
+
+# 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.
+EqSD.portf$objectives[[2]]$multiplier=1 # min pasd
+
+# Set up portfolio to maximize mean with mETL risk limit
+MeanRL.portf <- add.objective(portfolio=init.portf,
+ type='risk_budget',
+ name="ES",
+ min_prisk=-Inf,
+ 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
+MeanRL.portf$constraints[[2]]$max=rep(1, 7)
+
+# Set the 'R' variable
+R <- edhec.R
+
+start_time<-Sys.time()
+print(paste('Starting optimization at',Sys.time()))
+
+##### mean-mETL #####
+MeanmETL.DE <- optimize.portfolio(R=R,
+ portfolio=MeanmETL.portf,
+ optimize_method="DEoptim",
+ trace=TRUE,
+ search_size=2000,
+ traceDE=5)
+print(MeanmETL.DE)
+print(MeanmETL.DE$elapsed_time)
+chart.Weights(object=MeanmETL.DE, main="Mean-mETL Weights")
+chart.RiskReward(object=MeanmETL.DE, return.col="mean", risk.col="ES")
+# save(MeanmETL.DE, file=paste('MeanmETL',Sys.Date(),'rda',sep='.'))
+
+# Evaluate the objectives with DE through time
+# MeanmETL.DE.t <- optimize.portfolio.rebalancing(R=R,
+# portfolio=MeanSD.portf,
+# optimize_method="random",
+# trace=TRUE,
+# search_size=2000,
+# rebalance_on=rebalance_period,
+# training_period=36)
+# MeanmETL.w = extractWeights.rebal(MeanmETL.DE.t)
+# MeanmETL=Return.rebalancing(edhec.R, MeanmETL)
+# colnames(MeanmETL) = "MeanmETL"
+# save(MeanmETL.DE, MeanmETL.DE.t, MeanmETL.w, MeanmETL, file=paste('MeanmETL',Sys.Date(),'rda',sep='.'))
+
+print(paste('Completed MeanmETL optimization at',Sys.time(),'moving on to MinSD'))
+
+
+##### min pasd #####
+MinSD.DE <- optimize.portfolio(R=R,
+ portfolio=MinSD.portf,
+ optimize_method="DEoptim",
+ trace=TRUE,
+ search_size=2000,
+ traceDE=5)
+print(MinSD.DE)
+print(MinSD.DE$elapsed_time)
+chart.Weights(object=MinSD.DE, plot.type="barplot", legend.loc=NULL)
+chart.RiskReward(object=MinSD.DE, return.col="mean", risk.col="pasd")
+# save(MinSD.DE, file=paste('MinSD',Sys.Date(),'rda',sep='.'))
+
+print(paste('Completed MinSD optimization at',Sys.time(),'moving on to EqSD'))
+
+##### EqSD #####
+EqSD.DE <- optimize.portfolio(R=R,
+ portfolio=EqSD.portf,
+ optimize_method="DEoptim",
+ trace=TRUE,
+ search_size=2000,
+ traceDE=5)
+print(EqSD.DE)
+print(EqSD.DE$elapsed_time)
+# save(EqSD.DE, file=paste('EqSD',Sys.Date(),'rda',sep='.'))
+
+chart.Weights(object=EqSD.DE)
+chart.RiskReward(object=EqSD.DE, return.col="mean", risk.col="StdDev")
+chart.RiskBudget(object=EqSD.DE, risk.type="absolute")
+chart.RiskBudget(object=EqSD.DE, risk.type="pct_contrib")
+
+print(paste('Completed EqSD optimization at',Sys.time(),'moving on to MeanRL'))
+
+##### MeanRL.DE #####
+MeanRL.DE <- optimize.portfolio(R=R,
+ portfolio=MeanRL.portf,
+ optimize_method="DEoptim",
+ trace=TRUE,
+ search_size=2000,
+ traceDE=5)
+print(MeanRL.DE)
+print(MeanRL.DE$elapsed_time)
+# save(MeanRL.DE, file=paste('MeanRL',Sys.Date(),'rda',sep='.'))
+
+chart.Weights(object=MeanRL.DE)
+chart.RiskBudget(object=MeanRL.DE, risk.type="pct_contrib", neighbors=25)
+
+end_time<-Sys.time()
+print("Optimization Complete")
+print(end_time-start_time)
Copied: pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R (from rev 3022, pkg/PortfolioAnalytics/sandbox/testing_efficient_frontier.R)
===================================================================
--- pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R (rev 0)
+++ pkg/PortfolioAnalytics/demo/demo_efficient_frontier.R 2013-09-09 21:27:22 UTC (rev 3037)
@@ -0,0 +1,163 @@
+# Script to test efficient frontiers
+
+# 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
+
+library(PortfolioAnalytics)
+library(DEoptim)
+library(ROI)
+require(ROI.plugin.quadprog)
+require(ROI.plugin.glpk)
+
+rm(list=ls())
+
+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
+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",
+ groups=list(c(1, 3),
+ c(2, 4, 5)),
+ group_min=0.05,
+ group_max=0.7)
+
+# initial objective
+init <- add.objective(portfolio=init, type="return", name="mean")
+
+# create mean-etl portfolio
+meanetl.portf <- add.objective(portfolio=init, type="risk", name="ES")
+
+# create mean-var portfolio
+meanvar.portf <- add.objective(portfolio=init, type="risk", name="var", risk_aversion=1e6)
+
+# create efficient frontiers
+
+# mean-var efficient frontier
+meanvar.ef <- create.EfficientFrontier(R=R, portfolio=meanvar.portf, type="mean-StdDev")
+print(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 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
+chart.EfficientFrontier(meanvar.ef, match.col="StdDev", type="l", tangent.line=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
+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.Weights.EF(meanvar.ef, colorset=bluemono, match.col="StdDev")
+
+# 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
+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.
+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)
+
+# 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.
+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
+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
+ef <- extractEfficientFrontier(object=opt_meanvar, match.col="StdDev", n.portfolios=15)
+print(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
+meanetl.ef <- create.EfficientFrontier(R=R, portfolio=meanetl.portf, type="mean-ES")
+print(meanetl.ef)
+summary(meanetl.ef)
+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
+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")
+
+# mean-etl efficient frontier with optimize.portfolio output
+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
+init.portf <- portfolio.spec(assets=funds)
+init.portf <- add.constraint(portfolio=init.portf, type="full_investment")
+init.portf <- add.objective(portfolio=init.portf, type="risk", name="var")
+init.portf <- add.objective(portfolio=init.portf, type="return", name="mean")
+
+# long only constraints
+lo.portf <- add.constraint(portfolio=init.portf, type="long_only")
+
+# 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)
+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")
+
+portf.list <- list(lo.portf, box.portf, group.portf)
+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)
+
Copied: pkg/PortfolioAnalytics/demo/demo_factor_exposure.R (from rev 3022, pkg/PortfolioAnalytics/sandbox/testing_factor_exposure.R)
===================================================================
--- pkg/PortfolioAnalytics/demo/demo_factor_exposure.R (rev 0)
+++ pkg/PortfolioAnalytics/demo/demo_factor_exposure.R 2013-09-09 21:27:22 UTC (rev 3037)
@@ -0,0 +1,130 @@
+library(PortfolioAnalytics)
+library(ROI)
+require(ROI.plugin.quadprog)
+require(ROI.plugin.glpk)
+library(Rglpk)
+library(DEoptim)
+
+data(edhec)
+ret <- edhec[, 1:4]
+
+# Create portfolio object
+pspec <- portfolio.spec(assets=colnames(ret))
+# Leverage constraint
+lev_constr <- weight_sum_constraint(min_sum=1, max_sum=1)
+# box constraint
+lo_constr <- box_constraint(assets=pspec$assets, min=c(0.01, 0.02, 0.03, 0.04), max=0.65)
+# group constraint
+grp_constr <- group_constraint(assets=pspec$assets, groups=c(2, 1, 1), group_min=0.1, group_max=0.4)
+# 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.
+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
+exp_constr <- factor_exposure_constraint(assets=pspec$assets, B=B, lower=lower, upper=upper)
+
+# objective to minimize variance
+var_obj <- portfolio_risk_objective(name="var")
+# objective to maximize return
+ret_obj <- return_objective(name="mean")
+# objective to minimize ETL
+etl_obj <- portfolio_risk_objective(name="ETL")
+
+# group constraint and exposure constraint should result in same solution
+
+##### minimize var objective #####
+opta <- optimize.portfolio(R=ret, portfolio=pspec,
+ constraints=list(lev_constr, lo_constr, grp_constr),
+ objectives=list(var_obj),
+ optimize_method="ROI")
+opta
+
+optb <- optimize.portfolio(R=ret, portfolio=pspec,
+ constraints=list(lev_constr, lo_constr, exp_constr),
+ objectives=list(var_obj),
+ optimize_method="ROI")
+optb
+
+all.equal(opta$weights, optb$weights)
+
+##### maximize return objective #####
+optc <- optimize.portfolio(R=ret, portfolio=pspec,
+ constraints=list(lev_constr, lo_constr, grp_constr),
+ objectives=list(ret_obj),
+ optimize_method="ROI")
+optc
+
+optd <- optimize.portfolio(R=ret, portfolio=pspec,
+ constraints=list(lev_constr, lo_constr, exp_constr),
+ objectives=list(ret_obj),
+ optimize_method="ROI")
+optd
+
+all.equal(optc$weights, optd$weights)
+
+##### minimize ETL objective #####
+opte <- optimize.portfolio(R=ret, portfolio=pspec,
+ constraints=list(lev_constr, lo_constr, grp_constr),
+ objectives=list(etl_obj),
+ optimize_method="ROI")
+opte
+
+optf <- optimize.portfolio(R=ret, portfolio=pspec,
+ constraints=list(lev_constr, lo_constr, exp_constr),
+ objectives=list(etl_obj),
+ optimize_method="ROI")
+optf
+
+all.equal(opte$weights, optf$weights)
+
+##### maximize return objective with DEoptim #####
+set.seed(123)
+optde1 <- optimize.portfolio(R=ret, portfolio=pspec,
+ constraints=list(lev_constr, lo_constr, grp_constr),
+ objectives=list(ret_obj),
+ optimize_method="DEoptim",
+ search_size=2000,
+ trace=TRUE)
+optde1
+
+set.seed(123)
+optde2 <- optimize.portfolio(R=ret, portfolio=pspec,
+ constraints=list(lev_constr, lo_constr, exp_constr),
+ objectives=list(ret_obj),
+ optimize_method="DEoptim",
+ search_size=2000,
+ trace=TRUE)
+optde2
+
+all.equal(optde1$weights, optde2$weights)
+
+##### maximize return objective with random #####
+optrp1 <- optimize.portfolio(R=ret, portfolio=pspec,
+ constraints=list(lev_constr, lo_constr, grp_constr),
+ objectives=list(ret_obj),
+ optimize_method="random",
+ search_size=2000,
+ trace=TRUE)
+optrp1
+
+optrp2 <- optimize.portfolio(R=ret, portfolio=pspec,
+ constraints=list(lev_constr, lo_constr, exp_constr),
+ objectives=list(ret_obj),
+ optimize_method="random",
+ search_size=2000,
+ trace=TRUE)
+optrp2
+
+all.equal(optrp1$weights, optrp2$weights)
\ No newline at end of file
Copied: pkg/PortfolioAnalytics/demo/demo_group_ROI.R (from rev 3022, pkg/PortfolioAnalytics/sandbox/testing_group_multlevels.R)
===================================================================
--- pkg/PortfolioAnalytics/demo/demo_group_ROI.R (rev 0)
+++ pkg/PortfolioAnalytics/demo/demo_group_ROI.R 2013-09-09 21:27:22 UTC (rev 3037)
@@ -0,0 +1,42 @@
+
+library(PortfolioAnalytics)
+library(ROI)
+library(ROI.plugin.quadprog)
+library(ROI.plugin.quadprog)
+
+
+data(edhec)
+R <- edhec[, 1:4]
+colnames(R) <- c("CA", "CTAG", "DS", "EM")
+funds <- colnames(R)
+
+# set up portfolio with objectives and constraints
+pspec <- portfolio.spec(assets=funds)
+pspec <- add.constraint(portfolio=pspec, type="full_investment")
+pspec <- add.constraint(portfolio=pspec, type="long_only")
+# add two levels of grouping
+pspec <- add.constraint(portfolio=pspec, type="group",
+ groups=list(groupA=c(1, 3),
+ groupB=c(2, 4),
+ geoA=c(1, 2, 4),
+ geoB=3),
+ group_min=c(0.15, 0.25, 0.15, 0.2),
+ group_max=c(0.4, 0.7, 0.8, 0.62))
+pspec
+
+maxret <- add.objective(portfolio=pspec, type="return", name="mean")
+opt_maxret <- optimize.portfolio(R=R, portfolio=maxret, optimize_method="ROI")
+summary(opt_maxret)
+
+minvar <- add.objective(portfolio=pspec, type="risk", name="var")
+opt_minvar <- optimize.portfolio(R=R, portfolio=minvar, optimize_method="ROI")
+summary(opt_minvar)
+
+minetl <- add.objective(portfolio=pspec, type="risk", name="ETL")
+opt_minetl <- optimize.portfolio(R=R, portfolio=minetl, optimize_method="ROI")
+summary(opt_minetl)
+
+maxqu <- add.objective(portfolio=pspec, type="return", name="mean")
+maxqu <- add.objective(portfolio=maxqu, type="risk", name="var", risk_aversion=0.25)
+opt_maxqu <- optimize.portfolio(R=R, portfolio=maxqu, optimize_method="ROI")
+summary(opt_maxqu)
Copied: pkg/PortfolioAnalytics/demo/demo_maxret_ROI.R (from rev 3022, pkg/PortfolioAnalytics/sandbox/testing_maxret_ROI.R)
===================================================================
--- pkg/PortfolioAnalytics/demo/demo_maxret_ROI.R (rev 0)
+++ pkg/PortfolioAnalytics/demo/demo_maxret_ROI.R 2013-09-09 21:27:22 UTC (rev 3037)
@@ -0,0 +1,56 @@
+library(PortfolioAnalytics)
+library(foreach)
+library(iterators)
+library(quadprog)
+library(Rglpk)
+library(ROI)
+require(ROI.plugin.glpk)
+require(ROI.plugin.quadprog)
+
+
+data(edhec)
+ret <- edhec[, 1:4]
+funds <- colnames(ret)
+
+##### Method 1 #####
+# Set up portfolio object with constraints and objectives to maximize return
+# using the portfolio object to add constraints and objectives
+pspec1 <- portfolio.spec(assets=funds)
+pspec1 <- add.constraint(portfolio=pspec1, type="full_investment")
+pspec1 <- add.constraint(portfolio=pspec1, type="box", min=0, max=0.65)
+pspec1 <- add.objective(portfolio=pspec1, type="return", name="mean")
+
+opt1 <- optimize.portfolio(R=ret, portfolio=pspec1, optimize_method="ROI")
+
+##### Method 2 #####
+# Set up portfolio object with constraints and objective to maximize return
+# using separate constraint and objective objects
+pspec2 <- portfolio.spec(assets=funds)
+weight_constr <- weight_sum_constraint(min_sum=1, max_sum=1)
+box_constr <- box_constraint(assets=pspec2$assets, min=0, max=0.65)
+ret_obj <- return_objective(name="mean")
+cset <- list(weight_constr, box_constr)
+obj <- list(ret_obj)
+
+opt2 <- optimize.portfolio(R=ret, portfolio=pspec2, constraints=cset,
+ objectives=obj, optimize_method="ROI")
+
+all.equal(extractWeights(opt1), extractWeights(opt2))
+
+##### Method 1 Backtesting #####
+opt_rebal1 <- optimize.portfolio.rebalancing(R=ret, portfolio=pspec1,
+ optimize_method="ROI",
+ rebalance_on="months")
+class(opt_rebal1)
+inherits(opt_rebal1, "optimize.portfolio.rebalancing")
+wts1 <- extractWeights(opt_rebal1)
+
+##### Method 2 Backtesting #####
+opt_rebal2 <- optimize.portfolio.rebalancing(R=ret, portfolio=pspec2,
+ constraints=cset,
+ objectives=obj,
+ optimize_method="ROI",
+ rebalance_on="months")
+wts2 <- extractWeights(opt_rebal2)
+all.equal(wts1, wts2)
+
Copied: pkg/PortfolioAnalytics/demo/demo_opt_combine.R (from rev 3026, pkg/PortfolioAnalytics/sandbox/testing_mult_opt_weights.R)
===================================================================
--- pkg/PortfolioAnalytics/demo/demo_opt_combine.R (rev 0)
+++ pkg/PortfolioAnalytics/demo/demo_opt_combine.R 2013-09-09 21:27:22 UTC (rev 3037)
@@ -0,0 +1,47 @@
+
+library(PortfolioAnalytics)
+library(ROI)
+library(ROI.plugin.glpk)
+library(ROI.plugin.quadprog)
+
+# We should be able to compare portfolios with different constraints,
+# objectives, and number of assets
+
+data(edhec)
+R <- edhec[, 1:4]
+funds <- colnames(R)
+
+##### Construct Portfolios #####
+# GMV long only
+port.gmv.lo <- portfolio.spec(assets=funds)
+port.gmv.lo <- add.constraint(portfolio=port.gmv.lo, type="full_investment")
+port.gmv.lo <- add.constraint(portfolio=port.gmv.lo, type="long_only")
+port.gmv.lo <- add.objective(portfolio=port.gmv.lo, type="risk", name="var")
+
+# GMV with shorting
+port.gmv.short <- portfolio.spec(assets=funds)
+port.gmv.short <- add.constraint(portfolio=port.gmv.short, type="full_investment")
+port.gmv.short <- add.constraint(portfolio=port.gmv.short, type="box", min=-0.3, max=1)
+port.gmv.short <- add.objective(portfolio=port.gmv.short, type="risk", name="var")
+
+# QU box constraints
+port.qu <- portfolio.spec(assets=funds)
+port.qu <- add.constraint(portfolio=port.qu, type="full_investment")
+port.qu <- add.constraint(portfolio=port.qu, type="box", min=0.05, max=0.6)
+port.qu <- add.objective(portfolio=port.qu, type="risk", name="var", risk_aversion=0.25)
+port.qu <- add.objective(portfolio=port.qu, type="return", name="mean")
+
+##### Run Optimizations #####
+opt.gmv.lo <- optimize.portfolio(R=R, portfolio=port.gmv.lo, optimize_method="ROI", trace=TRUE)
+opt.gmv.short <- optimize.portfolio(R=R, portfolio=port.gmv.short, optimize_method="ROI", trace=TRUE)
+opt.qu <- optimize.portfolio(R=R, portfolio=port.qu, optimize_method="ROI", trace=TRUE)
+
+
+opt <- optimizations.combine(list(GMV.LO=opt.gmv.lo, GMV.SHORT=opt.gmv.short, QU=opt.qu))
+class(opt)
+
+chart.Weights(opt, legend.loc="topleft", cex.legend=0.8, ylim=c(-0.3, 1))
+
+chart.Weights(opt, plot.type="bar", cex.lab=0.8, legend.loc="topleft", cex.legend=0.8, ylim=c(-0.3, 1))
+
+extractWeights(opt)
Copied: pkg/PortfolioAnalytics/demo/demo_random_portfolios.R (from rev 3022, pkg/PortfolioAnalytics/sandbox/testing_rp_opt_script.R)
===================================================================
--- pkg/PortfolioAnalytics/demo/demo_random_portfolios.R (rev 0)
+++ pkg/PortfolioAnalytics/demo/demo_random_portfolios.R 2013-09-09 21:27:22 UTC (rev 3037)
@@ -0,0 +1,211 @@
+# Demonstrate examples from script.workshop2012.R using the v2 specification
+
[TRUNCATED]
To get the complete diff run:
svnlook diff /svnroot/returnanalytics -r 3037
More information about the Returnanalytics-commits
mailing list