[Returnanalytics-commits] r3947 - in pkg/Meucci: R demo man
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Thu Aug 13 08:56:04 CEST 2015
Author: xavierv
Date: 2015-08-13 08:56:03 +0200 (Thu, 13 Aug 2015)
New Revision: 3947
Modified:
pkg/Meucci/R/RobustBayesianAllocation.R
pkg/Meucci/demo/S_BondProjectionPricingNormal.R
pkg/Meucci/demo/S_BondProjectionPricingStudentT.R
pkg/Meucci/demo/S_BuyNHold.R
pkg/Meucci/man/robustBayesianPortfolioOptimization.Rd
Log:
fixed R check errors and formatted demoscripts until S_C*
Modified: pkg/Meucci/R/RobustBayesianAllocation.R
===================================================================
--- pkg/Meucci/R/RobustBayesianAllocation.R 2015-08-12 09:33:01 UTC (rev 3946)
+++ pkg/Meucci/R/RobustBayesianAllocation.R 2015-08-13 06:56:03 UTC (rev 3947)
@@ -135,8 +135,8 @@
#' efficient frontier
#' weights: the weights of each portfolio along
#' the Bayesian efficient frontier
-#'
-#' \deqn{ w_{rB}^{(i)} = argmax_{w \in C, w' \Sigma_{1} w \leq
+#' @note
+#' \deqn{ w_{rB}^{(i)}} = argmax_{w \in C, w' \Sigma_{1} w \leq
#' \gamma_{\Sigma}^{(i)} } \big\{w' \mu^{1} - \gamma _{\mu}
#' \sqrt{w' \Sigma_{1} w} \big\},
#'
@@ -144,7 +144,7 @@
#' \frac{v_{1}}{v_{1} - 2} }
#'
#' \gamma_{\Sigma}^{(i)} \equiv \frac{v^{(i)}}{ \frac{ \nu_{1}}{\nu_{1}+N+1} +
-#' \sqrt{ \frac{2\nu_{1}^{2}q_{\Sigma}^{2}}{ (\nu_{1}+N+1)^{3} } } } }
+#' \sqrt{ \frac{2\nu_{1}^{2}q_{\Sigma}^{2}}{ (\nu_{1}+N+1)^{3} } } }
#' @references
#' A. Meucci - Robust Bayesian Allocation - See formula (19) - (21)
#' \url{ http://papers.ssrn.com/sol3/papers.cfm?abstract_id=681553 }
Modified: pkg/Meucci/demo/S_BondProjectionPricingNormal.R
===================================================================
--- pkg/Meucci/demo/S_BondProjectionPricingNormal.R 2015-08-12 09:33:01 UTC (rev 3946)
+++ pkg/Meucci/demo/S_BondProjectionPricingNormal.R 2015-08-13 06:56:03 UTC (rev 3947)
@@ -1,63 +1,69 @@
-#'This script projects the distribution of the market invariants for the bond markets
-#'(i.e. the changes in yield to maturity) from the estimation interval to the investment horizon
-#'Then it computes the distribution of prices at the investment horizon as described in A. Meucci,
-#'"Risk and Asset Allocation", Springer, 2005, Chapter 3.
+#' This script projects the distribution of the market invariants for the bond
+#' markets
+#'(i.e. the changes in yield to maturity) from the estimation interval to the
+#' investment horizon
+#' Then it computes the distribution of prices at the investment horizon as
+#' described in A. Meucci, "Risk and Asset Allocation", Springer, 2005, Ch. 3
#'
#' @references
-#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
-#' "E 140 - Fixed-income market: projection of normal invariants".
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management"
+#' \url{http://symmys.com/node/170},
+#' "E 140 - Fixed-income market: projection of normal invariants"
#'
#' See Meucci's script for "S_BondProjectionPricingNormal.m"
#'
#' @author Xavier Valls \email{xaviervallspla@@gmail.com}
-##################################################################################################################
+################################################################################
### Inputs
-tau = 1/52; # time to horizon expressed in years
-tau_tilde = 1/52; # estimation period expressed in years
+tau <- 1/52 # time to horizon expressed in years
+tau_tilde <- 1/52 # estimation period expressed in years
-FlatCurve = 0.04;
-TimesToMat = c( 1, 5, 10, 52, 520 ) / 52; # time to maturity of selected bonds expressed in years
+FlatCurve <- 0.04
+# time to maturity of selected bonds expressed in years
+TimesToMat <- c(1, 5, 10, 52, 520) / 52
# parameters of the distribution of the changes in yield to maturity
-u_minus_tau = TimesToMat - tau;
-mus = 0 * u_minus_tau;
-sigmas = ( 20 + 5 / 4 * u_minus_tau ) / 10000;
+u_minus_tau <- TimesToMat - tau
+mus <- 0 * u_minus_tau
+sigmas <- (20 + 5 / 4 * u_minus_tau) / 10000
-nSim = 100000;
+nSim <- 100000
-##################################################################################################################
+################################################################################
### Bond market projection to horizon and pricing
-BondCurrent_Prices_Shifted = exp( -FlatCurve * u_minus_tau );
-BondCurrent_Prices = exp( -FlatCurve * TimesToMat );
+BondCurrent_Prices_Shifted <- exp(-FlatCurve * u_minus_tau)
+BondCurrent_Prices <- exp(-FlatCurve * TimesToMat)
# project bond market to horizon
-N = length( TimesToMat ); # number of bonds
-U = runif( nSim );
-BondMarket_Scenarios = matrix( 0, nSim, N );
-for( n in 1 : N )
-{
+N <- length(TimesToMat) # number of bonds
+U <- runif(nSim)
+BondMarket_Scenarios <- matrix(0, nSim, N)
+for (n in 1 : N) {
# generate co-dependent changes in yield-to-maturity
- DY_Scenarios = qnorm( U, mus[ n ] * tau / tau_tilde, sigmas[ n ] * sqrt( tau / tau_tilde ) );
+ DY_Scenarios <- qnorm(U, mus[n] * tau / tau_tilde, sigmas[n] *
+ sqrt(tau / tau_tilde))
- # compute the horizon prices, (3.81) in "Risk and Asset Allocation" - Springer
- X = -u_minus_tau[ n ] * DY_Scenarios;
- BondMarket_Scenarios[ , n ] = BondCurrent_Prices_Shifted[ n ] * exp( X );
+ # compute the horizon prices, (3.81) in "Risk and Asset Allocation"-Springer
+ X <- -u_minus_tau[n] * DY_Scenarios
+ BondMarket_Scenarios[, n] <- BondCurrent_Prices_Shifted[n] * exp(X)
}
-##################################################################################################################
+################################################################################
### MV inputs - analytical
-Exp_Hrzn_DY_Hat = mus * tau / tau_tilde;
-SDev_Hrzn_DY_Hat = sigmas * sqrt( tau / tau_tilde );
-Corr_Hrzn_DY_Hat = matrix( 1, N, N ); # full co-dependence
-Cov_Hrzn_DY_Hat = diag( SDev_Hrzn_DY_Hat ) %*% Corr_Hrzn_DY_Hat %*% diag( SDev_Hrzn_DY_Hat );
-Bond = ConvertChangeInYield2Price( Exp_Hrzn_DY_Hat, Cov_Hrzn_DY_Hat, u_minus_tau, BondCurrent_Prices_Shifted );
-print( Bond$Exp_Prices );
-print( Bond$Cov_Prices );
+Exp_Hrzn_DY_Hat <- mus * tau / tau_tilde
+SDev_Hrzn_DY_Hat <- sigmas * sqrt(tau / tau_tilde)
+Corr_Hrzn_DY_Hat <- matrix(1, N, N) # full co-dependence
+Cov_Hrzn_DY_Hat <- diag(SDev_Hrzn_DY_Hat) %*% Corr_Hrzn_DY_Hat %*%
+ diag(SDev_Hrzn_DY_Hat)
+Bond <- ConvertChangeInYield2Price(Exp_Hrzn_DY_Hat, Cov_Hrzn_DY_Hat,
+ u_minus_tau, BondCurrent_Prices_Shifted)
+print(Bond$Exp_Prices)
+print(Bond$Cov_Prices)
-##################################################################################################################
+################################################################################
### MV inputs - numerical
-BondExp_Prices = t( apply(BondMarket_Scenarios, 2, mean) );
-BondCov_Prices = cov( BondMarket_Scenarios );
-print( BondExp_Prices );
-print( BondCov_Prices );
+BondExp_Prices <- t(apply(BondMarket_Scenarios, 2, mean))
+BondCov_Prices <- cov(BondMarket_Scenarios)
+print(BondExp_Prices)
+print(BondCov_Prices)
Modified: pkg/Meucci/demo/S_BondProjectionPricingStudentT.R
===================================================================
--- pkg/Meucci/demo/S_BondProjectionPricingStudentT.R 2015-08-12 09:33:01 UTC (rev 3946)
+++ pkg/Meucci/demo/S_BondProjectionPricingStudentT.R 2015-08-13 06:56:03 UTC (rev 3947)
@@ -1,60 +1,64 @@
-#'This script projects the distribution of the market invariants for the bond markets
-#'(i.e. the changes in yield to maturity) from the estimation interval (Student t assumption)
-#'to the investment horizon. Then it computes the distribution of prices at the investment
-#'horizon as described in A. Meucci,"Risk and Asset Allocation", Springer, 2005, Chapter 3.
+#'This script projects the distribution of the market invariants for the bond
+#' markets (i.e. the changes in yield to maturity) from the estimation interval
+#' (Student t assumption) to the investment horizon. Then it computes the
+#' distribution of prices at the investment horizon as described in A. Meucci,
+#' "Risk and Asset Allocation", Springer, 2005, Chapter 3.
#'
#' @references
-#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
-#' "E 141 - Fixed-income market: projection of Student t invariants".
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management"
+#' \url{http://symmys.com/node/170}, "E 141 - Fixed-income market: projection of
+#' Student t invariants".
#'
#' See Meucci's script for "S_BondProjectionPricingStudentT.m"
#'
#' @author Xavier Valls \email{xaviervallspla@@gmail.com}
-##################################################################################################################
+################################################################################
### Inputs
-tau = 4/52; # time to horizon expressed in years
-tau_tilde = 1/52; # estimation period expressed in years
+tau <- 4/52 # time to horizon expressed in years
+tau_tilde <- 1/52 # estimation period expressed in years
-FlatCurve = 0.04;
-TimesToMat = c( 4, 5, 10, 52, 520 ) / 52; # time to maturity of selected bonds expressed in years
+FlatCurve <- 0.04
+# time to maturity of selected bonds expressed in years
+TimesToMat <- c(4, 5, 10, 52, 520) / 52
-# determine the parameters of the distribution of the invariants (changes in yield to maturity)
-Periods = tau / tau_tilde; # number of estimation periods until the investment horizon
-u_minus_tau = TimesToMat - tau;
+# determine the parameters of the distribution of the invariants
+# (changes in yield to maturity)
+# number of estimation periods until the investment horizon
+Periods <- tau / tau_tilde
+u_minus_tau <- TimesToMat - tau
-nu = 8;
-mus = 0 * u_minus_tau;
-sigmas = ( 20 + 5 / 4 * u_minus_tau ) / 10000;
-Num_Scenarios = 100000;
+nu <- 8
+mus <- 0 * u_minus_tau
+sigmas <- (20 + 5 / 4 * u_minus_tau) / 10000
+Num_Scenarios <- 100000
-##################################################################################################################
-### Projection and pricing
-BondCurrent_Prices_Shifted = exp(-FlatCurve * u_minus_tau);
-BondCurrent_Prices = exp(-FlatCurve * TimesToMat);
+################################################################################
+### Projection and pricing
+BondCurrent_Prices_Shifted <- exp(-FlatCurve * u_minus_tau)
+BondCurrent_Prices <- exp(-FlatCurve * TimesToMat)
# generate common source of randomness
-U = runif( Num_Scenarios );
+U <- runif(Num_Scenarios)
-N = length( TimesToMat ); # number of bonds
-par( mfrow = c( N,1 ));
-for( n in 1 : N )
-{
+N <- length(TimesToMat) # number of bonds
+par(mfrow = c(N,1))
+for (n in 1 : N) {
# project bond market to horizon
- Projection = ProjectionStudentT( nu, mus[ n ], sigmas[ n ], Periods);
+ Projection <- ProjectionStudentT(nu, mus[n], sigmas[n], Periods)
# generate co-dependent changes in yield-to-maturity
- DY_Scenarios = interp1( Projection$F, Projection$x, U, method = "linear");
+ DY_Scenarios <- interp1(Projection$F, Projection$x, U, method = "linear")
- # compute the horizon prices, (3.81) in "Risk and Asset Allocation" - Springer
- X = -u_minus_tau[ n ] * DY_Scenarios;
- Z = BondCurrent_Prices_Shifted[ n ] * exp(X);
-
+ # compute the horizon prices, (3.81) in "Risk and Asset Allocation"-Springer
+ X <- -u_minus_tau[n] * DY_Scenarios
+ Z <- BondCurrent_Prices_Shifted[n] * exp(X)
+
# compute and plot linear returns
- L = Z / BondCurrent_Prices[ n ] - 1;
+ L <- Z / BondCurrent_Prices[n] - 1
#for n=1 histogram represents the only bar (not empty)
- hist(L, round(10 * log(Num_Scenarios)), xlab = paste( "Linear returns for bond", n ), main = "" );
-
+ hist(L, round(10 * log(Num_Scenarios)), xlab = paste("Linear returns for
+ bond", n ), main = "")
}
Modified: pkg/Meucci/demo/S_BuyNHold.R
===================================================================
--- pkg/Meucci/demo/S_BuyNHold.R 2015-08-12 09:33:01 UTC (rev 3946)
+++ pkg/Meucci/demo/S_BuyNHold.R 2015-08-13 06:56:03 UTC (rev 3947)
@@ -1,101 +1,112 @@
-#' This script illustrates the buy & hold dynamic strategy, as described in A. Meucci,"Risk and Asset Allocation",
-#' Springer, 2005, Chapter 6.
+#' This script illustrates the buy & hold dynamic strategy, as described in
+#' A. Meucci,"Risk and Asset Allocation", Springer, 2005, Chapter 6.
#'
#' @references
-#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management" \url{http://symmys.com/node/170},
-#' "E 261 - Buy and hold".
+#' A. Meucci - "Exercises in Advanced Risk and Portfolio Management"
+#' \url{http://symmys.com/node/170}, "E 261 - Buy and hold".
#'
#' See Meucci's script for "S_BuyNHold.m"
#
#' @author Xavier Valls \email{xaviervallspla@@gmail.com}
-##################################################################################################################
+################################################################################
### Input parameters
-Initial_Investment = 1000;
-Time_Horizon = 6 / 12; # in years
-Time_Step = 1 / 252; # in years
+Initial_Investment <- 1000
+Time_Horizon <- 6 / 12 # in years
+Time_Step <- 1 / 252 # in years
-m = 0.2; # yearly expected return on the underlying
-s = 0.40; # yearly expected percentage volatility on the stock index
-r = 0.04; # risk-free (money market) interest rate
+m <- 0.2 # yearly expected return on the underlying
+s <- 0.40 # yearly expected percentage volatility on the stock index
+r <- 0.04 # risk-free (money market) interest rate
-NumSimul = 30000;
+NumSimul <- 30000
-##################################################################################################################
+################################################################################
# proportion of underlying you want to hold in the beginning, e.g.: 50
-Prct = 50 ;
+Prct <- 50
-##################################################################################################################
+################################################################################
#### Initialize values
-Underlying_Index = Initial_Investment; # value of the underlyting at starting time, normalzed to equal investment
-Start = Underlying_Index;
-Elapsed_Time = 0;
-Portfolio_Value = Initial_Investment;
+# value of the underlyting at starting time, normalzed to equal investment
+Underlying_Index <- Initial_Investment
+Start <- Underlying_Index
+Elapsed_Time <- 0
+Portfolio_Value <- Initial_Investment
-Underlying_in_Portfolio_Percent = Prct / 100;
+Underlying_in_Portfolio_Percent <- Prct / 100
-Underlyings_in_Portfolio = Portfolio_Value * Underlying_in_Portfolio_Percent;
-Cash_in_Portfolio = Portfolio_Value - Underlyings_in_Portfolio;
+Underlyings_in_Portfolio <- Portfolio_Value * Underlying_in_Portfolio_Percent
+Cash_in_Portfolio <- Portfolio_Value - Underlyings_in_Portfolio
-##################################################################################################################
+################################################################################
### Initialize parameters for the plot (no theory in this)
-Portfolio_Series = Portfolio_Value;
-Market_Series = Underlying_Index;
-Percentage_Series = Underlying_in_Portfolio_Percent;
+Portfolio_Series <- Portfolio_Value
+Market_Series <- Underlying_Index
+Percentage_Series <- Underlying_in_Portfolio_Percent
-# asset evolution and portfolio rebalancing
-while( Elapsed_Time < (Time_Horizon - 10^(-5)) ) # add this term to avoid errors
-{
+## asset evolution and portfolio rebalancing
+
+# add this term to avoid errors
+while(Elapsed_Time < (Time_Horizon - 10^(-5)) ) {
+
# time elapses...
- Elapsed_Time = Elapsed_Time + Time_Step;
+ Elapsed_Time <- Elapsed_Time + Time_Step
# ...asset prices evolve and portfolio takes on new value...
- Multiplicator = exp( (m - s ^ 2 / 2) * Time_Step + s * sqrt( Time_Step ) * rnorm(NumSimul));
- Underlying_Index = Underlying_Index * Multiplicator;
- Underlyings_in_Portfolio = Underlyings_in_Portfolio * Multiplicator;
- Cash_in_Portfolio = Cash_in_Portfolio * exp(r * Time_Step);
- Portfolio_Value = Underlyings_in_Portfolio + Cash_in_Portfolio;
+ Multiplicator <- exp((m - s ^ 2 / 2) * Time_Step + s * sqrt(Time_Step) *
+ rnorm(NumSimul))
+ Underlying_Index <- Underlying_Index * Multiplicator
+ Underlyings_in_Portfolio <- Underlyings_in_Portfolio * Multiplicator
+ Cash_in_Portfolio <- Cash_in_Portfolio * exp(r * Time_Step)
+ Portfolio_Value <- Underlyings_in_Portfolio + Cash_in_Portfolio
# ...and we rebalance our portfolio
- Underlying_in_Portfolio_Percent = Underlyings_in_Portfolio / Portfolio_Value;
+ Underlying_in_Portfolio_Percent <- Underlyings_in_Portfolio /
+ Portfolio_Value
# store one path for the movie (no theory in this)
- Portfolio_Series = cbind( Portfolio_Series, Portfolio_Value[ 1 ] ); ##ok<*AGROW>
- Market_Series = cbind( Market_Series, Underlying_Index[ 1 ] );
- Percentage_Series = cbind( Percentage_Series, Underlying_in_Portfolio_Percent[ 1 ] );
+ Portfolio_Series <- cbind(Portfolio_Series, Portfolio_Value[1])
+ Market_Series <- cbind(Market_Series, Underlying_Index[1])
+ Percentage_Series <- cbind(Percentage_Series,
+ Underlying_in_Portfolio_Percent[1])
}
-##################################################################################################################
+################################################################################
### Play the movie for one path
-Time = seq( 0, Time_Horizon, Time_Step);
-y_max = max( cbind( Portfolio_Series, Market_Series) ) * 1.2;
-dev.new();
-par( mfrow = c(2,1))
-for( i in 1 : length(Time) )
+Time <- seq(0, Time_Horizon, Time_Step)
+y_max <- max(cbind(Portfolio_Series, Market_Series)) * 1.2
+dev.new()
+par(mfrow <- c(2,1))
+for(i in 1 : length(Time))
{
- plot( Time[ 1:i ], Portfolio_Series[ 1:i ], type ="l", lwd = 2.5, col = "blue", ylab = "value",
- xlim = c(0, Time_Horizon), ylim = c(0, y_max), main = "investment (blue) vs underlying (red) value");
- lines( Time[ 1:i ], Market_Series[ 1:i ], lwd = 2, col = "red" );
- #axis( 1, [0, Time_Horizon, 0, y_max]);
+ plot(Time[1:i], Portfolio_Series[1:i], type ="l", lwd = 2.5, col = "blue",
+ ylab = "value", xlim = c(0, Time_Horizon), ylim = c(0, y_max),
+ main = "investment (blue) vs underlying (red) value")
+ lines(Time[1:i], Market_Series[1:i], lwd = 2, col = "red")
- plot(Time[ 1:i ], Percentage_Series[ 1:i ], type = "h", col = "red", xlab = "time", ylab = "#",
- xlim = c(0, Time_Horizon), ylim =c(0,1), main = "percentage of underlying in portfolio");
+ plot(Time[1:i], Percentage_Series[1:i], type = "h", col = "red",
+ xlab = "time", ylab = "#", xlim = c(0, Time_Horizon), ylim =c(0,1),
+ main = "percentage of underlying in portfolio")
}
-##################################################################################################################
+################################################################################
### Plots
# plot the scatterplot
-dev.new();
+dev.new()
# marginals
-NumBins = round(10 * log(NumSimul));
-layout( matrix(c(1,2,2,2,1,2,2,2,1,2,2,2,0,3,3,3), 4, 4, byrow = TRUE));
-barplot( table( cut( Portfolio_Value, NumBins )), horiz=TRUE, yaxt="n")
+NumBins <- round(10 * log(NumSimul))
+layout(matrix(c(1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 0, 3, 3, 3), 4, 4,
+ byrow = TRUE))
+barplot(table(cut(Portfolio_Value, NumBins)), horiz = TRUE, yaxt = "n")
# joint scatter plot
-plot(Underlying_Index, Portfolio_Value, xlab = "underlying at horizon (~ buy & hold )", ylab = "investment at horizon" );
-so = sort( Underlying_Index );
-lines( so, so, col = "red" );
+plot(Underlying_Index, Portfolio_Value,
+ xlab = "underlying at horizon (~ buy & hold)",
+ ylab = "investment at horizon")
-barplot( table( cut( Underlying_Index, NumBins )), yaxt="n")
+so <- sort(Underlying_Index)
+lines(so, so, col = "red")
+
+barplot(table(cut(Underlying_Index, NumBins)), yaxt = "n")
Modified: pkg/Meucci/man/robustBayesianPortfolioOptimization.Rd
===================================================================
--- pkg/Meucci/man/robustBayesianPortfolioOptimization.Rd 2015-08-12 09:33:01 UTC (rev 3946)
+++ pkg/Meucci/man/robustBayesianPortfolioOptimization.Rd 2015-08-13 06:56:03 UTC (rev 3947)
@@ -62,8 +62,15 @@
efficient frontier
weights: the weights of each portfolio along
the Bayesian efficient frontier
-
-\deqn{ w_{rB}^{(i)} = argmax_{w \in C, w' \Sigma_{1} w \leq
+}
+\description{
+Construct a collection of portfolios along the Bayesian
+mean-variance efficient frontier where each portfolio is equally distanced in
+return space. The function also returns the most robust portfolio along the
+Bayesian efficient frontier
+}
+\note{
+\deqn{ w_{rB}^{(i)}} = argmax_{w \in C, w' \Sigma_{1} w \leq
\gamma_{\Sigma}^{(i)} } \big\{w' \mu^{1} - \gamma _{\mu}
\sqrt{w' \Sigma_{1} w} \big\},
@@ -71,14 +78,8 @@
\frac{v_{1}}{v_{1} - 2} }
\gamma_{\Sigma}^{(i)} \equiv \frac{v^{(i)}}{ \frac{ \nu_{1}}{\nu_{1}+N+1} +
-\sqrt{ \frac{2\nu_{1}^{2}q_{\Sigma}^{2}}{ (\nu_{1}+N+1)^{3} } } } }
+\sqrt{ \frac{2\nu_{1}^{2}q_{\Sigma}^{2}}{ (\nu_{1}+N+1)^{3} } } }
}
-\description{
-Construct a collection of portfolios along the Bayesian
-mean-variance efficient frontier where each portfolio is equally distanced in
-return space. The function also returns the most robust portfolio along the
-Bayesian efficient frontier
-}
\author{
Ram Ahluwalia \email{ram at wingedfootcapital.com}
}
More information about the Returnanalytics-commits
mailing list