[Returnanalytics-commits] r3377 - in pkg/PortfolioAnalytics/sandbox/RFinance2014: . R
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Sun Apr 27 04:53:28 CEST 2014
Author: rossbennett34
Date: 2014-04-27 04:53:24 +0200 (Sun, 27 Apr 2014)
New Revision: 3377
Added:
pkg/PortfolioAnalytics/sandbox/RFinance2014/R/charting.R
Modified:
pkg/PortfolioAnalytics/sandbox/RFinance2014/makefile
pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_analysis.R
pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R
pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd
pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.md
pkg/PortfolioAnalytics/sandbox/RFinance2014/slides.pdf
pkg/PortfolioAnalytics/sandbox/RFinance2014/slidy_presentation.html
Log:
Updating presentation
Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/R/charting.R
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/R/charting.R (rev 0)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/R/charting.R 2014-04-27 02:53:24 UTC (rev 3377)
@@ -0,0 +1,99 @@
+nvd3WeightsPlot <- function(object,
+ type=c("stackedAreaChart", "multiBarChart")
+ ){
+ type <- match.arg(type)
+
+ # extract the weights and turn into a data.frame
+ weights <- extractWeights(object)
+ weights.df <- reshape2::melt(
+ data.frame(date=format(index(weights)), weights),
+ id.vars = 1,
+ variable.name = "stock",
+ value.name = "weight"
+ )
+ weights.df$date <- as.Date(weights.df$date)
+
+ # plot
+ n1 <- rCharts::nPlot(
+ weight ~ date,
+ group = "stock",
+ data = weights.df,
+ type = type
+ )
+ n1$xAxis(
+ tickFormat = "#!function(d){
+ return d3.time.format('%b %Y')(new Date(d * 24 * 60 * 60 * 1000))
+ }!#"
+ )
+ n1$yAxis(
+ tickFormat = "#!function(d){
+ return d3.format('0.2%')(d)
+ }!#"
+ )
+ return(n1)
+}
+
+nvd3RiskPlot <- function(object,
+ type=c("stackedAreaChart", "multiBarChart")
+ ){
+ type <- match.arg(type)
+
+ # extract the risk budget pct_contrib and turn into a data.frame
+ tmp <- extractObjectiveMeasures(object)
+ rb <- tmp[,grep("pct_contrib", colnames(tmp))]
+ colnames(rb) <- gsub("^.*\\.", "", colnames(rb))
+ rb.df <- reshape2::melt(
+ data.frame(date=as.Date(format(index(rb))), rb),
+ id.vars = 1,
+ variable.name = "fund",
+ value.name = "risk"
+ )
+
+ # plot
+ n1 <- rCharts::nPlot(
+ risk ~ date,
+ group = "fund",
+ data = rb.df,
+ type = type
+ )
+ n1$xAxis(
+ tickFormat = "#!function(d){
+ return d3.time.format('%b %Y')(new Date(d * 24 * 60 * 60 * 1000))
+ }!#"
+ )
+ n1$yAxis(
+ tickFormat = "#!function(d){
+ return d3.format('0.2%')(d)
+ }!#"
+ )
+ return(n1)
+}
+
+# require(rCharts)
+# weights <- extractWeights(opt.minVarSample)
+# weights.df <- reshape2::melt(
+# data.frame(
+# date=format(index(weights)),
+# weights
+# ),
+# id.vars = 1,
+# variable.name = "stock",
+# value.name = "weight"
+# )
+#
+# d1 <- dPlot(
+# weight ~ date,
+# groups = "stock",
+# data = weights.df,
+# type = "bubble" #area, bar, or bubble
+# )
+# d1$xAxis(
+# type = "addTimeAxis",
+# inputFormat = "%Y-%m-%d",
+# outputFormat = "%b %Y"
+# )
+# d1$yAxis(
+# outputFormat = "0.2%",
+# orderBy = "weight"
+# )
+# d1
\ No newline at end of file
Modified: pkg/PortfolioAnalytics/sandbox/RFinance2014/makefile
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/makefile 2014-04-21 03:47:59 UTC (rev 3376)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/makefile 2014-04-27 02:53:24 UTC (rev 3377)
@@ -13,8 +13,12 @@
# Generate slidy presentation from markdown file
slidy_presentation.html: $(RFILES) $(OUT_FILES) presentation.md
- pandoc -t slidy -s presentation.md -o slidy_presentation.html
+ pandoc -t slidy -s --mathjax presentation.md -o slidy_presentation.html
+# Generate slidy presentation from markdown file
+slides.pdf: $(RFILES) $(OUT_FILES) presentation.md
+ pandoc -t -S beamer —-slide-level 2 presentation.md -o slides.pdf
+
# Generate markdown file from R markdown file
presentation.md: presentation.Rmd
Rscript -e "library(knitr); knit('presentation.Rmd')"
@@ -38,6 +42,9 @@
lwShrink.Rout: R/lwShrink.R
R CMD BATCH --vanilla R/lwShrink.R
+charting.Rout: R/charting.R
+ R CMD BATCH --vanilla R/charting.R
+
# Use Rscript to run the necessary R files as an alternative to R CMD BATCH
runR:
Rscript data_prep.R
@@ -52,4 +59,5 @@
rm -f optimization_results/*.rda
rm -f *.md
rm -f *.html
+ rm -f cache/*
\ No newline at end of file
Modified: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_analysis.R
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_analysis.R 2014-04-21 03:47:59 UTC (rev 3376)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_analysis.R 2014-04-27 02:53:24 UTC (rev 3377)
@@ -1,6 +1,8 @@
library(PortfolioAnalytics)
library(methods)
+source("R/charting.R")
+
# Set the directory where the optimization results are saved
results.dir <- "optimization_results"
figures.dir <- "optimization_figures"
@@ -15,10 +17,17 @@
chart.Weights(opt.minVarSample, main="minVarSample Weights", legend.loc=NULL)
dev.off()
+w1 <- nvd3WeightsPlot(opt.minVarSample)
+save(w1, file=paste(figures.dir, "w1.rda", sep="/"))
+
+
png(paste(figures.dir, "weights_minVarLW.png", sep="/"))
chart.Weights(opt.minVarLW, main="minVarLW Weights", legend.loc=NULL)
dev.off()
+w2 <- nvd3WeightsPlot(opt.minVarLW)
+save(w2, file=paste(figures.dir, "w2.rda", sep="/"))
+
# Compute the returns and chart the performance summary
ret.minVarSample <- summary(opt.minVarSample)$portfolio_returns
ret.minVarRobust <- summary(opt.minVarLW)$portfolio_returns
@@ -65,8 +74,9 @@
# plot the feasible space
par(mar=c(7,4,4,1)+0.1)
plot(xtract.ES, xtract.mean, col="gray",
+ main="Minimum ES Portfolios",
xlab="ES", ylab="Mean",
- ylim=c(0.005, 0.008),
+ ylim=c(0.005, 0.007),
xlim=c(0.015, 0.085))
# min ES
@@ -92,7 +102,7 @@
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)
-# par(mar=c(7,4,4,1)+0.1)
+par(mar=c(5,4,4,1)+0.1)
dev.off()
# Chart the risk contribution
@@ -146,6 +156,13 @@
charts.PerformanceSummary(ret.bt.opt)
dev.off()
+###
+# interactive plot of risk budgets through time using nvd3
+# nvd3RiskPlot(bt.opt.minES[[1]])
+# nvd3RiskPlot(bt.opt.minES[[2]])
+# nvd3RiskPlot(bt.opt.minES[[3]])
+###
+
##### Example 4 #####
load(file=paste(results.dir, "opt.crra.rda", sep="/"))
load(file=paste(results.dir, "bt.opt.crra.rda", sep="/"))
Modified: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R 2014-04-21 03:47:59 UTC (rev 3376)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R 2014-04-27 02:53:24 UTC (rev 3377)
@@ -62,8 +62,8 @@
# Add constraints
# weights sum to 1
portf.minvar <- add.constraint(portf.init, type="full_investment")
-# box constraints such that no stock has weight less than 1% or greater than 20%
-portf.minvar <- add.constraint(portf.minvar, type="box", min=0.01, max=0.2)
+# box constraints
+portf.minvar <- add.constraint(portf.minvar, type="box", min=0.01, max=0.45)
# Add objective
# objective to minimize portfolio variance
@@ -368,7 +368,15 @@
x.assets <- StdDev(R)
y.assets <- colMeans(R)
-
+ ###
+ # create an interactive plot using rCharts and nvd3 scatterChart
+ # tmp1 <- data.frame(name="sample", mean=rp1_mean, sd=rp1_StdDev)
+ # tmp2 <- data.frame(name="simplex", mean=rp2_mean, sd=rp2_StdDev)
+ # tmp3 <- data.frame(name="grid", mean=rp3_mean, sd=rp3_StdDev)
+ # tmp <- rbind(tmp1, tmp2, tmp3)
+ # n1 <- nPlot(mean ~ sd, group="name", data=tmp, type="scatterChart")
+ # n1
+ ###
x.lower <- min(x.assets) * 0.9
x.upper <- max(x.assets) * 1.1
y.lower <- min(y.assets) * 0.9
Modified: pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd 2014-04-21 03:47:59 UTC (rev 3376)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd 2014-04-27 02:53:24 UTC (rev 3377)
@@ -1,14 +1,32 @@
-% R/Finance 2014: Complex Portfolio Optimization with PortfolioAnalytics
-% Ross Bennett
-% May 16, 2014
+---
+title : Complex Portfolio Optimization with PortfolioAnalytics
+subtitle : R/Finance 2014
+author : Ross Bennett
+date : May 16, 2014
+---
-# Overview
+```{r, echo=FALSE, message=FALSE}
+library(PortfolioAnalytics)
+```
+
+
+## Overview
* Discuss Portfolio Optimization
* Introduce PortfolioAnalytics
* Demonstrate PortfolioAnalytics with Examples
-# Portfolio Optimization
+<!---
+Discuss Portfolio Optimization
+- Some background and theory of portfolio theory
+- challenges
+Introduce PortfolioAnalytics
+- What PortfolioAnalytics does and the problems it solves
+Demonstrate PortfolioAnalytics with Examples
+- Brief overview of the examples I will be giving
+-->
+---
+
## Modern Portfolio Theory
"Modern" Portfolio Theory (MPT) was introduced by Harry Markowitz in 1952.
@@ -22,9 +40,11 @@
How do we define risk? What about more complex objectives?
<!---
-Several approaches follow the Markowitz approach using mean return as a measure of gain and standard deviation of returns as a measure of risk
+Several approaches follow the Markowitz approach using mean return as a measure of gain and standard deviation of returns as a measure of risk.
-->
+---
+
## Portfolio Optimization Objectives
* Minimize Risk
* Volatility
@@ -43,10 +63,9 @@
The challenge here is knowing what solver to use and the capabilities/limits of the chosen solver. Talk about pros/cons of closed-form solvers vs. global solvers and what objectives can be solved.
-->
-# PortfolioAnalytics
+---
-## Overview
-
+## PortfolioAnalytics Overview
PortfolioAnalytics is an R package designed to provide numerical solutions and visualizations for portfolio optimization problems with complex constraints and objectives.
* Support for multiple constraint and objective types
@@ -69,9 +88,9 @@
- Periodic rebalancing and analyzing out of sample performance will help refine objectives and constraints
-->
+---
## Support Multiple Solvers
-
Linear and Quadratic Programming Solvers
* R Optimization Infrastructure (ROI)
@@ -90,6 +109,8 @@
Brief explanation of each solver and what optimization problems (constraints and objectives) are supported
-->
+---
+
## Random Portfolios
PortfolioAnalytics has three methods to generate random portfolios.
@@ -107,18 +128,25 @@
The grid method to generate random portfolios is based on the gridSearch function in NMOF package. The grid search method only satisfies the min and max box constraints. The min_sum and max_sum leverage constraint will likely be violated and the weights in the random portfolios should be normalized. Normalization may cause the box constraints to be violated and will be penalized in constrained_objective.
-->
+---
+
## Comparison of Random Portfolio Methods
![](optimization_figures/rp_plot.png)
+<!---
+This chart is a prime candidate for an interactive viz
+-->
+
+---
+
## Random Portfolios: Simplex Method
![](optimization_figures/fev_plot.png)
+---
## Workflow
-TODO: Add a nice graphic here (Guy might have one)
+![](misc_figures/workflow.png)
-Specify a Portfolio --> Add Constraints --> Add Objectives --> Run Optimization --> Analyze Results
-
<!---
Describe each function:
- portfolio.spec
@@ -128,10 +156,87 @@
Just give a general description of the functions to analyze results
-->
+---
-# Example 1
+## Workflow: Specify Portfolio
+```{r}
+args(portfolio.spec)
+```
-## Data Setup
+---
+
+## Workflow: Add Constraints
+```{r}
+args(add.constraint)
+```
+
+Supported Constraint Types
+
+* Sum of Weights
+* Box
+* Group
+* Turnover
+* Diversification
+* Position Limit
+* Return
+* Factor Exposure
+
+---
+
+## Workflow: Add Objectives
+```{r}
+args(add.objective)
+```
+
+Supported Objective types
+
+* Return
+* Risk
+* Risk Budget
+* Weight Concentration
+
+---
+
+## Workflow: Run Optimization
+```{r}
+args(optimize.portfolio)
+args(optimize.portfolio.rebalancing)
+```
+
+Supported Optimization Methods
+
+* ROI
+* random
+* DEoptim
+* pso
+* GenSA
+
+---
+
+## Workflow: Analyze Results
+
+Charting Functions
+
+* plot
+* chart.Concentration
+* chart.EfficientFrontier
+* chart.RiskBudget
+* chart.RiskReward
+* chart.Weights
+
+Extract Functions
+
+* extractObjectiveMeasures
+* extractStats
+* extractWeights
+
+<!---
+I'd like to make this a two column slide if possible. Might have to try slidify.
+-->
+
+---
+
+## Example 1: Data Setup
Here we will look at portfolio optimization in the context of stocks.
* Selection of large cap, mid cap, and small cap stocks from CRSP data
@@ -145,16 +250,26 @@
smallcap_weekly[,1:5])
```
+---
+
## Distribution of Monthly Returns
![](data_figures/equity_box.png)
+---
+
## Minimum Variance Portfolio
-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.
+Here we consider a portfolio of stocks. Our objective is 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.
+$$
+\min_{w} w^{T} \Sigma w
+$$
+
<!---
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.
-->
+---
+
## Specify Portfolio
```{r,eval=FALSE}
# Specify an initial portfolio
@@ -165,8 +280,8 @@
portf.minvar <- add.constraint(portf.init, type="full_investment")
# Add box constraint such that no asset can have a weight of greater than
-# 20% or less than 1%
-portf.minvar <- add.constraint(portf.minvar, type="box", min=0.01, max=0.2)
+# 45% or less than 1%
+portf.minvar <- add.constraint(portf.minvar, type="box", min=0.01, max=0.45)
# Add objective to minimize portfolio variance
portf.minvar <- add.objective(portf.minvar, type="risk", name="var")
@@ -176,6 +291,8 @@
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}
@@ -187,39 +304,32 @@
}
```
-## Backtesting Parameters
-```{r, eval=FALSE}
-# Set rebalancing frequency
-rebal.freq <- "quarters"
+---
-# Training Period
-training <- 400
-
-# Trailing Period
-trailing <- 250
-```
-<!---
-Explain each of the rebalancing parameters
--->
-
## Run Optimization
```{r, eval=FALSE, tidy=FALSE}
# Backtest using sample covariance matrix estimate
opt.minVarSample <- optimize.portfolio.rebalancing(equity.data, portf.minvar,
optimize_method="ROI",
- rebalance_on=rebal.freq,
- training_period=training,
- trailing_periods=trailing)
+ rebalance_on="quarters",
+ training_period=400,
+ trailing_periods=250)
# Backtest 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)
+ rebalance_on="quarters",
+ training_period=400,
+ trailing_periods=250)
```
+<!---
+Explain each of the rebalancing parameters
+-->
+
+---
+
## Chart Weights Through Time
```{r, eval=FALSE}
chart.Weights(opt.minVarSample, main="minVarSample Weights", legend.loc=NULL)
@@ -228,6 +338,8 @@
![](optimization_figures/weights_minVarSample.png)
![](optimization_figures/weights_minVarLW.png)
+---
+
## Returns
Compute the portfolio rebalancing returns and chart the performance.
```{r, eval=FALSE}
@@ -237,20 +349,20 @@
colnames(ret.minVar) <- c("Sample", "LW")
charts.PerformanceSummary(ret.minVar)
```
-
-## Performance Summary
![](optimization_figures/ret_minVar.png)
-# Example 2
+---
-## Market Neutral Portfolio
+## Example 2: Market Neutral Portfolio
Here we consider a portfolio of stocks. Our objective is to maximize portfolio return with a target of 0.0015 and minimize portfolio StdDev with a target of 0.02 subject to dollar neutral, beta, box, and position limit constraints. We will use the same data considered in Example 1.
<!---
-comments
+This involves combining several constraints. This is an MIQPQC problem that can't be solved by quadprog so we will use random portfolios.
-->
-## Specify Portfolio: Contraints
+---
+
+## Specify Portfolio: Constraints
```{r, eval=FALSE, tidy=FALSE}
portf.init <- portfolio.spec(stocks)
@@ -277,6 +389,8 @@
explain the constraints
-->
+---
+
## Specify Portfolio: Objectives
```{r,eval=FALSE, tidy=FALSE}
# Add objective to maximize portfolio return with a target of 0.0015
@@ -292,6 +406,8 @@
explain the objectives, specifically the target
-->
+---
+
## Run Optimization
```{r, eval=FALSE, tidy=FALSE}
# Generate random portfolios
@@ -307,16 +423,17 @@
generate a set of random portfolios and then pass directly to optimize.portfolio. Could just specify optimize_method = "random" and will automatically generate for you.
-->
+---
+
## Plot Results
```{r, eval=FALSE, tidy=FALSE}
plot(opt.dn, main="Dollar Neutral Portfolio", risk.col="StdDev", neighbors=10)
```
![](optimization_figures/opt_dn.png)
+---
-# Example 3
-
-## Data Setup
+## Example 3: Data Setup
Here we will look at portfolio optimization in the context of portfolio of hedge funds.
* EDHEC-Risk Alternative Indexes
@@ -328,7 +445,6 @@
* Emerging Markets (EM)
* Global Macro (GM)
-## Data
```{r, eval=FALSE, tidy=FALSE}
R <- edhec[,c("Convertible.Arbitrage", "Equity.Market.Neutral",
"Fixed.Income.Arbitrage",
@@ -337,14 +453,18 @@
colnames(R) <- c("CA", "EMN", "FIA", "CTAG", "EM", "GM")
```
+---
+
## Monthly Returns
![](data_figures/relative_barvar.png)
![](data_figures/directional_barvar.png)
+---
## Distribution of Monthly Returns
![](data_figures/edhec_box.png)
+---
## 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 modified expected shortfall, then add risk budget percent contribution limit, and finally add equal risk contribution limit.
@@ -353,12 +473,16 @@
* 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 x_i^2$
+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 $$
+
<!---
comments
-->
+---
+
## Specify Initial Portfolio
```{r, eval=FALSE, tidy=FALSE}
# Specify an initial portfolio
@@ -384,6 +508,8 @@
basic comments about setting up an initial portfolio
-->
+---
+
## Add Objectives
```{r, eval=FALSE, tidy=FALSE}
# Add objective to minimize expected shortfall
@@ -407,6 +533,7 @@
Key points here are that we are creating 3 new portfolios by reusing the initial portfolio and we are relaxing the box constraints because we are no longer concerned with controlling weight concentration. We have limits on risk contribution.
-->
+---
## Run Optimization
```{r, eval=FALSE, tidy=FALSE}
@@ -424,9 +551,13 @@
explain how portf is a list of portfolios and passed to optimize.portfolio
-->
+---
+
## Plot in Risk-Return Space
![](optimization_figures/opt_minES.png)
+---
+
## Chart Risk Budgets
```{r, eval=FALSE, tidy=FALSE}
chart.RiskBudget(opt.minES[[2]], main="Risk Budget Limit",
@@ -438,6 +569,8 @@
![](optimization_figures/rb_minES.png)
![](optimization_figures/eqrb_minES.png)
+---
+
## Set Rebalancing Parameters and Run Backtest
```{r, eval=FALSE, tidy=FALSE}
# Set rebalancing frequency
@@ -458,18 +591,25 @@
traceDE=0)
```
+---
+
## Min ES Risk Contributions and Weights Through Time
![](optimization_figures/risk_minES.png)
![](optimization_figures/weights_minES.png)
+---
+
## Min ES Risk Budget Limit Risk Contributions and Weights Through Time
![](optimization_figures/risk_minESRB.png)
![](optimization_figures/weights_minESRB.png)
+---
+
## Min ES Equal Component Contribution Risk Contributions and Weights Through Time
![](optimization_figures/risk_minESEqRB.png)
![](optimization_figures/weights_minESEqRB.png)
+---
## Compute Returns and Chart Performance
```{r, eval=FALSE, tidy=FALSE}
@@ -480,18 +620,23 @@
```
![](optimization_figures/ret_minES.png)
+---
-# Example 4
-
-## Maximize CRRA
+## Example 4: Maximize CRRA
Consider an allocation to hedge funds using the EDHEC-Risk Alternative Index as a proxy. Our objective to maximize the fourth order expansion of the Constant Relative Risk Aversion (CRRA) expected utility function as in the Boudt paper and Martinelli paper. We use the same data as Example 3.
-TODO: Add equation
+$$
+EU_{\lambda}(w) = - \frac{\lambda}{2} m_{(2)}(w) +
+\frac{\lambda (\lambda + 1)}{6} m_{(3)}(w) -
+\frac{\lambda (\lambda + 1) (\lambda + 2)}{24} m_{(4)}(w)
+$$
<!---
Demonstrate a custom moment function and a custom objective function.
-->
+---
+
## Define a function to compute CRRA
```{r, eval=FALSE, tidy=FALSE}
CRRA <- function(R, weights, lambda, sigma, m3, m4){
@@ -511,6 +656,8 @@
The function arguments should have 'R' as the name of the returns and 'weights' as the name of the weights. 'R' and 'weights' are automatically matched, any other function arguments can be passed in through arguments in add.objective.
-->
+---
+
## Specify Portfolio
```{r, eval=FALSE, tidy=FALSE}
# Specify portfolio
@@ -528,12 +675,20 @@
# Add objective to maximize CRRA
portf.crra <- add.objective(portf.crra, type="return",
name="CRRA", arguments=list(lambda=10))
+
+# I just want these for plotting
+# Set multiplier=0 so that it is calculated, but does not affect the optimization
+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)
```
<!---
Focus on how CRRA is added as an objective
-->
+---
+
## Run Optimization
```{r, eval=FALSE, tidy=FALSE}
opt.crra <- optimize.portfolio(R, portf.crra, optimize_method="DEoptim",
@@ -541,14 +696,31 @@
momentFUN="crra.moments")
```
+```{r, echo=FALSE}
+load("optimization_results/opt.crra.rda")
+```
+```{r, tidy=FALSE, cache=TRUE}
+opt.crra
+```
+
+
<!---
remember to specify a momentFUN to match the arguments in CRRA
-->
+---
+
## Chart Results
+```{r, eval=FALSE}
+chart.RiskReward(opt.crra, risk.col="ES")
+chart.RiskReward(opt.crra, risk.col="StdDev")
+```
+
![](optimization_figures/crra_RR_ES.png)
![](optimization_figures/crra_RR_StdDev.png)
+---
+
## Run Backtest and Compute Returns
```{r, eval=FALSE, tidy=FALSE}
bt.opt.crra <- optimize.portfolio.rebalancing(R, portf.crra,
@@ -568,6 +740,8 @@
Run optimization and extract the portfolio rebalancing returns from the summary method
-->
+---
+
## Chart Performance
```{r, eval=FALSE, tidy=FALSE}
charts.PerformanceSummary(cbind(ret.bt.opt, ret.crra),
@@ -575,8 +749,14 @@
```
![](optimization_figures/ret_crra.png)
-# Conclusion
+---
+## Conclusion
+TODO
+
+* Overview of what was covered
+* Additional information and plans for PortfolioAnalytics
+
## Acknowledgements
Many thanks to
@@ -591,7 +771,10 @@
- Google for funding the Google Summer of Code for PortfolioAnalytics and many other proposals for R
-->
-## References
+---
+
+## References and Useful Links
+
* [ROI](http://cran.r-project.org/web/packages/ROI/index.html)
* [DEoptim](http://cran.r-project.org/web/packages/DEoptim/index.html)
* [pso](http://cran.r-project.org/web/packages/pso/index.html)
@@ -602,4 +785,4 @@
* Martinelli paper
* Boudt paper
* [PortfolioAnalytics on R-Forge](https://r-forge.r-project.org/projects/returnanalytics/)
-* Shiny App?
+* [Shiny App](http://spark.rstudio.com/rossbennett3/PortfolioOptimization/)
Modified: pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.md
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.md 2014-04-21 03:47:59 UTC (rev 3376)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.md 2014-04-27 02:53:24 UTC (rev 3377)
@@ -1,14 +1,31 @@
-% R/Finance 2014: Complex Portfolio Optimization with PortfolioAnalytics
-% Ross Bennett
-% May 16, 2014
+---
+title : Complex Portfolio Optimization with PortfolioAnalytics
+subtitle : R/Finance 2014
+author : Ross Bennett
+date : May 16, 2014
+---
-# Overview
+
+
+
+
+## Overview
* Discuss Portfolio Optimization
* Introduce PortfolioAnalytics
* Demonstrate PortfolioAnalytics with Examples
-# Portfolio Optimization
+<!---
+Discuss Portfolio Optimization
+- Some background and theory of portfolio theory
+- challenges
+Introduce PortfolioAnalytics
+- What PortfolioAnalytics does and the problems it solves
+Demonstrate PortfolioAnalytics with Examples
+- Brief overview of the examples I will be giving
+-->
+---
+
## Modern Portfolio Theory
"Modern" Portfolio Theory (MPT) was introduced by Harry Markowitz in 1952.
@@ -22,9 +39,11 @@
How do we define risk? What about more complex objectives?
<!---
-Several approaches follow the Markowitz approach using mean return as a measure of gain and standard deviation of returns as a measure of risk
+Several approaches follow the Markowitz approach using mean return as a measure of gain and standard deviation of returns as a measure of risk.
-->
+---
+
## Portfolio Optimization Objectives
* Minimize Risk
* Volatility
@@ -43,10 +62,9 @@
The challenge here is knowing what solver to use and the capabilities/limits of the chosen solver. Talk about pros/cons of closed-form solvers vs. global solvers and what objectives can be solved.
-->
-# PortfolioAnalytics
+---
-## Overview
-
+## PortfolioAnalytics Overview
PortfolioAnalytics is an R package designed to provide numerical solutions and visualizations for portfolio optimization problems with complex constraints and objectives.
* Support for multiple constraint and objective types
@@ -69,9 +87,9 @@
- Periodic rebalancing and analyzing out of sample performance will help refine objectives and constraints
-->
+---
## Support Multiple Solvers
-
Linear and Quadratic Programming Solvers
* R Optimization Infrastructure (ROI)
@@ -90,6 +108,8 @@
Brief explanation of each solver and what optimization problems (constraints and objectives) are supported
-->
+---
+
## Random Portfolios
PortfolioAnalytics has three methods to generate random portfolios.
@@ -107,18 +127,25 @@
The grid method to generate random portfolios is based on the gridSearch function in NMOF package. The grid search method only satisfies the min and max box constraints. The min_sum and max_sum leverage constraint will likely be violated and the weights in the random portfolios should be normalized. Normalization may cause the box constraints to be violated and will be penalized in constrained_objective.
-->
+---
+
## Comparison of Random Portfolio Methods
![](optimization_figures/rp_plot.png)
+<!---
+This chart is a prime candidate for an interactive viz
+-->
+
+---
+
## Random Portfolios: Simplex Method
![](optimization_figures/fev_plot.png)
+---
## Workflow
-TODO: Add a nice graphic here (Guy might have one)
+![](misc_figures/workflow.png)
-Specify a Portfolio --> Add Constraints --> Add Objectives --> Run Optimization --> Analyze Results
-
<!---
Describe each function:
- portfolio.spec
@@ -128,10 +155,132 @@
Just give a general description of the functions to analyze results
-->
+---
-# Example 1
+## Workflow: Specify Portfolio
-## Data Setup
+```r
+args(portfolio.spec)
+```
+
+```
+## function (assets = NULL, category_labels = NULL, weight_seq = NULL,
+## message = FALSE)
+## NULL
+```
+
+
+---
+
+## Workflow: Add Constraints
+
+```r
+args(add.constraint)
+```
+
+```
+## function (portfolio, type, enabled = TRUE, message = FALSE, ...,
+## indexnum = NULL)
+## NULL
+```
+
+
+Supported Constraint Types
+
+* Sum of Weights
+* Box
+* Group
+* Turnover
+* Diversification
+* Position Limit
+* Return
+* Factor Exposure
+
+---
+
+## Workflow: Add Objectives
+
+```r
+args(add.objective)
+```
+
+```
+## function (portfolio, constraints = NULL, type, name, arguments = NULL,
+## enabled = TRUE, ..., indexnum = NULL)
+## NULL
+```
+
+
+Supported Objective types
+
+* Return
+* Risk
+* Risk Budget
+* Weight Concentration
+
+---
+
+## Workflow: Run Optimization
+
+```r
+args(optimize.portfolio)
+```
+
+```
+## function (R, portfolio = NULL, constraints = NULL, objectives = NULL,
+## optimize_method = c("DEoptim", "random", "ROI", "pso", "GenSA"),
+## search_size = 20000, trace = FALSE, ..., rp = NULL, momentFUN = "set.portfolio.moments",
+## message = FALSE)
+## NULL
+```
+
+```r
+args(optimize.portfolio.rebalancing)
+```
+
+```
+## function (R, portfolio = NULL, constraints = NULL, objectives = NULL,
+## optimize_method = c("DEoptim", "random", "ROI"), search_size = 20000,
+## trace = FALSE, ..., rp = NULL, rebalance_on = NULL, training_period = NULL,
+## trailing_periods = NULL)
+## NULL
+```
+
+
+Supported Optimization Methods
+
+* ROI
+* random
+* DEoptim
+* pso
+* GenSA
+
+---
+
+## Workflow: Analyze Results
+
+Charting Functions
+
+* plot
+* chart.Concentration
+* chart.EfficientFrontier
+* chart.RiskBudget
+* chart.RiskReward
+* chart.Weights
+
+Extract Functions
+
+* extractObjectiveMeasures
+* extractStats
+* extractWeights
+
+<!---
+I'd like to make this a two column slide if possible. Might have to try slidify.
+-->
+
+---
+
+## Example 1: Data Setup
Here we will look at portfolio optimization in the context of stocks.
* Selection of large cap, mid cap, and small cap stocks from CRSP data
@@ -147,16 +296,26 @@
```
+---
+
## Distribution of Monthly Returns
![](data_figures/equity_box.png)
+---
+
## Minimum Variance Portfolio
-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.
+Here we consider a portfolio of stocks. Our objective is 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.
+$$
+\min_{w} w^{T} \Sigma w
+$$
+
<!---
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.
-->
+---
+
## Specify Portfolio
```r
@@ -168,8 +327,8 @@
portf.minvar <- add.constraint(portf.init, type = "full_investment")
# Add box constraint such that no asset can have a weight of greater than
-# 20% or less than 1%
-portf.minvar <- add.constraint(portf.minvar, type = "box", min = 0.01, max = 0.2)
+# 45% or less than 1%
+portf.minvar <- add.constraint(portf.minvar, type = "box", min = 0.01, max = 0.45)
# Add objective to minimize portfolio variance
portf.minvar <- add.objective(portf.minvar, type = "risk", name = "var")
@@ -180,6 +339,8 @@
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.
@@ -193,43 +354,34 @@
```
-## Backtesting Parameters
+---
-```r
-# Set rebalancing frequency
-rebal.freq <- "quarters"
-
-# Training Period
-training <- 400
-
-# Trailing Period
-trailing <- 250
-```
-
-<!---
-Explain each of the rebalancing parameters
--->
-
## Run Optimization
```r
# Backtest using sample covariance matrix estimate
opt.minVarSample <- optimize.portfolio.rebalancing(equity.data, portf.minvar,
optimize_method="ROI",
- rebalance_on=rebal.freq,
- training_period=training,
- trailing_periods=trailing)
+ rebalance_on="quarters",
+ training_period=400,
+ trailing_periods=250)
# Backtest using Ledoit-Wolf shrinkage covariance matrix estimate
[TRUNCATED]
To get the complete diff run:
svnlook diff /svnroot/returnanalytics -r 3377
More information about the Returnanalytics-commits
mailing list