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

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Sat Jun 21 07:59:41 CEST 2014


Author: pragnya
Date: 2014-06-21 07:59:41 +0200 (Sat, 21 Jun 2014)
New Revision: 3433

Added:
   pkg/FactorAnalytics/R/paFM.r
   pkg/FactorAnalytics/R/plot.pafm.r
   pkg/FactorAnalytics/R/print.pafm.r
   pkg/FactorAnalytics/R/summary.pafm.r
   pkg/FactorAnalytics/man/fitTimeSeriesFactorModel.Rd
   pkg/FactorAnalytics/man/paFM.Rd
   pkg/FactorAnalytics/man/plot.pafm.Rd
   pkg/FactorAnalytics/man/print.pafm.Rd
   pkg/FactorAnalytics/man/summary.pafm.Rd
Removed:
   pkg/FactorAnalytics/R/factorModelPerformanceAttribution.r
   pkg/FactorAnalytics/R/plot.FM.attribution.r
   pkg/FactorAnalytics/R/print.FM.attribution.r
   pkg/FactorAnalytics/R/summary.FM.attribution.r
   pkg/FactorAnalytics/man/factorModelPerformanceAttribution.Rd
   pkg/FactorAnalytics/man/fitTimeseriesFactorModel.Rd
   pkg/FactorAnalytics/man/plot.FM.attribution.Rd
   pkg/FactorAnalytics/man/print.FM.attribution.Rd
   pkg/FactorAnalytics/man/summary.FM.attribution.Rd
Modified:
   pkg/FactorAnalytics/DESCRIPTION
   pkg/FactorAnalytics/NAMESPACE
   pkg/FactorAnalytics/R/factorModelEsDecomposition.R
   pkg/FactorAnalytics/R/factorModelMonteCarlo.R
   pkg/FactorAnalytics/R/factorModelVaRDecomposition.R
   pkg/FactorAnalytics/R/fitFundamentalFactorModel.R
   pkg/FactorAnalytics/R/fitStatisticalFactorModel.R
   pkg/FactorAnalytics/R/fitTimeSeriesFactorModel.R
   pkg/FactorAnalytics/R/plot.FundamentalFactorModel.r
   pkg/FactorAnalytics/R/plot.StatFactorModel.r
   pkg/FactorAnalytics/R/plot.TimeSeriesFactorModel.r
   pkg/FactorAnalytics/R/predict.FundamentalFactorModel.r
   pkg/FactorAnalytics/R/predict.TimeSeriesFactorModel.r
   pkg/FactorAnalytics/man/plot.TimeSeriesFactorModel.Rd
   pkg/FactorAnalytics/man/predict.FundamentalFactorModel.Rd
   pkg/FactorAnalytics/vignettes/fundamentalFM.Rnw
Log:
Removed library(), require() from all functions. Changed the name of the function factorModelPerformanceAttribution to paFM and its returned object class to "pafm". 
Changed the vignette, plot, print and summary methods for paFM accordingly. Changed the 1st argument in the method functions to match up with the default methods in plot, print and summary. Fixed asset.names in predict.FundamentalFactorModel to correctly reflect output from the fitted object.

Modified: pkg/FactorAnalytics/DESCRIPTION
===================================================================
--- pkg/FactorAnalytics/DESCRIPTION	2014-06-20 20:56:58 UTC (rev 3432)
+++ pkg/FactorAnalytics/DESCRIPTION	2014-06-21 05:59:41 UTC (rev 3433)
@@ -1,30 +1,30 @@
-Package: factorAnalytics
-Type: Package
-Title: Factor Analytics
-Version: 1.0
-Date: 2014-06-18
-Author: Eric Zivot and Yi-An Chen
-Maintainer: Yi-An Chen <chenyian 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 are also provided for the results
-    of the fitted models.
-License: GPL-2
-Depends:
-    R (>= 2.14.0),
-    robust,
-    leaps,
-    lars,
-    PerformanceAnalytics,
-    sn,
-    tseries,
-    strucchange,
-    ellipse,
-    doParallel
-Suggests:
-    testthat
-LazyLoad: yes
+Package: factorAnalytics
+Type: Package
+Title: Factor Analytics
+Version: 1.0
+Date: 2014-06-18
+Author: Eric Zivot and Yi-An Chen
+Maintainer: Yi-An Chen <chenyian 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 are also provided for the results
+    of the fitted models.
+License: GPL-2
+Depends:
+    R (>= 2.14.0),
+    robust,
+    leaps,
+    lars,
+    PerformanceAnalytics,
+    sn,
+    tseries,
+    strucchange,
+    ellipse,
+    doParallel
+Suggests:
+    testthat, quantmod
+LazyLoad: yes

Modified: pkg/FactorAnalytics/NAMESPACE
===================================================================
--- pkg/FactorAnalytics/NAMESPACE	2014-06-20 20:56:58 UTC (rev 3432)
+++ pkg/FactorAnalytics/NAMESPACE	2014-06-21 05:59:41 UTC (rev 3433)
@@ -1,30 +1,30 @@
 # Generated by roxygen2 (4.0.1): do not edit by hand
 
-S3method(plot,FM.attribution)
 S3method(plot,FundamentalFactorModel)
 S3method(plot,StatFactorModel)
 S3method(plot,TimeSeriesFactorModel)
+S3method(plot,pafm)
 S3method(predict,FundamentalFactorModel)
 S3method(predict,StatFactorModel)
 S3method(predict,TimeSeriesFactorModel)
-S3method(print,FM.attribution)
 S3method(print,FundamentalFactorModel)
 S3method(print,StatFactorModel)
 S3method(print,TimeSeriesFactorModel)
-S3method(summary,FM.attribution)
+S3method(print,pafm)
 S3method(summary,FundamentalFactorModel)
 S3method(summary,StatFactorModel)
 S3method(summary,TimeSeriesFactorModel)
+S3method(summary,pafm)
 export(dCornishFisher)
 export(factorModelCovariance)
 export(factorModelEsDecomposition)
 export(factorModelMonteCarlo)
-export(factorModelPerformanceAttribution)
 export(factorModelSdDecomposition)
 export(factorModelVaRDecomposition)
 export(fitFundamentalFactorModel)
 export(fitStatisticalFactorModel)
 export(fitTimeSeriesFactorModel)
 export(pCornishFisher)
+export(paFM)
 export(qCornishFisher)
 export(rCornishFisher)

Modified: pkg/FactorAnalytics/R/factorModelEsDecomposition.R
===================================================================
--- pkg/FactorAnalytics/R/factorModelEsDecomposition.R	2014-06-20 20:56:58 UTC (rev 3432)
+++ pkg/FactorAnalytics/R/factorModelEsDecomposition.R	2014-06-21 05:59:41 UTC (rev 3433)
@@ -1,132 +1,131 @@
-#' Compute Factor Model ES Decomposition
-#' 
-#' Compute the factor model factor expected shortfall (ES) decomposition for an
-#' asset based on Euler's theorem given historic or simulated data and factor
-#' model parameters. 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 compute as the sample quantile of
-#' the historic or simulated data.
-#' 
-#' The factor model has the form \cr \code{R(t) = beta'F(t) + e(t) = beta.star'F.star(t)}\cr
-#' where beta.star = (beta, sig.e)' and F.star(t) = (F(t)', z(t))' By Euler's
-#' theorem:\cr \code{ES.fm = sum(cES.fm) = sum(beta.star*mES.fm)} \cr
-#' 
-#' @param Data \code{B x (k+2)} matrix of historic or simulated data. The first
-#' column contains the fund returns, the second through \code{k+1}st columns
-#' contain the returns on the \code{k} factors, and the \code{(k+2)}nd column
-#' contain residuals scaled to have unit variance.
-#' @param beta.vec \code{k x 1} vector of factor betas.
-#' @param sig2.e scalar, residual variance from factor model.
-#' @param tail.prob scalar, tail probability for VaR quantile. Typically 0.01
-#' or 0.05.
-#' @param VaR.method character, method for computing VaR. Valid choices are
-#' one of "modified","gaussian","historical", "kernel". computation is done with the \code{VaR}
-#' in the PerformanceAnalytics package.
-#' 
-#' 
-#' @return A list with the following components:
-#' \itemize{
-#' \item{VaR} {Scalar, nonparametric VaR value for fund reported as a
-#' positive number.}
-#' \item{n.exceed} Scalar, number of observations beyond VaR.
-#' \item{idx.exceed} n.exceed x 1 vector giving index values of exceedences.
-#' \item{ES.fm}  Scalar. nonparametric ES value for fund reported as a positive number.
-#' \item{mES.fm} (K+1) x 1 vector of factor marginal contributions to ES.
-#' \item{cES.fm} (K+1) x 1 vector of factor component contributions to ES.
-#' \item{pcES.fm} (K+1) x 1 vector of factor percentage component contributions to ES.
-#' }
-#' @author Eric Zviot and Yi-An Chen.
-#' @references \enumerate{ 
-#' \item Hallerback (2003), "Decomposing Portfolio Value-at-Risk: A
-#' General Analysis", The Journal of Risk 5/2.
-#' \item Yamai and Yoshiba (2002)."Comparative Analyses of Expected Shortfall and Value-at-Risk: Their
-#' Estimation Error, Decomposition, and Optimization Bank of Japan.
-#' \item Meucci (2007). "Risk Contributions from Generic User-Defined Factors," Risk. 
-#' \item Epperlein and Smillie (2006) "Cracking VAR with Kernels," Risk.
-#' }
-#' @examples
-#' 
-#' data(managers.df)
-#' fit.macro <- fitTimeSeriesFactorModel(assets.names=colnames(managers.df[,(1:6)]),
-#'                                      factors.names=c("EDHEC.LS.EQ","SP500.TR"),
-#'                                      data=managers.df,fit.method="OLS")
-#' # risk factor contribution to ETL
-#' # combine fund returns, factor returns and residual returns for HAM1
-#' tmpData = cbind(managers.df[,1],managers.df[,c("EDHEC.LS.EQ","SP500.TR")] ,
-#' residuals(fit.macro$asset.fit$HAM1)/sqrt(fit.macro$resid.variance[1]))
-#' colnames(tmpData)[c(1,4)] = c("HAM1", "residual")
-#' factor.es.decomp.HAM1 = factorModelEsDecomposition(tmpData, fit.macro$beta[1,],
-#'                                                   fit.macro$resid.variance[1], tail.prob=0.05,
-#'                                                   VaR.method="historical" )
-#' 
-#' # fundamental factor model
-#' # try to find factor contribution to ES for STI 
-#' data(Stock.df)
-#' fit.fund <- fitFundamentalFactorModel(exposure.names=c("BOOK2MARKET", "LOG.MARKETCAP")
-#'                                       , data=stock,returnsvar = "RETURN",datevar = "DATE",  
-#'                                      assetvar = "TICKER",
-#'                                       wls = TRUE, regression = "classic", 
-#'                                       covariance = "classic", full.resid.cov = FALSE)
-#'  idx <- fit.fund$data[,fit.fund$assetvar]  == "STI"  
-#' asset.ret <- fit.fund$data[idx,fit.fund$returnsvar]
-#' tmpData = cbind(asset.ret, fit.fund$factor.returns,
-#'                 fit.fund$residuals[,"STI"]/sqrt(fit.fund$resid.variance["STI"]) )
-#' colnames(tmpData)[c(1,length(tmpData[1,]))] = c("STI", "residual")
-#' factorModelEsDecomposition(tmpData, 
-#'                           fit.fund$beta["STI",],
-#'                           fit.fund$resid.variance["STI"], tail.prob=0.05,VaR.method="historical")
-#' 
-#' @export
-#' 
-factorModelEsDecomposition <-
-function(Data, beta.vec, sig2.e, tail.prob = 0.05,
-         VaR.method=c("modified", "gaussian", "historical", "kernel")) {
-
-  require(PerformanceAnalytics)
-  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, sqrt(sig2.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)
-}
-
+#' Compute Factor Model ES Decomposition
+#' 
+#' Compute the factor model factor expected shortfall (ES) decomposition for an
+#' asset based on Euler's theorem given historic or simulated data and factor
+#' model parameters. 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 compute as the sample quantile of
+#' the historic or simulated data.
+#' 
+#' The factor model has the form \cr \code{R(t) = beta'F(t) + e(t) = beta.star'F.star(t)}\cr
+#' where beta.star = (beta, sig.e)' and F.star(t) = (F(t)', z(t))' By Euler's
+#' theorem:\cr \code{ES.fm = sum(cES.fm) = sum(beta.star*mES.fm)} \cr
+#' 
+#' @param Data \code{B x (k+2)} matrix of historic or simulated data. The first
+#' column contains the fund returns, the second through \code{k+1}st columns
+#' contain the returns on the \code{k} factors, and the \code{(k+2)}nd column
+#' contain residuals scaled to have unit variance.
+#' @param beta.vec \code{k x 1} vector of factor betas.
+#' @param sig2.e scalar, residual variance from factor model.
+#' @param tail.prob scalar, tail probability for VaR quantile. Typically 0.01
+#' or 0.05.
+#' @param VaR.method character, method for computing VaR. Valid choices are
+#' one of "modified","gaussian","historical", "kernel". computation is done with the \code{VaR}
+#' in the PerformanceAnalytics package.
+#' 
+#' 
+#' @return A list with the following components:
+#' \itemize{
+#' \item{VaR} {Scalar, nonparametric VaR value for fund reported as a
+#' positive number.}
+#' \item{n.exceed} Scalar, number of observations beyond VaR.
+#' \item{idx.exceed} n.exceed x 1 vector giving index values of exceedences.
+#' \item{ES.fm}  Scalar. nonparametric ES value for fund reported as a positive number.
+#' \item{mES.fm} (K+1) x 1 vector of factor marginal contributions to ES.
+#' \item{cES.fm} (K+1) x 1 vector of factor component contributions to ES.
+#' \item{pcES.fm} (K+1) x 1 vector of factor percentage component contributions to ES.
+#' }
+#' @author Eric Zviot and Yi-An Chen.
+#' @references \enumerate{ 
+#' \item Hallerback (2003), "Decomposing Portfolio Value-at-Risk: A
+#' General Analysis", The Journal of Risk 5/2.
+#' \item Yamai and Yoshiba (2002)."Comparative Analyses of Expected Shortfall and Value-at-Risk: Their
+#' Estimation Error, Decomposition, and Optimization Bank of Japan.
+#' \item Meucci (2007). "Risk Contributions from Generic User-Defined Factors," Risk. 
+#' \item Epperlein and Smillie (2006) "Cracking VAR with Kernels," Risk.
+#' }
+#' @examples
+#' 
+#' data(managers.df)
+#' fit.macro <- fitTimeSeriesFactorModel(assets.names=colnames(managers.df[,(1:6)]),
+#'                                      factors.names=c("EDHEC.LS.EQ","SP500.TR"),
+#'                                      data=managers.df,fit.method="OLS")
+#' # risk factor contribution to ETL
+#' # combine fund returns, factor returns and residual returns for HAM1
+#' tmpData = cbind(managers.df[,1],managers.df[,c("EDHEC.LS.EQ","SP500.TR")] ,
+#' residuals(fit.macro$asset.fit$HAM1)/sqrt(fit.macro$resid.variance[1]))
+#' colnames(tmpData)[c(1,4)] = c("HAM1", "residual")
+#' factor.es.decomp.HAM1 = factorModelEsDecomposition(tmpData, fit.macro$beta[1,],
+#'                                                   fit.macro$resid.variance[1], tail.prob=0.05,
+#'                                                   VaR.method="historical" )
+#' 
+#' # fundamental factor model
+#' # try to find factor contribution to ES for STI 
+#' data(Stock.df)
+#' fit.fund <- fitFundamentalFactorModel(exposure.names=c("BOOK2MARKET", "LOG.MARKETCAP")
+#'                                       , data=stock,returnsvar = "RETURN",datevar = "DATE",  
+#'                                      assetvar = "TICKER",
+#'                                       wls = TRUE, regression = "classic", 
+#'                                       covariance = "classic", full.resid.cov = FALSE)
+#'  idx <- fit.fund$data[,fit.fund$assetvar]  == "STI"  
+#' asset.ret <- fit.fund$data[idx,fit.fund$returnsvar]
+#' tmpData = cbind(asset.ret, fit.fund$factor.returns,
+#'                 fit.fund$residuals[,"STI"]/sqrt(fit.fund$resid.variance["STI"]) )
+#' colnames(tmpData)[c(1,length(tmpData[1,]))] = c("STI", "residual")
+#' factorModelEsDecomposition(tmpData, 
+#'                           fit.fund$beta["STI",],
+#'                           fit.fund$resid.variance["STI"], tail.prob=0.05,VaR.method="historical")
+#' 
+#' @export
+#' 
+factorModelEsDecomposition <-
+function(Data, beta.vec, sig2.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, sqrt(sig2.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)
+}
+

Modified: pkg/FactorAnalytics/R/factorModelMonteCarlo.R
===================================================================
--- pkg/FactorAnalytics/R/factorModelMonteCarlo.R	2014-06-20 20:56:58 UTC (rev 3432)
+++ pkg/FactorAnalytics/R/factorModelMonteCarlo.R	2014-06-21 05:59:41 UTC (rev 3433)
@@ -1,157 +1,154 @@
-#' Simulate returns using factor model Monte Carlo method.
-#' 
-#' Simulate returns using factor model Monte Carlo method. Parametric method
-#' like normal distribution, Cornish-Fisher and skew-t distribution for
-#' residuals can be selected. Resampling method such as non-parametric bootstrap
-#' or stationary bootstrap can be selected.
-#' 
-#' The factor model Monte Carlo method is described in Jiang (2009).
-#' 
-#' @param n.boot Integer number of bootstrap samples.
-#' @param factorData \code{n.months x n.funds} matrix or data.frame of factor
-#' returns.
-#' @param Beta.mat \code{n.funds x n.factors} matrix of factor betas.
-#' @param Alpha.mat \code{n.funds x 1} matrix of factor alphas (intercepts). If
-#' \code{NULL} then assume that all alphas are zero.
-#' @param residualData \code{n.funds x n.parms} matrix of residual distribution
-#' parameters. The columns of \code{residualData} depend on the value of
-#' \code{residual.dist}. If \code{residual.dist = "normal"}, then
-#' \code{residualData} has one column containing variance values; if
-#' \code{residual.dist = "Cornish-Fisher"}, then \code{residualData} has three
-#' columns containing variance, skewness and excess kurtosis values; if
-#' \code{residual.dist="skew-t"}, then \code{residualData} has four columns
-#' containing location, scale, shape, and df values.
-#' @param residual.dist character vector specifying the residual distribution.
-#' Choices are "normal" for the normal distribution; "Cornish-Fisher" for the
-#' Cornish-Fisher distribution based on the Cornish-Fisher expansion of the
-#' normal distribution quantile; "skew-t" for the skewed Student's t
-#' distribution of Azzalini and Captiano.
-#' @param boot.method character vector specifying the resampling method.
-#' Choices are "random" for random sampling with replacement (non-parametric
-#' bootstrap); "block" for stationary block bootstrapping.
-#' @param seed integer random number seed used for resampling the factor
-#' returns.
-#' @param return.factors logical; if \code{TRUE} then return resampled factors
-#' in output list object.
-#' @param return.residuals logical; if \code{TRUE} then return simulated
-#' residuals in output list object.
-#' @return A list with the following components:
-#' \itemize{
-#' \item{returns} \code{n.boot x n.funds} matrix of simulated fund
-#' returns.
-#' \item{factors} \code{n.boot x n.factors} matrix of resampled factor
-#' returns. Returned only if \code{return.factors = TRUE}.
-#' \item{residuals} \code{n.boot x n.funds} matrix of simulated fund
-#' residuals. Returned only if \code{return.residuals = TRUE}.
-#' }
-#' @author Eric Zivot and Yi-An Chen.
-#' @references Jiang, Y. (2009). UW PhD Thesis.
-#' @export
-#' @examples
-#' 
-#' # load data from the database
-#' data(managers.df)
-#' fit <- fitTimeSeriesFactorModel(assets.names=colnames(managers.df[,(1:6)]),
-#'                                 factors.names=c("EDHEC.LS.EQ","SP500.TR"),
-#'                                 data=managers.df,fit.method="OLS")
-#' factorData= managers.df[,c("EDHEC.LS.EQ","SP500.TR")]  
-#' Beta.mat=fit$beta
-#' residualData=as.matrix(fit$resid.variance,1,6) 
-#' n.boot=1000
-#' # bootstrap returns data from factor model with residuals sample from normal distribution
-#' bootData <- factorModelMonteCarlo(n.boot, factorData,Beta.mat, residual.dist="normal",
-#'                                   residualData, Alpha.mat=NULL, boot.method="random",
-#'                                   seed = 123, return.factors = "TRUE", return.residuals = 
-#'                                   "TRUE")
-#' # Cornish-Fisher distribution
-#' # build different residualData matrix
-#' residualData <- cbind(c(1,2,1,3,0.1,0.5),rnorm(6),c(2,3,1,2,1,0))
-#' colnames(residualData) <- c("var","skew","ekurt")
-#' rownames(residualData) <- colnames(managers.df[,(1:6)])
-#' bootData <- factorModelMonteCarlo(n.boot, factorData,Beta.mat, residual.dist="Cornish-Fisher",
-#'                                   residualData, Alpha.mat=NULL, boot.method="random",
-#'                                   seed = 123, return.factors = "TRUE", return.residuals =
-#'                                   "TRUE")
-#' 
-#' 
-#' # skew-t distribution
-#' # build residualData matrix
-#' residualData <- cbind(rnorm(6),c(1,2,1,3,0.1,0.5),rnorm(6),c(2,3,1,6,10,100))
-#' colnames(residualData) <- c("xi","omega","alpha","nu")
-#' rownames(residualData) <- colnames(managers.df[,(1:6)])
-#' bootData <- factorModelMonteCarlo(n.boot, factorData,Beta.mat, residual.dist="skew-t",
-#'                                   residualData, Alpha.mat=NULL, boot.method="random",
-#'                                   seed = 123, return.factors = "TRUE", return.residuals =
-#'                                   "TRUE")
-#' 
-factorModelMonteCarlo <-
-  function (n.boot = 1000, factorData, Beta.mat, Alpha.mat = NULL, 
-            residualData, residual.dist = c("normal", "Cornish-Fisher", 
-                                            "skew-t"), boot.method = c("random", "block"), seed = 123, 
-            return.factors = FALSE, return.residuals = FALSE) 
-  {
-    require(tseries)
-    require(sn)
-    require(PerformanceAnalytics)
-    boot.method = boot.method[1]
-    residual.dist = residual.dist[1]
-    set.seed(seed)
-    if (nrow(Beta.mat) != nrow(residualData)) {
-      stop("Beta.mat and residualData have different number of rows")
-    }
-    factorData = as.matrix(factorData)
-    n.funds = nrow(Beta.mat)
-    fund.names = rownames(Beta.mat)
-    if (is.null(Alpha.mat)) {
-      Alpha.mat = matrix(0, nrow(Beta.mat))
-      rownames(Alpha.mat) = fund.names
-    }
-    if (boot.method == "random") {
-      bootIdx = sample(nrow(factorData), n.boot, replace = TRUE)
-    }
-    else {
-      n.samples = round(n.boot/nrow(factorData))
-      n.adj = n.boot - n.samples * nrow(factorData)
-      bootIdx = as.vector(tsbootstrap(1:nrow(factorData), nb = n.samples))
-      if (n.adj > 0) {
-        bootIdx = c(bootIdx, bootIdx[1:n.adj])
-      }
-    }
-    factorDataBoot = factorData[bootIdx, ]
-    fundReturnsBoot = matrix(0, n.boot, n.funds)
-    residualsSim = matrix(0, n.boot, n.funds)
-    colnames(fundReturnsBoot) = colnames(residualsSim) = fund.names
-    for (i in fund.names) {
-      set.seed(which(fund.names == i))
-      if (residual.dist == "normal") {
-        residualsSim[, i] = rnorm(n.boot, sd = sqrt(residualData[i, 
-                                                                 ]))
-      }
-      else if (residual.dist == "Cornish-Fisher") {
-        residualsSim[, i] = rCornishFisher(n.boot, sigma = sqrt(residualData[i, 
-                                                                             "var"]), skew = residualData[i, "skew"], ekurt = residualData[i, 
-                                                                                                                                           "ekurt"])
-      }
-      else if (residual.dist == "skew-t") {
-        residualsSim[, i] = rst(n.boot, xi = residualData[i, 
-                                                                "xi"], omega = residualData[i, "omega"], 
-                                alpha = residualData[i, "alpha"], nu = residualData[i, 
-                                                                                    "nu"])
-      }
-      else {
-        stop("Invalid residual distribution")
-      }
-      fundReturnsBoot[, i] = Alpha.mat[i, 1] + factorDataBoot[, 
-                                                              colnames(Beta.mat)] %*% t(Beta.mat[i, , drop = FALSE]) + 
-        residualsSim[, i]
-    }
-    ans = list(returns = fundReturnsBoot)
-    if (return.factors) {
-      ans$factors = factorDataBoot
-    }
-    if (return.residuals) {
-      ans$residuals = residualsSim
-    }
-    return(ans)
-  }
-
+#' Simulate returns using factor model Monte Carlo method.
+#' 
+#' Simulate returns using factor model Monte Carlo method. Parametric method
+#' like normal distribution, Cornish-Fisher and skew-t distribution for
+#' residuals can be selected. Resampling method such as non-parametric bootstrap
+#' or stationary bootstrap can be selected.
+#' 
+#' The factor model Monte Carlo method is described in Jiang (2009).
+#' 
+#' @param n.boot Integer number of bootstrap samples.
+#' @param factorData \code{n.months x n.funds} matrix or data.frame of factor
+#' returns.
+#' @param Beta.mat \code{n.funds x n.factors} matrix of factor betas.
+#' @param Alpha.mat \code{n.funds x 1} matrix of factor alphas (intercepts). If
+#' \code{NULL} then assume that all alphas are zero.
+#' @param residualData \code{n.funds x n.parms} matrix of residual distribution
+#' parameters. The columns of \code{residualData} depend on the value of
+#' \code{residual.dist}. If \code{residual.dist = "normal"}, then
+#' \code{residualData} has one column containing variance values; if
+#' \code{residual.dist = "Cornish-Fisher"}, then \code{residualData} has three
+#' columns containing variance, skewness and excess kurtosis values; if
+#' \code{residual.dist="skew-t"}, then \code{residualData} has four columns
+#' containing location, scale, shape, and df values.
+#' @param residual.dist character vector specifying the residual distribution.
+#' Choices are "normal" for the normal distribution; "Cornish-Fisher" for the
+#' Cornish-Fisher distribution based on the Cornish-Fisher expansion of the
+#' normal distribution quantile; "skew-t" for the skewed Student's t
+#' distribution of Azzalini and Captiano.
+#' @param boot.method character vector specifying the resampling method.
+#' Choices are "random" for random sampling with replacement (non-parametric
+#' bootstrap); "block" for stationary block bootstrapping.
+#' @param seed integer random number seed used for resampling the factor
+#' returns.
+#' @param return.factors logical; if \code{TRUE} then return resampled factors
+#' in output list object.
+#' @param return.residuals logical; if \code{TRUE} then return simulated
+#' residuals in output list object.
+#' @return A list with the following components:
+#' \itemize{
+#' \item{returns} \code{n.boot x n.funds} matrix of simulated fund
+#' returns.
+#' \item{factors} \code{n.boot x n.factors} matrix of resampled factor
+#' returns. Returned only if \code{return.factors = TRUE}.
+#' \item{residuals} \code{n.boot x n.funds} matrix of simulated fund
+#' residuals. Returned only if \code{return.residuals = TRUE}.
+#' }
+#' @author Eric Zivot and Yi-An Chen.
+#' @references Jiang, Y. (2009). UW PhD Thesis.
+#' @export
+#' @examples
+#' 
+#' # load data from the database
+#' data(managers.df)
+#' fit <- fitTimeSeriesFactorModel(assets.names=colnames(managers.df[,(1:6)]),
+#'                                 factors.names=c("EDHEC.LS.EQ","SP500.TR"),
+#'                                 data=managers.df,fit.method="OLS")
+#' factorData= managers.df[,c("EDHEC.LS.EQ","SP500.TR")]  
+#' Beta.mat=fit$beta
+#' residualData=as.matrix(fit$resid.variance,1,6) 
+#' n.boot=1000
+#' # bootstrap returns data from factor model with residuals sample from normal distribution
+#' bootData <- factorModelMonteCarlo(n.boot, factorData,Beta.mat, residual.dist="normal",
+#'                                   residualData, Alpha.mat=NULL, boot.method="random",
+#'                                   seed = 123, return.factors = "TRUE", return.residuals = 
+#'                                   "TRUE")
+#' # Cornish-Fisher distribution
+#' # build different residualData matrix
+#' residualData <- cbind(c(1,2,1,3,0.1,0.5),rnorm(6),c(2,3,1,2,1,0))
+#' colnames(residualData) <- c("var","skew","ekurt")
+#' rownames(residualData) <- colnames(managers.df[,(1:6)])
+#' bootData <- factorModelMonteCarlo(n.boot, factorData,Beta.mat, residual.dist="Cornish-Fisher",
+#'                                   residualData, Alpha.mat=NULL, boot.method="random",
+#'                                   seed = 123, return.factors = "TRUE", return.residuals =
+#'                                   "TRUE")
+#' 
+#' 
+#' # skew-t distribution
+#' # build residualData matrix
+#' residualData <- cbind(rnorm(6),c(1,2,1,3,0.1,0.5),rnorm(6),c(2,3,1,6,10,100))
+#' colnames(residualData) <- c("xi","omega","alpha","nu")
+#' rownames(residualData) <- colnames(managers.df[,(1:6)])
+#' bootData <- factorModelMonteCarlo(n.boot, factorData,Beta.mat, residual.dist="skew-t",
+#'                                   residualData, Alpha.mat=NULL, boot.method="random",
+#'                                   seed = 123, return.factors = "TRUE", return.residuals =
+#'                                   "TRUE")
+#' 
+factorModelMonteCarlo <-
+  function (n.boot = 1000, factorData, Beta.mat, Alpha.mat = NULL, 
+            residualData, residual.dist = c("normal", "Cornish-Fisher", 
+                                            "skew-t"), boot.method = c("random", "block"), seed = 123, 
+            return.factors = FALSE, return.residuals = FALSE) 
+  {
+    boot.method = boot.method[1]
+    residual.dist = residual.dist[1]
+    set.seed(seed)
+    if (nrow(Beta.mat) != nrow(residualData)) {
+      stop("Beta.mat and residualData have different number of rows")
+    }
+    factorData = as.matrix(factorData)
+    n.funds = nrow(Beta.mat)
+    fund.names = rownames(Beta.mat)
+    if (is.null(Alpha.mat)) {
+      Alpha.mat = matrix(0, nrow(Beta.mat))
+      rownames(Alpha.mat) = fund.names
+    }
+    if (boot.method == "random") {
+      bootIdx = sample(nrow(factorData), n.boot, replace = TRUE)
+    }
+    else {
+      n.samples = round(n.boot/nrow(factorData))
+      n.adj = n.boot - n.samples * nrow(factorData)
+      bootIdx = as.vector(tsbootstrap(1:nrow(factorData), nb = n.samples))
+      if (n.adj > 0) {
+        bootIdx = c(bootIdx, bootIdx[1:n.adj])
+      }
+    }
+    factorDataBoot = factorData[bootIdx, ]
+    fundReturnsBoot = matrix(0, n.boot, n.funds)
+    residualsSim = matrix(0, n.boot, n.funds)
+    colnames(fundReturnsBoot) = colnames(residualsSim) = fund.names
+    for (i in fund.names) {
+      set.seed(which(fund.names == i))
+      if (residual.dist == "normal") {
+        residualsSim[, i] = rnorm(n.boot, sd = sqrt(residualData[i, 
+                                                                 ]))
+      }
+      else if (residual.dist == "Cornish-Fisher") {
+        residualsSim[, i] = rCornishFisher(n.boot, sigma = sqrt(residualData[i, 
+                                                                             "var"]), skew = residualData[i, "skew"], ekurt = residualData[i, 
+                                                                                                                                           "ekurt"])
+      }
+      else if (residual.dist == "skew-t") {
+        residualsSim[, i] = rst(n.boot, xi = residualData[i, 
+                                                                "xi"], omega = residualData[i, "omega"], 
+                                alpha = residualData[i, "alpha"], nu = residualData[i, 
+                                                                                    "nu"])
+      }
+      else {
+        stop("Invalid residual distribution")
+      }
+      fundReturnsBoot[, i] = Alpha.mat[i, 1] + factorDataBoot[, 
+                                                              colnames(Beta.mat)] %*% t(Beta.mat[i, , drop = FALSE]) + 
+        residualsSim[, i]
+    }
+    ans = list(returns = fundReturnsBoot)
+    if (return.factors) {
+      ans$factors = factorDataBoot
+    }
+    if (return.residuals) {
+      ans$residuals = residualsSim
+    }
+    return(ans)
+  }
+

Deleted: pkg/FactorAnalytics/R/factorModelPerformanceAttribution.r
===================================================================
--- pkg/FactorAnalytics/R/factorModelPerformanceAttribution.r	2014-06-20 20:56:58 UTC (rev 3432)
+++ pkg/FactorAnalytics/R/factorModelPerformanceAttribution.r	2014-06-21 05:59:41 UTC (rev 3433)
@@ -1,239 +0,0 @@
-#' Compute performance attribution
-#' 
-#' Decompose total returns into returns attributed to factors and specific returns. 
-#' Class of FM.attribution is generated and generic function \code{plot()} and \code{summary()},\code{print()} can be applied.
-#' 
-#' Total returns can be decomposed into returns attributed to factors and
-#' specific returns. \cr \eqn{R_t = \sum  b_j * f_jt + u_t,t=1...T} \cr
-#' \code{b_j} is exposure to factor j and \code{f_jt} is factor j. 
-#' The returns attributed to factor j is \code{b_j * f_jt} and specific 
-#' returns is \code{u_t}. 
-#' 
-#' @param fit Class of "TimeSeriesFactorModel", "FundamentalFactorModel" or
-#' "statFactorModel".
[TRUNCATED]

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


More information about the Returnanalytics-commits mailing list