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

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Tue Feb 3 03:13:27 CET 2015


Author: chenyian
Date: 2015-02-03 03:13:26 +0100 (Tue, 03 Feb 2015)
New Revision: 3590

Added:
   pkg/FactorAnalytics/data/managers.RData
Removed:
   pkg/FactorAnalytics/data/managers.rda
Modified:
   pkg/FactorAnalytics/.Rbuildignore
   pkg/FactorAnalytics/DESCRIPTION
   pkg/FactorAnalytics/R/fitTsfm.R
   pkg/FactorAnalytics/R/fitTsfmTiming.r
   pkg/FactorAnalytics/R/fmCov.R
   pkg/FactorAnalytics/R/fmSdDecomp.R
   pkg/FactorAnalytics/R/paFm.r
   pkg/FactorAnalytics/R/plot.tsfm.r
   pkg/FactorAnalytics/R/predict.tsfm.r
   pkg/FactorAnalytics/R/print.pafm.r
   pkg/FactorAnalytics/R/print.tsfm.r
   pkg/FactorAnalytics/R/summary.pafm.r
   pkg/FactorAnalytics/R/summary.tsfm.r
   pkg/FactorAnalytics/man/fitTsfm.Rd
   pkg/FactorAnalytics/man/fitTsfmTiming.Rd
   pkg/FactorAnalytics/man/fmCov.Rd
   pkg/FactorAnalytics/man/fmSdDecomp.Rd
   pkg/FactorAnalytics/man/paFm.Rd
   pkg/FactorAnalytics/man/plot.tsfm.Rd
   pkg/FactorAnalytics/man/predict.tsfm.Rd
   pkg/FactorAnalytics/man/print.pafm.Rd
   pkg/FactorAnalytics/man/print.tsfm.Rd
   pkg/FactorAnalytics/man/summary.pafm.Rd
   pkg/FactorAnalytics/man/summary.tsfm.Rd
Log:
Modify the column names of managers.RData and related examples to accommodate the column name changes if merge.xts is used. Basically, the naming fashion is c("EDHEC.LS.EQ","SP500.TR","US.10Y.TR","US.3m.TR") rather than c("EDHEC LS EQ","SP500 TR","US 10Y TR","US 3m TR").  

Modified: pkg/FactorAnalytics/.Rbuildignore
===================================================================
--- pkg/FactorAnalytics/.Rbuildignore	2015-02-02 20:15:56 UTC (rev 3589)
+++ pkg/FactorAnalytics/.Rbuildignore	2015-02-03 02:13:26 UTC (rev 3590)
@@ -1,9 +1,2 @@
-^\.svn$
-^sandbox/*$
-^R/\.svn$
-^data/\.svn$
-^inst/\.svn$
-^man/\.svn$
-^vignettes/\.svn$
 ^.*\.Rproj$
 ^\.Rproj\.user$

Modified: pkg/FactorAnalytics/DESCRIPTION
===================================================================
--- pkg/FactorAnalytics/DESCRIPTION	2015-02-02 20:15:56 UTC (rev 3589)
+++ pkg/FactorAnalytics/DESCRIPTION	2015-02-03 02:13:26 UTC (rev 3590)
@@ -1,36 +1,36 @@
-Package: factorAnalytics
-Type: Package
-Title: Factor Analytics
-Version: 2.0.10
-Date: 2015-01-27
-Author: Eric Zivot, Sangeetha Srinivasan and Yi-An Chen
-Maintainer: Sangeetha Srinivasan <sangee at uw.edu>
-Description: An R package for the estimation and risk analysis of linear factor
-    models for asset returns and portfolios. It contains model fitting methods
-    for the three major types of factor models: time series (or, macroeconomic)
-    factor model, fundamental factor model and statistical factor model. They
-    allow for different types of distributions to be specified for modeling the
-    fat-tailed behavior of financial returns, including Edgeworth expansions.
-    Risk analysis measures such as VaR and ES, as well as performance 
-    attribution for factor models (factor-contributed vs idiosyncratic returns) 
-    are included. 
-License: GPL-2
-Depends:
-    R (>= 3.0.0),
-    xts (>= 0.9)
-Imports: 
-    PerformanceAnalytics(>= 1.1.0),
-    corrplot,  
-    robust, 
-    leaps, 
-    lars,
-    strucchange,
-    lmtest,
-    sandwich,
-    lattice,
-    MASS
-Suggests:
-    testthat, quantmod, knitr
-LazyLoad: yes
-LazyDataCompression: xz
-URL: http://r-forge.r-project.org/R/?group_id=579
+Package: factorAnalytics
+Type: Package
+Title: Factor Analytics
+Version: 2.0.10
+Date: 2015-01-27
+Author: Eric Zivot, Sangeetha Srinivasan and Yi-An Chen
+Maintainer: Sangeetha Srinivasan <sangee at uw.edu>
+Description: An R package for the estimation and risk analysis of linear factor
+    models for asset returns and portfolios. It contains model fitting methods
+    for the three major types of factor models: time series (or, macroeconomic)
+    factor model, fundamental factor model and statistical factor model. They
+    allow for different types of distributions to be specified for modeling the
+    fat-tailed behavior of financial returns, including Edgeworth expansions.
+    Risk analysis measures such as VaR and ES, as well as performance 
+    attribution for factor models (factor-contributed vs idiosyncratic returns) 
+    are included. 
+License: GPL-2
+Depends:
+    R (>= 3.0.0),
+    xts (>= 0.9)
+Imports: 
+    PerformanceAnalytics(>= 1.1.0),
+    corrplot,  
+    robust, 
+    leaps, 
+    lars,
+    strucchange,
+    lmtest,
+    sandwich,
+    lattice,
+    MASS
+Suggests:
+    testthat, quantmod, knitr
+LazyLoad: yes
+LazyDataCompression: xz
+URL: http://r-forge.r-project.org/R/?group_id=579

Modified: pkg/FactorAnalytics/R/fitTsfm.R
===================================================================
--- pkg/FactorAnalytics/R/fitTsfm.R	2015-02-02 20:15:56 UTC (rev 3589)
+++ pkg/FactorAnalytics/R/fitTsfm.R	2015-02-03 02:13:26 UTC (rev 3590)
@@ -155,10 +155,6 @@
 #' # group plot; type selected from menu prompt; auto-looped for multiple plots
 #' # plot(fit)
 #' 
-#' # example: Market-timing factors with robust fit
-#' fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, 
-#'                mkt.name="SP500 TR", mkt.timing="HM", data=managers, 
-#'                fit.method="Robust")
 #' 
 #' # example using "subsets" variable selection
 #' fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
@@ -169,7 +165,7 @@
 #' # example using "lars" variable selection and subtracting risk-free rate
 #' fit.lar <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
 #'                    factor.names=colnames(managers[,(7:9)]), 
-#'                    rf.name="US 3m TR", data=managers, 
+#'                    rf.name="US.3m.TR", data=managers, 
 #'                    variable.selection="lars", lars.criterion="cv") 
 #' 
 #' @importFrom PerformanceAnalytics checkData
@@ -201,10 +197,10 @@
     factor.names <- NULL
   }
   
-  if (xor(is.null(mkt.name), is.null(mkt.timing))) {
-    stop("Missing argument: Both mkt.name and mkt.timing are necessary to add 
-         market timing factors")
-  }
+#   if (xor(is.null(mkt.name), is.null(mkt.timing))) {
+#     stop("Missing argument: Both mkt.name and mkt.timing are necessary to add 
+#          market timing factors")
+#   }
   
   # extract arguments to pass to different fit and variable selection functions
   decay <- control$decay

Modified: pkg/FactorAnalytics/R/fitTsfmTiming.r
===================================================================
--- pkg/FactorAnalytics/R/fitTsfmTiming.r	2015-02-02 20:15:56 UTC (rev 3589)
+++ pkg/FactorAnalytics/R/fitTsfmTiming.r	2015-02-03 02:13:26 UTC (rev 3590)
@@ -105,7 +105,7 @@
 #' Where N is the number of assets, K is the number of factors and T is the 
 #' number of time periods.
 #' 
-#' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen.
+#' @author Yi-An Chen.
 #' 
 #' @references 
 #' Christopherson, J. A., Carino, D. R., & Ferson, W. E. (2009). Portfolio 
@@ -142,7 +142,7 @@
 #' 
 #' # example: Market-timing factors with robust fit
 #' fit <- fitTsfmTiming(asset.names=colnames(managers[,(1:6)]), factor.names=NULL, 
-#'                mkt.name="SP500 TR",rf.name="US 3m TR",data=managers)
+#'                mkt.name="SP500.TR",rf.name="US.3m.TR",data=managers)
 #' summary(fit)
 #' fitted(fit)
 #'  
@@ -156,10 +156,13 @@
 fitTsfmTiming <- function(asset.names, factor.names=NULL, mkt.name=NULL, rf.name=NULL, 
                     data=data, fit.method=c("OLS","DLS","Robust"), 
                     variable.selection=c("none","stepwise","subsets","lars"), control=fitTsfm.control(...),...) {
+  if (is.null(mkt.name)){
+    stop("Missing argument: mkt.name has to be specified for market timing model.")
+  }
   
   factor.names <- union(factor.names,mkt.name)
   
-fit.Timing <-  fitTsfm(asset.names=asset.names,factor.names=factor.names,mkt.name=mkt.name,rf.name=rf.name,
+  fit.Timing <-  fitTsfm(asset.names=asset.names,factor.names=factor.names,mkt.name=mkt.name,rf.name=rf.name,
           data=data,fit.method=fit.method,variable.selection=variable.selection,control=control,mkt.timing="HM")
 
 return(fit.Timing)  

Modified: pkg/FactorAnalytics/R/fmCov.R
===================================================================
--- pkg/FactorAnalytics/R/fmCov.R	2015-02-02 20:15:56 UTC (rev 3589)
+++ pkg/FactorAnalytics/R/fmCov.R	2015-02-03 02:13:26 UTC (rev 3590)
@@ -1,128 +1,128 @@
-#' @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(i)*f(t) + e(i,t)}, \cr \cr  
-#' where, \code{alpha(i)} is the intercept, \code{f(t)} is a {K x 1} vector of 
-#' factor returns at time \code{t}, \code{beta(i)} 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)) = beta(i)*cov(F)*tr(beta(i)) + sig(i)^2}. \cr \cr
-#' And, the \code{N x N} covariance matrix of asset returns is \cr \cr
-#' \code{var(R) = B*cov(F)*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)
-#' 
-#' # Statistical Factor Model
-#' data(StockReturns)
-#' sfm.pca.fit <- fitSfm(r.M, k=2)
-#' fmCov(sfm.pca.fit)
-#'                       
-#' \dontrun{
-#' # 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)
-  # convert NAs to 0 to enable matrix multiplication
-  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)
-}
-
-#' @rdname fmCov
-#' @method fmCov sfm
-#' @export
-
-fmCov.sfm <- function(object, use="pairwise.complete.obs", ...) {
-  
-  # already computed via fitSfm function
-  return(object$Omega)
-}
-
+#' @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(i)*f(t) + e(i,t)}, \cr \cr  
+#' where, \code{alpha(i)} is the intercept, \code{f(t)} is a {K x 1} vector of 
+#' factor returns at time \code{t}, \code{beta(i)} 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)) = beta(i)*cov(F)*tr(beta(i)) + sig(i)^2}. \cr \cr
+#' And, the \code{N x N} covariance matrix of asset returns is \cr \cr
+#' \code{var(R) = B*cov(F)*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)
+#' 
+#' # Statistical Factor Model
+#' data(StockReturns)
+#' sfm.pca.fit <- fitSfm(r.M, k=2)
+#' fmCov(sfm.pca.fit)
+#'                       
+#' \dontrun{
+#' # 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)
+  # convert NAs to 0 to enable matrix multiplication
+  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)
+}
+
+#' @rdname fmCov
+#' @method fmCov sfm
+#' @export
+
+fmCov.sfm <- function(object, use="pairwise.complete.obs", ...) {
+  
+  # already computed via fitSfm function
+  return(object$Omega)
+}
+

Modified: pkg/FactorAnalytics/R/fmSdDecomp.R
===================================================================
--- pkg/FactorAnalytics/R/fmSdDecomp.R	2015-02-02 20:15:56 UTC (rev 3589)
+++ pkg/FactorAnalytics/R/fmSdDecomp.R	2015-02-03 02:13:26 UTC (rev 3590)
@@ -1,167 +1,167 @@
-#' @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, Sangeetha Srinivasan and Yi-An Chen
-#' 
-#' @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
-#' 
-#' # Statistical Factor Model
-#' data(StockReturns)
-#' sfm.pca.fit <- fitSfm(r.M, k=2)
-#' decomp <- fmSdDecomp(sfm.pca.fit)
-#' 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))
-## where the sum is across the K factors + 1 residual term
-
-#' @rdname fmSdDecomp
-#' @method fmSdDecomp tsfm
-#' @export
-
-fmSdDecomp.tsfm <- function(object, use="pairwise.complete.obs", ...) {
-  
-  # get beta.star: N x (K+1)
-  beta <- object$beta
-  beta[is.na(beta)] <- 0
-  beta.star <- as.matrix(cbind(beta, object$resid.sd))
-  colnames(beta.star)[dim(beta.star)[2]] <- "residual"
-  
-  # get cov(F): K x K
-  factor <- as.matrix(object$data[, object$factor.names])
-  factor.cov = cov(factor, use=use, ...)
-  
-  # get cov(F.star): (K+1) x (K+1)
-  K <- ncol(object$beta)
-  factor.star.cov <- diag(K+1)
-  factor.star.cov[1:K, 1:K] <- factor.cov
-  colnames(factor.star.cov) <- c(colnames(factor.cov),"residuals")
-  rownames(factor.star.cov) <- c(colnames(factor.cov),"residuals")
-  
-  # compute factor model sd; a vector of length N
-  Sd.fm <- sqrt(rowSums(beta.star %*% factor.star.cov * beta.star))
-  
-  # compute marginal, component and percentage contributions to sd
-  # each of these have dimensions: N x (K+1)
-  mSd <- (t(factor.star.cov %*% t(beta.star)))/Sd.fm 
-  cSd <- mSd * beta.star 
-  pcSd = 100* cSd/Sd.fm 
-  
-  fm.sd.decomp <- list(Sd.fm=Sd.fm, mSd=mSd, cSd=cSd, pcSd=pcSd)
-  
-  return(fm.sd.decomp)
-}
-
-#' @rdname fmSdDecomp
-#' @method fmSdDecomp sfm
-#' @export
-
-fmSdDecomp.sfm <- function(object, use="pairwise.complete.obs", ...) {
-  
-  # get beta.star: N x (K+1)
-  beta <- object$loadings
-  beta[is.na(beta)] <- 0
-  beta.star <- as.matrix(cbind(beta, object$resid.sd))
-  colnames(beta.star)[dim(beta.star)[2]] <- "residual"
-  
-  # get cov(F): K x K
-  factor <- as.matrix(object$factors)
-  factor.cov = cov(factor, use=use, ...)
-  
-  # get cov(F.star): (K+1) x (K+1)
-  K <- object$k
-  factor.star.cov <- diag(K+1)
-  factor.star.cov[1:K, 1:K] <- factor.cov
-  colnames(factor.star.cov) <- c(colnames(factor.cov),"residuals")
-  rownames(factor.star.cov) <- c(colnames(factor.cov),"residuals")
-  
-  # compute factor model sd; a vector of length N
-  Sd.fm <- sqrt(rowSums(beta.star %*% factor.star.cov * beta.star))
-  
-  # compute marginal, component and percentage contributions to sd
-  # each of these have dimensions: N x (K+1)
-  mSd <- (t(factor.star.cov %*% t(beta.star)))/Sd.fm 
-  cSd <- mSd * beta.star 
-  pcSd = 100* cSd/Sd.fm 
-  
-  fm.sd.decomp <- list(Sd.fm=Sd.fm, mSd=mSd, cSd=cSd, pcSd=pcSd)
-  
-  return(fm.sd.decomp)
-}
-
+#' @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, Sangeetha Srinivasan and Yi-An Chen
+#' 
+#' @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
+#' 
+#' # Statistical Factor Model
+#' data(StockReturns)
+#' sfm.pca.fit <- fitSfm(r.M, k=2)
+#' decomp <- fmSdDecomp(sfm.pca.fit)
+#' 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))
+## where the sum is across the K factors + 1 residual term
+
+#' @rdname fmSdDecomp
+#' @method fmSdDecomp tsfm
+#' @export
+
+fmSdDecomp.tsfm <- function(object, use="pairwise.complete.obs", ...) {
+  
+  # get beta.star: N x (K+1)
+  beta <- object$beta
+  beta[is.na(beta)] <- 0
+  beta.star <- as.matrix(cbind(beta, object$resid.sd))
+  colnames(beta.star)[dim(beta.star)[2]] <- "residual"
+  
+  # get cov(F): K x K
+  factor <- as.matrix(object$data[, object$factor.names])
+  factor.cov = cov(factor, use=use, ...)
+  
+  # get cov(F.star): (K+1) x (K+1)
+  K <- ncol(object$beta)
+  factor.star.cov <- diag(K+1)
+  factor.star.cov[1:K, 1:K] <- factor.cov
+  colnames(factor.star.cov) <- c(colnames(factor.cov),"residuals")
+  rownames(factor.star.cov) <- c(colnames(factor.cov),"residuals")
+  
+  # compute factor model sd; a vector of length N
+  Sd.fm <- sqrt(rowSums(beta.star %*% factor.star.cov * beta.star))
+  
+  # compute marginal, component and percentage contributions to sd
+  # each of these have dimensions: N x (K+1)
+  mSd <- (t(factor.star.cov %*% t(beta.star)))/Sd.fm 
+  cSd <- mSd * beta.star 
+  pcSd = 100* cSd/Sd.fm 
+  
+  fm.sd.decomp <- list(Sd.fm=Sd.fm, mSd=mSd, cSd=cSd, pcSd=pcSd)
+  
+  return(fm.sd.decomp)
+}
+
+#' @rdname fmSdDecomp
+#' @method fmSdDecomp sfm
+#' @export
+
+fmSdDecomp.sfm <- function(object, use="pairwise.complete.obs", ...) {
+  
+  # get beta.star: N x (K+1)
+  beta <- object$loadings
+  beta[is.na(beta)] <- 0
+  beta.star <- as.matrix(cbind(beta, object$resid.sd))
+  colnames(beta.star)[dim(beta.star)[2]] <- "residual"
+  
+  # get cov(F): K x K
+  factor <- as.matrix(object$factors)
+  factor.cov = cov(factor, use=use, ...)
+  
+  # get cov(F.star): (K+1) x (K+1)
+  K <- object$k
+  factor.star.cov <- diag(K+1)
+  factor.star.cov[1:K, 1:K] <- factor.cov
+  colnames(factor.star.cov) <- c(colnames(factor.cov),"residuals")
+  rownames(factor.star.cov) <- c(colnames(factor.cov),"residuals")
+  
+  # compute factor model sd; a vector of length N
+  Sd.fm <- sqrt(rowSums(beta.star %*% factor.star.cov * beta.star))
+  
+  # compute marginal, component and percentage contributions to sd
+  # each of these have dimensions: N x (K+1)
+  mSd <- (t(factor.star.cov %*% t(beta.star)))/Sd.fm 
+  cSd <- mSd * beta.star 
+  pcSd = 100* cSd/Sd.fm 
+  
+  fm.sd.decomp <- list(Sd.fm=Sd.fm, mSd=mSd, cSd=cSd, pcSd=pcSd)
+  
+  return(fm.sd.decomp)
+}
+

Modified: pkg/FactorAnalytics/R/paFm.r
===================================================================
--- pkg/FactorAnalytics/R/paFm.r	2015-02-02 20:15:56 UTC (rev 3589)
+++ pkg/FactorAnalytics/R/paFm.r	2015-02-03 02:13:26 UTC (rev 3590)
@@ -1,239 +1,239 @@
-#' @title Compute cumulative mean attribution for factor models
-#' 
-#' @description Decompose total returns into returns attributed to factors and 
-#' specific returns. An object of class \code{"pafm"} is generated, with 
-#' methods for generic functions \code{plot}, \code{summary} and \code{print}.
-#' 
-#' @details Total returns can be decomposed into returns attributed to factors 
-#' and specific returns. \cr \eqn{R_t = \sum  b_k * f_kt + u_t, t=1...T} \cr
-#' \code{b_k} is exposure to factor k and \code{f_kt} is factor k's return at 
-#' time t. The return attributed to factor k is \code{b_k * f_kt} and specific 
-#' return is \code{u_t}. 
-#' 
-#' @param fit an object of class \code{tsfm}, \code{sfm} or \code{ffm}.
-#' @param ... other arguments/controls passed to the fit methods.
-#' 
-#' @return The returned object is of class \code{"pafm"} containing
-#' \item{cum.ret.attr.f}{N X K matrix of cumulative return attributed to
-#' factors.}
-#' \item{cum.spec.ret}{length-N vector of cumulative specific returns.}
-#' \item{attr.list}{list of time series of attributed returns for every
-#' portfolio.}
-#' 
-#' @author Yi-An Chen and Sangeetha Srinivasan
-#' 
-#' @references Grinold, R. and Kahn, R. (1999) Active Portfolio Management: A 
-#' Quantitative Approach for Producing Superior Returns and Controlling Risk. 
-#' McGraw-Hill.
-#' 
-#' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}} 
-#' for the factor model fitting functions.
-#' 
-#' The \code{pafm} methods for generic functions: 
-#' \code{\link{plot.pafm}}, \code{\link{print.pafm}} and 
-#' \code{\link{summary.pafm}}. 
-#' 
-#' @examples
-#' data(managers)
-#' fit <- fitTsfm(asset.names=colnames(managers[, (1:6)]), 
-#'                factor.names=c("EDHEC LS EQ","SP500 TR"), data=managers)
-#' # without benchmark
-#' fm.attr <- paFm(fit)
-#' 
-#' @importFrom PerformanceAnalytics Return.cumulative
-#' 
-#' @export
-#' 
-
-paFm <- function(fit, ...) {
-  
-  # check input object validity
-  if (!inherits(fit, c("tsfm", "sfm", "ffm"))) {
-    stop("Invalid argument: fit should be of class 'tsfm', 'sfm' or 'ffm'.")
-  }
-  
-  # TSFM chunk  
-  
-  if (class(fit)=="tsfm") {
-    
-    # return attributed to factors
-    cum.attr.ret <- fit$beta
-    cum.spec.ret <- fit$alpha
-    factorNames <- fit$factor.names
-    fundNames <- fit$asset.names
-    
-    attr.list <- list()
-    
-    for (k in fundNames) {
-      fit.lm <- fit$asset.fit[[k]]
-      
-      ## extract information from lm, lmRob or lars object
-      reg.xts <- na.omit(fit$data[, c(k, factorNames)])
-      dates <- as.Date(index(reg.xts))
-      actual.xts <- xts(fit.lm$model[1], dates)
-      # attributed returns
-      # active portfolio management p.512 17A.9 
-      # top-down method
-      
-      cum.ret <- Return.cumulative(actual.xts)
-      # setup initial value
-      attr.ret.xts.all <- xts(, dates)
-      
-      for ( i in factorNames ) {
-        
-        if (is.na(fit$beta[k, i])) {
-          cum.attr.ret[k, i] <- NA
-          attr.ret.xts.all <- merge(attr.ret.xts.all, 
-                                    xts(rep(NA, length(date)), dates))  
-        } else {
-          attr.ret.xts <- actual.xts - 
-            xts(as.matrix(fit.lm$model[i])%*%as.matrix(fit.lm$coef[i]), dates)  
-          cum.attr.ret[k, i] <- cum.ret - 
-            Return.cumulative(actual.xts-attr.ret.xts)  
-          attr.ret.xts.all <- merge(attr.ret.xts.all, attr.ret.xts)
-        }
-      }
-      
-      # specific returns    
-      spec.ret.xts <- actual.xts - 
[TRUNCATED]

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


More information about the Returnanalytics-commits mailing list