[Returnanalytics-commits] r3494 - in pkg/FactorAnalytics: . R man

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Sun Aug 3 09:46:55 CEST 2014


Author: pragnya
Date: 2014-08-03 09:46:55 +0200 (Sun, 03 Aug 2014)
New Revision: 3494

Added:
   pkg/FactorAnalytics/R/fmCov.R
   pkg/FactorAnalytics/R/fmEsDecomp.R
   pkg/FactorAnalytics/R/fmSdDecomp.R
   pkg/FactorAnalytics/R/fmVaRDecomp.R
   pkg/FactorAnalytics/man/fmCov.Rd
   pkg/FactorAnalytics/man/fmEsDecomp.Rd
   pkg/FactorAnalytics/man/fmSdDecomp.Rd
   pkg/FactorAnalytics/man/fmVaRDecomp.Rd
Removed:
   pkg/FactorAnalytics/R/covFm.R
   pkg/FactorAnalytics/man/covFm.Rd
Modified:
   pkg/FactorAnalytics/NAMESPACE
   pkg/FactorAnalytics/R/fitTsfm.R
   pkg/FactorAnalytics/R/fitTsfm.control.R
   pkg/FactorAnalytics/R/plot.tsfm.r
   pkg/FactorAnalytics/man/fitTsfm.Rd
   pkg/FactorAnalytics/man/plot.tsfm.Rd
Log:
Corrected, updated factor model Risk Decomposition functions

Modified: pkg/FactorAnalytics/NAMESPACE
===================================================================
--- pkg/FactorAnalytics/NAMESPACE	2014-07-30 17:52:41 UTC (rev 3493)
+++ pkg/FactorAnalytics/NAMESPACE	2014-08-03 07:46:55 UTC (rev 3494)
@@ -1,8 +1,11 @@
 # Generated by roxygen2 (4.0.1): do not edit by hand
 
 S3method(coef,tsfm)
-S3method(covFm,tsfm)
 S3method(fitted,tsfm)
+S3method(fmCov,tsfm)
+S3method(fmEsDecomp,tsfm)
+S3method(fmSdDecomp,tsfm)
+S3method(fmVaRDecomp,tsfm)
 S3method(plot,FundamentalFactorModel)
 S3method(plot,StatFactorModel)
 S3method(plot,pafm)
@@ -20,7 +23,6 @@
 S3method(summary,StatFactorModel)
 S3method(summary,pafm)
 S3method(summary,tsfm)
-export(covFm)
 export(dCornishFisher)
 export(factorModelEsDecomposition)
 export(factorModelMonteCarlo)
@@ -30,6 +32,10 @@
 export(fitStatisticalFactorModel)
 export(fitTsfm)
 export(fitTsfm.control)
+export(fmCov)
+export(fmEsDecomp)
+export(fmSdDecomp)
+export(fmVaRDecomp)
 export(pCornishFisher)
 export(paFm)
 export(qCornishFisher)

Deleted: pkg/FactorAnalytics/R/covFm.R
===================================================================
--- pkg/FactorAnalytics/R/covFm.R	2014-07-30 17:52:41 UTC (rev 3493)
+++ pkg/FactorAnalytics/R/covFm.R	2014-08-03 07:46:55 UTC (rev 3494)
@@ -1,126 +0,0 @@
-#' @title Covariance Matrix for assets' returns from fitted factor model.
-#' 
-#' @description Computes the covariance matrix for assets' returns based on a 
-#' fitted factor model. This is a generic function with methods for classes 
-#' \code{tsfm}, \code{sfm} and \code{ffm}.
-#' 
-#' @details \code{R(i, t)}, the return on asset \code{i} at time \code{t}, 
-#' is assumed to follow a factor model of the form, \cr \cr 
-#' \code{R(i,t) = alpha(i) + beta*F(t) + e(i,t)}, \cr \cr  
-#' where, \code{alpha(i)} is the intercept, \code{F(t)} is a {K x 1} vector of 
-#' the \code{K} factor values at time \code{t}, \code{beta} is a \code{1 x K} 
-#' vector of factor exposures and the error terms \code{e(i,t)} are serially 
-#' uncorrelated across time and contemporaneously uncorrelated across assets 
-#' so that \code{e(i,t) ~ iid(0,sig(i)^2)}. Thus, the variance of asset 
-#' \code{i}'s return is given by \cr \cr
-#' \code{var(R(i,t)) = beta*var(F(t))*tr(beta) + sig(i)^2}. \cr \cr
-#' And, the \code{N x N} covariance matrix of N asset returns is \cr \cr
-#' \code{var(R) = B*var(F(t))*tr(B) + D}, \cr \cr 
-#' where, B is the \code{N x K} matrix of factor betas and \code{D} is a 
-#' diagonal matrix with \code{sig(i)^2} along the diagonal.
-#' 
-#' The method for computing covariance can be specified via the \dots 
-#' argument. Note that the default of \code{use="pairwise.complete.obs"} for 
-#' handling NAs restricts the method to "pearson".
-#' 
-#' @param object fit object of class \code{tsfm}, \code{sfm} or \code{ffm}.
-#' @param use an optional character string giving a method for computing 
-#' covariances in the presence of missing values. This must be (an 
-#' abbreviation of) one of the strings "everything", "all.obs", 
-#' "complete.obs", "na.or.complete", or "pairwise.complete.obs". Default is 
-#' "pairwise.complete.obs".
-#' @param ... optional arguments passed to \code{\link[stats]{cov}}.
-#' 
-#' @return The computed \code{N x N} covariance matrix for asset returns based 
-#' on the fitted factor model.
-#' 
-#' @author Eric Zivot, Yi-An Chen and Sangeetha Srinivasan.
-#' 
-#' @references 
-#' \enumerate{
-#' \item Zivot, Eric, and W. A. N. G. Jia-hui. "Modeling Financial Time Series 
-#' with S-Plus Springer-Verlag." (2006).
-#' }
-#' 
-#' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}}
-#' 
-#' \code{\link[stats]{cov}} for more details on arguments \code{use} and 
-#' \code{method}.
-#' 
-#' @examples
-#' \dontrun{
-#' # Time Series Factor model
-#' data(managers)
-#' factors = managers[, (7:9)]
-#' fit <- fitTsfm(asset.names=colnames(managers[, (1:6)]), 
-#'                factor.names=c("EDHEC LS EQ","SP500 TR"), data=managers)                              
-#' covFm(fit)
-#' 
-#' # Statistical Factor Model
-#' data(stat.fm.data)
-#' sfm.pca.fit <- fitSfm(sfm.dat, k=2)
-#' #' covFm(t(sfm.pca.fit$loadings), var(sfm.pca.fit$factors), 
-#'                          sfm.pca.fit$resid.sd)
-#' 
-#' sfm.apca.fit <- fitSfm(sfm.apca.dat, k=2)
-#' 
-#' covFm(t(sfm.apca.fit$loadings), var(sfm.apca.fit$factors), 
-#'                       sfm.apca.fit$resid.sd)
-#'
-#' # Fundamental Factor Model
-#' data(stock)
-#' # there are 447 assets  
-#' exposure.names <- c("BOOK2MARKET", "LOG.MARKETCAP") 
-#' beta.mat <- subset(stock, DATE=="2003-12-31")[, exposure.names]
-#' beta.mat1 <- cbind(rep(1, 447), beta.mat1)
-#' # FM return covariance 
-#' fit.fund <- fitFfm(exposure.names=c("BOOK2MARKET", "LOG.MARKETCAP"), 
-#'                    data=stock, returnsvar="RETURN", datevar="DATE", 
-#'                    assetvar="TICKER", wls=TRUE, regression="classic", 
-#'                    covariance="classic", full.resid.cov=FALSE)
-#' ret.cov.fundm <- covFm(beta.mat1,fit.fund$factor.cov$cov,fit.fund$resid.sd)
-#' fit.fund$returns.cov$cov == ret.cov.fundm
-#' }
-#' 
-#' @rdname covFm
-#' @export
-
-covFm <- function(object, ...){
-  UseMethod("covFm")
-}
-
-#' @rdname covFm
-#' @method covFm tsfm
-#' @export
-
-covFm.tsfm <- function(object, use="pairwise.complete.obs", ...) {
-  
-  # check input object validity
-  if (!inherits(object, c("tsfm", "sfm", "ffm"))) {
-    stop("Invalid argument: Object should be of class 'tsfm', 'sfm' or 'ffm'.")
-  }
-  
-  # get parameters and factors from factor model
-  beta <- as.matrix(object$beta)
-  beta[is.na(beta)] <- 0
-  sig2.e = object$resid.sd^2
-  factor <- as.matrix(object$data[, object$factor.names])
-  
-  # factor covariance matrix 
-  factor.cov = cov(factor, use=use, ...)
-  
-  # residual covariance matrix D
-  if (length(sig2.e) > 1) {
-    D.e = diag(sig2.e)
-  } else {
-    D.e =  as.vector(sig2.e)
-  }
-  
-  cov.fm = beta %*% factor.cov %*% t(beta) + D.e
-  
-  if (any(diag(chol(cov.fm))==0)) {
-    warning("Covariance matrix is not positive definite!")
-  }
-  
-  return(cov.fm)
-}

Modified: pkg/FactorAnalytics/R/fitTsfm.R
===================================================================
--- pkg/FactorAnalytics/R/fitTsfm.R	2014-07-30 17:52:41 UTC (rev 3493)
+++ pkg/FactorAnalytics/R/fitTsfm.R	2014-08-03 07:46:55 UTC (rev 3494)
@@ -1,7 +1,7 @@
 #' @title Fit a time series factor model using time series regression
 #' 
-#' @description Fits a time series (or, macroeconomic) factor model for one 
-#' or more asset returns (or, excess returns) using time series regression. 
+#' @description Fits a time series (a.k.a. macroeconomic) factor model for one 
+#' or more asset returns or excess returns using time series regression. 
 #' Users can choose between ordinary least squares-OLS, discounted least 
 #' squares-DLS (or) robust regression. Several variable selection options  
 #' including Stepwise, Subsets, Lars are available as well. An object of class 
@@ -10,7 +10,7 @@
 #' @details 
 #' Typically, factor models are fit using excess returns. \code{rf.name} gives 
 #' the option to supply a risk free rate variable to subtract from each asset 
-#' return and factor to create excess returns. 
+#' return and factor to compute excess returns. 
 #' 
 #' Estimation method "OLS" corresponds to ordinary least squares using 
 #' \code{\link[stats]{lm}}, "DLS" is discounted least squares (weighted least 
@@ -33,12 +33,12 @@
 #' 
 #' \code{mkt.timing} allows for market-timing factors to be added to any of the 
 #' above methods. Market timing accounts for the price movement of the general 
-#' stock market relative to fixed income securities). "HM" follows 
-#' Henriksson & Merton (1981) and \code{up-market = max(0, Rm-Rf)}, is added 
-#' as a factor in the regression. The coefficient of this up-market factor can 
-#' be interpreted as the number of free put options. Similarly, "TM" follows 
+#' stock market relative to fixed income securities. "HM" follows 
+#' Henriksson & Merton (1981) and \code{up-market=max(0,Rm-Rf)}, is added to 
+#' the regression. The coefficient of this up-market factor can be 
+#' interpreted as the number of free put options. Similarly, "TM" follows 
 #' Treynor-Mazuy (1966), to account for market timing with respect to 
-#' volatility, and \code{market.sqd = (Rm-Rf)^2} is added as a factor in the 
+#' volatility, and \code{market.sqd=(Rm-Rf)^2} is added as a factor in the 
 #' regression. Option "both" adds both of these factors.
 #' 
 #' \subsection{Data Processing}{
@@ -74,22 +74,15 @@
 #' @param control list of control parameters. The default is constructed by 
 #' the function \code{\link{fitTsfm.control}}. See the documentation for 
 #' \code{\link{fitTsfm.control}} for details.
-#' @param ... For \code{fitTsfm}: arguments passed to 
-#' \code{\link{fitTsfm.control}}. \cr
-#' For S3 methods: further arguments passed to or from other methods 
+#' @param ... arguments passed to \code{\link{fitTsfm.control}}
 #' 
-#' @return fitTsfm returns an object of class \code{tsfm}. 
+#' @return fitTsfm returns an object of class \code{tsfm} for which 
+#' \code{print}, \code{plot}, \code{predict} and \code{summary} methods exist. 
 #' 
-#' The generic functions \code{summary}, \code{predict} and \code{plot} are 
-#' used to obtain and print a summary, predicted asset returns for new factor 
-#' data and plot selected characteristics for one or more assets. The generic 
-#' accessor functions \code{coef}, \code{fitted} and \code{residuals} 
-#' extract various useful features of the fit object. \code{coef.tsfm} extracts 
-#' coefficients from the fitted factor model and returns an N x (K+1) matrix of 
-#' all coefficients, \code{fitted.tsfm} gives an N x T data object of fitted 
-#' values and \code{residuals.tsfm} gives an N x T data object of residuals. 
-#' Additionally, \code{covFm} computes the \code{N x N} covariance matrix for 
-#' asset returns based on the fitted factor model
+#' The generic accessor functions \code{coef}, \code{fitted} and 
+#' \code{residuals} extract various useful features of the fit object. 
+#' Additionally, \code{fmCov} computes the covariance matrix for asset returns 
+#' based on the fitted factor model
 #' 
 #' An object of class \code{tsfm} is a list containing the following 
 #' components:
@@ -97,10 +90,10 @@
 #' class \code{lm} if \code{fit.method="OLS" or "DLS"}, class \code{lmRob} if 
 #' the \code{fit.method="Robust"}, or class \code{lars} if 
 #' \code{variable.selection="lars"}.}
-#' \item{alpha}{N x 1 vector of estimated alphas.}
+#' \item{alpha}{length-N vector of estimated alphas.}
 #' \item{beta}{N x K matrix of estimated betas.}
-#' \item{r2}{N x 1 vector of R-squared values.}
-#' \item{resid.sd}{N x 1 vector of residual standard deviations.}
+#' \item{r2}{length-N vector of R-squared values.}
+#' \item{resid.sd}{length-N vector of residual standard deviations.}
 #' \item{fitted}{xts data object of fitted values; iff 
 #' \code{variable.selection="lars"}}
 #' \item{call}{the matched function call.}
@@ -115,29 +108,31 @@
 #' @author Eric Zivot, Yi-An Chen and Sangeetha Srinivasan.
 #' 
 #' @references 
-#' \enumerate{
-#' \item Christopherson, Jon A., David R. Carino, and Wayne E. Ferson. 
-#' Portfolio performance measurement and benchmarking. McGraw Hill 
-#' Professional, 2009.
-#' \item Efron, Bradley, Trevor Hastie, Iain Johnstone, and Robert Tibshirani. 
-#' "Least angle regression." The Annals of statistics 32, no.2 (2004): 407-499. 
-#' \item Hastie, Trevor, Robert Tibshirani, Jerome Friedman, T. Hastie, J. 
-#' Friedman, and R. Tibshirani. The elements of statistical learning. Vol. 2, 
-#' no. 1. New York: Springer, 2009.
-#' \item Henriksson, Roy D., and Robert C. Merton. "On market timing and 
-#' investment performance. II. Statistical procedures for evaluating 
-#' forecasting skills." Journal of business (1981): 513-533.
-#' \item Treynor, Jack, and Kay Mazuy. "Can mutual funds outguess the market." 
-#' Harvard business review 44, no. 4 (1966): 131-136.
-#' }
+#' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio 
+#' performance measurement and benchmarking. McGraw Hill Professional.
 #' 
+#' Efron, B., Hastie, T., Johnstone, I., & Tibshirani, R. (2004). Least angle 
+#' regression. The Annals of statistics, 32(2), 407-499. 
+#' 
+#' Hastie, T., Tibshirani, R., Friedman, J., Hastie, T., Friedman, J., & 
+#' Tibshirani, R. (2009). The elements of statistical learning (Vol. 2, No. 1). 
+#' New York: Springer.
+#' 
+#' Henriksson, R. D., & Merton, R. C. (1981). On market timing and investment 
+#' performance. II. Statistical procedures for evaluating forecasting skills. 
+#' Journal of business, 513-533.
+#' 
+#' Treynor, J., & Mazuy, K. (1966). Can mutual funds outguess the market. 
+#' Harvard business review, 44(4), 131-136.
+#' 
 #' @seealso The \code{tsfm} methods for generic functions: 
 #' \code{\link{plot.tsfm}}, \code{\link{predict.tsfm}}, 
 #' \code{\link{print.tsfm}} and \code{\link{summary.tsfm}}. 
 #' 
 #' And, the following extractor functions: \code{\link[stats]{coef}}, 
-#' \code{\link{covFm}}, \code{\link[stats]{fitted}} and 
-#' \code{\link[stats]{residuals}}.
+#' \code{\link[stats]{fitted}}, \code{\link[stats]{residuals}},
+#' \code{\link{fmCov}}, \code{\link{fmSdDecomp}}, \code{\link{fmVaRDecomp}} 
+#' and \code{\link{fmEsDecomp}}.
 #' 
 #' \code{\link{paFm}} for Performance Attribution. 
 #' 
@@ -171,8 +166,7 @@
 
 fitTsfm <- function(asset.names, factor.names, mkt.name=NULL, rf.name=NULL, 
                     data=data, fit.method=c("OLS","DLS","Robust"),
-                    variable.selection=c("none","stepwise","subsets",
-                                         "lars"),
+                    variable.selection=c("none","stepwise","subsets","lars"),
                     mkt.timing=NULL, control=fitTsfm.control(...), ...) {
   
   # record the call as an element to be returned
@@ -493,6 +487,7 @@
 
 #' @param object a fit object of class \code{tsfm} which is returned by 
 #' \code{fitTsfm}
+#' @param ... further arguments passed to or from other methods 
 
 #' @rdname fitTsfm
 #' @method coef tsfm

Modified: pkg/FactorAnalytics/R/fitTsfm.control.R
===================================================================
--- pkg/FactorAnalytics/R/fitTsfm.control.R	2014-07-30 17:52:41 UTC (rev 3493)
+++ pkg/FactorAnalytics/R/fitTsfm.control.R	2014-08-03 07:46:55 UTC (rev 3494)
@@ -142,6 +142,7 @@
                             lars.criterion="Cp", K = 10) {
   
   # get the user-specified arguments (that have no defaults)
+  # this part of the code was adapted from stats::lm
   call <- match.call()
   m <- match(c("weights","scope","scale","direction","method","type",
                "max.steps"), names(call), 0L) 

Added: pkg/FactorAnalytics/R/fmCov.R
===================================================================
--- pkg/FactorAnalytics/R/fmCov.R	                        (rev 0)
+++ pkg/FactorAnalytics/R/fmCov.R	2014-08-03 07:46:55 UTC (rev 3494)
@@ -0,0 +1,122 @@
+#' @title Covariance Matrix for assets' returns from fitted factor model.
+#' 
+#' @description Computes the covariance matrix for assets' returns based on a 
+#' fitted factor model. This is a generic function with methods for classes 
+#' \code{tsfm}, \code{sfm} and \code{ffm}.
+#' 
+#' @details \code{R(i, t)}, the return on asset \code{i} at time \code{t}, 
+#' is assumed to follow a factor model of the form, \cr \cr 
+#' \code{R(i,t) = alpha(i) + beta*F(t) + e(i,t)}, \cr \cr  
+#' where, \code{alpha(i)} is the intercept, \code{F(t)} is a {K x 1} vector of 
+#' the \code{K} factor values at time \code{t}, \code{beta} is a \code{1 x K} 
+#' vector of factor exposures and the error terms \code{e(i,t)} are serially 
+#' uncorrelated across time and contemporaneously uncorrelated across assets 
+#' so that \code{e(i,t) ~ iid(0,sig(i)^2)}. Thus, the variance of asset 
+#' \code{i}'s return is given by \cr \cr
+#' \code{var(R(i,t)) = beta*var(F(t))*tr(beta) + sig(i)^2}. \cr \cr
+#' And, the \code{N x N} covariance matrix of N asset returns is \cr \cr
+#' \code{var(R) = B*var(F(t))*tr(B) + D}, \cr \cr 
+#' where, B is the \code{N x K} matrix of factor betas and \code{D} is a 
+#' diagonal matrix with \code{sig(i)^2} along the diagonal.
+#' 
+#' The method for computing covariance can be specified via the \dots 
+#' argument. Note that the default of \code{use="pairwise.complete.obs"} for 
+#' handling NAs restricts the method to "pearson".
+#' 
+#' @param object fit object of class \code{tsfm}, \code{sfm} or \code{ffm}.
+#' @param use an optional character string giving a method for computing 
+#' covariances in the presence of missing values. This must be (an 
+#' abbreviation of) one of the strings "everything", "all.obs", 
+#' "complete.obs", "na.or.complete", or "pairwise.complete.obs". Default is 
+#' "pairwise.complete.obs".
+#' @param ... optional arguments passed to \code{\link[stats]{cov}}.
+#' 
+#' @return The computed \code{N x N} covariance matrix for asset returns based 
+#' on the fitted factor model.
+#' 
+#' @author Eric Zivot, Yi-An Chen and Sangeetha Srinivasan.
+#' 
+#' @references 
+#' Zivot, E., & Jia-hui, W. A. N. G. (2006). Modeling Financial Time 
+#' Series with S-Plus Springer-Verlag.
+#' 
+#' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}}
+#' 
+#' \code{\link[stats]{cov}} for more details on arguments \code{use} and 
+#' \code{method}.
+#' 
+#' @examples
+#' # Time Series Factor model
+#' data(managers)
+#' fit <- fitTsfm(asset.names=colnames(managers[, (1:6)]), 
+#'                factor.names=c("EDHEC LS EQ","SP500 TR"), data=managers)                              
+#' fmCov(fit)
+#' 
+#' \dontrun{
+#' # Statistical Factor Model
+#' data(stat.fm.data)
+#' sfm.pca.fit <- fitSfm(sfm.dat, k=2)
+#' #' fmCov(t(sfm.pca.fit$loadings), var(sfm.pca.fit$factors), 
+#'                          sfm.pca.fit$resid.sd)
+#' 
+#' sfm.apca.fit <- fitSfm(sfm.apca.dat, k=2)
+#' 
+#' fmCov(t(sfm.apca.fit$loadings), var(sfm.apca.fit$factors), 
+#'                       sfm.apca.fit$resid.sd)
+#'
+#' # Fundamental Factor Model
+#' data(stock)
+#' # there are 447 assets  
+#' exposure.names <- c("BOOK2MARKET", "LOG.MARKETCAP") 
+#' beta.mat <- subset(stock, DATE=="2003-12-31")[, exposure.names]
+#' beta.mat1 <- cbind(rep(1, 447), beta.mat1)
+#' # FM return covariance 
+#' fit.fund <- fitFfm(exposure.names=c("BOOK2MARKET", "LOG.MARKETCAP"), 
+#'                    data=stock, returnsvar="RETURN", datevar="DATE", 
+#'                    assetvar="TICKER", wls=TRUE, regression="classic", 
+#'                    covariance="classic", full.resid.cov=FALSE)
+#' ret.cov.fundm <- fmCov(beta.mat1,fit.fund$factor.cov$cov,fit.fund$resid.sd)
+#' fit.fund$returns.cov$cov == ret.cov.fundm
+#' }
+#' 
+#' @rdname fmCov
+#' @export
+
+fmCov <- function(object, ...){
+  # check input object validity
+  if (!inherits(object, c("tsfm", "sfm", "ffm"))) {
+    stop("Invalid argument: Object should be of class 'tsfm', 'sfm' or 'ffm'.")
+  }
+  UseMethod("fmCov")
+}
+
+#' @rdname fmCov
+#' @method fmCov tsfm
+#' @export
+
+fmCov.tsfm <- function(object, use="pairwise.complete.obs", ...) {
+  
+  # get parameters and factors from factor model
+  beta <- as.matrix(object$beta)
+  beta[is.na(beta)] <- 0
+  sig2.e = object$resid.sd^2
+  factor <- as.matrix(object$data[, object$factor.names])
+  
+  # factor covariance matrix 
+  factor.cov = cov(factor, use=use, ...)
+  
+  # residual covariance matrix D
+  if (length(sig2.e) > 1) {
+    D.e = diag(sig2.e)
+  } else {
+    D.e =  as.vector(sig2.e)
+  }
+  
+  cov.fm = beta %*% factor.cov %*% t(beta) + D.e
+  
+  if (any(diag(chol(cov.fm))==0)) {
+    warning("Covariance matrix is not positive definite!")
+  }
+  
+  return(cov.fm)
+}

Added: pkg/FactorAnalytics/R/fmEsDecomp.R
===================================================================
--- pkg/FactorAnalytics/R/fmEsDecomp.R	                        (rev 0)
+++ pkg/FactorAnalytics/R/fmEsDecomp.R	2014-08-03 07:46:55 UTC (rev 3494)
@@ -0,0 +1,225 @@
+#' @title Decompose ES into individual factor contributions
+#' 
+#' @description Compute the factor contributions to Expected Tail Loss or 
+#' Expected Shortfall (ES) of assets' returns  based on Euler's theorem, given 
+#' the fitted factor model. The partial derivative of ES with respect to factor 
+#' beta is computed as the expected factor return given fund return is less 
+#' than or equal to its value-at-risk (VaR). VaR is computed as the sample quantile of the historic or 
+#' simulated data.
+#' 
+#' @details The factor model for an asset's return at time \code{t} has the 
+#' form \cr \cr \code{R(t) = beta'F(t) + e(t) = beta.star'F.star(t)} \cr \cr 
+#' where, \code{beta.star=(beta,sig.e)} and \code{F.star(t)=[F(t)',z(t)]'}. By 
+#' Euler's theorem, the ES of the asset's return is given by:
+#' \cr \cr \code{ES.fm = sum(cES_k) = sum(beta.star_k*mES_k)} \cr \cr
+#' where, summation is across the \code{K} factors and the residual, 
+#' \code{cES} and \code{mES} are the component and marginal 
+#' contributions to \code{ES} respectively. The marginal contribution to ES is
+#' defined as the expected value of \code{F.star}, conditional on the loss 
+#' being less than or equal to \code{VaR.fm}. This is estimated as a sample 
+#' average of the observations in that data window. 
+#' 
+#' Computation of the VaR measure is done using 
+#' \code{\link[PerformanceAnalytics]{VaR}}. Arguments \code{p}, \code{method} 
+#' and \code{invert} are passed to this function. Refer to their help file for 
+#' details and other options. \code{invert} consistently affects the sign for 
+#' all VaR and ES measures.
+#' 
+#' @param object fit object of class \code{tsfm}, \code{sfm} or \code{ffm}.
+#' @param p confidence level for calculation. Default is 0.95.
+#' @param method method for computing VaR, one of "modified","gaussian",
+#' "historical", "kernel". Default is "modified". See details.
+#' @param invert logical; whether to invert the VaR measure. Default is 
+#' \code{FALSE}.
+#' @param ... other optional arguments passed to 
+#' \code{\link[PerformanceAnalytics]{VaR}}.
+#' 
+#' @return A list containing 
+#' \item{VaR.fm}{length-N vector of factor model VaRs of N-asset returns.}
+#' \item{n.exceed}{length-N vector of number of observations beyond VaR for 
+#' each asset.}
+#' \item{idx.exceed}{list of numeric vector of index values of exceedances.}
+#' \item{ES.fm}{length-N vector of factor model ES of N-asset returns.}
+#' \item{mES}{N x (K+1) matrix of marginal contributions to VaR.}
+#' \item{cES}{N x (K+1) matrix of component contributions to VaR.}
+#' \item{pcES}{N x (K+1) matrix of percentage component contributions to VaR.}
+#' Where, \code{K} is the number of factors and N is the number of assets. 
+#' 
+#' @author Eric Zviot, Yi-An Chen and Sangeetha Srinivasan
+#' 
+#' @references 
+#' Epperlein, E., & Smillie, A. (2006). Portfolio risk analysis Cracking VAR 
+#' with kernels. RISK-LONDON-RISK MAGAZINE LIMITED-, 19(8), 70.
+#' 
+#' Hallerback (2003). Decomposing Portfolio Value-at-Risk: A General Analysis. 
+#' The Journal of Risk, 5(2), 1-18.
+#' 
+#' Meucci, A. (2007). Risk contributions from generic user-defined factors. 
+#' RISK-LONDON-RISK MAGAZINE LIMITED-, 20(6), 84. 
+#' 
+#' Yamai, Y., & Yoshiba, T. (2002). Comparative analyses of expected shortfall 
+#' and value-at-risk: their estimation error, decomposition, and optimization. 
+#' Monetary and economic studies, 20(1), 87-121.
+#' 
+#' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}}
+#' for the different factor model fitting functions.
+#' 
+#' \code{\link[PerformanceAnalytics]{VaR}} for VaR computation.
+#' \code{\link{fmSdDecomp}} for factor model SD decomposition.
+#' \code{\link{fmVaRDecomp}} for factor model VaR decomposition.
+#' 
+#' @examples
+#' # Time Series Factor Model
+#' data(managers)
+#' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
+#'                      factor.names=colnames(managers[,(7:8)]), data=managers)
+#'
+#' ES.decomp <- fmEsDecomp(fit.macro)
+#' # get the component contributions
+#' ES.decomp$cES
+#' 
+#' @export
+
+fmEsDecomp <- function(object, ...){
+  # check input object validity
+  if (!inherits(object, c("tsfm", "sfm", "ffm"))) {
+    stop("Invalid argument: Object should be of class 'tsfm', 'sfm' or 'ffm'.")
+  }
+  UseMethod("fmEsDecomp")
+}
+
+#' @rdname fmEsDecomp
+#' @method fmEsDecomp tsfm
+#' @export
+
+fmEsDecomp.tsfm <- function(object, p=0.95, 
+                             method=c("modified","gaussian","historical",
+                                      "kernel"), invert=FALSE, ...) {
+  
+  # set defaults and check input vailidity
+  method = method[1]
+  
+  if (!(method %in% c("modified", "gaussian", "historical", "kernel"))) {
+    stop("Invalid argument: method must be 'modified', 'gaussian',
+         'historical' or 'kernel'")
+  }
+  
+  # get beta.star
+  beta.star <- as.matrix(cbind(object$beta, object$resid.sd))
+  colnames(beta.star)[dim(beta.star)[2]] <- "residual"
+  
+  # factor returns and residuals data
+  factors.xts <- object$data[,object$factor.names]
+  resid.xts <- t(t(residuals(object))/object$resid.sd)
+  
+  # initialize lists and matrices
+  N <- length(object$asset.names)
+  K <- length(object$factor.names)
+  VaR.fm <- rep(NA, N)
+  ES.fm <- rep(NA, N)
+  idx.exceed <- list()
+  n.exceed <- rep(NA, N)
+  names(VaR.fm) = names(ES.fm) = names(n.exceed) = object$asset.names
+  mES <- matrix(NA, N, K+1)
+  cES <- matrix(NA, N, K+1)
+  pcES <- matrix(NA, N, K+1)
+  rownames(mES)=rownames(cES)=rownames(pcES)=object$asset.names
+  colnames(mES)=colnames(cES)=colnames(pcES)=c(object$factor.names,"residuals")
+  
+  for (i in object$asset.names) {
+    # return data for asset i
+    R.xts <- object$data[,i]
+    # get VaR for asset i
+    VaR.fm[i] <- VaR(R.xts, p=p, method=method, invert=invert, ...)
+    # index of VaR exceedances
+    idx.exceed[[i]] <- which(R.xts <= VaR.fm[i])
+    # number of VaR exceedances
+    n.exceed[i] <- length(idx.exceed[[i]])
+    
+    # get F.star data object
+    factor.star <- merge(factors.xts, resid.xts[,i])
+    colnames(factor.star)[dim(factor.star)[2]] <- "residual"
+    
+    if (!invert) {inv=-1} else {inv=1}
+    
+    # compute ES as expected value of asset return, such that the given asset 
+    # return is less than or equal to its value-at-risk (VaR) and approximated
+    # by a kernel estimator.
+    idx <- which(R.xts <= inv*VaR.fm[i])
+    ES.fm[i] <- inv * mean(R.xts[idx], na.rm =TRUE)
+    
+    # compute marginal ES as expected value of factor returns, such that the
+    # given asset return is less than or equal to its value-at-risk (VaR) and 
+    # approximated by a kernel estimator.
+    mES[i,] <- inv * colMeans(factor.star[idx,], na.rm =TRUE)
+    
+    # correction factor to ensure that sum(cES) = portfolio ES
+    cf <- as.numeric( ES.fm[i] / sum(mES[i,]*beta.star[i,]) )
+    
+    # compute marginal, component and percentage contributions to ES
+    # each of these have dimensions: N x (K+1)
+    mES[i,] <- cf * mES[i,]
+    cES[i,] <- mES[i,] * beta.star[i,]
+    pcES[i,] <- cES[i,] / ES.fm[i]
+  }
+  
+  fm.ES.decomp <- list(VaR.fm=VaR.fm, n.exceed=n.exceed, idx.exceed=idx.exceed, 
+                       ES.fm=ES.fm, mES=mES, cES=cES, pcES=pcES)
+  
+  return(fm.ES.decomp)
+  }
+
+
+
+
+
+factorModelEsDecomposition <-
+  function(Data, beta.vec, sig.e, tail.prob = 0.05,
+           VaR.method=c("modified", "gaussian", "historical", "kernel")) {
+    
+    Data = as.matrix(Data)
+    ncol.Data = ncol(Data)
+    if(is.matrix(beta.vec)) {
+      beta.names = c(rownames(beta.vec), "residual")
+    } else if(is.vector(beta.vec)) {
+      beta.names = c(names(beta.vec), "residual")
+    } else {
+      stop("beta.vec is not an n x 1 matrix or a vector")
+    }  
+    beta.names = c(names(beta.vec), "residual")
+    beta.star.vec = c(beta.vec, sig.e)
+    names(beta.star.vec) = beta.names
+    
+    ## epsilon is calculated in the sense of minimizing mean square error by Silverman 1986
+    epi <- 2.575*sd(Data[,1]) * (nrow(Data)^(-1/5))
+    VaR.fm = as.numeric(VaR(Data[, 1], p=(1-tail.prob), method=VaR.method))
+    idx = which(Data[, 1] <= VaR.fm + epi & Data[,1] >= VaR.fm - epi)
+    
+    
+    
+    ES.fm = -mean(Data[idx, 1])
+    
+    ##
+    ## compute marginal contribution to ES
+    ##
+    ## compute marginal ES as expected value of factor return given fund
+    ## return is less than or equal to VaR
+    mcES.fm = -as.matrix(colMeans(Data[idx, -1]))
+    
+    ## compute correction factor so that sum of weighted marginal ES adds to portfolio ES
+    cf = as.numeric( ES.fm / sum(mcES.fm*beta.star.vec) )
+    mcES.fm = cf*mcES.fm
+    cES.fm = mcES.fm*beta.star.vec
+    pcES.fm = cES.fm/ES.fm
+    colnames(mcES.fm) = "MCES"
+    colnames(cES.fm) = "CES"
+    colnames(pcES.fm) = "PCES"
+    ans = list(VaR.fm = -VaR.fm,
+               n.exceed = length(idx),
+               idx.exceed = idx,
+               ES.fm = ES.fm, 
+               mES.fm = t(mcES.fm), 
+               cES.fm = t(cES.fm),
+               pcES.fm = t(pcES.fm))
+    return(ans)
+  }

Added: pkg/FactorAnalytics/R/fmSdDecomp.R
===================================================================
--- pkg/FactorAnalytics/R/fmSdDecomp.R	                        (rev 0)
+++ pkg/FactorAnalytics/R/fmSdDecomp.R	2014-08-03 07:46:55 UTC (rev 3494)
@@ -0,0 +1,122 @@
+#' @title Decompose standard deviation into individual factor contributions
+#' 
+#' @description Compute the factor contributions to standard deviation (SD) of 
+#' assets' returns based on Euler's theorem, given the fitted factor model.
+#' 
+#' @details The factor model for an asset's return at time \code{t} has the 
+#' form \cr \cr \code{R(t) = beta'F(t) + e(t) = beta.star'F.star(t)} \cr \cr 
+#' where, \code{beta.star=(beta,sig.e)} and \code{F.star(t)=[F(t)',z(t)]'}. 
+#' \cr \cr By Euler's theorem, the standard deviation of the asset's return 
+#' is given as: \cr \cr 
+#' \code{Sd.fm = sum(cSd_k) = sum(beta.star_k*mSd_k)} \cr \cr 
+#' where, summation is across the \code{K} factors and the residual, 
+#' \code{cSd} and \code{mSd} are the component and marginal 
+#' contributions to \code{SD} respectively. Computing \code{Sd.fm} and 
+#' \code{mSd} is very straight forward. The formulas are given below and 
+#' details are in the references. The covariance term is approximated by the 
+#' sample covariance. \cr \cr
+#' \code{Sd.fm = sqrt(beta.star''cov(F.star)beta.star)} \cr 
+#' \code{mSd = cov(F.star)beta.star / Sd.fm}
+#' 
+#' @param object fit object of class \code{tsfm}, \code{sfm} or \code{ffm}.
+#' @param use an optional character string giving a method for computing 
+#' covariances in the presence of missing values. This must be (an 
+#' abbreviation of) one of the strings "everything", "all.obs", 
+#' "complete.obs", "na.or.complete", or "pairwise.complete.obs". Default is 
+#' "pairwise.complete.obs".
+#' @param ... optional arguments passed to \code{\link[stats]{cov}}.
+#' 
+#' @return A list containing 
+#' \item{Sd.fm}{length-N vector of factor model SDs of N-asset returns.}
+#' \item{mSd}{N x (K+1) matrix of marginal contributions to SD.}
+#' \item{cSd}{N x (K+1) matrix of component contributions to SD.}
+#' \item{pcSd}{N x (K+1) matrix of percentage component contributions to SD.}
+#' Where, \code{K} is the number of factors and N is the number of assets.
+#' 
+#' @author Eric Zivot, Yi-An Chen and Sangeetha Srinivasan
+#' 
+#' @references 
+#' Hallerback (2003). Decomposing Portfolio Value-at-Risk: A General Analysis. 
+#' The Journal of Risk, 5(2), 1-18.
+#' 
+#' Meucci, A. (2007). Risk contributions from generic user-defined factors. 
+#' RISK-LONDON-RISK MAGAZINE LIMITED-, 20(6), 84. 
+#' 
+#' Yamai, Y., & Yoshiba, T. (2002). Comparative analyses of expected shortfall 
+#' and value-at-risk: their estimation error, decomposition, and optimization. 
+#' Monetary and economic studies, 20(1), 87-121.
+#' 
+#' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}}
+#' for the different factor model fitting functions.
+#' 
+#' \code{\link{fmCov}} for factor model covariance.
+#' \code{\link{fmVaRDecomp}} for factor model VaR decomposition.
+#' \code{\link{fmEsDecomp}} for factor model ES decomposition.
+#' 
+#' @examples
+#' # Time Series Factor Model
+#' data(managers)
+#' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
+#'                      factor.names=colnames(managers[,(7:9)]),
+#'                      rf.name="US 3m TR", data=managers)
+#' 
+#' decomp <- fmSdDecomp(fit.macro)
+#' # get the percentage component contributions
+#' decomp$pcSd
+#'  
+#' @export                                       
+
+fmSdDecomp <- function(object, ...){
+  # check input object validity
+  if (!inherits(object, c("tsfm", "sfm", "ffm"))) {
+    stop("Invalid argument: Object should be of class 'tsfm', 'sfm' or 'ffm'.")
+  }
+  UseMethod("fmSdDecomp")
+}
+
+## Remarks:
+## The factor model for asset i's return has the form
+## R(i,t) = beta_i'F(t) + e(i,t) = beta.star_i'F.star(t)
+## where beta.star_i = (beta_i, sig.e_i)' and F.star(t) = (F(t)', z(t))'
+
+## Standard deviation of the asset i's return
+## sd.fm_i = sqrt(beta.star_i'Cov(F.star)beta.star_i) 
+
+## By Euler's theorem
+## sd.fm_i = sum(cSd_i(k)) = sum(beta.star_i(k)*mSd_i(k))
[TRUNCATED]

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


More information about the Returnanalytics-commits mailing list