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

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Wed Apr 22 06:49:26 CEST 2015


Author: pragnya
Date: 2015-04-22 06:49:25 +0200 (Wed, 22 Apr 2015)
New Revision: 3637

Added:
   pkg/FactorAnalytics/tests/FactorAnalytics_04_21_15.pdf
Removed:
   pkg/FactorAnalytics/tests/FactorAnalytics_04_16_15.pdf
Modified:
   pkg/FactorAnalytics/DESCRIPTION
   pkg/FactorAnalytics/NAMESPACE
   pkg/FactorAnalytics/R/fitSfm.R
   pkg/FactorAnalytics/R/fitTsfm.R
   pkg/FactorAnalytics/R/plot.sfm.r
   pkg/FactorAnalytics/R/plot.tsfm.r
   pkg/FactorAnalytics/man/CornishFisher.Rd
   pkg/FactorAnalytics/man/fitSfm.Rd
   pkg/FactorAnalytics/man/fitTsfm.Rd
   pkg/FactorAnalytics/man/fitTsfm.control.Rd
   pkg/FactorAnalytics/man/fitTsfmLagBeta.Rd
   pkg/FactorAnalytics/man/fitTsfmMT.Rd
   pkg/FactorAnalytics/man/fitTsfmUpDn.Rd
   pkg/FactorAnalytics/man/fmCov.Rd
   pkg/FactorAnalytics/man/fmEsDecomp.Rd
   pkg/FactorAnalytics/man/fmSdDecomp.Rd
   pkg/FactorAnalytics/man/fmVaRDecomp.Rd
   pkg/FactorAnalytics/man/fmmc.Rd
   pkg/FactorAnalytics/man/fmmc.estimate.se.Rd
   pkg/FactorAnalytics/man/paFm.Rd
   pkg/FactorAnalytics/man/plot.pafm.Rd
   pkg/FactorAnalytics/man/plot.sfm.Rd
   pkg/FactorAnalytics/man/plot.tsfm.Rd
   pkg/FactorAnalytics/man/plot.tsfmUpDn.Rd
   pkg/FactorAnalytics/man/predict.sfm.Rd
   pkg/FactorAnalytics/man/predict.tsfm.Rd
   pkg/FactorAnalytics/man/predict.tsfmUpDn.Rd
   pkg/FactorAnalytics/man/print.pafm.Rd
   pkg/FactorAnalytics/man/print.sfm.Rd
   pkg/FactorAnalytics/man/print.tsfm.Rd
   pkg/FactorAnalytics/man/print.tsfmUpDn.Rd
   pkg/FactorAnalytics/man/summary.pafm.Rd
   pkg/FactorAnalytics/man/summary.sfm.Rd
   pkg/FactorAnalytics/man/summary.tsfm.Rd
   pkg/FactorAnalytics/man/summary.tsfmUpDn.Rd
   pkg/FactorAnalytics/vignettes/fitSfm_vignette.R
   pkg/FactorAnalytics/vignettes/fitSfm_vignette.Rnw
   pkg/FactorAnalytics/vignettes/fitSfm_vignette.pdf
   pkg/FactorAnalytics/vignettes/fitTsfm_vignette.R
   pkg/FactorAnalytics/vignettes/fitTsfm_vignette.Rnw
   pkg/FactorAnalytics/vignettes/fitTsfm_vignette.pdf
   pkg/FactorAnalytics/vignettes/fmmc_vignette.Rnw
Log:
Improved plot.sfm options and formatting. Updated Roxygen package for documentation.

Modified: pkg/FactorAnalytics/DESCRIPTION
===================================================================
--- pkg/FactorAnalytics/DESCRIPTION	2015-04-18 16:44:10 UTC (rev 3636)
+++ pkg/FactorAnalytics/DESCRIPTION	2015-04-22 04:49:25 UTC (rev 3637)
@@ -1,8 +1,8 @@
 Package: factorAnalytics
 Type: Package
 Title: Factor Analytics
-Version:2.0.17
-Date:2015-04-14
+Version:2.0.18
+Date:2015-04-21
 Author: Eric Zivot, Sangeetha Srinivasan and Yi-An Chen
 Maintainer: Sangeetha Srinivasan <sangee at uw.edu>
 Description: An R package for the estimation and risk analysis of linear factor

Modified: pkg/FactorAnalytics/NAMESPACE
===================================================================
--- pkg/FactorAnalytics/NAMESPACE	2015-04-18 16:44:10 UTC (rev 3636)
+++ pkg/FactorAnalytics/NAMESPACE	2015-04-22 04:49:25 UTC (rev 3637)
@@ -1,4 +1,4 @@
-# Generated by roxygen2 (4.1.0): do not edit by hand
+# Generated by roxygen2 (4.1.1): do not edit by hand
 
 S3method(coef,sfm)
 S3method(coef,tsfm)
@@ -60,7 +60,6 @@
 importFrom(RCurl,merge.list)
 importFrom(bestglm,bestglm)
 importFrom(boot,boot)
-importFrom(corrplot,corrplot)
 importFrom(corrplot,corrplot.mixed)
 importFrom(doSNOW,registerDoSNOW)
 importFrom(foreach,foreach)

Modified: pkg/FactorAnalytics/R/fitSfm.R
===================================================================
--- pkg/FactorAnalytics/R/fitSfm.R	2015-04-18 16:44:10 UTC (rev 3636)
+++ pkg/FactorAnalytics/R/fitSfm.R	2015-04-22 04:49:25 UTC (rev 3637)
@@ -15,19 +15,20 @@
 #' 
 #' Let \code{N} be the number of columns or assets and \code{T} be the number 
 #' of rows or observations. When \code{N < T}, Principal Component Analysis 
-#' (PCA) is performed. Otherwise, Asymptotic Principal Component Analysis 
-#' (APCA) is performed. In either case, any number of factors less than 
-#' \code{min(N,T)} can be chosen via argument \code{k}. Default is 1. Refer to 
-#' Zivot and Wang (2007) for more details and references.
+#' (PCA) is performed. Any number of factors less than \code{min(N,T)} can be 
+#' chosen via argument \code{k}. Default is 1. Refer to Zivot and Wang (2007) 
+#' for more details and references.
 #' 
-#' Alternately, for APCA, a method to determine the number of factors can be 
-#' specified: \code{k="bn"} corresponds to Bai and Ng (2002) and \code{k="ck"} 
-#' corresponds to Connor and Korajczyk (1993). User can specify the maximum 
-#' number of factors, \code{max.k} to consider with these methods. If not, it 
-#' is assumed to be either 10 or $T-1$, whichever is smaller. 
+#' When \code{N >= T}, Asymptotic Principal Component Analysis (APCA) is 
+#' performed. The user can directly specify \code{k} similar to PCA above, or a 
+#' method to automatically determine the number of factors can be specified: 
+#' \code{k="bn"} corresponds to Bai and Ng (2002) and \code{k="ck"} corresponds 
+#' to Connor and Korajczyk (1993). Users can choose the maximum number of 
+#' factors, \code{max.k}, to consider with these methods. The default for 
+#' \code{max.k} is set to be 10 or $T-1$, whichever is smaller. 
 #' 
 #' \code{refine} specifies whether a refinement of the APCA procedure from 
-#' Connor and Korajczyk (1988) that may improve efficiency is to be used. 
+#' Connor and Korajczyk (1988), that may improve efficiency, is to be used. 
 #' 
 #' When \code{corr=TRUE}, the correlation matrix of returns are used for 
 #' finding the principal components instead of the covariance matrix. This is 
@@ -44,8 +45,8 @@
 #' 
 #' @param data vector, matrix, data.frame, xts, timeSeries or zoo object with 
 #' asset returns. See details.
-#' @param k number of factors; a number (or) a method for determining the 
-#' optimal number of factors, one of "bn" or "ck". See details. Default is 1.
+#' @param k number of factors (or) a method for determining the optimal number 
+#' of factors, one of "bn" or "ck". See details. Default is 1.
 #' @param max.k scalar; the maximum number of factors to be considered for 
 #' methods "bn" or "ck". Default is \code{NULL}. See details.
 #' @param refine logical; whether to use the Connor-Korajczyk refinement for 

Modified: pkg/FactorAnalytics/R/fitTsfm.R
===================================================================
--- pkg/FactorAnalytics/R/fitTsfm.R	2015-04-18 16:44:10 UTC (rev 3636)
+++ pkg/FactorAnalytics/R/fitTsfm.R	2015-04-22 04:49:25 UTC (rev 3637)
@@ -84,8 +84,8 @@
 #' class \code{lm} if \code{fit.method="LS" or "DLS"}, class \code{lmRob} if 
 #' the \code{fit.method="Robust"}, or class \code{lars} if 
 #' \code{variable.selection="lars"}.}
-#' \item{alpha}{length-N vector of estimated alphas.}
-#' \item{beta}{N x K matrix of estimated betas.}
+#' \item{alpha}{N x 1 data.frame of estimated alphas.}
+#' \item{beta}{N x K data.frame of estimated betas.}
 #' \item{r2}{length-N vector of R-squared values.}
 #' \item{resid.sd}{length-N vector of residual standard deviations.}
 #' \item{fitted}{xts data object of fitted values; iff 
@@ -246,10 +246,10 @@
   } 
   
   # extract coefficients from fitted factor models returned above
-  coef.mat <- makePaddedDataFrame(lapply(reg.list, coef))
-  alpha <- coef.mat[, 1, drop=FALSE]
-  # to get alpha of class numeric, do: aplha <- coef.mat[,1]
-  beta <- coef.mat[, -1, drop=FALSE]
+  coef.df <- makePaddedDataFrame(lapply(reg.list, coef))
+  alpha <- coef.df[, 1, drop=FALSE]
+  # to get alpha of class numeric, do: aplha <- coef.df[,1]
+  beta <- coef.df[, -1, drop=FALSE]
   # reorder and expand columns of beta to match factor.names
   tmp <- matrix(NA, length(asset.names), length(factor.names))
   colnames(tmp) <- factor.names
@@ -478,10 +478,10 @@
 
 coef.tsfm <- function(object, ...) {
   # cbind alpha and beta; works for all fit and var selection methods
-  coef.mat <- cbind(object$alpha, object$beta)
+  coef.df <- cbind(object$alpha, object$beta)
   # name for alpha/intercept column
-  colnames(coef.mat)[1] <- "(Intercept)"
-  return(coef.mat)
+  colnames(coef.df)[1] <- "(Intercept)"
+  return(coef.df)
 }
 
 #' @rdname fitTsfm

Modified: pkg/FactorAnalytics/R/plot.sfm.r
===================================================================
--- pkg/FactorAnalytics/R/plot.sfm.r	2015-04-18 16:44:10 UTC (rev 3636)
+++ pkg/FactorAnalytics/R/plot.sfm.r	2015-04-22 04:49:25 UTC (rev 3637)
@@ -4,74 +4,82 @@
 #' Plots chosen characteristic(s) for one or more assets. 
 #' 
 #' @details 
-#' If the plot type argument is not specified, a menu prompts for user input 
-#' 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.sfm} call. Alternately, setting
-#' \code{loop=FALSE} will exit after plotting any one chosen characteristic 
-#' without the need for menu selection.
+#' The function can be used for group plots and individual plots. User can 
+#' select the type of plot either from the menu prompt (default) or directly 
+#' via argument \code{which}.
 #' 
-#' Group plots are the default. The variables in \code{asset.subset} and factors
-#' in \code{asset.subset} are plotted depending on the characteristic chosen. 
-#' The default is to show the first 4 factors and first 5 assets.
+#' In case multiple plots are needed, the menu is repeated after each plot 
+#' (enter 0 to exit). User can also input a numeric vector of plot options via 
+#' \code{which}.
 #' 
-#' Individual asset plots are selected by specifying \code{plot.single=TRUE}. 
-#' In which case, \code{asset.name} is necessary if multiple assets 
-#' were modeled in \code{x}. However, if the \code{fitSfm} object contains only 
-#' one asset's factor model fit, \code{plot.sfm} can infer this automatically, 
-#' without user input. 
+#' Group plots are the default. The selected assets in \code{a.sub} and 
+#' selected factors in \code{f.sub} are plotted depending on the 
+#' characteristic chosen. The default is to show the first 2 factors and first 
+#' 6 assets.
 #' 
+#' Setting \code{plot.single=TRUE} enables individual plots. If there is more 
+#' than one asset fit by \code{x}, \code{asset.name} should be specified. 
+#' In case the \code{tsfm} object \code{x} contains only a single asset fit, 
+#' plot.tsfm can infer \code{asset.name} without user input.  
+#' 
 #' @param x an object of class \code{sfm} produced by \code{fitSfm}.
-#' @param which.plot.group a number to indicate the type of group plot for 
-#' multiple assets. If \code{NULL} (default), the following menu appears: \cr 
+#' @param which a number to indicate the type of plot. If a subset of the plots 
+#' is required, specify a subset of the numbers 1:13 for group plots and 1:18 
+#' for individual plots. If \code{which=NULL} (default), the following menu 
+#' appears: \cr \cr
+#' For plots of a group of assets: \cr
 #' 1 = Screeplot of eigenvalues, \cr
 #' 2 = Time series plot of estimated factors, \cr
 #' 3 = Estimated factor loadings, \cr
 #' 4 = Histogram of R-squared, \cr
 #' 5 = Histogram of residual volatility,\cr
-#' 6 = Factor model residual correlation \cr
-#' 7 = Factor model correlation,\cr
-#' 8 = Factor contribution to SD,\cr
-#' 9 = Factor contribution to ES,\cr
-#' 10 = Factor contribution to VaR, \cr
-#' 11 = Factor mimicking portfolio weights - top long and short positions in each factor, \cr
-#' 12 = Asset correlations - top long and short positions in each factor
-#' @param factor.subset vector of names/indices of factors to show for group 
-#' plots. Default is 1:4.
-#' @param asset.subset vector of names/indices of assets to show for group 
-#' plots. Default is 1:5. 
+#' 6 = Factor model residuals scatterplot matrix, with histograms, density overlays, correlations and significance stars, \cr
+#' 7 = Factor model residual correlation \cr
+#' 8 = Factor model return correlation,\cr
+#' 9 = Factor contribution to SD,\cr
+#' 10 = Factor contribution to ES,\cr
+#' 11 = Factor contribution to VaR, \cr
+#' 12 = Factor mimicking portfolio weights - top long and short positions in each factor, \cr 
+#' 13 = Asset correlations - top long and short positions in each factor \cr \cr
+#' For individual asset plots:\cr
+#' 1 = Actual and fitted,\cr
+#' 2 = Actual vs fitted,\cr
+#' 3 = Residuals vs fitted, \cr
+#' 4 = Sqrt. of modified residuals vs fitted, \cr
+#' 5 = Residuals with standard error bands, \cr
+#' 6 = Time series of squared residuals, \cr
+#' 7 = Time series of absolute residuals,\cr
+#' 8 = SACF and PACF of residuals,\cr
+#' 9 = SACF and PACF of squared residuals,\cr
+#' 10 = SACF and PACF of absolute residuals,\cr
+#' 11 = Non-parametric density of residuals with normal overlaid, \cr
+#' 12 = Non-parametric density of residuals with skew-t overlaid, \cr 
+#' 13 = Histogram of residuals with non-parametric density and normal overlaid,\cr
+#' 14 = QQ-plot of residuals,\cr
+#' 15 = CUSUM test-Recursive residuals,\cr
+#' 16 = CUSUM test-LS residuals,\cr
+#' 17 = Recursive estimates (RE) test of LS regression coefficients,\cr
+#' 18 = Rolling regression over a 24-period observation window
+#' @param f.sub vector of indexes of factors to show for group plots. Default is 1:2.
+#' @param a.sub vector of indexes of assets to show for group plots. Default is 1:6. 
 #' @param n.top scalar; number of largest and smallest weights to display for 
 #' each factor mimicking portfolio. Default is 3.
 #' @param plot.single logical; If \code{TRUE} plots the characteristics of an 
 #' individual asset's factor model. The type of plot is given by 
-#' \code{which.plot.single}. Default is \code{FALSE}.
+#' \code{which}. Default is \code{FALSE}.
 #' @param asset.name name of the individual asset to be plotted. Is necessary 
 #' if \code{x} contains multiple asset fits and \code{plot.single=TRUE}.
-#' @param which.plot.single a number to indicate the type of group plot for an 
-#' individual asset. If \code{NULL} (default), the following menu appears: \cr
-#'  1 = Time series plot of actual and fitted asset returns,\cr
-#'  2 = Time series plot of residuals with standard error bands, \cr
-#'  3 = Time series plot of squared residuals, \cr
-#'  4 = Time series plot of absolute residuals,\cr
-#'  5 = SACF and PACF of residuals,\cr
-#'  6 = SACF and PACF of squared residuals,\cr
-#'  7 = SACF and PACF of absolute residuals,\cr
-#'  8 = Histogram of residuals with normal curve overlayed,\cr
-#'  9 = Normal qq-plot of residuals,\cr
-#'  10 = CUSUM test-Recursive residuals,\cr
-#'  11 = CUSUM test-LS residuals,\cr
-#'  12 = Recursive estimates (RE) test of LS regression coefficients,\cr
-#'  13 = Rolling estimates over a 24-period observation window
-#' @param colorset color palette to use for all the plots. Default is 
-#' \code{c(1:12)}. The 1st element will be used for individual time series 
-#' plots or the 1st series plotted, the 2nd element for the 2nd object in the 
-#' plot and so on.
+#' @param colorset color palette to use for all the plots. The 1st element will 
+#' be used for individual time series plots or the 1st object plotted, the 2nd 
+#' element for the 2nd object in the plot and so on.
 #' @param legend.loc places a legend into one of nine locations on the chart: 
 #' "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", 
 #' "right", or "center". Default is "bottomright". Use \code{legend.loc=NULL} 
 #' to suppress the legend.
 #' @param las one of {0, 1, 2, 3} to set the direction of axis labels, same as 
-#' in \code{plot}. Default here is 1.
+#' in \code{plot}. Default is 1.
+#' @param lwd set the line width, same as in \code{\link{plot}}. Default is 2.
+#' @param maxlag optional number of lags to be calculated for ACF. Default is 15.
 #' @param VaR.method a method for computing VaR; one of "modified", "gaussian",
 #' "historical" or "kernel". VaR is computed using 
 #' \code{\link[PerformanceAnalytics]{VaR}}. Default is "historical".
@@ -80,29 +88,32 @@
 #' @param cum.var logical; If \code{TRUE}, the cumulative fraction of the
 #' variance is printed above each bar in the screeplot of eigenvalues. Default
 #' is \code{TRUE}.
-#' @param loop logical to indicate if the plot menu should be repeated. Default
-#' is \code{TRUE}.
 #' @param ... further arguments to be passed to other plotting functions.
 #' 
 #' @author Eric Zivot, Sangeetha Srinivasan and Yi-An Chen
 #' 
-#' @seealso \code{\link{fitSfm}} and \code{\link{summary.sfm}} for details
-#' about the time series factor model fit, extractor functions and summary 
-#' statistics.
+#' @seealso \code{\link{fitSfm}}, \code{\link{residuals.sfm}}, 
+#' \code{\link{fitted.sfm}}, \code{\link{fmCov.sfm}} and 
+#' \code{\link{summary.sfm}} for statistical factor model fitting and related 
+#' S3 methods. Refer to \code{\link{fmSdDecomp}}, \code{\link{fmEsDecomp}}, 
+#' \code{\link{fmVaRDecomp}} for factor model risk measures.
 #' 
-#' \code{\link[strucchange]{efp}} for CUSUM tests.
+#' Here is a list of plotting functions used. (I=individual, G=Group)
+#' I(1,5,6,7) - \code{\link[PerformanceAnalytics]{chart.TimeSeries}}, 
+#' I(2,3,4) - \code{\link[graphics]{plot.default}},
+#' I(3,4) - \code{\link[graphics]{panel.smooth}},
+#' I(8,9,10) - \code{\link[PerformanceAnalytics]{chart.ACFplus}}, 
+#' I(11,12) - \code{\link[stats]{plot.density}},
+#' I(13), G(4,5) - \code{\link[PerformanceAnalytics]{chart.Histogram}},
+#' I(14) - \code{\link[PerformanceAnalytics]{chart.QQPlot}}, 
+#' I(15,16,17) - \code{\link[strucchange]{plot.efp}},
+#' I(18) - \code{\link[zoo]{plot.zoo}},
+#' G(1,12) - \code{\link[graphics]{barplot}}, 
+#' G(2) - \code{\link[lattice]{xyplot}},
+#' G(3,9,10,11) - \code{\link[lattice]{barchart}},
+#' G(6) - \code{\link[PerformanceAnalytics]{chart.Correlation}} and
+#' G(7,8,13) - \code{\link[corrplot]{corrplot.mixed}}. 
 #' 
-#' \code{\link[xts]{plot.xts}}, 
-#' \code{\link[PerformanceAnalytics]{chart.TimeSeries}}, 
-#' \code{\link[PerformanceAnalytics]{chart.ACFplus}}, 
-#' \code{\link[PerformanceAnalytics]{chart.Histogram}},
-#' \code{\link[PerformanceAnalytics]{chart.QQPlot}}, 
-#' \code{\link[graphics]{barplot}}, \code{\link[lattice]{barchart}} and 
-#' \code{\link[corrplot]{corrplot}} for plotting methods used.
-#' 
-#' \code{\link{fmSdDecomp}}, \code{\link{fmEsDecomp}}, 
-#' \code{\link{fmVaRDecomp}} for factor model risk measures.
-#' 
 #' @examples
 #' 
 #' # load data from the database
@@ -111,37 +122,43 @@
 #' # APCA with number of factors, k=15
 #' fit.apca <- fitSfm(r.W, k=15, refine=TRUE)
 #' 
-#' # group plot(default); select type from menu prompt
-#' # menu is auto-looped to get multiple types of plots based on the same fit
+#' # for group plots (default), user can select plot option from menu prompt
+#' # menu is repeated to get multiple types of plots based on the same fit
 #' # plot(fit.apca)
 #' 
-#' # plot the factor betas of 1st 4 assets fitted above
-#' # loop disabled to get one type of plot without interative menu
-#' plot(fit.apca, asset.subset=1:4, which.plot.group=3, loop=FALSE)
+#' # choose specific plot option(s) using which
+#' # plot the first 4 factor betas of the first 4 assets fitted above
+#' plot(fit.apca, f.sub=1:4, a.sub=1:4, which=3)
 #' 
-#' # plot factor model return correlation; angular order of the eigenvectors
-#' plot(fit.apca, which.plot.group=7, loop=FALSE, 
-#'      order="AOE", method="ellipse", tl.pos = "d")
+#' # plot factor model residuals scatterplot matrix, with histograms, density 
+#' # overlays, correlations and significance stars
+#' plot(fit.apca, which=6)
 #' 
+#' # for individual plots: set plot.single=TRUE and specify asset.name
 #' # histogram of residuals from an individual asset's factor model fit 
-#' plot(fit.apca, plot.single=TRUE, asset.name="AFL", which.plot.single=8, 
-#'      loop=FALSE)
+#' plot(fit.apca, plot.single=TRUE, asset.name="AFL", which=13)
 #' 
 #' @importFrom PerformanceAnalytics chart.TimeSeries chart.ACFplus
-#' chart.Histogram chart.QQPlot
+#' chart.Histogram chart.QQPlot chart.Correlation
 #' @importFrom lattice barchart xyplot panel.barchart panel.grid
-#' @importFrom corrplot corrplot
+#' @importFrom corrplot corrplot.mixed
 #' @importFrom strucchange efp
+#' @importFrom sn dst st.mple
 #' 
 #' @method plot sfm
 #' @export
 
-plot.sfm <- function(x, which.plot.group=NULL, factor.subset=1:4, 
-                     asset.subset=1:5, n.top=3, plot.single=FALSE, asset.name, 
-                     which.plot.single=NULL, colorset=(1:12), 
-                     legend.loc="topleft", las=1, VaR.method="historical", 
-                     cum.var=TRUE, eig.max=0.9, loop=TRUE, ...) {
+plot.sfm <- function(x, which=NULL, f.sub=1:2, a.sub=1:6, n.top=3, 
+                     plot.single=FALSE, asset.name,
+                     colorset=c("royalblue","dimgray","olivedrab","firebrick",
+                                "goldenrod","mediumorchid","deepskyblue",
+                                "chocolate","darkslategray"), 
+                     legend.loc="topleft", las=1, lwd=2, maxlag=15, 
+                     VaR.method="historical", eig.max=0.9, cum.var=TRUE, ...) {
   
+  which.vec <- which
+  which <- which[1]
+  
   if (plot.single==TRUE) {
     
     if (missing(asset.name) && length(x$asset.names)>1) {
@@ -153,24 +170,35 @@
       i <- asset.name
     }
     # extract info from the fitSfm object
-    plotData <- merge.xts(x$data[,i], fitted(x)[,i])
-    colnames(plotData) <- c("Actual","Fitted")
-    Residuals <- residuals(x)[,i]
-    fit <- lm(x$data[,i] ~ x$factors)
+    plotData <- merge.xts(x$data[,i], fitted(x)[,i], residuals(x)[,i])
+    colnames(plotData) <- c("Actual","Fitted","Residuals")
+    Residuals <- na.omit(plotData[,"Residuals"])
+    fitData <- merge(x$data[,i], x$factors)
+    fit <- lm(as.formula(paste(i," ~ .")), data=fitData)
+    resid.sd <- x$resid.sd[i]
+    den <- density(Residuals)
+    xval <- den$x
+    den.norm <- dnorm(xval, mean=mean(Residuals), sd=resid.sd)
+    den.st <- dst(xval, dp=st.mple(x=matrix(1,nrow(Residuals)), y=as.vector(Residuals))$dp)
     
     # plot selection
     repeat {
-      if (is.null(which.plot.single)) {
-        which.plot.single <- 
-          menu(c("Time series plot of actual and fitted asset returns",
-                 "Time series plot of residuals with standard error bands",
-                 "Time series plot of squared residuals",
-                 "Time series plot of absolute residuals",
+      if (is.null(which)) {
+        which <- 
+          menu(c("Actual and fitted asset returns",
+                 "Actual vs fitted asset returns",
+                 "Residuals vs fitted asset returns",
+                 "Sqrt. of modified residuals vs fitted",
+                 "Residuals with standard error bands",
+                 "Time series of squared residuals",
+                 "Time series of absolute residuals",
                  "SACF and PACF of residuals",
                  "SACF and PACF of squared residuals",
                  "SACF and PACF of absolute residuals",
-                 "Histogram of residuals with normal curve overlayed",
-                 "Normal qq-plot of residuals",
+                 "Non-parametric density of residuals with normal overlaid",
+                 "Non-parametric density of residuals with skew-t overlaid",
+                 "Histogram of residuals with non-parametric density and normal overlaid",
+                 "QQ-plot of residuals",
                  "CUSUM test-Recursive residuals",
                  "CUSUM test-LS residuals",
                  "Recursive estimates (RE) test of LS regression coefficients",
@@ -180,104 +208,163 @@
       
       par(las=las) # default horizontal axis labels
       
-      switch(which.plot.single,
+      switch(which,
              "1L" =  {
-               ##  time series plot of actual and fitted asset returns
-               chart.TimeSeries(plotData, main=paste("Returns:",i), 
-                                colorset=colorset, xlab="",
-                                ylab="Actual and fitted asset returns", 
+               ##  Time series plot of actual and fitted asset returns
+               chart.TimeSeries(plotData[,1:2], main=paste("Actual and fitted:",i), 
+                                colorset=colorset, xlab="", ylab="Returns", lwd=lwd,
                                 legend.loc=legend.loc, pch=NULL, las=las, ...)
              }, "2L" = {
-               ## time series plot of residuals with standard error bands
+               ## Actual vs fitted asset returns
+               plot(x=coredata(plotData[,2]), y=coredata(plotData[,1]), 
+                    xlab="Fitted", ylab="Actual", col=colorset[1], 
+                    main=paste("Actual vs fitted:",i), las=las, ...)
+               abline(0, 1, col="dimgray",lty="dotted", lwd=lwd)
+             }, "3L" = {
+               ## Residuals vs fitted asset returns
+               plot(x=coredata(plotData[,2]), y=coredata(plotData[,3]), 
+                    xlab="Fitted", ylab="Residuals", col=colorset[1], 
+                    main=paste("Residuals vs fitted:",i), las=las, ...)
+               panel.smooth(x=coredata(plotData[,2]), y=coredata(plotData[,3]), 
+                            col=colorset[1], col.smooth=colorset[2], lwd=lwd)
+             }, "4L" = {
+               ## Square root of absolute modified residuals vs fitted asset returns 
+               yval <- sqrt(abs(Residuals/sqrt(1-hatvalues(fit))))
+               plot(x=coredata(na.omit(plotData[,2])), y=yval, xlab="Fitted", 
+                    ylab=expression(sqrt(abs("Modified Residuals"))), col=colorset[1], 
+                    main=paste("Sqrt. modified residuals vs fitted:",i), las=las, ...)
+               panel.smooth(x=coredata(na.omit(plotData[,2])), y=yval, 
+                            col=colorset[1], col.smooth=colorset[2], lwd=lwd)
+             }, "5L" = {
+               ## Time series plot of residuals with standard error bands
                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
+                                lwd=lwd, lty="solid", las=las, ...)
+               abline(h=1.96*x$resid.sd[i], lwd=lwd, lty="dotted", col=colorset[2])
+               abline(h=-1.96*x$resid.sd[i], lwd=lwd, lty="dotted", col=colorset[2])
+               legend(x=legend.loc, lty=c("solid","dotted"), col=c(colorset[1:2]), 
+                      lwd=lwd, bty="n", legend=c("Residuals",expression("\u00b1 1.96 "*sigma)))
+             }, "6L" = {
+               ## Time series plot of squared residuals
                chart.TimeSeries(Residuals^2, colorset=colorset, xlab="", 
-                                ylab=" Squared Residuals",
+                                ylab=" Squared Residuals", lwd=lwd,
                                 main=paste("Squared Residuals:",i), 
-                                legend.loc=legend.loc, pch=NULL, las=las, ...)
-             }, "4L" = {
+                                legend.loc=NULL, pch=NULL, las=las, ...)
+             }, "7L" = {
                ## time series plot of absolute residuals
                chart.TimeSeries(abs(Residuals), colorset=colorset, xlab="", 
-                                ylab="Absolute Residuals",
+                                ylab="Absolute Residuals", lwd=lwd,
                                 main=paste("Absolute Residuals:",i), 
-                                legend.loc=legend.loc, pch=NULL, las=las, ...)
-             }, "5L" = {
+                                legend.loc=NULL, pch=NULL, las=las, ...)
+             }, "8L" = {
                ## SACF and PACF of residuals
-               chart.ACFplus(Residuals, col=colorset[1],
+               chart.ACFplus(Residuals, maxlag=maxlag,
                              main=paste("SACF & PACF - Residuals:",i), ...)
-             }, "6L" = {
+             }, "9L" = {
                ## SACF and PACF of squared residuals
-               chart.ACFplus(Residuals^2, col=colorset[1], ...,
-                             main=paste("SACF & PACF - Squared residuals:",i))
-             }, "7L" = {
+               chart.ACFplus(Residuals^2, maxlag=maxlag,
+                             main=paste("SACF & PACF - Squared residuals:",i), ...)
+             }, "10L" = {
                ## SACF and PACF of absolute residuals
                chart.ACFplus(abs(Residuals), col=colorset[1], ...,
                              main=paste("SACF & PACF - Absolute Residuals:",i))
-             }, "8L" = {
-               ## histogram of residuals with normal curve overlayed
+             }, "11L" = {
+               ## Non-parametric density of residuals with normal overlaid
+               ymax <- ceiling(max(0,den$y,den.norm))
+               plot(den, xlab="Return residuals", lwd=lwd, col=colorset[1], 
+                    ylim=c(0,ymax), main=paste("Density of residuals:",i), ...)
+               rug(Residuals, col="dimgray")
+               lines(xval, den.norm, col=colorset[2], lwd=lwd, lty="dashed")
+               legend(x=legend.loc, lty=c("solid","dashed"), col=c(colorset[1:2]), 
+                      lwd=lwd, bty="n", legend=c("KDE","Normal"))
+             }, "12L" = {
+               ## Non-parametric density of residuals with skew-t overlaid
+               ymax <- ceiling(max(0,den$y,den.st))
+               plot(den, xlab="Return residuals", lwd=lwd, col=colorset[1], 
+                    ylim=c(0,ymax), main=paste("Density of residuals:",i), ...)
+               rug(Residuals, col="dimgray")
+               lines(xval, den.st, col=colorset[2], lty="dashed", lwd=lwd)
+               legend(x=legend.loc, lty=c("solid","dashed"), col=c(colorset[1:2]), 
+                      lwd=lwd, bty="n", legend=c("KDE","Skew-t"))
+             }, "13L" = {
+               ## Histogram of residuals with non-parametric density and normal overlaid
                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
-               chart.QQPlot(Residuals, envelope=0.95, col=colorset,
+               chart.Histogram(Residuals, xlab="Return residuals", methods=methods,
+                               colorset=colorset[c(1,2,3)], 
+                               lwd=lwd, main=paste("Histogram of residuals:",i), ...)
+               legend(x=legend.loc, col=colorset[c(2,3)], lwd=lwd, bty="n", 
+                      legend=c("KDE","Normal"))
+             }, "14L" = {
+               ##  QQ-plot of residuals
+               chart.QQPlot(Residuals, envelope=0.95, col=colorset[1:2], lwd=lwd,
                             main=paste("QQ-plot of Residuals:",i), ...)
-               legend(x=legend.loc, col="red", lty="dotted", lwd=1,
-                      legend=c("0.95 confidence envelope"))
-             }, "10L" = {
+               legend(x=legend.loc, col=colorset[2], lty="dashed", lwd=1, bty="n",
+                      legend=c("0.95 C.Env."))
+             }, "15L" = {
                ##  Recursive CUSUM test
                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" = {
+                    col=colorset, lwd=lwd, ...)
+             }, "16L" = {
                ##  LS-based CUSUM test
-               cusum.ols <- efp(formula(fit), type="LS-CUSUM", data=fit$model)
+               cusum.ols <- efp(formula(fit), type="OLS-CUSUM", data=fit$model)
                plot(cusum.ols, main=paste("LS-based CUSUM test:",i), las=las, 
-                    col=colorset, ...)
-             }, "12L" = {
-               ##  Recursive estimates (RE) test of LS regression coefficients      
+                    col=colorset, lwd=lwd, ...)
+             }, "17L" = {
+               ##  Recursive estimates (RE) test of LS regression coefficients  
+               if (x$k > 9) {
+                 stop("Plotting limit: This option is not available when K > 9.")
+               }
                cusum.est <- efp(formula(fit), type="RE", data=fit$model)
-               plot(cusum.est, functional=NULL, col=colorset, las=0,
+               plot(cusum.est, functional=NULL, col=colorset, las=0, cex.lab=0.7,
                     main=paste("RE test (Recursive estimates test):",i), ...)
-             }, "13L" = {
+               par(las=las, cex.lab=1)
+             }, "18L" = {
                ##  Rolling estimates over 24-period observation window 
-               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), 
-                                      width=24, by.column=FALSE, align="right")
+               rollReg.z <- rollapply(reg.z, width=24, by.column=FALSE, align="right",
+                                      FUN = function(z) coef(lm(formula(fit), data=as.data.frame(z))))
                par(las=0)
-               plot(rollReg.z, ..., las=las,
-                    main=paste("Rolling estimates (24-period obs window):",i))
-               par(las=las)
+               plot(rollReg.z, las=las, cex=0.8, lwd=lwd, col=colorset[1], ...,
+                    main=paste("Rolling regression (24-period obs window):",i))
+               par(las=las, cex=1)
              }, 
              invisible()
       )
       # repeat menu if user didn't choose to exit from the plot options
-      if (which.plot.single==0 || loop==FALSE) {break} 
-      else {which.plot.single=NULL}
+      if (which==0 || length(which.vec)==1) {break} 
+      if (length(which.vec)>1) {
+        which.vec <- which.vec[-1]
+        which <- which.vec[1]
+        par(ask=TRUE)
+      } else {which=NULL}
     } 
   } else { # start of group asset plots
     
+    n <- length(x$asset.names)
+    if (n<=1) {
+      stop("Error: Two or more assets required for group plots.")
+    }
+    k <- x$k
+    f.names <- paste("F", 1:k, sep = ".")
+    
+    if (!(all(f.sub %in% f.names) || all(f.sub %in% 1:k))) {
+      stop("Invalid argument: f.sub is not a valid subset of factor names.") 
+    }
+    if (!(all(a.sub %in% x$asset.names) || all(a.sub %in% 1:n))) {
+      stop("Invalid argument: a.sub is not a valid subset of asset names.") 
+    }
+    
     # plot selection
     repeat {
-      if (is.null(which.plot.group)) {
-        which.plot.group <- 
+      if (is.null(which)) {
+        which <- 
           menu(c("Screeplot of eigenvalues",
[TRUNCATED]

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


More information about the Returnanalytics-commits mailing list