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

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Wed Jul 30 02:15:15 CEST 2014


Author: pragnya
Date: 2014-07-30 02:15:14 +0200 (Wed, 30 Jul 2014)
New Revision: 3490

Modified:
   pkg/FactorAnalytics/DESCRIPTION
   pkg/FactorAnalytics/R/covFm.R
   pkg/FactorAnalytics/R/fitTsfm.R
   pkg/FactorAnalytics/R/plot.tsfm.r
   pkg/FactorAnalytics/man/covFm.Rd
   pkg/FactorAnalytics/man/fitTsfm.Rd
   pkg/FactorAnalytics/man/plot.tsfm.Rd
Log:
Edits to defaults, arguments passed to plot.tsfm, covFm

Modified: pkg/FactorAnalytics/DESCRIPTION
===================================================================
--- pkg/FactorAnalytics/DESCRIPTION	2014-07-29 22:55:01 UTC (rev 3489)
+++ pkg/FactorAnalytics/DESCRIPTION	2014-07-30 00:15:14 UTC (rev 3490)
@@ -21,7 +21,7 @@
     leaps,
     lars,
     lmtest,
-    PerformanceAnalytics (>= 1.1.0),
+    PerformanceAnalytics (>= 1.1.3),
     sn,
     tseries,
     strucchange,

Modified: pkg/FactorAnalytics/R/covFm.R
===================================================================
--- pkg/FactorAnalytics/R/covFm.R	2014-07-29 22:55:01 UTC (rev 3489)
+++ pkg/FactorAnalytics/R/covFm.R	2014-07-30 00:15:14 UTC (rev 3490)
@@ -19,12 +19,16 @@
 #' 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.
 #' 
-#' Though method for handling NAs and the method for computing covariance can 
-#' be specified via the \dots arguments. As a reasonable default, 
-#' \code{use="pairwise.complete.obs"} is used, which restricts the method to
-#' "pearson".
+#' 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 
@@ -40,6 +44,9 @@
 #' 
 #' @seealso \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}}
 #' 
+#' \code{\link[stats]{cov}} for more details on arguments \code{use} and 
+#' \code{method}.
+#' 
 #' @examples
 #' \dontrun{
 #' # Time Series Factor model
@@ -81,3 +88,39 @@
 covFm <- function(object, ...){
   UseMethod("covFm")
 }
+
+#' @rdname covFm
+#' @method covFm tsfm
+#' @export
+
+covFm.tsfm <- function(object, use="pairwise.complete.obs", ...) {
+  
+  # check input object validity
+  if (!inherits(object, c("tsfm", "sfm", "ffm"))) {
+    stop("Invalid argument: Object should be of class 'tsfm', 'sfm' or 'ffm'.")
+  }
+  
+  # get parameters and factors from factor model
+  beta <- as.matrix(object$beta)
+  beta[is.na(beta)] <- 0
+  sig2.e = object$resid.sd^2
+  factor <- as.matrix(object$data[, object$factor.names])
+  
+  # factor covariance matrix 
+  factor.cov = cov(factor, use=use, ...)
+  
+  # residual covariance matrix D
+  if (length(sig2.e) > 1) {
+    D.e = diag(sig2.e)
+  } else {
+    D.e =  as.vector(sig2.e)
+  }
+  
+  cov.fm = beta %*% factor.cov %*% t(beta) + D.e
+  
+  if (any(diag(chol(cov.fm))==0)) {
+    warning("Covariance matrix is not positive definite!")
+  }
+  
+  return(cov.fm)
+}

Modified: pkg/FactorAnalytics/R/fitTsfm.R
===================================================================
--- pkg/FactorAnalytics/R/fitTsfm.R	2014-07-29 22:55:01 UTC (rev 3489)
+++ pkg/FactorAnalytics/R/fitTsfm.R	2014-07-30 00:15:14 UTC (rev 3490)
@@ -74,7 +74,9 @@
 #' @param control list of control parameters. The default is constructed by 
 #' the function \code{\link{fitTsfm.control}}. See the documentation for 
 #' \code{\link{fitTsfm.control}} for details.
-#' @param ... arguments passed to \code{\link{fitTsfm.control}}
+#' @param ... For \code{fitTsfm}: arguments passed to 
+#' \code{\link{fitTsfm.control}}. \cr
+#' For S3 methods: further arguments passed to or from other methods 
 #' 
 #' @return fitTsfm returns an object of class \code{tsfm}. 
 #' 
@@ -145,16 +147,13 @@
 #' fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
 #'                factor.names=colnames(managers[,(7:9)]), 
 #'                mkt.name="SP500 TR", mkt.timing="both", 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")
+#' # plot actual returns vs. fitted factor model returns for HAM1
+#' plot(fit, plot.single=TRUE, asset.name="HAM1", which.plot.single=1, 
+#'      loop=FALSE)
+#' # group plot; type selected from menu prompt; auto-looped for multiple plots
+#' # plot(fit)
 #' 
 #' # example using "subsets" variable selection
 #' fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
@@ -565,40 +564,3 @@
   time(residuals.xts) <- as.Date(time(residuals.xts))
   return(residuals.xts)
 }
-
-#' @rdname fitTsfm
-#' @method covFm tsfm
-#' @export
-
-covFm.tsfm <- 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'.")
-  }
-  
-  # get parameters and factors from factor model
-  beta <- as.matrix(object$beta)
-  beta[is.na(beta)] <- 0
-  sig2.e = object$resid.sd^2
-  factor <- as.matrix(object$data[, object$factor.names])
-  
-  if (!exists("use")) {use="pairwise.complete.obs"}
-  # factor covariance matrix 
-  factor.cov = cov(factor, use=use, ...)
-  
-  # residual covariance matrix D
-  if (length(sig2.e) > 1) {
-    D.e = diag(sig2.e)
-  } else {
-    D.e =  as.vector(sig2.e)
-  }
-  
-  cov.fm = beta %*% factor.cov %*% t(beta) + D.e
-  
-  #   if (any(diag(chol(cov.fm)) == 0)) {
-  #     warning("Covariance matrix is not positive definite!")
-  #   }
-  
-  return(cov.fm)
-}

Modified: pkg/FactorAnalytics/R/plot.tsfm.r
===================================================================
--- pkg/FactorAnalytics/R/plot.tsfm.r	2014-07-29 22:55:01 UTC (rev 3489)
+++ pkg/FactorAnalytics/R/plot.tsfm.r	2014-07-30 00:15:14 UTC (rev 3490)
@@ -8,7 +8,8 @@
 #' and the corresponding plot is output. And, the menu is repeated for 
 #' user convenience in plotting multiple characteristics. Selecting '0' from 
 #' the menu exits the current \code{plot.tsfm} call. Alternately, setting
-#' \code{loop=FALSE} will exit after plotting any one chosen characteristic.
+#' \code{loop=FALSE} will exit after plotting any one chosen characteristic 
+#' without the need for menu selection.
 #' 
 #' For group plots (the default), the first \code{max.show} assets are plotted.
 #' For individual plots, \code{asset.name} is necessary if multiple assets 
@@ -96,24 +97,30 @@
 #' 
 #' @examples
 #' 
-#' \dontrun{
 #' # load data from the database
 #' data(managers)
 #' fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
 #'                      factor.names=colnames(managers[,(7:8)]),
 #'                      rf.name="US 3m TR", data=managers)
-#' # plot the 1st 4 assets fitted above.
-#' plot(fit.macro, max.show=4)
-#' # plot of an individual asset, "HAM1" 
-#' plot(fit.macro, plot.single=TRUE, asset.name="HAM1")
-#' }
+#'                    
+#' # plot the factor betas of 1st 4 assets fitted above.
+#' plot(fit.macro, max.show=4, which.plot.group=2, loop=FALSE)
+#' # plot the factor model return correlation, order = hierarchical clustering
+#' plot(fit.macro, which.plot.group=7, loop=FALSE, order="hclust", addrect=3)
 #' 
+#' # histogram of residuals from an individual asset's factor model fit 
+#' plot(fit.macro, plot.single=TRUE, asset.name="HAM1", which.plot.single=8, 
+#'      loop=FALSE)
+#' 
+#' # group plot; type selected from menu prompt; auto-looped for multiple plots
+#' # plot(fit.macro)
+#' 
 #' @method plot tsfm
 #' @export
 
 plot.tsfm <- function(x, which.plot.group=NULL, max.show=6, plot.single=FALSE, 
                       asset.name, which.plot.single=NULL, colorset=(1:12), 
-                      legend.loc="bottomright", las=1, 
+                      legend.loc="topleft", las=1, 
                       VaR.method="historical", loop=TRUE, ...) {
   
   if (plot.single==TRUE) {
@@ -131,7 +138,6 @@
     colnames(plotData) <- c("Actual","Fitted")
     Residuals <- residuals(x)[,i]
     fit <- x$asset.fit[[i]]
-    par(las=las) # default horizontal axis labels
     
     # plot selection
     repeat {
@@ -164,26 +170,22 @@
                                 legend.loc=legend.loc, pch=NULL, las=las, ...)
              }, "2L" = {
                ## time series plot of residuals with standard error bands
-               if(!exists("lwd")) {lwd=2} 
-               if(!exists("lty")) {lty="solid"} 
-               chart.TimeSeries(Residuals, main=paste("Residuals:",i), lty=lty,
-                                colorset=colorset, xlab="", 
-                                ylab="Residuals", lwd=lwd, las=las, ...)
-               abline(h=1.96*x$resid.sd[i], lwd=lwd, lty="dotted", col="red")
-               abline(h=-1.96*x$resid.sd[i], lwd=lwd, lty="dotted", col="red")
-               legend(x=legend.loc, lty=c(lty,"dotted"), 
-                      col=c(colorset[1],"red"), lwd=lwd, 
+               chart.TimeSeries(Residuals, main=paste("Residuals:",i), 
+                                colorset=colorset, xlab="", ylab="Residuals", 
+                                lwd=2, lty="solid", las=las, ...)
+               abline(h=1.96*x$resid.sd[i], lwd=2, lty="dotted", col="red")
+               abline(h=-1.96*x$resid.sd[i], lwd=2, lty="dotted", col="red")
+               legend(x=legend.loc, lty=c("solid","dotted"), 
+                      col=c(colorset[1],"red"), lwd=2, 
                       legend=c("Residuals",expression("\u00b1 1.96"*sigma)))
              }, "3L" = {
                ## time series plot of squared residuals
-               if (!is.null(legend.loc)) {legend.loc="topright"}
                chart.TimeSeries(Residuals^2, colorset=colorset, xlab="", 
                                 ylab=" Squared Residuals",
                                 main=paste("Squared Residuals:",i), 
                                 legend.loc=legend.loc, pch=NULL, las=las, ...)
              }, "4L" = {
                ## time series plot of absolute residuals
-               if (!is.null(legend.loc)) {legend.loc="topright"}
                chart.TimeSeries(abs(Residuals), colorset=colorset, xlab="", 
                                 ylab="Absolute Residuals",
                                 main=paste("Absolute Residuals:",i), 
@@ -202,23 +204,22 @@
                              main=paste("SACF & PACF - Absolute Residuals:",i))
              }, "8L" = {
                ## histogram of residuals with normal curve overlayed
-               if(!exists("methods")) {
-                 methods=c("add.density","add.normal","add.rug","add.risk")
-               } 
-               chart.Histogram(Residuals, methods=methods,
-                               main=paste("Histogram of Residuals:",i), 
-                               xlab="Return residuals", colorset=colorset, ...)
+               methods <- c("add.density","add.normal","add.rug")
+               chart.Histogram(Residuals, xlab="Return residuals",
+                               methods=methods, colorset=colorset, 
+                               main=paste("Histogram of Residuals:",i), ...)
              }, "9L" = {
                ##  normal qq-plot of residuals
-               if(!exists("envelope")) {envelope=0.95} 
-               chart.QQPlot(Residuals, envelope=envelope, col=colorset,
+               chart.QQPlot(Residuals, envelope=0.95, col=colorset,
                             main=paste("QQ-plot of Residuals:",i), ...)
+               legend(x=legend.loc, col="red", lty="dotted", lwd=1,
+                      legend=c("0.95 confidence envelope"))
              }, "10L" = {
                ##  Recursive CUSUM test
                if (!x$fit.method=="OLS") {
                  stop("CUSUM analysis applicable only for 'OLS' fit.method.")
                }
-               cusum.rec = efp(formula(fit), type="Rec-CUSUM", data=fit$model)
+               cusum.rec <- efp(formula(fit), type="Rec-CUSUM", data=fit$model)
                plot(cusum.rec, main=paste("Recursive CUSUM test:",i), las=las, 
                     col=colorset, ...)
              }, "11L" = {
@@ -226,7 +227,7 @@
                if (!x$fit.method=="OLS") {
                  stop("CUSUM analysis applicable only for 'OLS' fit.method.")
                }
-               cusum.ols = efp(formula(fit), type="OLS-CUSUM", data=fit$model)
+               cusum.ols <- efp(formula(fit), type="OLS-CUSUM", data=fit$model)
                plot(cusum.ols, main=paste("OLS-based CUSUM test:",i), las=las, 
                     col=colorset, ...)
              }, "12L" = {
@@ -234,7 +235,7 @@
                if (!x$fit.method=="OLS") {
                  stop("CUSUM analysis applicable only for 'OLS' fit.method.")
                }        
-               cusum.est = efp(formula(fit), type="RE", data=fit$model)
+               cusum.est <- efp(formula(fit), type="RE", data=fit$model)
                plot(cusum.est, functional=NULL, col=colorset, las=0,
                     main=paste("RE test (Recursive estimates test):",i), ...)
              }, "13L" = {
@@ -243,8 +244,8 @@
                  rollReg <- function(data.z, formula) {
                    coef(lm(formula, data=as.data.frame(data.z)))  
                  }
-                 reg.z = zoo(fit$model, as.Date(rownames(fit$model)))
-                 rollReg.z = rollapply(reg.z, FUN=rollReg, formula(fit), 
+                 reg.z <- zoo(fit$model, as.Date(rownames(fit$model)))
+                 rollReg.z <- rollapply(reg.z, FUN=rollReg, formula(fit), 
                                        width=24, by.column=FALSE, align="right")
                } else if (x$fit.method=="DLS") {
                  # get decay factor
@@ -259,16 +260,16 @@
                  rollReg.w <- function(data.z, formula, w) {
                    coef(lm(formula, weights=w, data=as.data.frame(data.z)))  
                  }
-                 reg.z = zoo(fit$model[-length(fit$model)], 
+                 reg.z <- zoo(fit$model[-length(fit$model)], 
                              as.Date(rownames(fit$model)))
-                 rollReg.z = rollapply(reg.z, FUN=rollReg.w, formula(fit), w, 
+                 rollReg.z <- rollapply(reg.z, FUN=rollReg.w, formula(fit), w, 
                                        width=24, by.column=FALSE, align="right")
                } else if (x$fit.method=="Robust") {
                  rollReg.Rob <- function(data.z, formula) {
                    coef(lmRob(formula=formula, data=as.data.frame(data.z)))  
                  }
-                 reg.z = zoo(fit$model, as.Date(rownames(fit$model)))
-                 rollReg.z = rollapply(reg.z, width=24, FUN=rollReg.Rob, 
+                 reg.z <- zoo(fit$model, as.Date(rownames(fit$model)))
+                 rollReg.z <- rollapply(reg.z, width=24, FUN=rollReg.Rob, 
                                        formula(fit), by.column=FALSE, 
                                        align="right")
                } else if (is.null(x$fit.method)) {
@@ -287,17 +288,9 @@
     } 
   } else { # start of group asset plots
     
-    # extract info from the fitTsfm object
-    n <- length(x$asset.names)
-    if (n > max.show) {
-      cat(paste("Displaying only the first", max.show,"assets, since the 
-                  number of assets > 'max.show' =", max.show))
-      n <- max.show 
-    }
-    
     # plot selection
     repeat {
-      if (is.null(which.plot.single)) {
+      if (is.null(which.plot.group)) {
         which.plot.group <- 
           menu(c("Factor model coefficients: Alpha",
                  "Factor model coefficients: Betas",
@@ -318,7 +311,7 @@
              "1L" = { 
                ## Factor model coefficients: Alpha
                #  ylab="Intercept estimate"
-               barplot(coef(x)[,1], main="Factor model Alpha", 
+               barplot(coef(x)[,1], main="Factor model Alpha (Intercept)", 
                        xlab="Assets", col="darkblue", las=las, ...)
                abline(h=0, lwd=1, lty=1, col=1)
                
@@ -330,8 +323,8 @@
                            as the number of factors > 'max.show' =", max.show))
                  k <- max.show 
                }
-               par(mfrow=c(k/2,2))
-               for (i in 2:k+1) {
+               par(mfrow=c(ceiling(k/2),2))
+               for (i in 2:(k+1)) {
                  main=paste("Factor Betas:", colnames(coef(x))[i])
                  barplot(coef(x)[,i], main=main, col="darkblue", xlab="Assets",
                          ylab="Coefficient estimate", las=las, ...)
@@ -340,11 +333,17 @@
                par(mfrow=c(1,1))
              }, "3L" = {    
                ## Actual and Fitted asset returns
-               par(mfrow=c(n,1))
+               n <- length(x$asset.names)
+               if (n > max.show) {
+                 cat(paste("Displaying only the first", max.show,"assets, since the 
+                  number of assets > 'max.show' =", max.show))
+                 n <- max.show 
+               }
+               par(mfrow=c(ceiling(n/2),2))
                for (i in 1:n) {
                  plotData <- merge.xts(x$data[,i], fitted(x)[,i])
                  colnames(plotData) <- c("Actual","Fitted")
-                 main = paste("Factor model asset returns:", x$asset.names[i])
+                 main <- paste("Factor model asset returns:", x$asset.names[i])
                  chart.TimeSeries(plotData, colorset=colorset, main=main, 
                                   xlab="", ylab="Actual and fitted values", 
                                   legend.loc=legend.loc, pch=NULL, las=las,...)
@@ -367,32 +366,29 @@
              },    
              "6L" = {
                ## Factor Model Residual Correlation
-               cor.resid <- cor(residuals(x),use="pairwise.complete.obs")
-               if(!exists("order")) {order="AOE"}
-               corrplot::corrplot(cor.resid, order=order, ...)
+               cor.resid <- cor(residuals(x), use="pairwise.complete.obs")
+               corrplot::corrplot(cor.resid, ...)
              },
              "7L" = {
                ## Factor Model Return Correlation
-               cov.fm<- covFm(x)    
-               cor.fm = cov2cor(cov.fm) 
-               if(!exists("order")) {order="AOE"}
-               corrplot::corrplot(cor.fm, order=order, ...)
+               cor.fm <- cov2cor(covFm(x)) 
+               corrplot::corrplot(cor.fm, ...)
              },
 #              "8L" = {
 #                ## Factor Contribution to SD
-#                factor.sd.decomp.list = list()
+#                factor.sd.decomp.list <- list()
 #                for (i in asset.names) {
 #                  factor.sd.decomp.list[[i]] =
 #                    factorModelSdDecomposition(x$beta[i,],
 #                                               cov.factors, x$resid.variance[i])
 #                }
 #                # function to extract contribution to sd from list
-#                getCSD = function(x) {
+#                getCSD <- function(x) {
 #                  x$cSd.fm
 #                }
 #                # extract contributions to SD from list
-#                cr.sd = sapply(factor.sd.decomp.list, getCSD)
-#                rownames(cr.sd) = c(factor.names, "residual")
+#                cr.sd <- sapply(factor.sd.decomp.list, getCSD)
+#                rownames(cr.sd) <- c(factor.names, "residual")
 #                # create stacked barchart
 #                barplot(cr.sd, main="Factors' Contribution to SD",
 #                        legend.text=T, args.legend=list(x="topleft"))
@@ -400,20 +396,20 @@
 #              },
 #              "9L"={
 #                ## Factor Contribution to ES
-#                factor.es.decomp.list = list()
+#                factor.es.decomp.list <- list()
 #                if (variable.selection == "lar" || variable.selection == "lasso") {
 #                  
 #                  for (i in asset.names) {
-#                    idx = which(!is.na(plot.data[,i]))
-#                    alpha = x$alpha[i]
-#                    beta = as.matrix(x$beta[i,])        
-#                    fitted = alpha+as.matrix(plot.data[,factor.names])%*%beta
-#                    residual = plot.data[,i]-fitted
-#                    tmpData = cbind(coredata(plot.data[idx,i]),
+#                    idx <- which(!is.na(plot.data[,i]))
+#                    alpha <- x$alpha[i]
+#                    beta <- as.matrix(x$beta[i,])        
+#                    fitted <- alpha+as.matrix(plot.data[,factor.names])%*%beta
+#                    residual <- plot.data[,i]-fitted
+#                    tmpData <- cbind(coredata(plot.data[idx,i]),
 #                                    coredata(plot.data[idx,factor.names]),
 #                                    (residual[idx,]/sqrt(x$resid.variance[i])) )
-#                    colnames(tmpData)[c(1,length(tmpData))] = c(i, "residual")
-#                    factor.es.decomp.list[[i]] = 
+#                    colnames(tmpData)[c(1,length(tmpData))] <- c(i, "residual")
+#                    factor.es.decomp.list[[i]] <- 
 #                      factorModelEsDecomposition(tmpData, 
 #                                                 x$beta[i,],
 #                                                 x$resid.variance[i], tail.prob=0.05)
@@ -423,12 +419,12 @@
 #                  
 #                  for (i in asset.names) {
 #                    # check for missing values in fund data
-#                    idx = which(!is.na(plot.data[,i]))
-#                    tmpData = cbind(coredata(plot.data[idx,i]),
+#                    idx <- which(!is.na(plot.data[,i]))
+#                    tmpData <- cbind(coredata(plot.data[idx,i]),
 #                                    coredata(plot.data[idx,factor.names]),
 #                                    residuals(x$asset.fit[[i]])/sqrt(x$resid.variance[i]))
-#                    colnames(tmpData)[c(1,dim(tmpData)[2])] = c(i, "residual")
-#                    factor.es.decomp.list[[i]] = 
+#                    colnames(tmpData)[c(1,dim(tmpData)[2])] <- c(i, "residual")
+#                    factor.es.decomp.list[[i]] <- 
 #                      factorModelEsDecomposition(tmpData, 
 #                                                 x$beta[i,],
 #                                                 x$resid.variance[i], tail.prob=0.05,
@@ -437,32 +433,32 @@
 #                }     
 #                
 #                # stacked bar charts of percent contributions to SD
-#                getCETL = function(x) {
+#                getCETL <- function(x) {
 #                  x$cES.fm
 #                }
 #                # report as positive number
-#                cr.etl = sapply(factor.es.decomp.list, getCETL)
-#                rownames(cr.etl) = c(factor.names, "residual")
+#                cr.etl <- sapply(factor.es.decomp.list, getCETL)
+#                rownames(cr.etl) <- c(factor.names, "residual")
 #                barplot(cr.etl, main="Factors' Contribution to ES",
 #                        legend.text=T, args.legend=list(x="topleft")) 
 #              },
 #              "10L" ={
 #                ## Factor Contribution to VaR
-#                factor.VaR.decomp.list = list()
+#                factor.VaR.decomp.list <- list()
 #                
 #                if (variable.selection == "lar" || variable.selection == "lasso") {
 #                  
 #                  for (i in asset.names) {
-#                    idx = which(!is.na(plot.data[,i]))
-#                    alpha = x$alpha[i]
-#                    beta = as.matrix(x$beta[i,])        
-#                    fitted = alpha+as.matrix(plot.data[,factor.names])%*%beta
-#                    residual = plot.data[,i]-fitted
-#                    tmpData = cbind(coredata(plot.data[idx,i]),
+#                    idx <- which(!is.na(plot.data[,i]))
+#                    alpha <- x$alpha[i]
+#                    beta <- as.matrix(x$beta[i,])        
+#                    fitted <- alpha+as.matrix(plot.data[,factor.names])%*%beta
+#                    residual <- plot.data[,i]-fitted
+#                    tmpData <- cbind(coredata(plot.data[idx,i]),
 #                                    coredata(plot.data[idx,factor.names]),
 #                                    (residual[idx,]/sqrt(x$resid.variance[i])) )
-#                    colnames(tmpData)[c(1,length(tmpData))] = c(i, "residual")
-#                    factor.VaR.decomp.list[[i]] = 
+#                    colnames(tmpData)[c(1,length(tmpData))] <- c(i, "residual")
+#                    factor.VaR.decomp.list[[i]] <- 
 #                      factorModelVaRDecomposition(tmpData, 
 #                                                  x$beta[i,],
 #                                                  x$resid.variance[i], tail.prob=0.05,VaR.method=VaR.method)
@@ -471,12 +467,12 @@
 #                } else {
 #                  for (i in asset.names) {
 #                    # check for missing values in fund data
-#                    idx = which(!is.na(plot.data[,i]))
-#                    tmpData = cbind(coredata(plot.data[idx,i]),
+#                    idx <- which(!is.na(plot.data[,i]))
+#                    tmpData <- cbind(coredata(plot.data[idx,i]),
 #                                    coredata(plot.data[idx,factor.names]),
 #                                    residuals(x$asset.fit[[i]])/sqrt(x$resid.variance[i]))
-#                    colnames(tmpData)[c(1,dim(tmpData)[2])] = c(i, "residual")
-#                    factor.VaR.decomp.list[[i]] = 
+#                    colnames(tmpData)[c(1,dim(tmpData)[2])] <- c(i, "residual")
+#                    factor.VaR.decomp.list[[i]] <- 
 #                      factorModelVaRDecomposition(tmpData, 
 #                                                  x$beta[i,],
 #                                                  x$resid.variance[i], tail.prob=0.05,
@@ -485,12 +481,12 @@
 #                }
 #                
 #                # stacked bar charts of percent contributions to SD
-#                getCVaR = function(x) {
+#                getCVaR <- function(x) {
 #                  x$cVaR.fm
 #                }
 #                # report as positive number
-#                cr.VaR = sapply(factor.VaR.decomp.list, getCVaR)
-#                rownames(cr.VaR) = c(factor.names, "residual")
+#                cr.VaR <- sapply(factor.VaR.decomp.list, getCVaR)
+#                rownames(cr.VaR) <- c(factor.names, "residual")
 #                barplot(cr.VaR, main="Factors' Contribution to VaR",
 #                        legend.text=T, args.legend=list(x="topleft"))
 #              },

Modified: pkg/FactorAnalytics/man/covFm.Rd
===================================================================
--- pkg/FactorAnalytics/man/covFm.Rd	2014-07-29 22:55:01 UTC (rev 3489)
+++ pkg/FactorAnalytics/man/covFm.Rd	2014-07-30 00:15:14 UTC (rev 3490)
@@ -1,13 +1,22 @@
 % Generated by roxygen2 (4.0.1): do not edit by hand
 \name{covFm}
 \alias{covFm}
+\alias{covFm.tsfm}
 \title{Covariance Matrix for assets' returns from fitted factor model.}
 \usage{
 covFm(object, ...)
+
+\method{covFm}{tsfm}(object, use = "pairwise.complete.obs", ...)
 }
 \arguments{
 \item{object}{fit object of class \code{tsfm}, \code{sfm} or \code{ffm}.}
 
+\item{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".}
+
 \item{...}{optional arguments passed to \code{\link[stats]{cov}}.}
 }
 \value{
@@ -35,10 +44,9 @@
 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.
 
-Though method for handling NAs and the method for computing covariance can
-be specified via the \dots arguments. As a reasonable default,
-\code{use="pairwise.complete.obs"} is used, which restricts the method to
-"pearson".
+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".
 }
 \examples{
 \dontrun{
@@ -86,5 +94,8 @@
 }
 \seealso{
 \code{\link{fitTsfm}}, \code{\link{fitSfm}}, \code{\link{fitFfm}}
+
+\code{\link[stats]{cov}} for more details on arguments \code{use} and
+\code{method}.
 }
 

Modified: pkg/FactorAnalytics/man/fitTsfm.Rd
===================================================================
--- pkg/FactorAnalytics/man/fitTsfm.Rd	2014-07-29 22:55:01 UTC (rev 3489)
+++ pkg/FactorAnalytics/man/fitTsfm.Rd	2014-07-30 00:15:14 UTC (rev 3490)
@@ -1,7 +1,6 @@
 % Generated by roxygen2 (4.0.1): do not edit by hand
 \name{fitTsfm}
 \alias{coef.tsfm}
-\alias{covFm.tsfm}
 \alias{fitTsfm}
 \alias{fitted.tsfm}
 \alias{residuals.tsfm}
@@ -17,8 +16,6 @@
 \method{fitted}{tsfm}(object, ...)
 
 \method{residuals}{tsfm}(object, ...)
-
-\method{covFm}{tsfm}(object, ...)
 }
 \arguments{
 \item{asset.names}{vector containing names of assets, whose returns or
@@ -51,7 +48,9 @@
 the function \code{\link{fitTsfm.control}}. See the documentation for
 \code{\link{fitTsfm.control}} for details.}
 
-\item{...}{arguments passed to \code{\link{fitTsfm.control}}}
+\item{...}{For \code{fitTsfm}: arguments passed to
+\code{\link{fitTsfm.control}}. \cr
+For S3 methods: further arguments passed to or from other methods}
 
 \item{object}{a fit object of class \code{tsfm} which is returned by
 \code{fitTsfm}}
@@ -151,16 +150,13 @@
 fit <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
                factor.names=colnames(managers[,(7:9)]),
                mkt.name="SP500 TR", mkt.timing="both", 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")
+# plot actual returns vs. fitted factor model returns for HAM1
+plot(fit, plot.single=TRUE, asset.name="HAM1", which.plot.single=1,
+     loop=FALSE)
+# group plot; type selected from menu prompt; auto-looped for multiple plots
+# plot(fit)
 
 # example using "subsets" variable selection
 fit.sub <- fitTsfm(asset.names=colnames(managers[,(1:6)]),

Modified: pkg/FactorAnalytics/man/plot.tsfm.Rd
===================================================================
--- pkg/FactorAnalytics/man/plot.tsfm.Rd	2014-07-29 22:55:01 UTC (rev 3489)
+++ pkg/FactorAnalytics/man/plot.tsfm.Rd	2014-07-30 00:15:14 UTC (rev 3490)
@@ -5,7 +5,7 @@
 \usage{
 \method{plot}{tsfm}(x, which.plot.group = NULL, max.show = 6,
   plot.single = FALSE, asset.name, which.plot.single = NULL,
-  colorset = (1:12), legend.loc = "bottomright", las = 1,
+  colorset = (1:12), legend.loc = "topleft", las = 1,
   VaR.method = "historical", loop = TRUE, ...)
 }
 \arguments{
@@ -81,7 +81,8 @@
 and the corresponding plot is output. And, the menu is repeated for
 user convenience in plotting multiple characteristics. Selecting '0' from
 the menu exits the current \code{plot.tsfm} call. Alternately, setting
-\code{loop=FALSE} will exit after plotting any one chosen characteristic.
+\code{loop=FALSE} will exit after plotting any one chosen characteristic
+without the need for menu selection.
 
 For group plots (the default), the first \code{max.show} assets are plotted.
 For individual plots, \code{asset.name} is necessary if multiple assets
@@ -96,18 +97,24 @@
 \code{variable.slection="lars"}.
 }
 \examples{
-\dontrun{
 # load data from the database
 data(managers)
 fit.macro <- fitTsfm(asset.names=colnames(managers[,(1:6)]),
                      factor.names=colnames(managers[,(7:8)]),
                      rf.name="US 3m TR", data=managers)
-# plot the 1st 4 assets fitted above.
-plot(fit.macro, max.show=4)
-# plot of an individual asset, "HAM1"
-plot(fit.macro, plot.single=TRUE, asset.name="HAM1")
+
+# plot the factor betas of 1st 4 assets fitted above.
+plot(fit.macro, max.show=4, which.plot.group=2, loop=FALSE)
+# plot the factor model return correlation, order = hierarchical clustering
+plot(fit.macro, which.plot.group=7, loop=FALSE, order="hclust", addrect=3)
+
+# histogram of residuals from an individual asset's factor model fit
+plot(fit.macro, plot.single=TRUE, asset.name="HAM1", which.plot.single=8,
+     loop=FALSE)
+
+# group plot; type selected from menu prompt; auto-looped for multiple plots
+# plot(fit.macro)
 }
-}
 \author{
 Eric Zivot, Yi-An Chen and Sangeetha Srinivasan
 }



More information about the Returnanalytics-commits mailing list