[Returnanalytics-commits] r3146 - in pkg/Meucci: . R demo man

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Fri Sep 20 13:53:14 CEST 2013


Author: xavierv
Date: 2013-09-20 13:53:14 +0200 (Fri, 20 Sep 2013)
New Revision: 3146

Added:
   pkg/Meucci/R/pHistPriorPosterior.R
   pkg/Meucci/demo/S_EntropyView.R
   pkg/Meucci/man/pHistPriorPosterior.Rd
Modified:
   pkg/Meucci/DESCRIPTION
   pkg/Meucci/NAMESPACE
   pkg/Meucci/R/EntropyProg.R
   pkg/Meucci/TODO
   pkg/Meucci/demo/00Index
   pkg/Meucci/demo/S_BlackLittermanBasic.R
   pkg/Meucci/demo/S_EvaluationGeneric.R
   pkg/Meucci/man/EntropyProg.Rd
   pkg/Meucci/man/pHist.Rd
Log:
 - updated documentation until the end of the book and added S_EntropyView demo script from chapter 9

Modified: pkg/Meucci/DESCRIPTION
===================================================================
--- pkg/Meucci/DESCRIPTION	2013-09-20 05:16:14 UTC (rev 3145)
+++ pkg/Meucci/DESCRIPTION	2013-09-20 11:53:14 UTC (rev 3146)
@@ -34,7 +34,8 @@
     mvtnorm,
     dlm,
     quadprog,
-    kernlab
+    kernlab,
+    nloptr,
 Suggests:
     limSolve,
     Matrix,
@@ -42,7 +43,6 @@
     reshape2,
     Hmisc,
     moments,
-    nloptr,
     ggplot2,
     expm,
     latticeExtra,
@@ -105,3 +105,4 @@
     'data.R'
     'ButterflyTradingFunctions.R'
     'RankingInformationFunctions.R'
+    'pHistPriorPosterior.R'

Modified: pkg/Meucci/NAMESPACE
===================================================================
--- pkg/Meucci/NAMESPACE	2013-09-20 05:16:14 UTC (rev 3145)
+++ pkg/Meucci/NAMESPACE	2013-09-20 11:53:14 UTC (rev 3146)
@@ -48,6 +48,7 @@
 export(PanicCopula)
 export(PartialConfidencePosterior)
 export(PerformIidAnalysis)
+export(pHistPriorPosterior)
 export(PlotCompositionEfficientFrontier)
 export(PlotDistributions)
 export(PlotFrontier)

Modified: pkg/Meucci/R/EntropyProg.R
===================================================================
--- pkg/Meucci/R/EntropyProg.R	2013-09-20 05:16:14 UTC (rev 3145)
+++ pkg/Meucci/R/EntropyProg.R	2013-09-20 11:53:14 UTC (rev 3146)
@@ -41,13 +41,15 @@
 #' Reversing 'p' and 'p_' leads to the empirical likelihood" estimator of Qin and Lawless (1994). 
 #' See Robertson et al, "Forecasting Using Relative Entropy" (2002) for more theory
 #'  @export
-EntropyProg = function( p , A , b , Aeq , beq )
+EntropyProg = function( p , A = NULL , b = NULL , Aeq , beq )
 {
-    library( nloptr )    
-    
+    library( nloptr ) 
+
+    if( !length(b) ) A = matrix( ,nrow = 0, ncol = 0)
+    if( !length(b) ) b = matrix( ,nrow = 0, ncol = 0)
     # count the number of constraints
     K_ = nrow( A )  # K_ is the number of inequality constraints in the matrix-vector pair A-b
-    K = nrow( Aeq ) # K is the number of equality views in the matrix-vector pair Aeq-beq
+    K  = nrow( Aeq ) # K is the number of equality views in the matrix-vector pair Aeq-beq
     
     # parameter checks        
     if ( K_ + K == 0 ) { stop( "at least one equality or inequality constraint must be specified")}    
@@ -56,8 +58,8 @@
     if ( nrow(A)!=nrow(b) ) { stop( "number of equality constraints in matrix A must match number of elements in vector b") }              
     
     # calculate derivatives of constraint matrices
-    A_ = t( A )
-    b_= t( b )    
+    A_   = t( A )
+    b_   = t( b )    
     Aeq_ = t( Aeq )
     beq_ = t( beq )        
     
@@ -104,9 +106,7 @@
         v = optimResult$solution
         p_ = exp( log(p) - 1 - Aeq_ %*% v ) 	    
         optimizationPerformance = list( converged = (optimResult$status > 0) , ml = optimResult$objective , iterations = optimResult$iterations , sumOfProbabilities = sum( p_ ) )        
-    }
-    
-    else # case inequality constraints are specified    
+    }else # case inequality constraints are specified    
     {        
         # setup variables for constrained optimization
         InqMat = -diag( 1 , K_ + K ) # -1 * Identity Matrix with dimension equal to number of constraints
@@ -194,7 +194,7 @@
 #' @references 
 #' \url{http://www.symmys.com}
 #' See Meucci script pHist.m used for plotting
-#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com}
+#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls \email{flamejat@@gmail.com}
 
 pHist = function( X , p , nBins, freq = FALSE )    
 {      
@@ -204,7 +204,7 @@
     nBins = round( 10 * log(J) )
   }
   
-  dist = hist( x = X , breaks = nBins , freq = FALSE , main = "Portfolio return distribution" )
+  dist = hist( x = X , breaks = nBins , plot = FALSE );
   n = dist$counts
   x = dist$breaks    
   D = x[2] - x[1]
@@ -221,7 +221,7 @@
     f = np/D
   }
   
-  barplot( f , x , 1 )
+  plot( x , f , type = "h", main = "Portfolio return distribution")
   
   return( list( f = f , x = x ) )
 }

Added: pkg/Meucci/R/pHistPriorPosterior.R
===================================================================
--- pkg/Meucci/R/pHistPriorPosterior.R	                        (rev 0)
+++ pkg/Meucci/R/pHistPriorPosterior.R	2013-09-20 11:53:14 UTC (rev 3146)
@@ -0,0 +1,52 @@
+#' @title Plot prior and posterior distributions.
+#'
+#' @description Plot prior and posterior distributions, as described in  A. Meucci,
+#' "Risk and Asset Allocation", Springer, 2005.
+#'  
+#'  @param   X  : [matrix] (J x N) simulations
+#'  @param   p  : [vector] (J x 1) prior probabilities
+#'  @param   p_ : [vector] (J x 1) posterior probabilities
+#'
+#' @references
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170}.
+#'
+#' See Meucci's script for "pHistPriorPosterior.m"
+#'
+#' @author Xavier Valls \email{flamejat@@gmail.com}
+#' @export
+
+pHistPriorPosterior = function( X, p, p_)
+{
+    X = as.matrix(X);
+    J = dim(X)[1];
+    N = dim(X)[2];
+    NBins  = round(10 * log(J));
+
+    for( n in 1 : N )
+    {
+        dev.new();
+        
+        # set ranges
+        xl = min(X[ , n]);
+        xh = max(X[ , n]);
+        
+        par( mfrow = c( 2, 1 ) );
+
+        # prior numerical
+        pHist( X[ , n ], p, NBins);
+        # xlim([xl, xh]);
+        # y1 = ylim();
+        # title('prior');
+        
+        # posterior numerical
+        pHist( X[ , n ], p_, NBins);
+        # xlim([xl, xh]);
+        # y2 = ylim();
+        # ylim([min(y1(1), y2(1)), max(y1(2), y2(2))]);
+        # title('posterior');
+        
+        # subplot(2, 1, 1);
+        # ylim([min(y1(1), y2(1)), max(y1(2), y2(2))]);
+    }
+
+}
\ No newline at end of file

Modified: pkg/Meucci/TODO
===================================================================
--- pkg/Meucci/TODO	2013-09-20 05:16:14 UTC (rev 3145)
+++ pkg/Meucci/TODO	2013-09-20 11:53:14 UTC (rev 3146)
@@ -1,7 +1,11 @@
 Xavi's notes:
 
 * Matlab package doesn't seem to be necessary, find substitutes for its functions where possible
-* There are some problems with charts and what can be done with base graphics. Maybe using ggplot2 instead of base graphics can provide more flexibility.
+* There are some problems with charts and what can be done with base graphics:
+	- Maybe using ggplot2 instead of base graphics can provide more flexibility.
+	- How to change the layout after the plot like in MATLAB to change name, limits... (look at pHistPriorPosterior code for an example )
+	- How to draw a histogram passing the x,y coordinates using the barplot function
+	...
 * All the scripts from the papers need to be revised, some don't even work.
 * Maybe there are some packages that aren't needed anymore. Find out which of them. 
 * Documentation for papers and functions from Ram - Manan.
@@ -10,7 +14,6 @@
 * Change coding style to one more R alike
 * Still 2 scripts left from the book: S_MeanVarianceCallsRobust from chapter 9 and S_OptionReplication from chapter 6
 * Improve documentation for every script from the book: 
-	- find the exercises and sections they come from
 	- write down the equations
 * Not Sure if EntropyProg returns what it should with empty matrices as arguments for the constraints
-* Write text version of the formulas in the documentation
\ No newline at end of file
+* Write text version of the formulas in the documentation

Modified: pkg/Meucci/demo/00Index
===================================================================
--- pkg/Meucci/demo/00Index	2013-09-20 05:16:14 UTC (rev 3145)
+++ pkg/Meucci/demo/00Index	2013-09-20 11:53:14 UTC (rev 3146)
@@ -39,6 +39,7 @@
 S_ESContributionsStudentT         	 computes the expected shortfall and the contributions to ES from each security  
 S_EigenvalueDispersion               displays the sample eigenvalues dispersion phenomenon
 S_EllipticalNDim                     decomposes the N-variate normal distribution into its radial and uniform components to generate an elliptical distribution
+S_EntropyView						 illustrates the Entropy Pooling approach
 S_EquitiesInvariants                 performs the quest for invariance in the stock market
 S_EquityProjectionPricing            projects the distribution of the market invariants for the stock market from the estimation interval (normal assumption) to the investment horizon. Then it computes the distribution of prices at the investment horizon analytically.
 S_EstimateExpectedValueEvaluation 	 script familiarizes the user with the evaluation of an estimator replicability, loss, error, bias and inefficiency 

Modified: pkg/Meucci/demo/S_BlackLittermanBasic.R
===================================================================
--- pkg/Meucci/demo/S_BlackLittermanBasic.R	2013-09-20 05:16:14 UTC (rev 3145)
+++ pkg/Meucci/demo/S_BlackLittermanBasic.R	2013-09-20 11:53:14 UTC (rev 3146)
@@ -5,9 +5,11 @@
 #' Springer, 2005,  Chapter 9.
 #'
 #' @references
-#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170}.
-#' See Meucci's script for "S_BlackLittermanBasic.m"
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
+#' "E 303 - Black-Litterman and beyond II".
 #'
+#' See Meucci's script for "S_BlackLittermanBasic.m" and "E 302 - Black-Litterman and beyond I"
+#'
 #' @author Xavier Valls \email{flamejat@@gmail.com}
 
 ##################################################################################################################
@@ -23,7 +25,7 @@
 
 ##################################################################################################################
 ### Modify expected returns the Black-Litterman way and compute new efficient frontier 
-P = cbind( 1, 0, 0, 0, 0, -1 ); # pick matrix
+P     = cbind( 1, 0, 0, 0, 0, -1 ); # pick matrix
 Omega = P %*% covNRets$Sigma %*% t( P );
 Views = sqrt( diag( Omega ) ); # views value
 

Added: pkg/Meucci/demo/S_EntropyView.R
===================================================================
--- pkg/Meucci/demo/S_EntropyView.R	                        (rev 0)
+++ pkg/Meucci/demo/S_EntropyView.R	2013-09-20 11:53:14 UTC (rev 3146)
@@ -0,0 +1,32 @@
+#' This script  illustrates the Entropy Pooling approach, as described in A. Meucci, "Risk and Asset Allocation",
+#' Springer, 2005,  Chapter 9.
+#'
+#' @references
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
+#' "E 304 - Entropy pooling".
+#'
+#' See Meucci's script for "S_EntropyView.m"
+#'
+#' @author Xavier Valls \email{flamejat@@gmail.com}
+
+##################################################################################################################
+### Market simulations
+nSim = 100000;
+B = ( runif( nSim ) < 0.5);
+X = B * rnorm( nSim, -1, 1 ) + ( 1 - B ) * rnorm( nSim, 1, 1 );
+
+##################################################################################################################
+### View
+# specify view E{X} = 0.5 and constraint 1'*p = 1.
+p_prior = matrix( 1, nSim, 1) / nSim;
+Aeq = rbind( X, matrix( 1, 1, nSim ) );
+beq = rbind( 0.5, 1 );
+
+##################################################################################################################
+### Posterior market distribution using the Entropy Pooling approach
+#Using package's EntropyProg instead of Books EntropyMinimization (Same function, different names)
+p_post = EntropyProg( p_prior, Aeq = Aeq, beq = beq)$p;
+pHistPriorPosterior(X,p_prior, p_post);
+fprintf('prior sample mean = #f\n', mean(X));
+fprintf('posterior sample mean = #f\n', X' * p_post);
+

Modified: pkg/Meucci/demo/S_EvaluationGeneric.R
===================================================================
--- pkg/Meucci/demo/S_EvaluationGeneric.R	2013-09-20 05:16:14 UTC (rev 3145)
+++ pkg/Meucci/demo/S_EvaluationGeneric.R	2013-09-20 11:53:14 UTC (rev 3146)
@@ -6,12 +6,14 @@
 #'  @return Allocation      : [vector] (N x 1)
 #'
 #' @note
-#' 	compute optimal allocation, only possible if hidden parameters were known: thus it is not a "decision", we call it a "choice"
+#' 	Compute optimal allocation, only possible if hidden parameters were known: thus it is not a "decision", we call it a "choice"
 #'
 #' @references
-#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170}.
-#' See Meucci's script for " EvaluationChoiceOptimal.m"
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
+#' "E 285 - Estimation risk and opportunity cost".
 #'
+#' See Meucci's script for " EvaluationChoiceOptimal.m" 
+#'
 #' @author Xavier Valls \email{flamejat@@gmail.com}
 
 
@@ -40,7 +42,9 @@
 #'  @return CertaintyEquivalent : [scalar]
 #'
 #' @references
-#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170}.
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
+#' "E 285 - Estimation risk and opportunity cost".
+#'
 #' See Meucci's script for " EvaluationSatisfaction.m"
 #'
 #' @author Xavier Valls \email{flamejat@@gmail.com}
@@ -66,7 +70,9 @@
 #' 	scenario-dependent decision that tries to pick the optimal allocation
 #'
 #' @references
-#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170}.
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
+#' "E 285 - Estimation risk and opportunity cost".
+#'
 #' See Meucci's script for "EvaluationDecisionBestPerformer.m"
 #'
 #' @author Xavier Valls \email{flamejat@@gmail.com}
@@ -93,7 +99,9 @@
 #'  @return C_Plus          : [scalar] cost
 #'
 #' @references
-#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170}.
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
+#' "E 285 - Estimation risk and opportunity cost".
+#'
 #' See Meucci's script for "EvaluationDecisionBestPerformer.m"
 #'
 #' @author Xavier Valls \email{flamejat@@gmail.com}
@@ -117,7 +125,9 @@
 #' Described in A. Meucci "Risk and Asset Allocation", Springer, 2005, Chapter 8.
 #'
 #' @references
-#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170}.
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
+#' "E 285 - Estimation risk and opportunity cost".
+#'
 #' See Meucci's script for "S_EvaluationGeneric.m"
 #
 #' @author Xavier Valls \email{flamejat@@gmail.com}
@@ -140,12 +150,12 @@
 ##################################################################################################################
 ### Input market parameters
 NumAssets = 10;  
-a = 0.5; # effect of correlation on expected values and volatility (hidden)
+a      = 0.5; # effect of correlation on expected values and volatility (hidden)
 Bottom = 0.06; 
-Top = 0.36; 
-Step = (Top - Bottom) / (NumAssets - 1); 
-v = seq( Bottom, Top, Step ) ; # volatility vector
-Market = NULL;
+Top    = 0.36; 
+Step   = (Top - Bottom) / (NumAssets - 1); 
+v      = seq( Bottom, Top, Step ) ; # volatility vector
+Market = list();
 Market$T = 20; # not hidden
 Market$CurrentPrices = 10 * array( 1, NumAssets);  # not hidden
 

Modified: pkg/Meucci/man/EntropyProg.Rd
===================================================================
--- pkg/Meucci/man/EntropyProg.Rd	2013-09-20 05:16:14 UTC (rev 3145)
+++ pkg/Meucci/man/EntropyProg.Rd	2013-09-20 11:53:14 UTC (rev 3146)
@@ -2,7 +2,7 @@
 \alias{EntropyProg}
 \title{Entropy pooling program for blending views on scenarios with a prior scenario-probability distribution}
 \usage{
-  EntropyProg(p, A, b, Aeq, beq)
+  EntropyProg(p, A = NULL, b = NULL, Aeq, beq)
 }
 \arguments{
   \item{p}{a vector of initial probabilities based on prior

Modified: pkg/Meucci/man/pHist.Rd
===================================================================
--- pkg/Meucci/man/pHist.Rd	2013-09-20 05:16:14 UTC (rev 3145)
+++ pkg/Meucci/man/pHist.Rd	2013-09-20 11:53:14 UTC (rev 3146)
@@ -24,7 +24,8 @@
   Generates histogram
 }
 \author{
-  Ram Ahluwalia \email{ram at wingedfootcapital.com}
+  Ram Ahluwalia \email{ram at wingedfootcapital.com} and
+  Xavier Valls \email{flamejat at gmail.com}
 }
 \references{
   \url{http://www.symmys.com} See Meucci script pHist.m

Added: pkg/Meucci/man/pHistPriorPosterior.Rd
===================================================================
--- pkg/Meucci/man/pHistPriorPosterior.Rd	                        (rev 0)
+++ pkg/Meucci/man/pHistPriorPosterior.Rd	2013-09-20 11:53:14 UTC (rev 3146)
@@ -0,0 +1,27 @@
+\name{pHistPriorPosterior}
+\alias{pHistPriorPosterior}
+\title{Plot prior and posterior distributions.}
+\usage{
+  pHistPriorPosterior(X, p, p_)
+}
+\arguments{
+  \item{X}{: [matrix] (J x N) simulations}
+
+  \item{p}{: [vector] (J x 1) prior probabilities}
+
+  \item{p_}{: [vector] (J x 1) posterior probabilities}
+}
+\description{
+  Plot prior and posterior distributions, as described in
+  A. Meucci, "Risk and Asset Allocation", Springer, 2005.
+}
+\author{
+  Xavier Valls \email{flamejat at gmail.com}
+}
+\references{
+  A. Meucci - "Exercises in Advanced Risk and Portfolio
+  Management" \url{http://symmys.com/node/170}.
+
+  See Meucci's script for "pHistPriorPosterior.m"
+}
+



More information about the Returnanalytics-commits mailing list