[Returnanalytics-commits] r3347 - in pkg/PortfolioAnalytics/sandbox/RFinance2014: . R

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Sun Apr 6 02:07:28 CEST 2014


Author: rossbennett34
Date: 2014-04-06 02:07:26 +0200 (Sun, 06 Apr 2014)
New Revision: 3347

Added:
   pkg/PortfolioAnalytics/sandbox/RFinance2014/R/
   pkg/PortfolioAnalytics/sandbox/RFinance2014/R/lwShrink.R
Modified:
   pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R
   pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd
   pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.html
   pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.md
   pkg/PortfolioAnalytics/sandbox/RFinance2014/slides.pdf
Log:
Updating optimization script with new examples and data

Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/R/lwShrink.R
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/R/lwShrink.R	                        (rev 0)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/R/lwShrink.R	2014-04-06 00:07:26 UTC (rev 3347)
@@ -0,0 +1,54 @@
+lwShrink <- function(x, shrink=NULL){
+  # port of matlab code from http://www.econ.uzh.ch/faculty/wolf/publications.html#9
+  # Ledoit, O. and Wolf, M. (2004).
+  # Honey, I shrunk the sample covariance matrix.
+  # Journal of Portfolio Management 30, Volume 4, 110-119.
+  
+  # De-mean returns
+  n <- nrow(x)
+  p <- ncol(x)
+  meanx <- colMeans(x)
+  x <- x - matrix(rep(meanx, n), ncol=p, byrow=TRUE)
+  
+  # Compute sample covariance matrix using the de-meaned returns
+  sample <- (1 / n) * (t(x) %*% x)
+  
+  # Compute prior
+  var <- matrix(diag(sample), ncol=1)
+  sqrtvar <- sqrt(var)
+  tmpMat <- matrix(rep(sqrtvar, p), nrow=p)
+  rBar <- (sum(sum(sample / (tmpMat * t(tmpMat)))) - p) / (p * (p - 1))
+  prior <- rBar * tmpMat * t(tmpMat)
+  diag(prior) <- var
+  
+  if(is.null(shrink)){
+    # What is called pi-hat
+    y <- x^2
+    phiMat <- t(y) %*% y / n - 2 * (t(x) %*% x) * sample / n + sample^2
+    phi <- sum(phiMat)
+    
+    # What is called rho-hat
+    term1 <- (t(x^3) %*% x) / n
+    help <- t(x) %*% x / n
+    helpDiag <- matrix(diag(help), ncol=1)
+    term2 <- matrix(rep(helpDiag, p), ncol=p, byrow=FALSE) * sample
+    term3 <- help * matrix(rep(var, p), ncol=p, byrow=FALSE)
+    term4 <- matrix(rep(var, p), ncol=p, byrow=FALSE) * sample
+    thetaMat <- term1 - term2 - term3 + term4
+    diag(thetaMat) <- 0
+    rho <- sum(diag(phiMat)) + rBar * sum(sum(((1 / sqrtvar) %*% t(sqrtvar)) * thetaMat))
+    
+    # What is called gamma-hat
+    gamma <- norm(sample - prior, "F")^2
+    
+    # Compute shrinkage constant
+    kappa <- (phi - rho) / gamma
+    shrinkage <- max(0, min(1, kappa / n))
+  } else {
+    shrinkage <- shrink
+  }
+  # Compute the estimator
+  sigma <- shrinkage * prior + (1 - shrinkage) * sample
+  out <- list(cov=sigma, prior=prior, shrinkage=shrinkage)
+  return(out)
+}

Modified: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R	2014-04-03 18:33:08 UTC (rev 3346)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R	2014-04-06 00:07:26 UTC (rev 3347)
@@ -1,222 +1,264 @@
 # script used to run the portfolio optimizations
 
+# Examples to consider
+# Example 1: Consider a portfolio of stocks. Full investment and long 
+# only (or box) constraints. Objective to minimize portfolio variance. 
+# Demonstrate a custom moments function to compare a sample covariance 
+# matrix estimate and a robust covariance matrix estimate. An alternative 
+# to a MCD estimate is ledoit-wolf shrinkage, DCC GARCH model, 
+# factor model, etc.
+
+# Example 2: Consider a portfolio of stocks. Dollar neutral, beta
+# neutral, box constraints, and leverage_exposure constraints. Objective
+# to minimize portfolio StdDev. This will demonstrate some of the 
+# more advanced constraint types. Could also introduce position limit
+# constraints here in this example. 
+
+# Example 3: Consider an allocation to hedge funds using the 
+# EDHEC-Risk Alternative Index as a proxy. This will be an extended
+# example starting with an objective to minimize portfolio expected
+# shortfall, then risk budget percent contribution limit, then equal 
+# risk contribution limit. 
+
+# Example 4: Consider an allocation to hedge funds using the 
+# EDHEC-Risk Alternative Index as a proxy. 
+
+# Option 1 for example 4
+# Objective to maximize a risk adjusted return measure 
+# (e.g.Calmar Ratio, Sterling Ratio, Sortino Ratio, or Upside Potential 
+# Ratio)
+
+# I prefer doing this option
+# Option 2 for example 4
+# Objective to maximize the
+# fourth order expansion of the Constant Relative Risk Aversion (CRRA)
+# expected utility function. Demonstrate a custom moment function and
+# a custom objective function.
+
+# Load the packages
 library(PortfolioAnalytics)
+library(foreach)
+library(ROI)
+library(ROI.plugin.quadprog)
+library(ROI.plugin.glpk)
+
+# Source in the lwShrink function
+source("R/lwShrink.R")
+
+# Example 1 and Example 2 will use the crsp_weekly data
+# load the CRSP weekly data
+load("data/crsp_weekly.rda")
+
+# Example 3 and Example 4 will use the edhec data
 # Load the updated edhec dataset
 load("data/edhec.rda")
 
-# For now, use the first 8
-R <- edhec[,1:8]
-# Abreviate column names for convenience and plotting
-colnames(R) <- c("CA", "CTAG", "DS", "EM", "EQN", "ED", "FA", "GM")
-funds <- colnames(R)
 
-# Example 1
-# Box constraints, minimum variance portfolio
-# specify portfolio
-init <- portfolio.spec(funds)
+# Prep data for Examples 1 and 2
+# use the first 10 stocks in largecap_weekly, midcap_weekly, and smallcap_weekly
+N <- 10
+equity.data <- cbind(largecap_weekly[,1:N], 
+                     midcap_weekly[,1:N], 
+                     smallcap_weekly[,1:N])
+market <- largecap_weekly[,21]
+Rf <- largecap_weekly[,22]
+stocks <- colnames(equity.data)
 
+# Specify an initial portfolio
+portf.init <- portfolio.spec(stocks)
+
+##### Example 1 #####
 # Add constraints
-port1 <- add.constraint(init, type="full_investment")
-port1 <- add.constraint(port1, type="box", min=0.05, max=0.6)
+# 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)
 
 # Add objective
-port1 <- add.objective(port1, type="risk", name="var")
+# objective to minimize portfolio variance
+portf.minvar <- add.objective(portf.minvar, type="risk", name="var")
 
-# Custom moment function to use 
-robust.sigma <- function(R, ...){
-  out <- list()
-  set.seed(1234)
-  out$sigma <- MASS::cov.rob(R, method="mcd", ...)$cov
-  return(out)
-}
-
 # Rebalancing parameters
 # Set rebalancing frequency
 rebal.freq <- "quarters"
 # Training Period
-training <- 120
+training <- 400
 # Trailing Period
-trailing <- 72
+trailing <- 250
 
 # Run optimization
 # Sample Covariance Matrix Estimate
-opt.minVarSample <- optimize.portfolio.rebalancing(R, port1, 
-                                                   optimize_method="ROI", 
-                                                   rebalance_on=rebal.freq, 
-                                                   training_period=training, 
-                                                   trailing_periods=trailing)
-ret.minVarSample <- summary(opt.minVarSample)$portfolio_returns
 
+# By default, momentFUN uses set.portfolio.moments which computes the sample
+# moment estimates
 
-# MCD Covarinace Matrix Estimate
-opt.minVarRobust <- optimize.portfolio.rebalancing(R, port1, 
+opt.minVarSample <- optimize.portfolio.rebalancing(equity.data, portf.minvar, 
                                                    optimize_method="ROI", 
-                                                   momentFUN=robust.sigma,
                                                    rebalance_on=rebal.freq, 
                                                    training_period=training, 
                                                    trailing_periods=trailing)
 
-# Chart the weights
-chart.Weights(opt.minVarSample, main="minVarSample Weights")
-chart.Weights(opt.minVarRobust, main="minVarRobust Weights")
-
-# Calculate the turnover per period
-turnover.rebalancing <- function(object){
-  weights <- extractWeights(object)
-  n <- nrow(weights)
-  out <- vector("numeric", n)
-  out[1] <- NA
-  for(i in 2:n){
-    out[i] <- out[i] <- sum(abs(as.numeric(weights[i,]) - as.numeric(weights[i-1,])))
-  }
-  xts(out, index(weights))
+# Custom moment function to use Ledoit-Wolf shinkage covariance matrix estimate
+lw.sigma <- function(R, ...){
+  out <- list()
+  # estimate covariance matrix via robust covariance matrix estimate, 
+  # ledoit-wolf shrinkage, GARCH, factor model, etc.
+  # set.seed(1234)
+  # out$sigma <- MASS::cov.rob(R, method="mcd", ...)$cov
+  out$sigma <- lwShrink(R)$cov
+  #print(index(last(R)))
+  return(out)
 }
 
-# Compute the average turnover
-to.minVarSample <- mean(turnover.rebalancing(opt.minVarSample), na.rm=TRUE)
-to.minVarRobust <- mean(turnover.rebalancing(opt.minVarRobust), na.rm=TRUE)
+# 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)
 
+# Chart the weights
+chart.Weights(opt.minVarSample, main="minVarSample Weights")
+chart.Weights(opt.minVarLW, main="minVarLW Weights")
 
-# Calculate the diversification per period
-diversification.rebalancing <- function(object){
-  weights <- extractWeights(object)
-  n <- nrow(weights)
-  out <- vector("numeric", n)
-  for(i in 1:n){
-    out[i] <- 1 - sum(weights[i,]^2)
-  }
-  xts(out, index(weights))
-}
-
-# Compute the average diversification
-div.minVarSample <- mean(diversification.rebalancing(opt.minVarSample))
-div.minVarRobust <- mean(diversification.rebalancing(opt.minVarRobust))
-
-# Compute the returns
+# Compute and chart the returns
 ret.minVarSample <- summary(opt.minVarSample)$portfolio_returns
-ret.minVarRobust <- summary(opt.minVarRobust)$portfolio_returns
+ret.minVarRobust <- summary(opt.minVarLW)$portfolio_returns
 ret.minVar <- cbind(ret.minVarSample, ret.minVarRobust)
-colnames(ret.minVar) <- c("Sample", "Robust")
+colnames(ret.minVar) <- c("Sample", "LW")
 charts.PerformanceSummary(ret.minVar)
 
-## Example 2
+##### Example 2 #####
+portf.init <- portfolio.spec(stocks, 
+                             weight_seq=generatesequence(min=-0.2, max=0.2, by=0.001))
 
-# Example 2 will consider three portfolios
-# - meanES
-# - meanES with 30% component contribution limit
-# - meanES equal risk contribution
+# weights sum to 0
+portf.dn <- add.constraint(portf.init, type="weight_sum", 
+                                  min_sum=-0.01, max_sum=0.01)
+# box constraints such that no stock has weight less than -20% or greater than 20%
+portf.dn <- add.constraint(portf.dn, type="box", 
+                                  min=-0.2, max=0.2)
+# maximum of 20 non-zero positions
+portf.dn <- add.constraint(portf.dn, type="position_limit", max_pos=20)
 
-# meanES
-# Add constraints
-port2 <- add.constraint(init, type="full_investment")
-port2 <- add.constraint(port2, type="box", min=0, max=0.6)
+# cov(equity.data[,1], market) / var(market)
+# coef(lm(equity.data ~ market))[2,]
+betas <- t(CAPM.beta(equity.data, market, Rf))
+portf.dn <- add.constraint(portf.dn, type="factor_exposure", B=betas, 
+                           lower=-0.5, upper=0.5)
+# portf.dn <- add.constraint(portf.dn, type="leverage_exposure", leverage=2)
 
-# Add objectives
-port2 <- add.objective(port2, type="return", name="mean")
-port2 <- add.objective(port2, type="risk", name="ES", 
-                       arguments=list(p=0.92, clean="boudt"))
+rp <- random_portfolios(portf.dn, 10000, eliminate=TRUE)
+dim(rp)
 
-opt.MeanES.ROI <- optimize.portfolio(R, port2, optimize_method="ROI", trace=TRUE)
-plot(opt.MeanES.ROI)
+# Add objective
+# objective to minimize portfolio variance
+portf.dn.StdDev <- add.objective(portf.dn, type="return", name="mean", 
+                                 target=0.001)
+portf.dn.StdDev <- add.objective(portf.dn.StdDev, type="risk", name="StdDev")
 
-# relax the constraints for random portfolio
-port2$constraints[[1]]$min_sum <- 0.99
-port2$constraints[[1]]$max_sum <- 1.01
+opt <- optimize.portfolio(equity.data, portf.dn.StdDev, 
+                          optimize_method="random", rp=rp,
+                          trace=TRUE)
+opt
 
-search.size <- 20000
+plot(opt, risk.col="StdDev", neighbors=10)
 
-set.seed(123)
-rp <- random_portfolios(port2, permutations=search.size)
+# chart.RiskReward(opt, risk.col="StdDev", neighbors=25)
+# chart.Weights(opt, plot.type="bar", legend.loc=NULL)
+# wts <- extractWeights(opt)
+# t(wts) %*% betas
+# sum(abs(wts))
+# sum(wts[wts > 0])
+# sum(wts[wts < 0])
+# sum(wts != 0)
 
-#set.seed(123)
-#rp1 <- random_portfolios(port2, permutations=search.size)
-#all.equal(rp, rp1)
+# Prep data for Examples 3 and 4
+# For now, use the first 8
+R <- edhec[,1:8]
+# Abreviate column names for convenience and plotting
+colnames(R) <- c("CA", "CTAG", "DS", "EM", "EQN", "ED", "FA", "GM")
+funds <- colnames(R)
 
+##### Example 3 #####
+# Example 3 will consider three portfolios
+# - minES
+# - minES with 30% component contribution limit
+# - minES with equal risk contribution
 
-opt.MeanES.RP <- optimize.portfolio(R, port2, optimize_method="random", 
-                                    rp=rp, trace=TRUE)
-#extractObjectiveMeasures(combine.optimizations(list(opt.MeanES.ROI, opt.MeanES.RP)))
-#extractWeights(combine.optimizations(list(opt.MeanES.ROI, opt.MeanES.RP)))
+portf.init <- portfolio.spec(funds)
+portf.init <- add.constraint(portf.init, type="weight_sum", 
+                             min_sum=0.99, max_sum=1.01)
 
-plot(opt.MeanES.RP, neighbors=25)
+portf.init <- add.constraint(portf.init, type="box", 
+                             min=0.05, max=0.4)
 
-# Calculate the component contribution to risk
-portContribES <- ES(R, p=0.92, portfolio_method="component", 
-                    weights=extractWeights(opt.MeanES.RP))
-portContribES$pct_contrib_MES
+# Set multiplier=0 so that it is calculated, but does not affect the optimization
+portf.init <- add.objective(portf.init, type="return", 
+                            name="mean", multiplier=0)
 
-# Now suppose we want to place limits on percent component contribution to risk
-port3 <- add.objective(port2, type="risk_budget", name="ES", 
-                       arguments=list(p=0.92, clean="boudt"), max_prisk=0.35)
+# Add objective to minimize expected shortfall
+portf.minES <- add.objective(portf.init, type="risk", name="ES")
 
-opt.MeanES.RB <- optimize.portfolio(R, port3, optimize_method="random", 
-                                   trace=TRUE, rp=rp)
-opt.MeanES.RB
+# Add objective to 
+portf.minES.RB <- add.objective(portf.minES, type="risk_budget", 
+                                name="ES", max_prisk=0.3)
 
-chart.RiskBudget(opt.MeanES.RB, risk.type="percentage", neighbors=25)
+portf.minES.EqRB <- add.objective(portf.minES, type="risk_budget", 
+                                  name="ES", min_concentration=TRUE)
 
+portf <- combine.portfolios(list(minES=portf.minES, 
+                                 minES.RB=portf.minES.RB, 
+                                 minES.EqRB=portf.minES.EqRB))
 
-port4 <- add.objective(port2, type="risk_budget", name="ES", 
-                       arguments=list(p=0.92, clean="boudt"), 
-                       min_concentration=TRUE)
-opt.MeanES.EqRB <- optimize.portfolio(R, port4, optimize_method="random", 
-                                   trace=TRUE, rp=rp)
-opt.MeanES.EqRB
-chart.RiskBudget(opt.MeanES.EqRB, risk.type="percentage", neighbors=25)
+opt.minES <- optimize.portfolio(R, portf, optimize_method="DEoptim", 
+                                search_size=2000, trace=TRUE, traceDE=0,
+                                message=TRUE)
 
-# plot
-# - opt.meanES.ROI
-# - opt.meanES.RP
-# - opt.meanES.RB
-# - opt.meanES.EqRB
+extractObjectiveMeasures(opt.minES)
 
-xtract <- extractStats(opt.MeanES.RP)
+xtract <- extractStats(opt.minES)
+str(xtract)
 
+# get the mean column from each element of the list
+xtract.mean <- unlist(lapply(xtract, function(x) x[,"mean"]))
+xtract.ES <- unlist(lapply(xtract, function(x) x[,"ES"]))
+
 # plot the feasible space
-par(mar=c(6,4,4,1)+0.1)
-plot(xtract[,"ES"], xtract[,"mean"], col="gray", 
+par(mar=c(7,4,4,1)+0.1)
+plot(xtract.ES, xtract.mean, col="gray", 
      xlab="ES", ylab="Mean",
-     xlim=c(0, max(xtract[,"ES"])))
+     xlim=c(0, max(xtract.ES)))
 
-# opt.MeanES.ROI
-points(x=opt.MeanES.ROI$objective_measures$ES,
-       y=opt.MeanES.ROI$objective_measures$mean,
-       pch=15, col="blue")
-text(x=opt.MeanES.ROI$objective_measures$ES,
-       y=opt.MeanES.ROI$objective_measures$mean,
-       labels="Mean ES ROI", pos=4, col="blue", cex=0.8)
-
-# opt.MeanES.RP
-points(x=opt.MeanES.RP$objective_measures$ES,
-       y=opt.MeanES.RP$objective_measures$mean,
+# min ES
+points(x=opt.minES[[1]]$objective_measures$ES,
+       y=opt.minES[[1]]$objective_measures$mean,
        pch=15, col="purple")
-text(x=opt.MeanES.RP$objective_measures$ES,
-     y=opt.MeanES.RP$objective_measures$mean,
-     labels="Mean ES RP", pos=1, col="purple", cex=0.8)
+text(x=opt.minES[[1]]$objective_measures$ES,
+     y=opt.minES[[1]]$objective_measures$mean,
+     labels="Min ES", pos=4, col="purple", cex=0.8)
 
-# opt.MeanES.RB
-points(x=opt.MeanES.RB$objective_measures$ES$MES,
-       y=opt.MeanES.RB$objective_measures$mean,
+# min ES with Risk Budget
+points(x=opt.minES[[2]]$objective_measures$ES$MES,
+       y=opt.minES[[2]]$objective_measures$mean,
        pch=15, col="black")
-text(x=opt.MeanES.RB$objective_measures$ES$MES,
-     y=opt.MeanES.RB$objective_measures$mean,
-     labels="Mean ES RB", pos=4, col="black", cex=0.8)
+text(x=opt.minES[[2]]$objective_measures$ES$MES,
+     y=opt.minES[[2]]$objective_measures$mean,
+     labels="Min ES RB", pos=4, col="black", cex=0.8)
 
 # opt.MeanES.EqRB
-points(x=opt.MeanES.EqRB$objective_measures$ES$MES,
-       y=opt.MeanES.EqRB$objective_measures$mean,
+points(x=opt.minES[[3]]$objective_measures$ES$MES,
+       y=opt.minES[[3]]$objective_measures$mean,
        pch=15, col="darkgreen")
-text(x=opt.MeanES.EqRB$objective_measures$ES$MES,
-     y=opt.MeanES.EqRB$objective_measures$mean,
-     labels="Mean ES EqRB", pos=4, col="darkgreen", cex=0.8)
+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)
 
 
-# Backtest these three portfolios
-# I'm going to add a risk budget object to port2 with multiplier=0 so that
-# it is calculated, but does not affect the optimization
-port2 <- add.objective(port2, name="ES", type="risk_budget", arguments=list(p=0.92), multiplier=0)
+chart.RiskBudget(opt.minES[[2]], risk.type="percentage", neighbors=10)
+chart.RiskBudget(opt.minES[[3]], risk.type="percentage", neighbors=10)
 
-
 # Rebalancing parameters
 # Set rebalancing frequency
 rebal.freq <- "quarters"
@@ -225,47 +267,46 @@
 # Trailing Period
 trailing <- 72
 
-bt.opt.MeanES <- optimize.portfolio.rebalancing(R, port2, rp=rp,
-                                                optimize_method="random", 
-                                                rebalance_on=rebal.freq, 
-                                                training_period=training, 
-                                                trailing_periods=trailing)
-chart.RiskBudget(bt.opt.MeanES, main="Mean ES", risk.type="percentage")
+# Backtest
+bt.opt.minES <- optimize.portfolio.rebalancing(R, portf,
+                                               optimize_method="DEoptim", 
+                                               rebalance_on=rebal.freq, 
+                                               training_period=training, 
+                                               trailing_periods=trailing,
+                                               traceDE=0, message=TRUE)
 
-bt.opt.MeanES.RB <- optimize.portfolio.rebalancing(R, port3, rp=rp,
-                                                   optimize_method="random", 
-                                                   rebalance_on=rebal.freq, 
-                                                   training_period=training, 
-                                                   trailing_periods=trailing)
-chart.RiskBudget(bt.opt.MeanES.RB, main="Mean-ES 30% Limit", 
-                 risk.type="percentage")
+##### Example 4 #####
 
 
-bt.opt.MeanES.EqRB <- optimize.portfolio.rebalancing(R, port4, rp=rp,
-                                                     optimize_method="random", 
-                                                     rebalance_on=rebal.freq, 
-                                                     training_period=training, 
-                                                     trailing_periods=trailing)
-chart.RiskBudget(bt.opt.MeanES.EqRB, main="Mean-ES Equal Risk", 
-                 risk.type="percentage")
-
-# pass in a portfolio.list instead of typing this 3 times
-
-# calculate the returns
-ret.MeanES <- summary(bt.opt.MeanES)$portfolio_returns
-ret.MeanES.RB <- summary(bt.opt.MeanES.RB)$portfolio_returns
-ret.MeanES.EqRB <- summary(bt.opt.MeanES.EqRB)$portfolio_returns
-
-# Combine the returns
-ret <- cbind(ret.MeanES, ret.MeanES.RB, ret.MeanES.EqRB)
-colnames(ret) <- c("Mean.ES", "MeanES.RB", "MeanES.EqRB")
-charts.PerformanceSummary(ret)
-
 # CRRA 4th order expansion expected utility
-# look in PerformanceAnalytics
+# PerformanceAnalytics for moments
 # M3.MM
 # M4.MM
 # StdDev.MM
 # skewness.MM
 # kurtosis.MM
 
+
+
+# # Calculate the turnover per period
+# turnover.rebalancing <- function(object){
+#   weights <- extractWeights(object)
+#   n <- nrow(weights)
+#   out <- vector("numeric", n)
+#   out[1] <- NA
+#   for(i in 2:n){
+#     out[i] <- out[i] <- sum(abs(as.numeric(weights[i,]) - as.numeric(weights[i-1,])))
+#   }
+#   xts(out, index(weights))
+# }
+# 
+# # Calculate the diversification per period
+# diversification.rebalancing <- function(object){
+#   weights <- extractWeights(object)
+#   n <- nrow(weights)
+#   out <- vector("numeric", n)
+#   for(i in 1:n){
+#     out[i] <- 1 - sum(weights[i,]^2)
+#   }
+#   xts(out, index(weights))
+# }

Modified: pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd	2014-04-03 18:33:08 UTC (rev 3346)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd	2014-04-06 00:07:26 UTC (rev 3347)
@@ -6,8 +6,8 @@
 toc: true
 ---
 
-```{r}
-libary(knitr)
+```{r, echo=FALSE}
+library(knitr)
 opts_chunk$set(fig.height=4.5, fig.cap="", tidy=FALSE, cache=TRUE)
 ```
 
@@ -91,9 +91,18 @@
 
 Specify a Portfolio --> Add Constraints --> Add Objectives --> Run Optimization --> Analyze Results
 
-# Examples
+<!---
+Describe each function:
+- portfolio.spec
+- add.constraint
+- add.objective
+- optimize.portfolio and optimize.portfolio.rebalancing
+Just give a general description of the functions to analyze results
+-->
 
-## Data
+# Data
+
+## Data Setup
 Here we will look at portfolio optimization in the context of portfolio of hedge funds
 
 * EDHEC-Risk Alternative Indexes
@@ -127,13 +136,18 @@
 # dev.off()
 ```
 
-## Specify a Portfolio Object
-```{r}
-args(portfolio.spec)
-```
+# Example 1
 
-```{r}
-init.portf <- portfolio.spec(colnames(R))
+## Minimum Variance Portfolio
+Set up portfolio to minimize variance
+```{r, eval=FALSE}
+# Specify initial portfolio
+init <- portfolio.spec(funds)
+# Add constraints
+port1 <- add.constraint(init, type="full_investment")
+port1 <- add.constraint(port1, type="box", min=0.05, max=0.6)
+# Add objective
+port1 <- add.objective(port1, type="risk", name="var")
 ```
 
 

Modified: pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.html
===================================================================
--- pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.html	2014-04-03 18:33:08 UTC (rev 3346)
+++ pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.html	2014-04-06 00:07:26 UTC (rev 3347)
@@ -135,10 +135,47 @@
 
 </style>
 
+<!-- Styles for R syntax highlighter -->
+<style type="text/css">
+   pre .operator,
+   pre .paren {
+     color: rgb(104, 118, 135)
+   }
 
+   pre .literal {
+     color: rgb(88, 72, 246)
+   }
 
+   pre .number {
+     color: rgb(0, 0, 205);
+   }
 
+   pre .comment {
+     color: rgb(76, 136, 107);
+   }
 
+   pre .keyword {
+     color: rgb(0, 0, 255);
+   }
+
+   pre .identifier {
+     color: rgb(0, 0, 0);
+   }
+
+   pre .string {
+     color: rgb(3, 106, 7);
+   }
+</style>
+
+<!-- R syntax highlighter -->
+<script type="text/javascript">
[TRUNCATED]

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


More information about the Returnanalytics-commits mailing list