[Returnanalytics-commits] r3055 - in pkg/Meucci: R data demo

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Wed Sep 11 12:09:49 CEST 2013


Author: xavierv
Date: 2013-09-11 12:09:49 +0200 (Wed, 11 Sep 2013)
New Revision: 3055

Added:
   pkg/Meucci/data/returnsDistribution.rda
Modified:
   pkg/Meucci/R/PlotCompositionEfficientFrontier.R
   pkg/Meucci/R/PlotDistributions.R
   pkg/Meucci/R/Prior2Posterior.R
   pkg/Meucci/R/RankingInformation.R
   pkg/Meucci/demo/AnalyticalvsNumerical.R
   pkg/Meucci/demo/RankingInformation.R
Log:
 -fixed the errors from the Ranking information example for the Historical Scenarios paper

Modified: pkg/Meucci/R/PlotCompositionEfficientFrontier.R
===================================================================
--- pkg/Meucci/R/PlotCompositionEfficientFrontier.R	2013-09-11 05:34:29 UTC (rev 3054)
+++ pkg/Meucci/R/PlotCompositionEfficientFrontier.R	2013-09-11 10:09:49 UTC (rev 3055)
@@ -10,7 +10,7 @@
 #' @author Xavier Valls \email{flamejat@@gmail.com}
 #' @export
 
-PlotCompositionEfficientFrontier = function(Portfolios)
+PlotCompositionEfficientFrontier = function( Portfolios, s, e )
 {
 	dev.new();
 

Modified: pkg/Meucci/R/PlotDistributions.R
===================================================================
--- pkg/Meucci/R/PlotDistributions.R	2013-09-11 05:34:29 UTC (rev 3054)
+++ pkg/Meucci/R/PlotDistributions.R	2013-09-11 10:09:49 UTC (rev 3055)
@@ -7,8 +7,14 @@
 #' @param p_      a vector containing the posterior probability values
 #' @param Mu_     a vector containing the posterior means
 #' @param Sigma_  a vector containing the posterior standard deviations
+#'
+#' @references 
+#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158}
+#' See Meucci script for "PlotDistributions.m"
+#'
 #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com}
 #' @export
+
 PlotDistributions = function( X , p , Mu , Sigma , p_ , Mu_ , Sigma_ )
 {
   J = nrow( X )
@@ -21,7 +27,7 @@
     # set ranges
     xl = min( X[ , n ] )
     xh = max( X[ , n ] )
-    x = as.matrix(seq(from=xl, to=xh, by=(xh-xl)/100))
+    x = as.matrix( seq( from=xl, to=xh, by=(xh-xl) / 100 ) )
         
     # posterior numerical
     # h3 = pHist(X[ ,n] , p_ , NBins )
@@ -31,11 +37,11 @@
     h4 = plot( x , y1,  type='l', col='red', xlab='', ylab='' )        
         
     # prior analytical
-    par(new = TRUE)
+    par( new = TRUE )
     y2 = dnorm( x , Mu[n] ,sqrt( Sigma[n,n] ) )
     h2 = plot( x , y2, type='l', col='blue', xlab='', ylab='' )
         
     # xlim( cbind( xl , xh ) )
-    legend(x = 1.5, y =0.4 ,legend=c("analytical","prior"), lwd=c(0.2,0.2), lty=c(1,1), col=c("red", "blue"))
+    legend( x = 1.5, y =0.4 , legend=c("analytical","prior"), lwd=c(0.2,0.2), lty=c(1,1), col=c("red", "blue") )
   }
 }
\ No newline at end of file

Modified: pkg/Meucci/R/Prior2Posterior.R
===================================================================
--- pkg/Meucci/R/Prior2Posterior.R	2013-09-11 05:34:29 UTC (rev 3054)
+++ pkg/Meucci/R/Prior2Posterior.R	2013-09-11 10:09:49 UTC (rev 3055)
@@ -15,7 +15,7 @@
 #' @return S_   a covariance matrix with the full-confidence posterior distribution of Sigma
 #'
 #' @references 
-#' \url{http://www.symmys.com}
+#' \url{http://www.symmys.com/node/158}
 #' \url{http://ssrn.com/abstract=1213325}
 #' A. Meucci - "Fully Flexible Views: Theory and Practice". See formula (21) and (22) on page 7
 #' See Meucci script Prior2Posterior.m attached to Entropy Pooling Paper

Modified: pkg/Meucci/R/RankingInformation.R
===================================================================
--- pkg/Meucci/R/RankingInformation.R	2013-09-11 05:34:29 UTC (rev 3054)
+++ pkg/Meucci/R/RankingInformation.R	2013-09-11 10:09:49 UTC (rev 3055)
@@ -1,30 +1,90 @@
-# TODO: translate PlotResults function
-# TODO: update plot of efficient frontier to show maximum return case
 # TODO: add max weights constraint to EfficientFrontier()
 # TODO: add computeCVaR to EfficientFrontier()
-
 # TODO: confirm QuadProg does not have a bug (i.e. it can optimize expected returns without use dvec by adding an equality constraint)
 
-#' Generate a Stacked Bar Chart based on the frontier weights matrix
+#' Plots the efficient frontier, as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk Magazine,
+#'  October 2008, p 100-106.
 #'
-#' @param weightsMatrix     a matrix of weights where rows are efficient portfolios summing to one, and columns are assets
-StackedBarChart = function( weightsMatrix )
+#' @param  e  the NumPortf x 1 matrix of expected returns for each portfolio along the efficient frontier
+#' @param  s  the NumPortf x 1 matrix of standard deviation of returns for each portfolio along the efficient frontier
+#' @param  w  the NumPortf x N matrix of compositions (security weights) for each portfolio along the efficient frontier
+#'   
+#' @references 
+#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158}
+#' See Meucci script for "RankingInformation/PlotFrontier.m"
+#'
+#' @author Xavier Valls \email{flamejat@@gmail.com}
+#' @export 
+
+
+PlotFrontier = function( e, s, w )
 {
-  data = as.data.frame( weightsMatrix )
-  data$aspect = 1:nrow(data)
-  data2 = reshape2:::melt( data , id.vars = "aspect" )
-  p <- ggplot(data2, aes( x = factor(aspect), y = value, fill = factor( variable ) ) ) + geom_bar() #+ opts( title = expression( "Efficient Frontier Weights" ))
-  return( p )
+  xx = dim( w )[ 1 ];
+  N  = dim( w )[ 2 ];
+  Data = t( apply( w, 1, cumsum ) );
+
+  plot( c(min(s), 0), xlim = c( min(s) , max(s) ), ylim = c( 0, max(Data) ), 
+    main= "frontier", xlab = " Portfolio # risk propensity", ylab = "Portfolio composition" );
+  
+  for( n in 1 : N )
+  {
+      x = rbind( min(s), s, max(s) );
+      y = rbind( 0, matrix( Data[ , N-n+1 ] ), 0 );
+      polygon( x, y, col = rgb( 0.9 - mod(n,3)*0.2, 0.9 - mod(n,3)*0.2, 0.9 - mod(n,3)*0.2) );
+  }
 }
 
-#' view the rankings
+#' Plots the results of computing the efficient frontier (Expected returns and frontier), as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk Magazine,
+#' October 2008, p 100-106.
 #'
+#' @param  e      the NumPortf x 1 matrix of expected returns for each portfolio along the efficient frontier
+#' @param  s      the NumPortf x 1 matrix of standard deviation of returns for each portfolio along the efficient frontier
+#' @param  w      the NumPortf x N matrix of compositions (security weights) for each portfolio along the efficient frontier
+#' @param  M      the NumPortf x 1 vector of expected returns for each asset
+#' @param  Lower  constraints
+#' @param  Upper  constraints 
+#'   
+#' @references 
+#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158}
+#' See Meucci script for "RankingInformation/PlotResults.m"
+#'
+#' @author Xavier Valls \email{flamejat@@gmail.com}
+
+PlotResults = function( e, s, w, M, Lower = NULL , Upper = NULL)
+{
+  N = length( M );
+  dev.new();
+  par( mfrow = c( 1, 2 ) );
+  h1 = hist( M*100, plot = F )
+  barplot( h$density, horiz = T, main = "expected returns", xlab = "", ylab = "" );
+  if(length(Lower) || length(Upper))
+  {
+    Changed = array( 0, N );
+    Changed[ union( Lower, Upper ) ] = M[ union( Lower, Upper ) ] * 100;
+    h2 = hist(Changed, plot = F );
+    barplot( h2$density, horiz = T, col = "red", add = T );
+  }
+
+  PlotFrontier( e*100, s*100, w );
+}
+
+
+
+#' Computes posterior probabilities to view the rankings, as it appears in A. Meucci,
+#' "Fully Flexible Views: Theory and Practice", The Risk Magazine, October 2008, p 100-106.
+#'
 #' @param  X        a vector containing returns for all the asset classes
 #' @param  p        a vector containing the prior probability values
 #' @param  Lower    a vector of indexes indicating which column is lower than the corresponding column number in Upper
 #' @param  Upper    a vector of indexes indicating which column is lower than the corresponding column number in Upper
+#'
+#' @references 
+#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158}
+#' See Meucci script for "RankingInformation/ViewRanking.m"
+#'
+#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com}
 #' @export EntropyProg
-#  @example ViewRanking( X , p , Lower = c(3,4) , Upper = c(4,5) ) # two inequality views: asset 3 < asset 4 returns, and asset 4 < asset 5 returns
+#' @example ViewRanking( X , p , Lower = c(3,4) , Upper = c(4,5) ) # two inequality views: asset 3 < asset 4 returns, and asset 4 < asset 5 returns
 
 ViewRanking = function( X , p , Lower , Upper )
 {
@@ -53,19 +113,37 @@
   return( p_ )
 }
 
-#' Generates an efficient frontier based on Meucci's Ranking Information version with the following inputs
+#' Generates an efficient frontier based on Meucci's Ranking Information version and returns a A list with  
+#' NumPortf efficient portfolios whos returns are equally spaced along the whole range of the efficient frontier,
+#' as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk Magazine, October 2008, 
+#' p 100-106.
+#'
+#' Most recent version of article and MATLAB code available at
+#' http://www.symmys.com/node/158
+#'
 #' @param  X             a matrix with the joint-scenario probabilities by asset (rows are joint-scenarios, columns are assets)
 #' @param  p             a vector of probabilities associated with each scenario in matrix X
 #' @param  Options       a list of options....TBD
-#' @return A list with NumPortf efficient portfolios whos returns are equally spaced along the whole range of the efficient frontier
-#'          Exps          the NumPortf x 1 vector of expected returns for each asset
-#'          Covs          the NumPortf x N vector of security volatilities along the efficient frontier
-#'             w          the NumPortf x N matrix of compositions (security weights) for each portfolio along the efficient frontier
-#'             e          the NumPortf x 1 matrix of expected returns for each portfolio along the efficient frontier
-#'             s          the NumPortf x 1 matrix of standard deviation of returns for each portfolio along the efficient frontier
+#'
+#' @return Exps          the NumPortf x 1 vector of expected returns for each asset
+#' @return Covs          the NumPortf x N vector of security volatilities along the efficient frontier
+#' @return w             the NumPortf x N matrix of compositions (security weights) for each portfolio along the efficient frontier
+#' @return e             the NumPortf x 1 matrix of expected returns for each portfolio along the efficient frontier
+#' @return s             the NumPortf x 1 matrix of standard deviation of returns for each portfolio along the efficient frontier
+#'
+#' @references 
+#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158}
+#' See Meucci script for "RankingInformation/EfficientFrontier.m"
+#'
+#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls \email{flamejat@@gmail.com}
 #' @export
+
 RIEfficientFrontier = function( X , p , Options)
-{    
+{ 
+
+  if( !require("limSolve") ) stop("This script requieres the limSolve package installed")
+
+
   library( matlab )
     
   J = nrow( X ) # number of scenarios
@@ -73,38 +151,36 @@
     
   Exps = t(X) %*% p # probability-weighted expected return of each asset
     
-  Scnd_Mom = t(X) %*% (X * ( p %*% ones( 1 , N ) ) )
+  Scnd_Mom = t(X) %*% (X * ( p %*% matrix( 1, 1 , N ) ) )
   Scnd_Mom = ( Scnd_Mom + t(Scnd_Mom) ) / 2 # an N*N matrix
   Covs = Scnd_Mom - Exps %*% t( Exps )
     
   Constr = list()
     
   # constrain the sum of weights to 1
-  Constr$Aeq = ones( 1 , N )
+  Constr$Aeq = matrix( 1, 1 , N )
   Constr$beq = 1
     
   # constrain the weight of any security to between 0 and 1
-  Constr$Aleq = rbind( eye(N) , -eye(N) ) # linear coefficients matrix A in the inequality constraint A*x <= b
-  Constr$bleq = rbind( ones(N,1) , 0*ones(N,1) ) # constraint vector b in the inequality constraint A*x <= b
+  Constr$Aleq = rbind( diag( 1, N ) , - diag( 1, N ) ) # linear coefficients matrix A in the inequality constraint A*x <= b
+  Constr$bleq = rbind( matrix( 1, N, 1 ) , matrix( 0, N, 1 ) ) # constraint vector b in the inequality constraint A*x <= b
     
   Amat = rbind( Constr$Aeq , Constr$Aleq ) # stack the equality constraints on top of the inequality constraints
   bvec = rbind( Constr$beq , Constr$bleq ) # stack the equality constraints on top of the inequality constraints
     
   ############################################################################################
   # determine return of minimum-risk portfolio
-  FirstDegree = zeros( N , 1 ) # TODO: assumes that securities have zero expected returns when computing efficient frontier?
+  FirstDegree  = matrix( 0, N , 1 ) # TODO: assumes that securities have zero expected returns when computing efficient frontier?
   SecondDegree = Covs
-  library( quadprog )    
   # Why is FirstDegree "expected returns" set to 0? 
   # We capture the equality view in the equality constraints matrix
   # In other words, we have a constraint that the Expected Returns by Asset %*% Weights = Target Return
   MinVol_Weights = solve.QP( Dmat = SecondDegree , dvec = -1*FirstDegree , Amat = -1*t(Amat) , bvec = -1*bvec , meq = length( Constr$beq ) )
-  MinSDev_Exp = t( MinVol_Weights$solution ) %*% Exps
+  MinSDev_Exp    = t( MinVol_Weights$solution ) %*% Exps
     
   ############################################################################################
   # determine return of maximum-return portfolio
   FirstDegree = -Exps
-  library( limSolve )
   MaxRet_Weights = linp( E = Constr$Aeq , F = Constr$beq , G = -1*Constr$Aleq , H = -1*Constr$bleq , Cost = FirstDegree , ispos = FALSE )$X
   MaxExp_Exp = t( MaxRet_Weights) %*% Exps
     
@@ -120,7 +196,7 @@
     
   ############################################################################################
   # compute the NumPortf compositions and risk-return coordinates        
-  FirstDegree = zeros( N , 1 )
+  FirstDegree = matrix( 0, N , 1 )
     
   w = matrix( , ncol = N , nrow = 0 )
   e = matrix( , ncol = 1 , nrow = 0 )

Added: pkg/Meucci/data/returnsDistribution.rda
===================================================================
(Binary files differ)


Property changes on: pkg/Meucci/data/returnsDistribution.rda
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Modified: pkg/Meucci/demo/AnalyticalvsNumerical.R
===================================================================
--- pkg/Meucci/demo/AnalyticalvsNumerical.R	2013-09-11 05:34:29 UTC (rev 3054)
+++ pkg/Meucci/demo/AnalyticalvsNumerical.R	2013-09-11 10:09:49 UTC (rev 3055)
@@ -5,8 +5,8 @@
 #' http://www.symmys.com/node/158
 #'
 #' @references 
-#' A. Meucci, Fully Flexible Views: Theory and Practice \url{http://www.symmys.com/node/158}
-#' See Meucci script for "S_MAIN.m"
+#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158}
+#' See Meucci script for "AnalyticalvsNumerical/S_MAIN.m"
 #' 
 #' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls \email{flamejat@@gmail.com}
 

Modified: pkg/Meucci/demo/RankingInformation.R
===================================================================
--- pkg/Meucci/demo/RankingInformation.R	2013-09-11 05:34:29 UTC (rev 3054)
+++ pkg/Meucci/demo/RankingInformation.R	2013-09-11 10:09:49 UTC (rev 3055)
@@ -1,101 +1,50 @@
 #' Entropy Pooling Example - Ranking Information script
 #'
-#' This script performs ranking allocation using the 
-#' Entropy-Pooling approach by Attilio Meucci, as it appears in 
-#' "A. Meucci - Fully Flexible Views: Theory and Practice -
-#' The Risk Magazine, October 2008, p 100-106"
-#' available at www.symmys.com > Research > Working Papers
+#' This script performs ranking allocation using the Entropy-Pooling approach by Attilio Meucci, 
+#' as it appears in A. Meucci, "Fully Flexible Views: Theory and Practice", The Risk Magazine, 
+#' October 2008, p 100-106.
+#'
+#' Most recent version of article and MATLAB code available at
+#' http://www.symmys.com/node/158
+#'
+#' @references 
+#' A. Meucci, "Fully Flexible Views: Theory and Practice" \url{http://www.symmys.com/node/158}
+#' See Meucci script for "RankingInformation/S_MAIN.m"
+#' 
+#' @author  Xavier Valls \email{flamejat@@gmail.com}
 
-#' Code by A. Meucci, September 2008
-#' Last version available at www.symmys.com > Teaching > MATLAB
-
 #############################################################################
 # Load panel X of joint returns realizations and vector p of respective probabilities
 # In real life, these are provided by the estimation process
 #############################################################################
-data("ReturnsDistribution")
+load("../data/returnsDistribution.rda");
 
-#############################################################################
+###########################################################################################################
 # compute and plot efficient frontier based on prior market distribution
-#############################################################################
-Options = list()
-Options$NumPortf = 20 # number of portfolios in efficient frontier
-Options$FrontierSpan = c( .3 , .9 ) # range of normalized exp.vals. spanned by efficient frontier
+###########################################################################################################
+Options = list();
+Options$NumPortf = 20; # number of portfolios in efficient frontier
+Options$FrontierSpan = c( 0.3, 0.9 ); # range of normalized exp.vals. spanned by efficient frontier
 
-frontierPrior = RIEfficientFrontier( X , P , Options ) # Frontier Plot Data contains [e,s,w,M,S]
+EF = RIEfficientFrontier( returnsDistribution$X, returnsDistribution$p, Options );
+PlotResults( EF$e, EF$Sdev, EF$Composition, EF$Exps );
 
-# PlotResults( frontierPrior$e , frontierPrior$Sdev , frontierPrior$Composition , frontierPrior$Exps )
-plot( x = (frontierPrior$Sdev)^2 , y = frontierPrior$e , xlab = "Variance" , ylab = "Expected Return" , main = "Prior" , type = "l" , ylim = c( .03 , .1 ) )
-# create stacked bar chart. each bar is a row (20 rows). each row sums to one. add legend.
-options( warn = 0 )
-library( ggplot2 )
-plotStackedBar <- StackedBarChart( frontierPrior$Composition )
-plotStackedBar
-options( warn = 2 )
-#############################################################################
-# process ordering information (this is the core of the Entropy Pooling approach
-#############################################################################
+###########################################################################################################
+# process ordering information (this is the core of the Entropy Pooling approach)
+###########################################################################################################
 
-# print expected returns of assets 3 and 4
-frontierPrior$Exps[3]
-frontierPrior$Exps[4] # note that asset 4 has a higher expected return assuming the prior distribution
-
 # the expected return of each entry of Lower is supposed to be smaller than respective entry in Upper
-Lower = as.numeric( c( 4 ) )
-Upper = as.numeric( c( 3 ) )
-P_ = ViewRanking( X , P , Lower , Upper )$p_
+Lower = 4;  
+Upper = 3;
+p_ = ViewRanking( returnsDistribution$X, returnsDistribution$p, Lower, Upper )$p_; 
 
-# confidence
-c = .5 
-blendedProbability = (1-c) * P + c * P_
+#confidence
+c  = 0.5; 
+p_ = ( 1 - c ) * returnsDistribution$p + c * p_ ;
 
-#############################################################################
+###########################################################################################################
 # compute and plot efficient frontier based on posterior market distribution
-#############################################################################
+###########################################################################################################
 
-frontierFullConfidencePosterior = RIEfficientFrontier( X , P_ , Options )
-# print expected returns of assets 3 and 4
-frontierFullConfidencePosterior$Exps[3]
-frontierFullConfidencePosterior$Exps[4] # note that asset 3 and asset 4 have equal expected returns
-
-# bar chart of portfolios on frontier -- note asset 3 has substantially more weight vs. asset 4
-options( warn = 0 )
-library( ggplot2 )
-plotStackedBar <- StackedBarChart( frontierFullConfidencePosterior$Composition )
-plotStackedBar
-options( warn = 2 )
-
-frontierPosterior = RIEfficientFrontier( X , blendedProbability , Options )
-# print expected returns of assets 3 and 4
-frontierPosterior$Exps[3]
-frontierPosterior$Exps[4] # note that asset 4 still has a higher expected return, but less so
-
-plot( x = (frontierPosterior$Sdev)^2 , y = frontierPosterior$e , xlab = "Variance" , ylab = "Expected Return" , main = "Posterior" , type = "l" , ylim = c( .03 , .1 ) )
-# PlotResults( frontierPosterior$e , frontierPosterior$Sdev , frontierPosterior$Composition , frontierPosterior$Exps , Lower , Upper )
-
-# bar chart of portfolios on frontier
-options( warn = 0 )
-library( ggplot2 )
-plotStackedBar <- StackedBarChart( frontierPosterior$Composition )
-plotStackedBar
-options( warn = 2 )
-
-# Tests
-# Test1 - views that are already in the prior return no revision
-result  = ViewRanking( X , P , c(3,3) , c(4,4) ) # none of the probabilities are revised from 1e-05. Why? Because the expectation that asset 3 is lower than expected return of asset 4 is already satisfied in prior
-result2 = ViewRanking( X , P , c(3) , c(4) )     # none of the probabilities are revised from 1e-05
-
-# Test2 - indentical (repeated) views return the same probabilities
-result3 = ViewRanking( X , P , c(4) , c(3) )     # returns revised probability distribution
-result4 = ViewRanking( X , P , c(4,4) , c(3,3) ) # returns identical probability distribution as in result3
-
-# Test3 - indentical (repeated) views return the same probabilities
-result3 = ViewRanking( X , P , c(4) , c(3) )     # returns revised probability distribution
-result4 = ViewRanking( X , P , c(4,4) , c(3,3) ) # returns identical probability distribution as in result3
-
-# Test4 - indentical (repeated) views return the same probabilities
-result5 = ViewRanking( X , P , c(4) , c(3) )     # returns revised probability distribution
-result6 = ViewRanking( X , P , c(4,1) , c(3,2) ) # the second view is non-binding since it is already reflected in prior, so p_ matches result 5
-
-# Test5
-result7 = ViewRanking( X , P , c(4,2) , c(3,1) ) # the second view is non-binding since it is already reflected in prior, so p_ matches result 5
\ No newline at end of file
+EF_ = RIEfficientFrontier( returnsDistribution$X, p_, Options );
+PlotResults( EF_$e, EF_$Sdev, EF_$Composition, EF_$Exps, Lower, Upper );



More information about the Returnanalytics-commits mailing list