[Returnanalytics-commits] r3471 - in pkg/FactorAnalytics: . R data inst/tests man sandbox vignettes

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Tue Jul 15 03:00:59 CEST 2014


Author: pragnya
Date: 2014-07-15 03:00:58 +0200 (Tue, 15 Jul 2014)
New Revision: 3471

Added:
   pkg/FactorAnalytics/R/covFm.R
   pkg/FactorAnalytics/R/fitTsfm.R
   pkg/FactorAnalytics/R/paFm.r
   pkg/FactorAnalytics/man/covFm.Rd
   pkg/FactorAnalytics/man/fitTsfm.Rd
   pkg/FactorAnalytics/man/paFm.Rd
Removed:
   pkg/FactorAnalytics/R/covFM.r
   pkg/FactorAnalytics/R/fitTSFM.R
   pkg/FactorAnalytics/R/paFM.r
   pkg/FactorAnalytics/data/factors.rda
   pkg/FactorAnalytics/data/managers.df.rda
   pkg/FactorAnalytics/man/covFM.Rd
   pkg/FactorAnalytics/man/fitTSFM.Rd
   pkg/FactorAnalytics/man/managers.df.Rd
   pkg/FactorAnalytics/man/paFM.Rd
Modified:
   pkg/FactorAnalytics/NAMESPACE
   pkg/FactorAnalytics/R/factorModelEsDecomposition.R
   pkg/FactorAnalytics/R/factorModelMonteCarlo.R
   pkg/FactorAnalytics/R/factorModelVaRDecomposition.R
   pkg/FactorAnalytics/R/plot.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/inst/tests/test-fitTSFM.r
   pkg/FactorAnalytics/man/factorModelEsDecomposition.Rd
   pkg/FactorAnalytics/man/factorModelMonteCarlo.Rd
   pkg/FactorAnalytics/man/factorModelVaRDecomposition.Rd
   pkg/FactorAnalytics/man/plot.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
   pkg/FactorAnalytics/sandbox/test.vignette.r
   pkg/FactorAnalytics/vignettes/fundamentalFM.Rnw
Log:
Argument and function name changes in fitTsfm, covFm, paFm

Modified: pkg/FactorAnalytics/NAMESPACE
===================================================================
--- pkg/FactorAnalytics/NAMESPACE	2014-07-14 01:31:38 UTC (rev 3470)
+++ pkg/FactorAnalytics/NAMESPACE	2014-07-15 01:00:58 UTC (rev 3471)
@@ -1,7 +1,7 @@
 # Generated by roxygen2 (4.0.1): do not edit by hand
 
 S3method(coef,tsfm)
-S3method(covFM,tsfm)
+S3method(covFm,tsfm)
 S3method(fitted,tsfm)
 S3method(plot,FundamentalFactorModel)
 S3method(plot,StatFactorModel)
@@ -20,7 +20,7 @@
 S3method(summary,StatFactorModel)
 S3method(summary,pafm)
 S3method(summary,tsfm)
-export(covFM)
+export(covFm)
 export(dCornishFisher)
 export(factorModelEsDecomposition)
 export(factorModelMonteCarlo)
@@ -28,8 +28,8 @@
 export(factorModelVaRDecomposition)
 export(fitFundamentalFactorModel)
 export(fitStatisticalFactorModel)
-export(fitTSFM)
+export(fitTsfm)
 export(pCornishFisher)
-export(paFM)
+export(paFm)
 export(qCornishFisher)
 export(rCornishFisher)

Deleted: pkg/FactorAnalytics/R/covFM.r
===================================================================
--- pkg/FactorAnalytics/R/covFM.r	2014-07-14 01:31:38 UTC (rev 3470)
+++ pkg/FactorAnalytics/R/covFM.r	2014-07-15 01:00:58 UTC (rev 3471)
@@ -1,79 +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.
-#' 
-#' @param object fit object of class \code{tsfm}, \code{sfm} or \code{ffm}.
-#' 
-#' @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}}
-#' 
-#' @examples
-#' \dontrun{
-#' # Time Series Factor model
-#' data(managers.df)
-#' factors = managers.df[, (7:9)]
-#' fit <- fitTSFM(assets.names=colnames(managers.df[, (1:6)]), 
-#'                factors.names=c("EDHEC.LS.EQ","SP500.TR"), data=managers.df, 
-#'                add.up.market=FALSE, add.market.sqd=FALSE, fit.method="OLS")                              
-#' covFM(fit)
-#' 
-#' # Statistical Factor Model
-#' data(stat.fm.data)
-#' sfm.pca.fit <- fitStatisticalFactorModel(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")
-}

Added: pkg/FactorAnalytics/R/covFm.R
===================================================================
--- pkg/FactorAnalytics/R/covFm.R	                        (rev 0)
+++ pkg/FactorAnalytics/R/covFm.R	2014-07-15 01:00:58 UTC (rev 3471)
@@ -0,0 +1,77 @@
+#' @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.
+#' 
+#' @param object fit object of class \code{tsfm}, \code{sfm} or \code{ffm}.
+#' 
+#' @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}}
+#' 
+#' @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")
+}

Modified: pkg/FactorAnalytics/R/factorModelEsDecomposition.R
===================================================================
--- pkg/FactorAnalytics/R/factorModelEsDecomposition.R	2014-07-14 01:31:38 UTC (rev 3470)
+++ pkg/FactorAnalytics/R/factorModelEsDecomposition.R	2014-07-15 01:00:58 UTC (rev 3471)
@@ -7,9 +7,10 @@
 #' 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
+#' 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
+#' 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
@@ -20,8 +21,8 @@
 #' @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.
+#' one of "modified","gaussian","historical", "kernel". computation is done 
+#' with the \code{VaR} in the PerformanceAnalytics package.
 #' 
 #' 
 #' @return A list with the following components:
@@ -30,31 +31,31 @@
 #' 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{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.
+#' \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
+#' \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 Meucci (2007). "Risk Contributions from Generic User-Defined Factors". 
 #' \item Epperlein and Smillie (2006) "Cracking VAR with Kernels," Risk.
 #' }
 #' @examples
 #' \dontrun{
-#' data(managers.df)
-#' fit.macro <- fitTSFM (asset.names=colnames(managers.df[,(1:6)]), 
-#'                       factor.names=c("EDHEC.LS.EQ","SP500.TR"),
-#'                       data=managers.df, fit.method="OLS", 
-#'                       add.up.market=FALSE, add.market.sqd=FALSE,
-#'                       variable.selection="none")
+#' data(managers)
+#' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]), 
+#'                      factor.names=c("EDHEC LS EQ","SP500 TR"),data=managers)
 #' # 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")] ,
+#' tmpData = cbind(managers[,1],managers[,c("EDHEC LS EQ","SP500 TR")] ,
 #' residuals(fit.macro$asset.fit$HAM1)/sqrt(fit.macro$resid.sd[1]))
 #' colnames(tmpData)[c(1,4)] = c("HAM1", "residual")
 #' factor.es.decomp.HAM1 = factorModelEsDecomposition(tmpData, fit.macro$beta[1,],

Modified: pkg/FactorAnalytics/R/factorModelMonteCarlo.R
===================================================================
--- pkg/FactorAnalytics/R/factorModelMonteCarlo.R	2014-07-14 01:31:38 UTC (rev 3470)
+++ pkg/FactorAnalytics/R/factorModelMonteCarlo.R	2014-07-15 01:00:58 UTC (rev 3471)
@@ -50,12 +50,11 @@
 #' @examples
 #' 
 #' # load data from the database
-#' data(managers.df)
-#' fit <- fitTSFM(asset.names=colnames(managers.df[,(1:6)]),
-#'                factor.names=c("EDHEC.LS.EQ","SP500.TR"),
-#'                data=managers.df, add.up.market=FALSE, add.market.sqd=FALSE, 
-#'                fit.method="OLS", variable.selection="none")
-#' factorData= managers.df[,c("EDHEC.LS.EQ","SP500.TR")]  
+#' \dontrun{
+#' data(managers)
+#' fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
+#'                factor.names=c("EDHEC LS EQ","SP500 TR"), data=managers)
+#' factorData= managers[,c("EDHEC LS EQ","SP500 TR")]  
 #' Beta.mat=fit$beta
 #' residualData=as.matrix((fit$resid.sd)^2,1,6) 
 #' n.boot=1000
@@ -68,7 +67,7 @@
 #' # 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)])
+#' rownames(residualData) <- colnames(managers[,(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 =
@@ -79,11 +78,12 @@
 #' # 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)])
+#' rownames(residualData) <- colnames(managers[,(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, 

Modified: pkg/FactorAnalytics/R/factorModelVaRDecomposition.R
===================================================================
--- pkg/FactorAnalytics/R/factorModelVaRDecomposition.R	2014-07-14 01:31:38 UTC (rev 3470)
+++ pkg/FactorAnalytics/R/factorModelVaRDecomposition.R	2014-07-15 01:00:58 UTC (rev 3471)
@@ -42,15 +42,12 @@
 #' }
 #' @examples
 #' \dontrun{
-#' data(managers.df)
-#' fit.macro <- fitTSFM(asset.names=colnames(managers.df[,(1:6)]),
-#'                      factor.names=c("EDHEC.LS.EQ","SP500.TR"),
-#'                      add.up.market=FALSE, add.market.sqd=FALSE,
-#'                      data=managers.df, fit.method="OLS",
-#'                      variable.selection="none")
+#' data(managers)
+#' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
+#'                      factor.names=c("EDHEC LS EQ","SP500 TR"), data=managers)
 #' # risk factor contribution to VaR
 #' # combine fund returns, factor returns and residual returns for HAM1
-#' tmpData = cbind(managers.df[,1],managers.df[,c("EDHEC.LS.EQ","SP500.TR")] ,
+#' tmpData = cbind(managers[,1], managers[,c("EDHEC LS EQ","SP500 TR")] ,
 #' residuals(fit.macro$asset.fit$HAM1)/fit.macro$resid.sd[1])
 #' colnames(tmpData)[c(1,4)] = c("HAM1", "residual")
 #' factor.VaR.decomp.HAM1 = factorModelVaRDecomposition(tmpData, fit.macro$beta[1,],

Deleted: pkg/FactorAnalytics/R/fitTSFM.R
===================================================================
--- pkg/FactorAnalytics/R/fitTSFM.R	2014-07-14 01:31:38 UTC (rev 3470)
+++ pkg/FactorAnalytics/R/fitTSFM.R	2014-07-15 01:00:58 UTC (rev 3471)
@@ -1,557 +0,0 @@
-#' @title Fit a time series factor model using time series regression
-#' 
-#' @description Fits a time series (or, macroeconomic) factor model for single 
-#' or multiple 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 
-#' \code{tsfm} is returned.
-#' 
-#' @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. 
-#' 
-#' Estimation method "OLS" corresponds to ordinary least squares, "DLS" is 
-#' discounted least squares, which is weighted least squares estimation with 
-#' exponentially declining weights that sum to unity, and, "Robust" is robust 
-#' regression (uses \code{\link[robust]{lmRob}}). 
-#' 
-#' If \code{variable.selection="none"}, all chosen factors are used in the 
-#' factor model. Whereas, "stepwise" performs traditional forward/backward 
-#' stepwise OLS regression (using \code{\link[stats]{step}}), that starts from 
-#' the initial set of factors and adds factors only if the regression fit, as 
-#' measured by the Bayesian Information Criterion (BIC) or Akaike Information 
-#' Criterion (AIC), improves. And, "all subsets" enables subsets selection 
-#' using \code{\link[leaps]{regsubsets}} that chooses the n-best performing 
-#' subsets of any given size (specified as \code{num.factor.subsets} here). 
-#' \code{varaible.selection="lars"} corresponds to least angle regression 
-#' using \code{\link[lars]{lars}} with variants "lasso", "lar", 
-#' "forward.stagewise" or "stepwise". Note: If 
-#' \code{variable.selection="lars"}, \code{fit.method} will be ignored.
-#' 
-#' If \code{add.up.market=TRUE}, \code{max(0, Rm-Rf)} is added as a factor in 
-#' the regression, following Henriksson & Merton (1981), to account for market 
-#' timing (price movement of the general stock market relative to fixed income 
-#' securities). The coefficient can be interpreted as the number of free put 
-#' options. Similarly, if \code{add.market.sqd=TRUE}, \code{(Rm-Rf)^2} is added 
-#' as a factor in the regression, following Treynor-Mazuy (1966), to account 
-#' for market timing with respect to volatility.
-#' 
-#' \code{lars.criterion} selects the criterion (one of "Cp" or "cv") to 
-#' determine the best fitted model for \code{variable.selection="lars"}. The 
-#' "Cp" statistic (defined in page 17 of Efron et al. (2002)) is calculated 
-#' using \code{\link[lars]{summary.lars}}. While, "cv" computes the K-fold 
-#' cross-validated mean squared prediction error using 
-#' \code{\link[lars]{cv.lars}}.
-#' 
-#' @param asset.names vector containing names of assets, whose returns or 
-#' excess returns are the dependent variable.
-#' @param factor.names vector containing names of the macroeconomic factors.
-#' @param market.name name of the column for market excess returns (Rm-Rf). 
-#' Is required only if \code{add.up.market} or \code{add.market.sqd} 
-#' are \code{TRUE}. Default is NULL.
-#' @param Rf.name name of the column of risk free rate variable to calculate 
-#' excess returns for all assets and factors. Default is NULL, in which case, 
-#' the data is used as it is.
-#' @param data vector, matrix, data.frame, xts, timeSeries or zoo object  
-#' containing column(s) named in \code{asset.names}, \code{factor.names} and 
-#' optionally, \code{market.name} and \code{Rf.name}.
-#' @param fit.method the estimation method, one of "OLS", "DLS" or "Robust". 
-#' See details. 
-#' @param variable.selection the variable selection method, one of "none", 
-#' "stepwise","all subsets","lars". See details.
-#' @param subsets.method one of "exhaustive", "forward", "backward" or "seqrep" 
-#' (sequential replacement) to specify the type of subset search/selection. 
-#' Required if "all subsets" variable selection is chosen. 
-#' @param nvmax the maximum size of subsets to examine; an option for 
-#' "all subsets" variable selection. Default is 8. 
-#' @param force.in vector containing the names of factors that should always 
-#' be included in the model; an option for "all subsets" variable selection. 
-#' Default is NULL.
-#' @param num.factors.subset number of factors required in the factor model; 
-#' an option for "all subsets" variable selection. Default is 1. 
-#' Note: nvmax >= num.factors.subset >= length(force.in).
-#' @param add.up.market logical, adds max(0, Rm-Rf) as a factor. If 
-#' \code{TRUE}, \code{market.name} is required. Default is \code{TRUE}. 
-#' See Details. 
-#' @param add.market.sqd logical, adds (Rm-Rf)^2 as a factor. If \code{TRUE},
-#' \code{market.name} is required. Default is \code{TRUE}.
-#' @param decay a scalar in (0, 1] to specify the decay factor for 
-#' \code{fit.method="DLS"}. Default is 0.95.
-#' @param lars.type One of "lasso", "lar", "forward.stagewise" or "stepwise". 
-#' The names can be abbreviated to any unique substring. Default is "lasso".
-#' @param lars.criterion an option to assess model selection for the "lars" 
-#' method; one of "Cp" or "cv". See details. Default is "Cp".
-#' @param ... optional arguments passed to the \code{step} function for 
-#' variable.selection method "stepwise", such as direction, steps and 
-#' the penalty factor k. Note that argument k is available only for "OLS" 
-#' and "DLS" fits. Scope argument is not available presently. Also plan to
-#' include other controls passed to \code{lmRob} soon.
-#' 
-#' @return fitTSFM returns an object of class \code{tsfm}. 
-#' 
-#' 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{coefficients}, \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.
-#' 
-#' An object of class \code{tsfm} is a list containing the following 
-#' components:
-#' \item{asset.fit}{list of fitted objects for each asset. Each object is of 
-#' 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{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{call}{the matched function call.}
-#' \item{data}{xts data object containing the assets and factors.}
-#' \item{asset.names}{asset.names as input.}
-#' \item{factor.names}{factor.names as input.}
-#' \item{fit.method}{fit.method as input.}
-#' \item{variable.selection}{variable.selection as input.}
-#' Where N is the number of assets, K is the number of factors and T is the 
-#' number of time periods.
-#' 
-#' @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.
-#' }
-#' 
-#' @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{paFM}} for Performance Attribution. 
-#' 
-#' @examples
-#' # load data from the database
-#' data(managers)
-#' fit <- fitTSFM(asset.names=colnames(managers[,(1:6)]),
-#'                factor.names=colnames(managers[,(7:9)]), 
-#'                market.name="SP500 TR", data=managers)
-#' # summary 
-#' summary(fit)
-#' # fitted values for all assets' returns
-#' fitted(fit)
-#' # plot actual vs. fitted over time for HAM1
-#' # using chart.TimeSeries() function from PerformanceAnalytics package
-#' dataToPlot <- cbind(fitted(fit$asset.fit$HAM1), na.omit(managers$HAM1))
-#' colnames(dataToPlot) <- c("Fitted","Actual")
-#' chart.TimeSeries(dataToPlot, main="FM fit for HAM1",
-#'                  colorset=c("black","blue"), legend.loc="bottomleft")
-#'
-#'  @export
-
-fitTSFM <- function(asset.names, factor.names, market.name=NULL, Rf.name=NULL, 
-                    data=data, fit.method=c("OLS","DLS","Robust"),
-                    variable.selection=c("none","stepwise","all subsets",
-                                         "lars"),
-                    subsets.method=c("exhaustive","backward","forward",
-                                     "seqrep"),
-                    nvmax=8, force.in=NULL, num.factors.subset=1, 
-                    add.up.market=TRUE, add.market.sqd=TRUE, decay=0.95,
-                    lars.type=c("lasso","lar","forward.stagewise","stepwise"),
-                    lars.criterion="Cp", ...){
-  
-  # get all the arguments specified by their full names
-  call <- match.call()
-  
-  fit.method = fit.method[1] # default is OLS
-  variable.selection = variable.selection[1] # default is "none"
-  subsets.method = subsets.method[1] # default is "exhaustive"
-  lars.type=lars.type[1] # default is "lasso"
-  
-  if (!exists("direction")) {direction <- "backward"}
-  if (!exists("steps")) {steps <- 1000}
-  if (!exists("k")) {k <- 2}
-  if ((missing(market.name)|is.null(market.name)) && 
-        (add.up.market==TRUE | add.market.sqd==TRUE)) {
-    stop("Missing input: 'market.name' is required to include factors 
-         'up.market' or 'market.sqd'")
-  }
-  
-  # convert data into an xts object and hereafter work with xts objects
-  data.xts <- checkData(data)
-  
-  # extract columns to be used in the time series regression
-  dat.xts <- merge(data.xts[,asset.names], data.xts[,factor.names])
-  ### After merging xts objects, the spaces in names get converted to periods
-  
-  # convert all asset and factor returns to excess return form if specified
-  if (!is.null(Rf.name)) {
-    dat.xts <- "[<-"(dat.xts,,vapply(dat.xts, function(x) x-data.xts[,Rf.name], 
-                                     FUN.VALUE = numeric(nrow(dat.xts))))
-  }
-  
-  # opt add market-timing factors: up.market=max(0,Rm-Rf), market.sqd=(Rm-Rf)^2
-  if(add.up.market == TRUE) {
-    up.market <- data.xts[,market.name]
-    up.market [up.market < 0] <- 0
-    dat.xts <- merge.xts(dat.xts,up.market)
-    colnames(dat.xts)[dim(dat.xts)[2]] <- "up.market"
-    factor.names <- c(factor.names, "up.market")
-  }
-  if(add.market.sqd == TRUE) {
-    market.sqd <- data.xts[,market.name]^2   
-    dat.xts <- merge(dat.xts, market.sqd)
-    colnames(dat.xts)[dim(dat.xts)[2]] <- "market.sqd"
-    factor.names <- c(factor.names, "market.sqd")
-  }
-  
-  # spaces get converted to periods in colnames of xts object after merge
-  asset.names <- gsub(" ",".", asset.names, fixed=TRUE)
-  factor.names <- gsub(" ",".", factor.names, fixed=TRUE)
-  
-  # Selects regression procedure based on specified variable.selection method.
-  # Each method returns a list of fitted factor models for each asset.
-  if (variable.selection == "none") {
-    reg.list <- NoVariableSelection(dat.xts, asset.names, factor.names, 
-                                    fit.method, add.up.market, add.market.sqd, 
-                                    decay)
-  } else if (variable.selection == "stepwise"){
-    reg.list <- SelectStepwise(dat.xts, asset.names, factor.names, 
-                               fit.method, add.up.market, add.market.sqd, 
-                               decay, direction, steps, k)
-  } else if (variable.selection == "all subsets"){
-    reg.list <- SelectAllSubsets(dat.xts, asset.names, factor.names, 
-                                 fit.method, subsets.method, 
-                                 nvmax, force.in, num.factors.subset, 
-                                 add.up.market, add.market.sqd, decay)
-  } else if (variable.selection == "lars"){
-    result.lars <- SelectLars(dat.xts, asset.names, factor.names, 
-                              lars.type, add.up.market, add.market.sqd, 
-                              decay, lars.criterion)
-    input <- list(call=call, data=dat.xts, 
-                  asset.names=asset.names, factor.names=factor.names, 
-                  fit.method=fit.method, variable.selection=variable.selection)
-    result <- c(result.lars, input)
-    class(result) <- "tsfm"
-    return(result)
-  } 
-  else {
-    stop("Invalid argument: variable.selection must be either 'none',
-         'stepwise','all subsets','lars'")
-  }
-  
-  # extract the fitted factor models, coefficients, r2 values and residual vol 
-  # from returned factor model fits above
-  coef.mat <- makePaddedDataFrame(lapply(reg.list, coef))
-  alpha <- coef.mat[, 1, drop=FALSE]
-  # to make class of alpha numeric instead of matrix
-  # aplha <- coef.mat[,1]
-  beta <- coef.mat[, -1, drop=FALSE]
-  r2 <- sapply(reg.list, function(x) summary(x)$r.squared)
-  resid.sd <- sapply(reg.list, function(x) summary(x)$sigma)
-  # create list of return values.
-  result <- list(asset.fit=reg.list, alpha=alpha, beta=beta, r2=r2, 
-                 resid.sd=resid.sd, call=call, data=dat.xts, 
-                 asset.names=asset.names, factor.names=factor.names, 
-                 fit.method=fit.method, variable.selection=variable.selection)
-  class(result) <- "tsfm"
-  return(result)
-}
-
-
-### method variable.selection = "none"
-#
-NoVariableSelection <- function(dat.xts, asset.names, factor.names, fit.method, 
-                                add.up.market, add.market.sqd, decay){
-  # initialize list object to hold the fitted objects
-  reg.list <- list()
-  
-  # loop through and estimate model for each asset to allow unequal histories
-  for (i in asset.names){
-    # completely remove NA cases
-    reg.xts <- na.omit(dat.xts[, c(i, factor.names)])
-    
-    # formula to pass to lm or lmRob
-    fm.formula <- as.formula(paste(i," ~ ."))
-    
-    # fit based on time series regression method chosen
-    if (fit.method == "OLS") {
-      reg.list[[i]] <- lm(fm.formula, data=reg.xts)
-    } else if (fit.method == "DLS") {
-      w <- WeightsDLS(nrow(reg.xts), decay)
-      reg.list[[i]] <- lm(fm.formula, data=reg.xts, weights=w)
-    } else if (fit.method == "Robust") {
-      reg.list[[i]] <- lmRob(fm.formula, data=reg.xts)
-    } else {
-      stop("Invalid argument: fit.method must be 'OLS', 'DLS' or 'Robust'")
-    }
-  } 
-  reg.list  
-}
-
-
-### method variable.selection = "stepwise"
-#
-SelectStepwise <- function(dat.xts, asset.names, factor.names, fit.method, 
-                           add.up.market, add.market.sqd, decay, 
-                           direction, steps, k){
-  # initialize list object to hold the fitted objects
-  reg.list <- list()
-  
-  # loop through and estimate model for each asset to allow unequal histories
-  for (i in asset.names){
-    # completely remove NA cases
-    reg.xts <- na.omit(dat.xts[, c(i, factor.names)])
-    
-    # formula to pass to lm or lmRob
-    fm.formula <- as.formula(paste(i," ~ ."))
-    
-    # fit based on time series regression method chosen
-    if (fit.method == "OLS") {
-      reg.list[[i]] <- step(lm(fm.formula, data=reg.xts), direction=direction, 
-                            steps=steps, k=k, trace=0)
-    } else if (fit.method == "DLS") {
-      w <- WeightsDLS(nrow(reg.xts), decay)
-      reg.list[[i]] <- step(lm(fm.formula, data=reg.xts, weights=w), 
-                            direction=direction, steps=steps, k=k, trace=0)
-    } else if (fit.method == "Robust") {
-      reg.list[[i]] <- step.lmRob(lmRob(fm.formula, data=reg.xts), trace=FALSE,
-                                  direction=direction, steps=steps)
-    } else {
-      stop("Invalid argument: fit.method must be 'OLS', 'DLS' or 'Robust'")
-    }
-  }
-  reg.list
-}
-
-
-### method variable.selection = "all subsets"
-#
-SelectAllSubsets <- function(dat.xts, asset.names, factor.names, fit.method, 
-                             subsets.method, nvmax, force.in, 
[TRUNCATED]

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


More information about the Returnanalytics-commits mailing list